diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index 4be1c918..00000000 --- a/.gitattributes +++ /dev/null @@ -1,2 +0,0 @@ -# Disable LF normalization for all files -* -text \ No newline at end of file diff --git a/.github/workflows/python-ci.yml b/.github/workflows/python-ci.yml new file mode 100644 index 00000000..207d4cbd --- /dev/null +++ b/.github/workflows/python-ci.yml @@ -0,0 +1,70 @@ +name: Python CI + +on: + pull_request: + push: + branches: + - main + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + test-and-build: + runs-on: ubuntu-latest + env: + NSTAT_ALLOW_SYNTHETIC_DATA: "1" + NSTAT_EXPECTED_EXAMPLE_NOTEBOOKS: "25" + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + lfs: false + + - name: Setup Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + + - name: Install package and dev dependencies + run: | + python -m pip install --upgrade pip + python -m pip install -e .[dev] + + - name: Generate docs/notebooks/parity reports + run: | + python tools/generate_help_topic_docs.py + python tools/generate_example_notebooks.py + python tools/freeze_port_baseline.py + python tools/generate_method_parity_matrix.py + python tools/generate_implemented_method_coverage.py + + - name: Verify help docs coverage + run: | + python tools/verify_help_docs_coverage.py + + - name: Verify notebook execution and topic alignment (25/25) + run: | + python tools/verify_examples_notebooks.py + + - name: Build Sphinx docs + run: | + sphinx-build -b html docs docs/_build/html + + - name: Run offline standalone check (strict target install) + run: | + python tools/verify_offline_standalone.py --require-target-install + + - name: Run pytest + run: | + python -m pytest -vv --maxfail=1 --durations=20 + + - name: Upload reports + if: always() + uses: actions/upload-artifact@v4 + with: + name: nstat-python-reports + path: | + reports/*.json + docs/_build/html diff --git a/.gitignore b/.gitignore index 242ef139..53ff4d92 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,10 @@ -.DS_Store -.svn +__pycache__/ +*.pyc +.pytest_cache/ +.ipynb_checkpoints/ + +docs/_build/ +plots/ + +reports/pytest.log +reports/pytest.xml diff --git a/Analysis.m b/Analysis.m deleted file mode 100644 index cb2365e5..00000000 --- a/Analysis.m +++ /dev/null @@ -1,1777 +0,0 @@ -classdef Analysis -% ANALYSIS Collection of functions (static methods) used for GLM analysis -% of point process data. -% methods -% Analysis Examples -% -% see also Trial, CovColl, nstColl,History -% -% Reference page in Help browser -% doc Analysis - -%% -% nSTAT v1 Copyright (C) 2012 Masschusetts Institute of Technology -% Cajigas, I, Malik, WQ, Brown, EN -% This program is free software; you can redistribute it and/or -% modify it under the terms of the GNU General Public License as published -% by the Free Software Foundation; either version 2 of the License, or -% (at your option) any later version. -% -% This program is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -% See the GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with this program; if not, write to the Free Software Foundation, -% Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - - -properties (Constant) - colors = {'b','g','r','c','m','y','k'}; -end - - methods (Static) - function fitResults =RunAnalysisForNeuron(tObj,neuronNumber,configColl,makePlot,Algorithm,DTCorrection,batchMode) - % fitResults =RunAnalysisForNeuron(tObj,neuronNumber,configColl,makePlot,Algorithm) - % tObj: Trial to be analyzed - % neuronNumber: number of the neuron to be analyzed. Can be a - % vector to specify multiple neurons to be analyzed. - % If more than one neuron specified, then - % fitResults is a cell array of fitResult - % objects. fitResults{i} will contain the - % fitResults object for neuronNum(i). - % configColl: ConfigColl object containing the different - % configurations (description of the the types of fits, eg. covariates) that correspond to each fit. - % makePlot: Set to 1 to show a summary plot for this neuron. If performing multiple neuron analysis (eg. via RunAnalysisForAllNeurons) set ths parameter to zero to avoid screen clutter. - % Algorithm: Either 'GLM' or 'BNLRCG'. Default is 'GLM' - % GLM - Standard GLM regression from matlab. - % BNLRCG - faster Truncated, L-2 Regularized, - % Binomial Logistic Regression with Conjugate - % Gradient Solver by Demba Ba (demba@mit.edu). - % DTCorrection: 0 for no DT Correction of KS plot, 1 is the - % default. - % - % batchMode: when batchMode=1 neurons with same name are fit at once rather than separetely - - if(nargin<7 || isempty(batchMode)) - batchMode = 0; %default treat each spike train separately - end - - if(nargin<6 || isempty(DTCorrection)) - DTCorrection =1; - end - if(nargin<5 || isempty(Algorithm)) - Algorithm = 'GLM'; - end - if(nargin<4 || isempty(makePlot)) - makePlot=1; - end - numNeurons = length(neuronNumber); - labels=cell(numNeurons,1); - lambda=cell(numNeurons,1); - b =cell(numNeurons,1); - dev =zeros(numNeurons,1); - numHist=cell(numNeurons,1); - stats =cell(numNeurons,1); - histObj =cell(numNeurons,1); - ensHistObj=cell(numNeurons,1); - AIC =zeros(numNeurons,1); - BIC =zeros(numNeurons,1); - logLL =zeros(numNeurons,1); - windowSize = .01; % 1/tObj.sampleRate;% for Residual Computation; - spikeTraining = cell(1,numNeurons); - XvalData =cell(numNeurons,1); - XvalTime =cell(numNeurons,1); - spikeValidation = cell(1,numNeurons); - %% Fit Using Training Data - if(diff(tObj.validationWindow)~=0) - tObj.setTrialTimesFor('training'); - end - if(batchMode==1) - display('Running in batch mode: neurons with same name are fit simultaneously'); - end - - for i=1:configColl.numConfigs - configColl.setConfig(tObj,i); -% fprintf(strcat('Analyzing Configuration #',num2str(i))); - pool = gcp('nocreate'); - if(isempty(pool)) - pools = 0; - else - pools = pool.NumWorkers; - end%matlabpool('size'); - if(pools==0) - if(batchMode==0) - fprintf(strcat('Analyzing Configuration #',num2str(i),': Neuron #')); - for j=1:numNeurons - % fprintf(strcat('Analyzing Configuration #',num2str(i),': Neuron #',num2str(neuronNumber(j)))); - if(j==1) - fprintf('%d',neuronNumber(j)); - else - fprintf(',%d',neuronNumber(j)); - end - %clear tempLabels; - %tObj.setCurrentNeuron(neuronNumber); - otherLabels = tObj.getLabelsFromMask(neuronNumber(j)); - % labels{j}{i} = horzcat('Baseline',otherLabels); % Labels change depending on presence/absense of History or ensCovHist - labels{j}{i} = otherLabels; % Labels change depending on presence/absense of History or ensCovHist - numHist{j}{i} = tObj.getNumHist; - histObj{j}{i} = tObj.history; - ensHistObj{j}{i} = tObj.ensCovHist; - [lambdaTemp, bTemp, devTemp, statsTemp,AICTemp,BICTemp,logLLTemp, distribTemp] = Analysis.GLMFit(tObj,neuronNumber(j),i,Algorithm); - lambda{j}{i} = lambdaTemp; b{j}{i} = bTemp; stats{j}{i} = statsTemp; - dev(j,i) = devTemp; AIC(j,i)= AICTemp; BIC(j,i)= BICTemp; logLL(j,i) = logLLTemp; - distrib{j}{i} =distribTemp; - spikeTraining{j} = tObj.nspikeColl.getNST(neuronNumber(j));%.nstCopy; - spikeTraining{j}.setName(num2str(neuronNumber(j))); - - %% Collect the validation Data - if(diff(tObj.validationWindow)~=0) - tObj.setTrialTimesFor('validation'); - XvalData{j}{i}=tObj.getDesignMatrix(neuronNumber(j)); - XvalTime{j}{i}=tObj.covarColl.getCov(1).time; - spikeValidation{j} = tObj.nspikeColl.getNST(neuronNumber(j));%.nstCopy; - spikeTraining{j}.setName(num2str(neuronNumber(j))); - tObj.setTrialTimesFor('training') - end - - end - elseif(batchMode==1) - neuronNames=neuronNumber; % This is an index of names in the batchMode case - fprintf(strcat('Analyzing Configuration #',num2str(i),': Neuron #')); - for j=1:numNeurons - - % if(isa(neuronNames,'cell')) - % fprintf(strcat('Analyzing Configuration #',num2str(i),': Neuron #')); - % display(strcat('Analyzing Configuration #',num2str(i),': Neuron #',neuronNames{j})); - % elseif(isa(neuronNames,'char')) - % display(strcat('Analyzing Configuration #',num2str(i),': Neuron #',neuronNames)); - % elseif(isa(neuronNames,'double')) - % display(strcat('Analyzing Configuration #',num2str(i),': Neuron #',num2str(neuronNames))); - % end - if(isa(neuronNames,'cell')) - if(j==1) - fprintf('%s',neuronNames{j}); - else - fprintf(',%s',neuronNames{j}); - end - elseif(isa(neuronNames,'char')) - if(j==1) - fprintf('%s',neuronNames); - else - fprintf(',%s',neuronNames); - end - elseif(isa(neuronNames,'double')) - if(j==1) - fprintf('%d',neuronNames); - else - fprintf(',%d',neuronNames); - end - end - - %clear tempLabels; - %tObj.setCurrentNeuron(neuronNumber); - otherLabels = tObj.getLabelsFromMask(neuronNumber(j)); - % labels{j}{i} = horzcat('Baseline',otherLabels); % Labels change depending on presence/absense of History or ensCovHist - labels{j}{i} = otherLabels; % Labels change depending on presence/absense of History or ensCovHist - numHist{j}{i} = tObj.getNumHist; - histObj{j}{i} = tObj.history; - ensHistObj{j}{i} = tObj.ensCovHist; - if(isa(neuronNames,'cell')) - [lambdaTemp, bTemp, devTemp, statsTemp,AICTemp,BICTemp,logLLTemp,distribTemp] = Analysis.GLMFit(tObj,neuronNumber{j},i,Algorithm); - elseif(isa(neuronNames,'char')) - [lambdaTemp, bTemp, devTemp, statsTemp,AICTemp,BICTemp,logLLTemp,distribTemp] = Analysis.GLMFit(tObj,neuronNumber,i,Algorithm); - else - [lambdaTemp, bTemp, devTemp, statsTemp,AICTemp,BICTemp,logLLTemp,distribTemp] = Analysis.GLMFit(tObj,neuronNumber(j),i,Algorithm); - end - - lambda{j}{i} = lambdaTemp; b{j}{i} = bTemp; stats{j}{i} = statsTemp; - dev(j,i) = devTemp; AIC(j,i)= AICTemp; BIC(j,i)= BICTemp; logLL(j,i) = logLLTemp; - distrib{j}{i} =distribTemp; - if(isa(neuronNames,'cell')) - currSpikes=tObj.nspikeColl.getNST(tObj.getNeuronIndFromName(neuronNames{j})); - elseif(isa(neuronNames,'char')) - currSpikes=tObj.nspikeColl.getNST(tObj.getNeuronIndFromName(neuronNames)); - else - currSpikes=tObj.nspikeColl.getNST(neuronNames(j)); - end - - - for n=1:length(currSpikes) - if(isa(currSpikes,'cell')) - currSpikes{n} = currSpikes{n}.nstCopy; - if(isa(neuronNames,'cell')) - currSpikes{n}.setName(neuronNames{j}); - elseif(isa(neuronNames,'char')) - currSpikes{n}.setName(neuronNames); - else - currSpikes{n}.setName(neuronNames(j)); - end - - else - currSpikes = currSpikes.nstCopy; - - if(isa(neuronNames,'cell')) - currSpikes.setName(neuronNames{j}); - elseif(isa(neuronNames,'char')) - currSpikes.setName(neuronNames); - else - currSpikes.setName(neuronNames(j)); - end - - end - end - - spikeTraining{j} = currSpikes; - - %% Collect the validation Data - if(diff(tObj.validationWindow)~=0) - tObj.setTrialTimesFor('validation'); - tempIndices=tObj.getNeuronIndFromName(neuronNames{j}); - currSpikes=tObj.nspikeColl.getNST(tempIndices); - tempX = []; - tempTime=[]; - for n=1:length(tempIndices) - currSpikes{n} = currSpikes{n}.nstCopy; - currSpikes{n}.setName(neuronNames{j}); - if(n==1) - tempX =tObj.getDesignMatrix(tempIndices(n)); - tempTime =tObj.covarColl.getCov(1).time; - else - tempX = [tempX; tObj.getDesignMatrix(tempIndices(n))]; - offset = max(tempTime)+1/tObj.sampeRate; - tempTime = [tempTime;(tObj.covarColl.getCov(1).time+offset)]; - end - end - spikeValidation{j} = currSpikes; - XvalData{j}{i}=tempX; - XvalTime{j}{i}=tempTime; - - tObj.setTrialTimesFor('training') - end - end - end - fprintf('\n'); - else %use parallel toolbox - if(batchMode==0) - fprintf(strcat('Analyzing Configuration #',num2str(i),': Neuron #',num2str(neuronNumber))); - for j=1:numNeurons - %clear tempLabels; - %tObj.setCurrentNeuron(neuronNumber); - otherLabels = tObj.getLabelsFromMask(neuronNumber(j)); - % labels{j}{i} = horzcat('Baseline',otherLabels); % Labels change depending on presence/absense of History or ensCovHist - labels{j}{i} = otherLabels; % Labels change depending on presence/absense of History or ensCovHist - numHist{j}{i} = tObj.getNumHist; - histObj{j}{i} = tObj.history; - ensHistObj{j}{i} = tObj.ensCovHist; - [lambdaTemp, bTemp, devTemp, statsTemp,AICTemp,BICTemp,logLLTemp,distribTemp] = Analysis.GLMFit(tObj,neuronNumber(j),i,Algorithm); - lambda{j}{i} = lambdaTemp; b{j}{i} = bTemp; stats{j}{i} = statsTemp; - dev(j,i) = devTemp; AIC(j,i)= AICTemp; BIC(j,i)= BICTemp; logLL(j,i)=logLLTemp; - distrib{j}{i} =distribTemp; - spikeTraining{j} = tObj.nspikeColl.getNST(neuronNumber(j));%.nstCopy; - spikeTraining{j}.setName(num2str(neuronNumber(j))); - - %% Collect the validation Data - if(diff(tObj.validationWindow)~=0) - tObj.setTrialTimesFor('validation'); - XvalData{j}{i}=tObj.getDesignMatrix(neuronNumber(j)); - XvalTime{j}{i}=tObj.covarColl.getCov(1).time; - spikeValidation{j} = tObj.nspikeColl.getNST(neuronNumber(j));%.nstCopy; - spikeTraining{j}.setName(num2str(neuronNumber(j))); - tObj.setTrialTimesFor('training') - end - - end - elseif(batchMode==1) - neuronNames=neuronNumber; % This is an index of names in the batchMode case - fprintf(strcat('Analyzing Configuration #',num2str(i),': Neuron #',num2str(neuronNames))); - for j=1:numNeurons - - %clear tempLabels; - %tObj.setCurrentNeuron(neuronNumber); - otherLabels = tObj.getLabelsFromMask(neuronNumber(j)); - % labels{j}{i} = horzcat('Baseline',otherLabels); % Labels change depending on presence/absense of History or ensCovHist - labels{j}{i} = otherLabels; % Labels change depending on presence/absense of History or ensCovHist - numHist{j}{i} = tObj.getNumHist; - histObj{j}{i} = tObj.history; - ensHistObj{j}{i} = tObj.ensCovHist; - if(isa(neuronNames,'cell')) - [lambdaTemp, bTemp, devTemp, statsTemp,AICTemp,BICTemp,logLLTemp,distribTemp] = Analysis.GLMFit(tObj,neuronNumber{j},i,Algorithm); - elseif(isa(neuronNames,'char')) - [lambdaTemp, bTemp, devTemp, statsTemp,AICTemp,BICTemp,logLLTemp,distribTemp] = Analysis.GLMFit(tObj,neuronNumber,i,Algorithm); - else - [lambdaTemp, bTemp, devTemp, statsTemp,AICTemp,BICTemp,logLLTemp,distribTemp] = Analysis.GLMFit(tObj,neuronNumber(j),i,Algorithm); - end - - lambda{j}{i} = lambdaTemp; b{j}{i} = bTemp; stats{j}{i} = statsTemp; - dev(j,i) = devTemp; AIC(j,i)= AICTemp; BIC(j,i)= BICTemp; logLL(j,i) = logLLTemp; - distrib{j}{i} =distribTemp; - if(isa(neuronNames,'cell')) - currSpikes=tObj.nspikeColl.getNST(tObj.getNeuronIndFromName(neuronNames{j})); - elseif(isa(neuronNames,'char')) - currSpikes=tObj.nspikeColl.getNST(tObj.getNeuronIndFromName(neuronNames)); - else - currSpikes=tObj.nspikeColl.getNST(neuronNames(j)); - end - - - for n=1:length(currSpikes) - if(isa(currSpikes,'cell')) - currSpikes{n} = currSpikes{n}.nstCopy; - if(isa(neuronNames,'cell')) - currSpikes{n}.setName(neuronNames{j}); - elseif(isa(neuronNames,'char')) - currSpikes{n}.setName(neuronNames); - else - currSpikes{n}.setName(neuronNames(j)); - end - - else - currSpikes = currSpikes.nstCopy; - - if(isa(neuronNames,'cell')) - currSpikes.setName(neuronNames{j}); - elseif(isa(neuronNames,'char')) - currSpikes.setName(neuronNames); - else - currSpikes.setName(neuronNames(j)); - end - - end - end - - spikeTraining{j} = currSpikes; - - %% Collect the validation Data - if(diff(tObj.validationWindow)~=0) - tObj.setTrialTimesFor('validation'); - tempIndices=tObj.getNeuronIndFromName(neuronNames{j}); - currSpikes=tObj.nspikeColl.getNST(tempIndices); - tempX = []; - tempTime=[]; - for n=1:length(tempIndices) - currSpikes{n} = currSpikes{n}.nstCopy; - currSpikes{n}.setName(neuronNames{j}); - if(n==1) - tempX =tObj.getDesignMatrix(tempIndices(n)); - tempTime =tObj.covarColl.getCov(1).time; - else - tempX = [tempX; tObj.getDesignMatrix(tempIndices(n))]; - offset = max(tempTime)+1/tObj.sampeRate; - tempTime = [tempTime;(tObj.covarColl.getCov(1).time+offset)]; - end - end - spikeValidation{j} = currSpikes; - XvalData{j}{i}=tempX; - XvalTime{j}{i}=tempTime; - - tObj.setTrialTimesFor('training') - end - end - end - fprintf('\n'); - end - end - - -% %% Collect the validation Data -% -% if(diff(tObj.validationWindow)~=0) -% tObj.setTrialTimesFor('validation'); -% for i=1:configColl.numConfigs -% configColl.setConfig(tObj,i); -% for j=1:numNeurons -% XvalData{j,i}=tObj.getDesignMatrix(neuronNumber(j)); -% XvalTime{j,i}=tObj.covarColl.getCov(1).time; -% spikeValidation{j} = tObj.nspikeColl.getNST(neuronNumber(j)).nstCopy; -% spikeTraining{j}.setName(num2str(neuronNumber(j))); -% end -% end -% -% %tObj.setTrialTimesFor('training'); -% end -% - - %% Store the results - - fitResults =cell(length(neuronNumber),1); - for j=1:numNeurons - fitResults{j}=FitResult(spikeTraining{j},labels{j},numHist{j},histObj{j},ensHistObj{j},lambda{j},b{j}, dev(j,:), stats{j},AIC(j,:),BIC(j,:),logLL(j,:),configColl,XvalData{j},XvalTime{j},distrib{j}); - if(diff(tObj.validationWindow)~=0) - tObj.setTrialTimesFor('validation'); - [lambdaValidation, logLLValidation] = fitResults{j}.computeValLambda; - ValResults = FitResult(spikeValidation{j},labels{j},numHist{j},histObj{j},ensHistObj{j},lambdaValidation,b{j}, dev(j,:), stats{j},AIC(j,:),BIC(j,:),logLLValidation,configColl,XvalData{j},XvalTime{j},distrib); - fitResults{j}.validation = ValResults; %validation field is actually another fitResults object but with the validation data - end - %% Process the results and compute further parameters - if(makePlot==1) - scrsz = get(0,'ScreenSize'); - figure('Position',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.8 scrsz(4)*.8]); - subplot(2,4,[1 2]); Analysis.KSPlot(fitResults{j},DTCorrection,makePlot); %make the plot - hold on; text(.45, .95,strcat('Neuron:',num2str(neuronNumber(j)))); - subplot(2,4,3); Analysis.plotInvGausTrans(fitResults{j},makePlot); - subplot(2,4,4); Analysis.plotSeqCorr(fitResults{j}); - subplot(2,4,[7 8]); Analysis.plotFitResidual(fitResults{j},windowSize,makePlot); - subplot(2,4,[5 6]); Analysis.plotCoeffs(fitResults{j}); - else - Analysis.KSPlot(fitResults{j},DTCorrection,makePlot); - Analysis.plotInvGausTrans(fitResults{j},makePlot); - Analysis.plotFitResidual(fitResults{j},windowSize,makePlot); - %fitResults.computePlotParams; - end - end - if(length(neuronNumber)==1) - fitResults = fitResults{1}; - end - - end - function fitResults = RunAnalysisForAllNeurons(tObj,configs,makePlot,Algorithm,DTCorrection,batchMode) - % fitResults = RunAnalysisForAllNeurons(tObj,configs,makePlot,Algorithm) - % Runs the fits specifed by configs (a ConfigColl object) on - % all the neurons that are unmasked in the trial tObj. - % tObj - trial to be analyzed - % configs - ConfigColl object specifying the types of fits to - % be performed. - % makePlot - Set to 1 to generate a summary plot for each - % neuron. - % Algorithm: Either 'GLM' or 'BNLRCG'. Default is 'GLM' - % GLM - Standard GLM regression from matlab. - % BNLRCG - faster Truncated, L-2 Regularized, - % Binomial Logistic Regression with Conjugate - % Gradient Solver by Demba Ba (demba@mit.edu). - % DTCorrection: 0 for no DT Correction of KS plot, 1 is the - % default. - % batchMode: when batchMode=1 neurons with same name are fit at once rather than separetely - - if(nargin<6 || isempty(batchMode)) - batchMode = 0; %default treat each spike train separately - end - if(nargin<5 || isempty(DTCorrection)) - DTCorrection =1; - end - - if(nargin<4 || isempty(Algorithm)) - Algorithm = 'GLM'; - end - if(nargin<3 || isempty(makePlot)) - makePlot=1; %default to plotting results - end - - - if(batchMode==0) - neuronIndex=tObj.getNeuronIndFromMask; - elseif(batchMode==1) - neuronIndex=tObj.getUniqueNeuronNames; - end -% numLoops = floor(length(neuronIndex)/4); -% loopArray = cell(1,numLoops); -% for k=1:numLoops -% if(k==numLoops) -% loopArray{k} = neuronIndex((4*(k-1)+1):end); -% else -% loopArray{k} = neuronIndex((4*(k-1)+1):4*k); -% end -% end - - % parfor i=1:length(neuronIndex) - fitResults = Analysis.RunAnalysisForNeuron(tObj,neuronIndex,configs,makePlot,Algorithm,DTCorrection,batchMode); - %end - - end - - - function [lambda,b, dev, stats,AIC, BIC,logLL, distribution] = GLMFit(tObj,neuronNumber,lambdaIndex,Algorithm) - % [lambda,b, dev, stats,AIC, BIC] = GLMFit(tObj,neuronNumber,lambdaIndex,Algorithm) - % Given a trial, tObj, and a neuronNumber specifying a neuron - % from the trial, extracts the design matrix X from the current - % covariate masks, history, and ensemble history in the trial, - % and the observation vector,Y, and performs the GLM regression - % using the specified algorithm. lambdaIndex: is used to - % labeling the returned lambda with the number of the - % configuration that it corresponds to. - % Algorithm: Either 'GLM' or 'BNLRCG'. Default is 'GLM' - % GLM - Standard GLM regression from matlab. - % BNLRCG - faster Truncated, L-2 Regularized, - % Binomial Logistic Regression with Conjugate - % Gradient Solver by Demba Ba (demba@mit.edu). - % Returns: - % lambda - Covariate containing the resulting conditional - % intensity function evaluated with the design matrix data. - % b - the GLM regression coefficients. Constant term is - % first followed by the components in X. - % - % dev - deviance for the this regression. - % stats - stats structure from the GLM regression - % (p-values,std dev, etc.) - % AIC - Akaike's information criteria for this regression. - % BIC - Bayes Information Criteria for this regression. - % logLL - Log Likelihood evaluated with the fit parameters. - - if(nargin<4) - Algorithm='GLM'; - end - if(isa(neuronNumber,'double')) - binaryRep=tObj.nspikeColl.getNST(neuronNumber).isSigRepBinary; - indices=neuronNumber; - elseif(isa(neuronNumber,'char')) - indices=tObj.getNeuronIndFromName(neuronNumber); - binRep=zeros(size(indices)); - for i=1:length(indices) - binRep(i)=tObj.nspikeColl.getNST(indices(i)).isSigRepBinary; - end - binaryRep=prod(binRep); - elseif(isa(neuronNumber,'cell')) - indices=tObj.getNeuronIndFromName(neuronNumber{1}); - binRep=zeros(size(indices)); - for i=1:length(indices) - binRep(i)=tObj.nspikeColl.getNST(indices(i)).isSigRepBinary; - end - binaryRep=prod(binRep); - end - - if(strcmp(Algorithm,'BNLRCG') && ~binaryRep) - error('To use BNLRCG Algorithm, spikeTrain must have a binary representation. Increase sampleRate and try again'); - end - - %If performing batchMode analysis, this stacks up the - %corresponding spike vectors and the design matrices - for i=1:length(indices) - if(i==1) - y=tObj.getSpikeVector(indices(i)); - X=tObj.getDesignMatrix(indices(i)); - lambdaTime = tObj.getCov(1).time; - else - y=[y; tObj.getSpikeVector(indices(i))]; - X=[X; tObj.getDesignMatrix(indices(i))]; - offset = max(lambdaTime)+1/tObj.sampleRate; - lambdaTime = [lambdaTime; (tObj.getCov(1).time +offset)]; - - end - end - %For a single neuron given covariates,perform the GLM fit. -% -% if(binaryRep) -% distribution = 'binomial'; -% linkfunction = 'logit'; -% else -% distribution = 'poisson'; -% linkfunction = 'log'; -% end -% size(X) -% size(y) - if(strcmp(Algorithm,'GLM')) - distribution = 'poisson'; - linkfunction = 'log'; - [b,dev,stats] = glmfit(X,y,distribution, 'link', linkfunction,'constant','off'); - elseif(strcmp(Algorithm,'BNLRCG')) - distribution = 'binomial'; - linkfunction = 'logit'; - rrflag=0; %ML estimation - [b,dev,stats] = bnlrCG(X,y,rrflag); - - else - error('Algorithm not supported!'); - end - b=real(b); %make sure to avoid complex coefficients ... sometimes algorithms return - %complex b with the imaginary part near zero. - %Need to explore why. For now just keep the real - %part. - if(length(b)>=1) - if(strcmp(distribution,'binomial')) - data = exp(X*b(1:end)); - data = (data./(1+data)).*tObj.sampleRate; - - elseif(strcmp(distribution,'poisson')); - data = exp(X*b(1:end)).*tObj.sampleRate; - -% - end - end - - - - lambdaIndexStr = num2str(lambdaIndex); - - lambda=Covariate(lambdaTime,data,... - '\lambda(t)',tObj.getCov(1).xlabelval,... - tObj.getCov(1).xunits,'Hz',strcat('\lambda_{',lambdaIndexStr,'}')); - mu=b; - s=stats.se; -% Mc=30; -% for c=1:Mc -% z=normrnd(0,1,length(s),1); -% bKDraw(:,c)=mu+(s.*z); -% end -% if(strcmp(distribution,'poisson')) -% lambdaDraw=exp(X*bKDraw)*(tObj.sampleRate); -% else -% lambdaDraw=exp(X*bKDraw)./(1+exp(X*bKDraw))*(tObj.sampleRate); -% end -% lambdaDraw(isinf(lambdaDraw))=0; -% alphaVal=.05; -% for k=1:length(lambdaDraw) -% [f,x] = ecdf(squeeze(lambdaDraw(k,:))); -% CIs(k,1) = x(find(f(1-alphaVal/2),1,'first')); -% end -% -% -% ciPSTHGLM = ConfidenceInterval(lambdaTime,CIs,'CI_{psth_GLM}',lambda.xlabelval,lambda.xunits,lambda.yunits); -% lambda.setConfInterval(ciPSTHGLM); - - %The deviance should be real since it a probability measure - %and therefore any imaginary part is ignored. - AIC = 2*length(b)+real(dev); - BIC = length(b)*log(length(y))+real(dev); - delta = 1/tObj.sampleRate; - logLL =sum(y.*log(data*delta)+(1-y).*(1-data*delta)); - - end - function handle = plotInvGausTrans(fitResults,makePlot) - % handle = plotInvGausTrans(fitResults,makePlot) - % Given the CDF of the rescaled spike times (the u'js) computes - % the auto-correlation function inverse gaussian tranformated - % u'js and the 95% confidence interval that they are distinct - % from zero. - % Idea: if gaussian RVs are uncorrelated, they are indep., then - % this suggest independence of the uj's and of the zj's - % from the time-rescaling theorem. If zj's are - % independent and KS plot is within 95% confidence - % interval suggests that candidate lambda is close to the - % true lambda. - if(nargin<2) - makePlot=0; - end - [X,rhoSig,confBoundSig] = Analysis.computeInvGausTrans(fitResults.Z); - fitResults.setInvGausStats(X,rhoSig,confBoundSig); - - if(fitResults.isValDataPresent) - [X,rhoSig,confBoundSig] = Analysis.computeInvGausTrans(fitResults.validation.Z); - fitResults.validation.setInvGausStats(X,rhoSig,confBoundSig); - end - - if(makePlot==1) - handle=fitResults.plotInvGausTrans; - end - - end - function plotFitResidual(fitResults,windowSize,makePlot) - % plotFitResidual(fitResults,windowSize,makePlot) - % computes the point process residual between the true spike - % train and that predicted by the candidate conditional - % intensity function. - % The result is stored in fitResult. - % - if(nargin<3 || isempty(makePlot)) - makePlot=1; - end - if(nargin<2 || isempty(windowSize)) - windowSize=.01; - end - M = Analysis.computeFitResidual(fitResults.neuralSpikeTrain,fitResults.lambda,windowSize); - fitResults.setFitResidual(M); - - if(fitResults.isValDataPresent) - M = Analysis.computeFitResidual(fitResults.validation.neuralSpikeTrain,fitResults.validation.lambda,windowSize); - fitResults.validation.setFitResidual(M); - end - - if(makePlot) - fitResults.plotResidual; - end - end - function handle = KSPlot(fitResults,DTCorrection,makePlot) - %handle = KSPlot(fitResults,makePlot) - % Computes the KS statistics and makes the plot. Stores - % appropriate parameters in fitResults. - % If validation data is also available, it does the same for - % the validation data. - % DTCorrection: 0 for no DT Correction of KS plot, 1 is the - % default. - if(nargin <3) - makePlot =1; %By default make the plot - end - if(nargin<2) - DTCorrection = 1; - end - - - [Z, U, xAxis, KSSorted, ks_stat] = Analysis.computeKSStats(fitResults.neuralSpikeTrain,fitResults.lambda,DTCorrection); - fitResults.setKSStats(Z,U, xAxis, KSSorted, ks_stat); - - - if(fitResults.isValDataPresent) - %make sure nst is in appropriate window - [Z, U, xAxis, KSSorted, ks_stat] = Analysis.computeKSStats(fitResults.validation.neuralSpikeTrain,fitResults.validation.lambda,DTCorrection); - fitResults.validation.setKSStats(Z, U, xAxis, KSSorted, ks_stat); - - end - - if(makePlot) - handle = fitResults.KSPlot; - else - handle = []; - end - - end - function handle = plotSeqCorr(fitResults) - % handle = plotSeqCorr(fitResults) - % Plots the sequential correlation coefficients of the rescaled - % ISIs. zj vs. zj-1 - handle = fitResults.plotSeqCorr; - - end - function handle = plotCoeffs(fitResults) - % handle = plotCoeffs(fitResults) - % Plots the regression coefficients for all the different fits. - - handle = fitResults.plotCoeffs; - - end - - - function [X,rhoSig,confBoundSig] = computeInvGausTrans(Z) - % [U,X,rhoSig,confBoundSig] = computeInvGausTrans(Z) - % Take rescaled spikeTimes, zjs, transforms them to - % uniform(0,1), then computes the inverse gaussian - % transformation of these to xj's. rhoSig is the - % auto-correlation funcion of these xj's and is used to test - % for independence of the xj's. Independence of the xj's - % suggests indepence of the uj's and zj's (a condition - % necessary for the Time Rescaling Theorem). - U=1-exp(-Z); - U(U>=.999999)=.999999; %Prevent any 1 values which lead to infinity in X - U(U==0)=.000001; - U(U<0)=.000001; - X = norminv(U,0,1); - %X=erfinv(U); - [~,colm] = size(X); - if(~isempty(X)) - for i=1:colm - [c(:,i),lags] = xcov(X(:,i)); - end - else - [c,lags] = xcov(X); - end - index=find(lags==1); - lags=lags(index:end); - rho=c(index:end,:)./repmat(c(index-1,:),length(lags),1); - n=length(X); - % Defaults to the 95% confidence intervals - % Can extend to allow selection of 95% or 99% CI - confBound = 1.96/sqrt(n)*ones(length(lags),1); - % size(lags) - % size(rho) - - confBoundSig = SignalObj(lags,[confBound -confBound],'ACF[ \Phi^{-1}(u_i) ]','\Delta \tau','sec'); - confBoundSig.setPlotProps({' ''r'', ''LineWidth'' ,3'},1); - confBoundSig.setPlotProps({' ''r'', ''LineWidth'' ,3'},2); - - handle=[]; - rhoSig = SignalObj(lags,rho, 'ACF[ \Phi^-1(u_i) ]','Lag \Delta \tau','sec'); - plotProps = cell(1,colm); - if(~isempty(X)) - for i=1:colm - plotProps{i}=strcat('''', '.',Analysis.colors{mod(i-1,length(Analysis.colors))+1},''''); - end - else - plotProps=strcat('''', '.',Analysis.colors{1},''''); - end - rhoSig.setPlotProps(plotProps); - - end - function [Z,U,xAxis,KSSorted, ks_stat] = computeKSStats(nspikeObj,lambdaInput,DTCorrection) - % [Z,U,xAxis,KSSorted, ks_stat] = computeKSStats(nspikeTrain,lambdaInput) - % Given a neural spike train (a sequence of spike times) and a - % conditional intensity function, computes the rescaled ISIs - % according to the time-rescaling theorem in Z. The Uj are - % returned in U and correspond to a transformation fo the Zjs - % (exponential rate 1 (according to T-R theorem) to be - % uniform(0,1). - % - % DTCorrection: 0 for no DT Correction of KS plot, 1 is the - % default. - % nspikeTrain: a nspikeTrain object - % lambdaInput: candidate conditional intensity function (a Covariate) - % Z: rescaled spike times - % U: Zjs tranformed to be uniform(0,1) - % xAxis: x-axis of the KS plot - % KSSorted: y-axis of KS plot - % ks_stat: the KS statistic. Maximum deviations from the 45 - % degree line for each conditional intensity function. - - %get the relevant spike train - if(nargin<3) - DTCorrection =1; - end - - - if(length(nspikeObj)>1) %in batch analysis we get multiple trials - nstCollObj = nstColl(nspikeObj); - nCopy = nstCollObj.toSpikeTrain; - - else - nCopy =nspikeObj.nstCopy; -% nCopy =nspikeObj; - - end - - -% minTime = nCopy.minTime; -% maxTime = nCopy.maxTime; - nCopy.resample(lambdaInput.sampleRate); - nCopy.setMinTime(lambdaInput.minTime); - nCopy.setMaxTime(lambdaInput.maxTime); - - repBin = nCopy.isSigRepBin; - if(~repBin) - lambdaInput=lambdaInput.resample(2*lambdaInput.sampleRate); - nCopy.resample(lambdaInput.sampleRate); - end - - if(DTCorrection==1 && repBin) - % Use DT Correction for Time Rescaling Theorem - Haslinger, Pipa and Brown (2010) - pkSignal=lambdaInput; - pk = pkSignal.data.*(1/lambdaInput.sampleRate); - pk = max(pk,1e-10); - spikeTrain = nCopy.getSigRep.data; - minDim = min(size(pk,1),size(spikeTrain,1)); - pk=pk(1:minDim,:); - spikeTrain=spikeTrain(1:minDim,:); - - intValues=zeros(length(nCopy.getSpikeTimes)-1,lambdaInput.dimension); - for i=1:lambdaInput.dimension - pk(:,i) = nanmin(nanmax(pk(:,i),0),1); - temp = ksdiscrete(pk(:,i),spikeTrain,'spiketrain'); -% length(temp) -% length(intValues(:,i)) - %sometimes ksdiscrete returns 1 less spike train than - %expected ... need to debug .... for now just fix - %using length(temp) to index into intValues; - intValues(1:length(temp),i) = temp; - end - - - else % do not correct for discrete time effects - - tempLambda = lambdaInput; -% tempLambda = tempLambda.resample(tempLambda.sampleRate*4); -% lambda=tempLambda.getSigInTimeWindow(minTime,maxTime);%.dataToMatrix; - lambdaPosdata = max(tempLambda.data,0); - lambda = Covariate(tempLambda.time,lambdaPosdata,tempLambda.name,tempLambda.xlabelval,tempLambda.xunits,tempLambda.yunits,tempLambda.dataLabels); - lambdaInt = lambda.integral; - - - if(nCopy.isSigRepBin) - spikeTimes = nCopy.getSpikeTimes; - spikeTimes = [0 spikeTimes]; - - else -% spikeTimes = nCopy.getSpikeTimes; -% maxBinSize=nCopy.getMaxBinSizeBinary; -% lambdaInt = lambda.resample(1/maxBinSize).integral; - nstSignal = nCopy.getSigRep; - spikeTimes=nstSignal.time(nstSignal.data~=0); - spikeTimes = [0 spikeTimes']; - - end - - if(~isempty(spikeTimes)) - tempVals = lambdaInt.getValueAt(spikeTimes); - intValues= tempVals(2:end,:)-tempVals(1:end-1,:); - else - intValues = 0; - end - - % intValues=2*intValues; - % lambdaInt.plot; hold all; - % vals =lambdaInt.getValueAt(spikeTimes); - % plot(spikeTimes,vals,'.') - - end - Z = intValues; % rescales spike times - exponential rate 1 - U = 1-exp(-Z); % store the rescaled spike times - uniform(0,1) - - - KSSorted = sort( U,'ascend' ); - N = size(KSSorted,1); - if(N~=0) - xAxis=(([1:N]-.5)/N)'*ones(1,lambdaInput.dimension); - ks_stat = max(abs(KSSorted - (([1:N]-.5)/N)'*ones(1,lambdaInput.dimension))); - else - ks_stat=1; - xAxis=[]; - end - end - function M=computeFitResidual(nspikeObj,lambda,windowSize) - % M=computeFitResidual(nspikeTrain,lambda,windowSize) - % Computes the Point Process residual defined in - % 'A point process framework for relating neural spiking - % activity to spiking history, W Truccolo, UT Eden, MR Fellows, - % JP Donoghue and EN. Brown. Journal of Neurophysiology 2005. - % - % nspikeTrain: nspikeTrain object - % lambda: candidate conditional intensity function evaluated on the time - % interval of the spike train. - % windowSize: the size of the window over which to compute the - % residual. - % M: the point process residual (a Covariate object). - % - if(nargin<3 || isempty(windowSize)) - windowSize=.01; - end - - - if(length(nspikeObj)>1) %in batch analysis we get multiple trials - nstCollObj = nstColl(nspikeObj); - nCopy = nstCollObj.toSpikeTrain; - else - nCopy =nspikeObj.nstCopy; -% nCopy =nspikeObj; - end - - nCopy.resample(lambda.sampleRate); - nCopy.setMinTime(lambda.minTime); - nCopy.setMaxTime(lambda.maxTime); - - - sumSpikes=nCopy.getSigRep(windowSize);%tObj.getNeuron(fitResults.neuronNumber).nstCopy; -% sumSpikesOverWindow = sumSpikes.data(1:end); -% windowTimes = nCopy.minTime:windowSize:lambda.maxTime; - windowTimes = linspace(nCopy.minTime,nCopy.maxTime,length(sumSpikes.time)); - lambdaInt = lambda.integral; - lambdaIntVals = lambdaInt.getValueAt(windowTimes(2:end))-lambdaInt.getValueAt(windowTimes(1:(end-1))); - if(length(lambdaIntVals)==length(sumSpikes.data)) - sumSpikesOverWindow = sumSpikes.data(1:end); - elseif(length(lambdaIntVals)valConfInt); - sigMat = zeros(size(devianceMat)); - sigMat(nonZeros) = h; - - tObj.resetEnsCovMask; - - %RunAnalysisForAllNeurons(tObj,configs,makePlot,Algorithm,DTCorrection,batchMode) - - - end - function [fitResults,tcc] = computeHistLag(tObj,neuronNum,windowTimes,CovLabels,Algorithm,batchMode,sampleRate,makePlot,histMinTimes,histMaxTimes) - % [fitResults,tcc] = computeHistLag(tObj,tObj,neuronNum,windowTimes,CovLabels,sampleRate,makePlot) - % For the neuron in neuronNum, runs an analysis with self - % history, and no extrinsic covariates, and no ensemble history - % as a covariates. The self history is specfied by a vector - % of windowTimes. There will be length(windowTimes) different - % results (configurations) corresponding to increasing number of history - % windows. - if(nargin<10) - histMaxTimes =[]; - end - if(nargin<9) - histMinTimes=[]; - end - if(nargin<8) - makePlot=1; - end - if(nargin<7 || isempty(sampleRate)) - sampleRate = tObj.sampleRate; - end - if(nargin<6 || isempty(batchMode)) - batchMode = 0; - end - if(nargin<5 || isempty(Algorithm)) - Algorithm = 'GLM'; - end - if(nargin<4) - CovLabels ={}; - end - if(nargin<3) - error('Must specify a vector of windowTimes'); - end - if(nargin<2 || isempty(neuronNum)) - neuronNum = tObj.getNeuronIndFromMask; - end - - % tcObj=TrialConfig(covMask,sampleRate, history,ensCovHist,ensCovMask,covLag,name) - tc=cell(1,length(windowTimes)-1); - for i=1:length(tc)+1 - %use no covariates - if(i==1) - tc{i} = TrialConfig(CovLabels,sampleRate,[],[]); tc{i}.setName('Baseline'); - else - if(and(isempty(histMinTimes),isempty(histMaxTimes))) - tc{i} = TrialConfig(CovLabels,sampleRate,windowTimes(1:i)); tc{i}.setName(strcat('Window',num2str(i-1))); - else - hTemp = History(windowTimes(1:i),histMinTimes,histMaxTimes); - tc{i} = TrialConfig(CovLabels,sampleRate,hTemp); tc{i}.setName(strcat('Window',num2str(i-1))); - end - end - - end - DTCorrection=1; - tcc = ConfigColl(tc); - - fitResults =Analysis.RunAnalysisForNeuron(tObj,neuronNum,tcc,makePlot,Algorithm,DTCorrection,batchMode); - - end - function fitResults = computeHistLagForAll(tObj,windowTimes,CovLabels,Algorithm,batchMode,sampleRate,makePlot,histMinTimes,histMaxTimes) - % [fitResults,tcc] = computeHistLagAll(tObj,windowTimes,CovLabels,sampleRate,makePlot) - % Calls computeHistLab for each neuron in the trial that is not masked. - if(nargin<9) - histMaxTimes =[]; - end - if(nargin<8) - histMinTimes=[]; - end - if(nargin<7) - makePlot=1; - end - if(nargin<6 || isempty(sampleRate)) - sampleRate = tObj.sampleRate; - end - if(nargin<5 || isempty(batchMode)) - batchMode=0; - end - if(nargin<4 || isempty(Algorithm)) - Algorithm = 'GLM'; - end - - if(nargin<3) - CovLabels ={}; - end - if(nargin<2) - error('Must specify a vector of windowTimes'); - end - - neuronIndex=tObj.getNeuronIndFromMask; - fitResults = cell(1,length(neuronIndex)); - for i=1:length(neuronIndex) - fitResults{i} = Analysis.computeHistLag(tObj,neuronIndex(i),windowTimes,CovLabels,Algorithm,batchMode,sampleRate,makePlot,histMinTimes,histMaxTimes); - end - - - - end - function [fitResults,tcc]=computeNeighbors(tObj,neuronNum,sampleRate,windowTimes,makePlot) - % [fitResults,tcc]=computeNeighbors(tObj,neuronNum,sampleRate,windowTimes,makePlot) - % For the neuron in neuronNum, runs an analysis with no self - % history, and no extrinsic covariates, only ensemble history - % as a covariate. The ensemble history is specfied by a vector - % of windowTimes. There will be length(windowTimes) different - % results corresponding to increasing number of history - % windows. - if(nargin<4) - makePlot=1; - end - if(nargin<3 || isempty(sampleRate)) - sampleRate = tObj.sampleRate; - end - if(nargin<2 || isempty(neuronNum)) - neuronNum = tObj.getNeuronIndFromMask; - end - tc=cell(1,length(windowTimes)-1); - for i=1:length(windowTimes) - % For reference: tcObj=TrialConfig(covMask,sampleRate, history,covHist,covLag,name) - if(i==1) - tc{i} = TrialConfig({},sampleRate,[],[]); tc{1}.setName('Baseline'); - else - tc{i} = TrialConfig({},sampleRate,[],windowTimes(1:i)); - end - end - tcc = ConfigColl(tc); - fitResults =Analysis.RunAnalysisForNeuron(tObj,neuronNum,tcc,makePlot); - end - - function cc=spikeTrigAvg(tObj,neuronNum,windowSize) - % cc=spikeTrigAvg(tObj,neuronNum,windowSize) - % Each covariate dimension is sampled at every spike time of - % the neuron specified +/- windowSize. The number of columns of - % each new covariate corresponds to the number of spikes in the - % spike train. A covariate collection is returned containing - % each covariate dimension as a new covariate. These can then - % be easily avergaged by using SignalObj method - % plotVariability. - - nCopy=tObj.getNeuron(neuronNum).nstCopy; - t=-windowSize/2:1/tObj.sampleRate:windowSize/2; - covIndex=0; - for i = 1:tObj.covarColl.numCov - tempCov=tObj.getCov(i); - data=[]; - dataIndex=0; - % for n=1:tObj.nspikeColl.numSpikeTrains -% nCopy=tObj.getNeuron(neuronNum).nstCopy; - spikeTimes = nCopy.getSpikeTimes'; - for j=1:length(spikeTimes) - dataIndex=dataIndex+1; - tc=tempCov.getSigInTimeWindow(spikeTimes(j)-windowSize/2,spikeTimes(j)+windowSize/2); - tc=tc.shift(-tc.minTime-windowSize/2); - tempData = tc.getValueAt(t); -% if(isempty(data)) -% data(dataIndex,1:length(tempData),:)=tempData; -% else -% data(dataIndex,:,:)=zeros(size(squeeze(data(1,:,:)))); - data(dataIndex,:,:)=tempData; -% end - end - %end - - for k=1:tempCov.dimension - covIndex = covIndex+1; - cov{covIndex} = Covariate(t,squeeze(data(:,:,k)),tempCov.dataLabels{k},tempCov.xlabelval,tempCov.xunits,tempCov.yunits,tempCov.dataLabels{k}); - end - end - cc=CovColl(cov); - - end - - - end - - - -end - - - -function [flatMask, maxIndex]=flatMaskCellToMat(flatMaskCell) - % [flatMask, maxIndex]=flatMaskCellToMat(flatMaskCell) - lMask =zeros(1,length(flatMaskCell)); - for i=1:length(flatMaskCell) - lMask(i) = length(flatMaskCell{i}); - end - [maxSize,maxIndex] = max(lMask); - flatMask = zeros(maxSize,length(flatMaskCell)); - for i=1:length(flatMaskCell) - flatMask(1:length(flatMaskCell{i}),i) = flatMaskCell{i}; - end -end -function [beta_new,devnew,stats] = bnlrCG(X,yframe,rrflag) -% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % -% % -% Truncated, L-2 Regularized, Binomial Logistic Regression with % -% Conjugate Gradient Solver % -% % -% Author: Demba Elimane Ba % -% MIT Department of EECS % -% Neuro Stat Research Lab (MIT Department of BCS) % -% Date : August the 25th, 2008 % -% % -% Note : Matlab implementation of Paul Komarek's TR-IRLS % -% % -% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % - -% Modified by Iahn Cajigas 9-23-09 to automatically add the DC term for the -% design matrix - -% Arguments: -% X: design matrix, including DC column of all ones (1st or last) -% yframe: column vector of binary observations -% rrflag: 1: MAP estimation with Gaussian(0,sigma^2) prior (default value -% 1/sigma^2 = 10) -% 0: ML estimation (1/sigma^2 = 0, i.e. sigma -> infinity) -% -% N.B: The equivalent call with glmfit is: -% -% [beta,dev,stats]=glmfit(X(:,2:end),[yframe ones(size(yframe))],'binomial','logit'); -% -% Unlike glmfit, this function assumes that the design matrix -% already has a column of all ones (1st or last). - - %Modify the design Matrix; - [rows,~]=size(X); -% X = [ones(rows,1), X]; - % CG parameters - cgmax = 30; - cgeps = 1e-6; - - % LR parameters - lrmax = 100; - lreps = 0.05; - lambda = 10; - - [n,d] = size(X); - % Perform logistic regression - i = 0; - % Initial guess for Beta = beta_old ? - beta_old = zeros(d,1); - n = X*beta_old; - u = exp(n)./(1+exp(n)); - W = repmat(u'.*(1-u)',d,1); - z = X*beta_old + (W(1,:)'.^-1).*(yframe - u); - - devold = -2*sum(yframe.*log(u) + (1-yframe).*log(1-u)); - devnew = 0; - devdiff = abs(devnew - devold); - -% B=[]; - while (i < lrmax && devdiff > lreps) - % Do CG -> beta_new, i.e. solve for beta_new: XtWX*beta_new = XtWz(beta_old) using CG - - A = X'.*W*X; b = X'.*W*z; - - % A needs to be positive definite so any zero or negative - % eigenvalues are set to machine precision. - [vec,val]=eig(A); val(val<=0)=eps; - A=vec*val*vec'; - - if(any(isnan(b))) - b(isnan(b))=0; - end - if rrflag == 1 - A = A + lambda*eye(size(A)); - end - - [beta_new, flag] = cgs(A,b,cgeps,cgmax,[],[],beta_old); - beta_old = beta_new; - - n = X*beta_old; - u = exp(n)./(1+exp(n)); - W = repmat(u'.*(1-u)',d,1); - z = X*beta_old + (W(1,:)'.^-1).*(yframe - u); - - devnew = -2*sum(yframe.*log(u) + (1-yframe).*log(1-u)); - devdiff = abs(devnew - devold); - devold = devnew; - - i = i+1; - -% B=[B,beta_new]; - end - - % Compute a few statistics - stats.dfe = 0; - stats.s = 0; - stats.sfit = 0; - stats.covb = inv(A); - stats.se = sqrt(diag(stats.covb)); - stats.coeffcorr = stats.covb./sqrt((repmat(diag(stats.covb),1,d).*repmat(diag(stats.covb)',d,1))); - stats.t = 0; - stats.p = 0; - stats.resid = 0; - stats.residp = 0; - stats.residd = 0; - stats.resida = 0; -end - - -function [rst,varargout] = ksdiscrete(pk,st,spikeflag) - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% -% ksdiscrete.m -% written by Rob Haslinger, December 2009 -% -% This function performs time rescaling of ISIs based upon the discrete -% time version of the time rescaling theorem as described in Haslinger, -% Pipa and Brown (2010?). This method corrects for biases in the KS plot -% caused by the temporal discretization. -% -% This function can be called in two ways -% -% 1) input the discrete time conditional probabilities "pk" where 0<=pk<= 1 -% and the spike train "spiketrain" which has elements either equal to 0 (no -% spike) or 1 (spike). There is also a flag 'spiketrain' to indicate that -% it is the full spike train. -% -% [rst,rstsort,xks,cb,rstoldsort] = ksdiscrete(pk,spiketrain,'spiketrain') -% -% 2) input the discrete time conditional probabilities "pk" and a list of -% the indicies "spikeind" of the bin indicies that the spikes are locaed in. -% There is also a flag 'spikeind' to indicate that the indicies are -% being given, not the full spike train -% -% [rst,rstsort,xks,cb,rstoldsort] = ksdiscrete(pk,spikeind,'spikeind'); -% -% required output: -% -% rst : a vector of unsorted uniformly distributed rescaled times. This is -% the only output that is required. -% -% optional output, given in the order they appear in the list function -% outputs : -% -% rstsort : a vector of rescaled times sorted into ascending order -% xks : a vector of x axis values to plot the sorted rescaled times against -% cb : the value of the 95% confidence bounds -% rstoldsort : a vector of sorted rescaled times done without the discrete -% time correction -% -% To make a KS plot one would do -% plot(xks,rstsort,'k-'); -% hold on; -% plot(xks,xks+cb,'k--',xks,xks-cb,'k--'); -% -% To make a Differential KS plot one would do -% plot(xks,rstsort-xks,'k-'); -% hold on; -% plot(xks,zeros(length(xks))+cb,'k--',xks,zeros(length(xks))-cb); -% -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -% Start with determining the inputs and some basic input error checking - - if nargin < 3 || nargin > 3; - error('Number of input arguments must be equal to 3'); - end; - - % make pk into a column vector; - - [m1,m2]=size(pk); - if (m1 ~=1 && m2 ~=1); error('pk must be a vector'); end; - if (m2>m1); pk=pk'; end; - [m1,m2]=size(pk); - - % make sure pk's are within [0,1] - index=find(pk<0); - if isempty(index) ~=1; - error('all values for pk must be within [0,1]'); - end; - index=find(pk>1); - if isempty(index) ~=1; - error('all values for pk must be within [0,1]'); - end; - clear index; - - % make column vector of spike indicies - - if strcmp(spikeflag,'spiketrain'); % spike train input - - [n1,n2]=size(st); - if (n1 ~=1 && n2 ~=1); error('spike train must be a vector'); end; - if (n2>n1); st=st'; end; - - if m1 ~= n1; error('pk and spike train must be same length'); end; - - spikeindicies=find(st==1); - - Nspikes=length(spikeindicies); - - elseif strcmp(spikeflag,'spikeind'); % spike index input - - [n1,n2]=size(st); - if (n1 ~=1 && n2 ~=1); error('spike indicies must be a vector'); end; - if (n2>n1); st=st'; end; - - spikeindicies=unique(st); - Nspikes=length(spikeindicies); - - end; - - % check that those indicies are in [1:length(pk)]; - - if(isempty(spikeindicies)) - rst = pk; - return; - end - if spikeindicies(1)<1; - error('There is at least one spike with index less than 0'); - end; - if spikeindicies(Nspikes)>length(pk); - error('There is at least one spike with a index greater than the length of pk'); - end; - - % error checking done - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % Now do the actual discrete time KS test - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - - % initialize random number generator - rng('shuffle','twister'); - %rand('twister',sum(100*clock)); - - % make the qk's - - qk=-log(1-pk); - - % make the rescaled times - - rst=zeros(Nspikes-1,1); - rstold=zeros(Nspikes-1,1); - - for r=1:Nspikes-1; - - total = 0; - - ind1=spikeindicies(r); - ind2=spikeindicies(r+1); - - total=total+sum(qk(ind1+1:ind2-1)); - - delta=-(1/qk(ind2))*log(1-rand()*(1-exp(-qk(ind2)))); - - if(delta~=0) - total=total+qk(ind2)*delta; - end - rst(r)=total; - - rstold(r)=sum(qk(ind1+1:ind2)); - - end; - -% rst=1-exp(-rst); -% rstold=1-exp(-rstold); - - % optional outputs - - rstsort=sort(rst); - varargout{1}=rstsort; - - inrst=1/(Nspikes-1); - xrst=(0.5*inrst:inrst:1-0.5*inrst)'; - varargout{2}=xrst; - - cb=1.36*sqrt(inrst); - varargout{3}=cb; - - varargout{4}=sort(rstold); -end - - -% fdr_bh() - Executes the Benjamini & Hochberg (1995) and the Benjamini & -% Yekutieli (2001) procedure for controlling the false discovery -% rate (FDR) of a family of hypothesis tests. FDR is the expected -% proportion of rejected hypotheses that are mistakenly rejected -% (i.e., the null hypothesis is actually true for those tests). -% FDR is a somewhat less conservative/more powerful method for -% correcting for multiple comparisons than procedures like Bonferroni -% correction that provide strong control of the family-wise -% error rate (i.e., the probability that one or more null -% hypotheses are mistakenly rejected). -% -% This function also returns the false coverage-statement rate -% (FCR)-adjusted selected confidence interval coverage (i.e., -% the coverage needed to construct multiple comparison corrected -% confidence intervals that correspond to the FDR-adjusted p-values). -% -% -% Usage: -% >> [h, crit_p, adj_ci_cvrg, adj_p]=fdr_bh(pvals,q,method,report); -% -% Required Input: -% pvals - A vector or matrix (two dimensions or more) containing the -% p-value of each individual test in a family of tests. -% -% Optional Inputs: -% q - The desired false discovery rate. {default: 0.05} -% method - ['pdep' or 'dep'] If 'pdep,' the original Bejnamini & Hochberg -% FDR procedure is used, which is guaranteed to be accurate if -% the individual tests are independent or positively dependent -% (e.g., Gaussian variables that are positively correlated or -% independent). If 'dep,' the FDR procedure -% described in Benjamini & Yekutieli (2001) that is guaranteed -% to be accurate for any test dependency structure (e.g., -% Gaussian variables with any covariance matrix) is used. 'dep' -% is always appropriate to use but is less powerful than 'pdep.' -% {default: 'pdep'} -% report - ['yes' or 'no'] If 'yes', a brief summary of FDR results are -% output to the MATLAB command line {default: 'no'} -% -% -% Outputs: -% h - A binary vector or matrix of the same size as the input "pvals." -% If the ith element of h is 1, then the test that produced the -% ith p-value in pvals is significant (i.e., the null hypothesis -% of the test is rejected). -% crit_p - All uncorrected p-values less than or equal to crit_p are -% significant (i.e., their null hypotheses are rejected). If -% no p-values are significant, crit_p=0. -% adj_ci_cvrg - The FCR-adjusted BH- or BY-selected -% confidence interval coverage. For any p-values that -% are significant after FDR adjustment, this gives you the -% proportion of coverage (e.g., 0.99) you should use when generating -% confidence intervals for those parameters. In other words, -% this allows you to correct your confidence intervals for -% multiple comparisons. You can NOT obtain confidence intervals -% for non-significant p-values. The adjusted confidence intervals -% guarantee that the expected FCR is less than or equal to q -% if using the appropriate FDR control algorithm for the -% dependency structure of your data (Benjamini & Yekutieli, 2005). -% FCR (i.e., false coverage-statement rate) is the proportion -% of confidence intervals you construct -% that miss the true value of the parameter. adj_ci=NaN if no -% p-values are significant after adjustment. -% adj_p - All adjusted p-values less than or equal to q are significant -% (i.e., their null hypotheses are rejected). Note, adjusted -% p-values can be greater than 1. -% -% -% References: -% Benjamini, Y. & Hochberg, Y. (1995) Controlling the false discovery -% rate: A practical and powerful approach to multiple testing. Journal -% of the Royal Statistical Society, Series B (Methodological). 57(1), -% 289-300. -% -% Benjamini, Y. & Yekutieli, D. (2001) The control of the false discovery -% rate in multiple testing under dependency. The Annals of Statistics. -% 29(4), 1165-1188. -% -% Benjamini, Y., & Yekutieli, D. (2005). False discovery rate?adjusted -% multiple confidence intervals for selected parameters. Journal of the -% American Statistical Association, 100(469), 71?81. doi:10.1198/016214504000001907 -% -% -% Example: -% nullVars=randn(12,15); -% [~, p_null]=ttest(nullVars); %15 tests where the null hypothesis -% %is true -% effectVars=randn(12,5)+1; -% [~, p_effect]=ttest(effectVars); %5 tests where the null -% %hypothesis is false -% [h, crit_p, adj_ci_cvrg, adj_p]=fdr_bh([p_null p_effect],.05,'pdep','yes'); -% data=[nullVars effectVars]; -% fcr_adj_cis=NaN*zeros(2,20); %initialize confidence interval bounds to NaN -% if ~isnan(adj_ci_cvrg), -% sigIds=find(h); -% fcr_adj_cis(:,sigIds)=tCIs(data(:,sigIds),adj_ci_cvrg); % tCIs.m is available on the -% %Mathworks File Exchagne -% end -% -% -% For a review of false discovery rate control and other contemporary -% techniques for correcting for multiple comparisons see: -% -% Groppe, D.M., Urbach, T.P., & Kutas, M. (2011) Mass univariate analysis -% of event-related brain potentials/fields I: A critical tutorial review. -% Psychophysiology, 48(12) pp. 1711-1725, DOI: 10.1111/j.1469-8986.2011.01273.x -% http://www.cogsci.ucsd.edu/~dgroppe/PUBLICATIONS/mass_uni_preprint1.pdf -% -% -% For a review of FCR-adjusted confidence intervals (CIs) and other techniques -% for adjusting CIs for multiple comparisons see: -% -% Groppe, D.M. (in press) Combating the scientific decline effect with -% confidence (intervals). Psychophysiology. -% http://biorxiv.org/content/biorxiv/early/2015/12/10/034074.full.pdf -% -% -% Author: -% David M. Groppe -% Kutaslab -% Dept. of Cognitive Science -% University of California, San Diego -% March 24, 2010 - -%%%%%%%%%%%%%%%% REVISION LOG %%%%%%%%%%%%%%%%% -% -% 5/7/2010-Added FDR adjusted p-values -% 5/14/2013- D.H.J. Poot, Erasmus MC, improved run-time complexity -% 10/2015- Now returns FCR adjusted confidence intervals - -function [h, crit_p, adj_ci_cvrg, adj_p]=fdr_bh(pvals,q,method,report) - -if nargin<1, - error('You need to provide a vector or matrix of p-values.'); -else - if ~isempty(find(pvals<0,1)), - error('Some p-values are less than 0.'); - elseif ~isempty(find(pvals>1,1)), - error('Some p-values are greater than 1.'); - end -end - -if nargin<2, - q=.05; -end - -if nargin<3, - method='pdep'; -end - -if nargin<4, - report='no'; -end - -s=size(pvals); -if (length(s)>2) || s(1)>1, - [p_sorted, sort_ids]=sort(reshape(pvals,1,prod(s))); -else - %p-values are already a row vector - [p_sorted, sort_ids]=sort(pvals); -end -[dummy, unsort_ids]=sort(sort_ids); %indexes to return p_sorted to pvals order -m=length(p_sorted); %number of tests - -if strcmpi(method,'pdep'), - %BH procedure for independence or positive dependence - thresh=(1:m)*q/m; - wtd_p=m*p_sorted./(1:m); - -elseif strcmpi(method,'dep') - %BH procedure for any dependency structure - denom=m*sum(1./(1:m)); - thresh=(1:m)*q/denom; - wtd_p=denom*p_sorted./[1:m]; - %Note, it can produce adjusted p-values greater than 1! - %compute adjusted p-values -else - error('Argument ''method'' needs to be ''pdep'' or ''dep''.'); -end - -if nargout>3, - %compute adjusted p-values; This can be a bit computationally intensive - adj_p=zeros(1,m)*NaN; - [wtd_p_sorted, wtd_p_sindex] = sort( wtd_p ); - nextfill = 1; - for k = 1 : m - if wtd_p_sindex(k)>=nextfill - adj_p(nextfill:wtd_p_sindex(k)) = wtd_p_sorted(k); - nextfill = wtd_p_sindex(k)+1; - if nextfill>m - break; - end; - end; - end; - adj_p=reshape(adj_p(unsort_ids),s); -end - -rej=p_sorted<=thresh; -max_id=find(rej,1,'last'); %find greatest significant pvalue -if isempty(max_id), - crit_p=0; - h=pvals*0; - adj_ci_cvrg=NaN; -else - crit_p=p_sorted(max_id); - h=pvals<=crit_p; - adj_ci_cvrg=1-thresh(max_id); -end - -if strcmpi(report,'yes'), - n_sig=sum(p_sorted<=crit_p); - if n_sig==1, - fprintf('Out of %d tests, %d is significant using a false discovery rate of %f.\n',m,n_sig,q); - else - fprintf('Out of %d tests, %d are significant using a false discovery rate of %f.\n',m,n_sig,q); - end - if strcmpi(method,'pdep'), - fprintf('FDR/FCR procedure used is guaranteed valid for independent or positively dependent tests.\n'); - else - fprintf('FDR/FCR procedure used is guaranteed valid for independent or dependent tests.\n'); - end -end - - - -end \ No newline at end of file diff --git a/CIF.m b/CIF.m deleted file mode 100644 index 934fe4a2..00000000 --- a/CIF.m +++ /dev/null @@ -1,1072 +0,0 @@ -classdef CIF < handle - %CIF - Conditional Intensity function. - %methods - % - %Reference page in Help browser - %doc CIF - - - % - % nSTAT v1 Copyright (C) 2012 Masschusetts Institute of Technology - % Cajigas, I, Malik, WQ, Brown, EN - % This program is free software; you can redistribute it and/or - % modify it under the terms of the GNU General Public License as published - % by the Free Software Foundation; either version 2 of the License, or - % (at your option) any later version. - % - % This program is distributed in the hope that it will be useful, - % but WITHOUT ANY WARRANTY; without even the implied warranty of - % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - % See the GNU General Public License for more details. - % - % You should have received a copy of the GNU General Public License - % along with this program; if not, write to the Free Software Foundation, - % Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - properties - - b %Regression Coefficients - varIn %The labels for the coefficients in b - stimVars %The subset of labels that correspond to the stimulus - indepVars % - stats - fitType % binomial or poisson - determines how lambda is related to the regression coefficients - lambdaDelta % symbolic expression for the product of lambda and delta - lambdaDeltaGamma - LogLambdaDeltaGamma - spikeTrain - - gradientLambdaDelta - gradientLogLambdaDelta %symbolic expression for first partial w.r.t. to stimulus variables - gradientLambdaDeltaGamma %symbolic expression for first partial w.r.t. to history coefficient variables - gradientLogLambdaDeltaGamma %symbolic expression for first partial w.r.t. to history coefficient variables - - jacobianLambdaDelta - jacobianLogLambdaDelta %symbolic expression for second partial w.r.t. to stimulus variables - jacobianLambdaDeltaGamma %symbolic expression for second partial w.r.t. to history variables - jacobianLogLambdaDeltaGamma %symbolic expression for second partial w.r.t. to history variables - history - histCoeffs - histCoeffVars %Defined in case we want to take derivatives with respect to the history params (as in the M-step of EM) - histVars - historyMat -% end - -% properties (Hidden) - - lambdaDeltaFunction % function handle to evaluate lambda*delta - lambdaDeltaGammaFunction - LogLambdaDeltaGammaFunction - gradientFunction % partial derivative of log(lambda*delta) w.r.t stimulus variables - gradientLogFunction - gradientFunctionGamma % partial derivative of lambda*delta w.r.t stimulus variables - gradientLogFunctionGamma % partial derivative of log(lambda*delta) w.r.t stimulus variables - - jacobianFunction % second partial derivative of (lambda*delta) w.r.t. to stimulus variables - jacobianLogFunction - jacobianFunctionGamma % second partial derivative of lambda*delta w.r.t. to stimulus variables - jacobianLogFunctionGamma % second partial derivative of log(lambda*delta) w.r.t. to stimulus variables - - argstr % parse out stimulus variables by each element since the above functions dont take vector inputs - argstrLDGamma - - end - - methods - function cifObj = CIF(beta,Xnames,stimNames,fitType,histCoeffs,historyObj,nst) - % cifObj = CIF(beta,Xnames,stimNames,fitType) - % beta: regression coefficients - % - % Xnames: names of the variables in the order they are - % specified by beta. - % - % stimNames: names of the subset of variables that are define - % the stimulus. - % - % fitType: poisson or binomial - defines how the parameters are - % related to the CIF. For poisson, lamda*delta = - % exp(X*beta). For binomial, lambda*delta= - % exp(X*beta)/(1+exp(X*beta)); - % - % histCoeffs: coefficients for each of the history windows - % defined in historyObj - % - % historyObj: an object of class History that defines the how - % the spiking activity is being windowed. This - % input could also be a vector of windowTimes to be - % used in creating the historyObj. - - if(nargin<7) - cifObj.spikeTrain = []; - else - cifObj.spikeTrain = nst.nstCopy; - end - if(nargin<6) - cifObj.history=[]; - else - cifObj.setHistory(historyObj); - end - if(nargin<5) - cifObj.histCoeffs = []; - else - [r,c] = size(histCoeffs); - if(r==1) - cifObj.histCoeffs = histCoeffs; - elseif(c==1) - cifObj.histCoeffs = histCoeffs'; - else - error('History Coefficient vector must have one dimension equal to 1'); - end - end - - if(nargin<4) - fitType = 'poisson'; - end - - - if(isa(Xnames,'sym')) - XnamesTemp=cell(length(Xnames),1); - for i=1:length(beta) - XnamesTemp{i} = char(Xnames(i)); - end - Xnames=XnamesTemp; - end - - % Define input variables as a vector; - [r,c] = size(Xnames); - if(r==1) - Xnames = Xnames'; - cifObj.varIn = sym(Xnames); - elseif(c==1) - cifObj.varIn = sym(Xnames); - - else - error(' Must have one dimension equal to 1'); - - end - - % Define stimulus variables as a vector - [r,c] = size(stimNames); - if(r==1) - cifObj.stimVars = sym(stimNames'); - elseif(c==1) - cifObj.stimVars = sym(stimNames); - - else - error(' Must have one dimension equal to 1'); - - end - - % Define beta as a row vector - if(isnumeric(beta)) - [r,c] = size(beta); - if(r==1) - cifObj.b = beta; - elseif(c==1) - cifObj.b = beta'; - elseif(isempty(beta)) -% error('Coefficient vector must have one dimension equal to 1'); - %define beta as symbolic - betaLabel=cell(1,length(cifObj.varIn)); - for i=1:length(cifObj.varIn) - betaLabel{i} = strcat('b',num2str(i)); - end - display('Beta is being treated as symbolic! Must provide an input vector length(beta)+length(Xnames) to evaluate'); - - cifObj.b = sym(betaLabel); - beta = cifObj.b; - allVarNames = cell(length(Xnames)+length(betaLabel),1); - allVarNames(1:length(betaLabel)) = betaLabel; - allVarNames((length(betaLabel)+1):(length(betaLabel)+length(Xnames)))=Xnames; - cifObj.varIn = sym(allVarNames); - end - elseif(isa(beta,'cell')) - [r,c] = size(beta); - if(r==1) - betaLabel = beta; - - elseif(c==1) - betaLabel = beta'; - - else - error(' Beta Must have one dimension equal to 1'); - end - cifObj.b = sym(betaLabel); - beta = cifObj.b; - allVarNames = cell(length(Xnames)+length(betaLabel),1); - allVarNames(1:length(betaLabel)) = betaLabel; - allVarNames((length(betaLabel)+1):(length(betaLabel)+length(Xnames)))=Xnames; - cifObj.varIn = sym(allVarNames); - elseif(isa(beta,'sym')) - betaLabel=cell(1,length(beta)); - for i=1:length(beta) - betaLabel{i} = char(beta(i)); - end - cifObj.b = sym(betaLabel); - beta = cifObj.b; - allVarNames = cell(length(Xnames)+length(betaLabel),1); - allVarNames(1:length(betaLabel)) = betaLabel; - allVarNames((length(betaLabel)+1):(length(betaLabel)+length(Xnames)))=Xnames; - cifObj.varIn = sym(allVarNames); - end - - - %Define History variables if they were passed in - if(and(~isempty(cifObj.histCoeffs),~isempty(cifObj.history))) - for i=1:length(cifObj.histCoeffs) - histNames{i} = strcat('dN',num2str(i)); - histCoeffVars{i} = strcat('gamma',num2str(i)); - end - cifObj.histVars = sym(histNames'); - cifObj.histCoeffVars = sym(histCoeffVars); - histCoeffsVarsTrans = sym(histCoeffVars'); - - else - cifObj.histVars = {}; - cifObj.histCoeffVars = {}; - histCoeffsVarsTrans = {}; - end - - - - % Define the functional form of the Conditonal Intensity - % Function based on how the data was fit. - cifObj.fitType = fitType; - if(isempty(cifObj.histVars)) - if(strcmp(fitType,'poisson')) - cifObj.lambdaDelta = simplify(exp(beta*cifObj.varIn)); - cifObj.lambdaDeltaFunction = matlabFunction(cifObj.lambdaDelta,'vars',cifObj.varIn); - elseif(strcmp(fitType,'binomial')) - cifObj.lambdaDelta = simplify(exp(beta*cifObj.varIn)./(1+exp(beta*cifObj.varIn))); - cifObj.lambdaDeltaFunction = matlabFunction(cifObj.lambdaDelta,'vars',symvar(cifObj.varIn)); - end - else - if(strcmp(fitType,'poisson')) - cifObj.lambdaDelta = simplify(exp(beta*cifObj.varIn + cifObj.histCoeffs*cifObj.histVars)); - cifObj.lambdaDeltaGamma = simplify(exp(beta*cifObj.varIn + cifObj.histCoeffVars*cifObj.histVars)); - cifObj.lambdaDeltaFunction = matlabFunction(cifObj.lambdaDelta,'vars',[cifObj.varIn; cifObj.histVars]); - cifObj.lambdaDeltaGammaFunction = matlabFunction(cifObj.lambdaDeltaGamma,'vars',[cifObj.varIn; cifObj.histVars; histCoeffsVarsTrans]); - - elseif(strcmp(fitType,'binomial')) - cifObj.lambdaDelta = simplify(exp(beta*cifObj.varIn + cifObj.histCoeffs*cifObj.histVars)./(1+exp(beta*cifObj.varIn + cifObj.histCoeffs*cifObj.histVars))); - cifObj.lambdaDeltaGamma = simplify(exp(beta*cifObj.varIn + cifObj.histCoeffVars*cifObj.histVars)./(1+exp(beta*cifObj.varIn + cifObj.histCoeffVars*cifObj.histVars))); - cifObj.lambdaDeltaFunction = matlabFunction(cifObj.lambdaDelta,'vars',symvar([cifObj.varIn; cifObj.histVars])); - cifObj.lambdaDeltaGammaFunction = matlabFunction(cifObj.lambdaDeltaGamma,'vars',symvar([cifObj.varIn; cifObj.histVars; histCoeffsVarsTrans])); - end - - - end - - % Additional Functions needed for decoding - % The gradient of log(lambda*delta) and the jacobian of - % log(lambda*delta) - cifObj.gradientLambdaDelta = simplify(jacobian(cifObj.lambdaDelta,cifObj.stimVars)); - cifObj.gradientLogLambdaDelta=simplify(jacobian(log(cifObj.lambdaDelta),cifObj.stimVars)); - cifObj.gradientFunction = matlabFunction(cifObj.gradientLambdaDelta,'vars',[symvar(cifObj.varIn); cifObj.histVars]); - cifObj.gradientLogFunction = matlabFunction(cifObj.gradientLogLambdaDelta,'vars',[symvar(cifObj.varIn); cifObj.histVars]); - - - cifObj.jacobianLambdaDelta=simplify(jacobian(cifObj.gradientLambdaDelta,cifObj.stimVars)); - cifObj.jacobianFunction = matlabFunction(cifObj.jacobianLambdaDelta,'vars',[symvar(cifObj.varIn); cifObj.histVars]); - - cifObj.jacobianLogLambdaDelta=simplify(jacobian(cifObj.gradientLogLambdaDelta,cifObj.stimVars)); - cifObj.jacobianLogFunction = matlabFunction(cifObj.jacobianLogLambdaDelta,'vars',[symvar(cifObj.varIn); cifObj.histVars]); - - - if(and(~isempty(cifObj.histCoeffs),~isempty(cifObj.history))) - cifObj.LogLambdaDeltaGamma=simplify(log(cifObj.lambdaDeltaGamma)); - cifObj.LogLambdaDeltaGammaFunction = matlabFunction(cifObj.LogLambdaDeltaGamma,'vars',[symvar(cifObj.varIn); cifObj.histVars;histCoeffsVarsTrans]); - - cifObj.gradientLogLambdaDeltaGamma=simplify(jacobian(log(cifObj.lambdaDeltaGamma),cifObj.histCoeffVars)); - cifObj.gradientLambdaDeltaGamma=simplify(jacobian((cifObj.lambdaDeltaGamma),cifObj.histCoeffVars)); - cifObj.gradientLogFunctionGamma = matlabFunction(cifObj.gradientLogLambdaDeltaGamma,'vars',[symvar(cifObj.varIn); cifObj.histVars;histCoeffsVarsTrans]); - cifObj.gradientFunctionGamma = matlabFunction(cifObj.gradientLambdaDeltaGamma,'vars',[symvar(cifObj.varIn); cifObj.histVars;histCoeffsVarsTrans]); - - cifObj.jacobianLogLambdaDeltaGamma=simplify(jacobian(cifObj.gradientLogLambdaDeltaGamma,cifObj.histCoeffVars)); - cifObj.jacobianLambdaDeltaGamma=simplify(jacobian(cifObj.gradientLambdaDeltaGamma,cifObj.histCoeffVars)); - cifObj.jacobianLogFunctionGamma = matlabFunction(cifObj.jacobianLogLambdaDeltaGamma,'vars',[symvar(cifObj.varIn); cifObj.histVars;histCoeffsVarsTrans]); - cifObj.jacobianFunctionGamma = matlabFunction(cifObj.jacobianLambdaDeltaGamma,'vars',[symvar(cifObj.varIn); cifObj.histVars;histCoeffsVarsTrans]); - - else - cifObj.LogLambdaDeltaGamma=[]; - cifObj.LogLambdaDeltaGammaFunction = []; - - cifObj.gradientLogLambdaDeltaGamma=[]; - cifObj.gradientLambdaDeltaGamma=[]; - cifObj.gradientLogFunctionGamma = []; - cifObj.gradientFunctionGamma = []; - - cifObj.jacobianLogLambdaDeltaGamma=[]; - cifObj.jacobianLambdaDeltaGamma=[]; - cifObj.jacobianLogFunctionGamma = []; - cifObj.jacobianFunctionGamma = []; - - end - cifObj.indepVars = symvar(cifObj.lambdaDelta); - - - % Determine the number of variables and make a default string - % that will be used to evaluate the above functions - % This is required since functions defined by using the - % matlabFunction command do not take vector inputs and so each - % value needs to be passed separatedly. Defining this string - % now simplifies how we evaluate these functions - argstr=''; - - if(length([symvar(cifObj.varIn); cifObj.histVars])==1) - argstr = 'val'; - else - for i=1:(length(symvar(cifObj.varIn))+length(cifObj.histVars)) - if(i==1) - argstr = 'val(1)'; - else - argstr = strcat(argstr,[',val(' num2str(i) ')']); - end - end - - end - - cifObj.argstr = argstr; - - - argstrVarHist=''; - - if(length([symvar(cifObj.varIn); cifObj.histVars; histCoeffsVarsTrans])==1) - argstrVarHist = 'val'; - else - for i=1:(length(symvar(cifObj.varIn))+length(cifObj.histVars)+length(histCoeffsVarsTrans)) - if(i==1) - argstrVarHist = 'val(1)'; - else - argstrVarHist = strcat(argstrVarHist,[',val(' num2str(i) ')']); - end - end - - end - - cifObj.argstrLDGamma = argstrVarHist; - - if(~isempty(cifObj.spikeTrain) && ~isempty(cifObj.history)) - cifObj.historyMat = cifObj.history.computeHistory(cifObj.spikeTrain).dataToMatrix; - else - cifObj.historyMat = []; - end - - end - - function cifObjNew = CIFCopy(cifObj) -% pause; -% cifObjNew = CIF(cifObj.b,cifObj.stimVars,cifObj.stimVars,cifObj.fitType); - %make a new CIF thats super simple - cifObjNew = CIF([1],['x'],['x'],cifObj.fitType); - - %copy parameters from the old cifObj to the new one - fnames = fields(cifObj); - for i=1:length(fnames) - cifObjNew.(fnames{i}) = cifObj.(fnames{i}); - end - - end - - function setSpikeTrain(cifObj, spikeTrain) - cifObj.spikeTrain = spikeTrain.nstCopy; - if(~isempty(cifObj.history)) - cifObj.historyMat = cifObj.history.computeHistory(cifObj.spikeTrain).dataToMatrix; - else - cifObj.historyMat = []; - end - - - end - function setHistory(cifObj,histObj) - %Sets the input history object to be the history object that - %corresponds to this CIF. - % histObj: can be of class History or a vector of doubles to be - % used in creating a History object - if(isa(histObj,'History')) - cifObj.history = History(histObj.windowTimes); - elseif(isa(histObj,'double')); - cifObj.history = History(histObj); - else - error('History can only be set by passing in a History Object or a vector of windowTimes'); - end - - - end - - - - function outVal = evalLambdaDelta(cifObj,stimVal,time_index,nst) - % outVal = evalLambdaDelta(cifObj,stimVal,nst) - % scalar value of lambda*delta where lambda is evaluated at the - % values in stimVal. If there this CIF has history dependence - % the nspikeTrain nst is used to compute the history effect - if(nargin<3) - time_index=[]; - histVal = []; - end - - if(nargin<4) - if(~isempty(time_index) && ~isempty(cifObj.historyMat)) - histVal=cifObj.historyMat(time_index,:)'; - end - else - if(isa(nst,'nspikeTrain')) - if(~isempty(cifObj.history)) - histData=cifObj.history.computeHistory(nst).dataToMatrix; - histVal = histData(end,:)'; - else - histVal = []; - end - else - error('Second Input must be of class nspikeTrain'); - end - end - - val = [stimVal;histVal]; - outVal = CIF.evalFunctionWithVectorArgs(cifObj.lambdaDeltaFunction,val); - end - function outVal = evalGradient(cifObj,stimVal,time_index,nst) - % outVal = evalGradient(cifObj,stimVal,nst) - % row vector of the gradient of log(lambda*delta) with respect - % to the stimulus variables. - % The gradient is evaluated at the - % values in stimVal. If there this CIF has history dependence - % the nspikeTrain nst is used to compute the history effect - if(nargin<3) - time_index=[]; - histVal = []; - end - - if(nargin<4) - if(~isempty(time_index) && ~isempty(cifObj.historyMat)) - histVal=cifObj.historyMat(time_index,:)'; - end - else - if(isa(nst,'nspikeTrain')) - if(~isempty(cifObj.history)) - histData=cifObj.history.computeHistory(nst).dataToMatrix; - histVal = histData(end,:)'; - else - histVal = []; - end - else - error('Second Input must be of class nspikeTrain'); - end - end - - val = [stimVal;histVal]; - outVal = CIF.evalFunctionWithVectorArgs(cifObj.gradientFunction,val); - - end - - function outVal = evalGradientLog(cifObj,stimVal,time_index,nst) - % outVal = evalGradient(cifObj,stimVal,nst) - % row vector of the gradient of log(lambda*delta) with respect - % to the stimulus variables. - % The gradient is evaluated at the - % values in stimVal. If there this CIF has history dependence - % the nspikeTrain nst is used to compute the history effect - if(nargin<3) - time_index=[]; - histVal = []; - end - - if(nargin<4) - if(~isempty(time_index) && ~isempty(cifObj.historyMat)) - histVal=cifObj.historyMat(time_index,:)'; - end - else - if(isa(nst,'nspikeTrain')) - if(~isempty(cifObj.history)) - histData=cifObj.history.computeHistory(nst).dataToMatrix; - histVal = histData(end,:)'; - else - histVal = []; - end - else - error('Second Input must be of class nspikeTrain'); - end - end - - val = [stimVal;histVal]; - outVal = CIF.evalFunctionWithVectorArgs(cifObj.gradientLogFunction,val); - - end - - - function outVal = evalJacobian(cifObj,stimVal,time_index,nst) - - % outVal = evalJacobian(cifObj,stimVal,nst) - % matrix vector of the jacobian of log(lambda*delta) with - % to the stimulus variables. The gradient is evaluated at the - % values in stimVal. If there this CIF has history dependence - % the nspikeTrain nst is used to compute the history effect - - if(nargin<3) - time_index=[]; - histVal = []; - end - - if(nargin<4) - if(~isempty(time_index) && ~isempty(cifObj.historyMat)) - histVal=cifObj.historyMat(time_index,:)'; - end - else - if(isa(nst,'nspikeTrain')) - if(~isempty(cifObj.history)) - histData=cifObj.history.computeHistory(nst).dataToMatrix; - histVal = histData(end,:)'; - else - histVal = []; - end - else - error('Second Input must be of class nspikeTrain'); - end - end - val = [stimVal;histVal]; - outVal = CIF.evalFunctionWithVectorArgs(cifObj.jacobianFunction,val); - end - - function outVal = evalJacobianLog(cifObj,stimVal,time_index,nst) - - % outVal = evalJacobian(cifObj,stimVal,nst) - % matrix vector of the jacobian of log(lambda*delta) with - % to the stimulus variables. The gradient is evaluated at the - % values in stimVal. If there this CIF has history dependence - % the nspikeTrain nst is used to compute the history effect - - if(nargin<3) - time_index=[]; - histVal = []; - end - - if(nargin<4) - if(~isempty(time_index) && ~isempty(cifObj.historyMat)) - histVal=cifObj.historyMat(time_index,:)'; - end - else - if(isa(nst,'nspikeTrain')) - if(~isempty(cifObj.history)) - histData=cifObj.history.computeHistory(nst).dataToMatrix; - histVal = histData(end,:)'; - else - histVal = []; - end - else - error('Second Input must be of class nspikeTrain'); - end - end - val = [stimVal;histVal]; - outVal = CIF.evalFunctionWithVectorArgs(cifObj.jacobianLogFunction,val); - end - - - - %%For history parameters - - function outVal = evalLDGamma(cifObj,stimVal,time_index,nst,gamma) - % outVal = evalLambdaDelta(cifObj,stimVal,nst) - % scalar value of lambda*delta where lambda is evaluated at the - % values in stimVal. If there this CIF has history dependence - % the nspikeTrain nst is used to compute the history effect - - if(nargin<3) - time_index=[]; - histVal = []; - end - - if(nargin<4 || isempty(nst)) - if(~isempty(time_index) && ~isempty(cifObj.historyMat)) - histVal=cifObj.historyMat(time_index,:)'; - end - else - if(isa(nst,'nspikeTrain')) - if(~isempty(cifObj.history)) - histData=cifObj.history.computeHistory(nst).dataToMatrix; - histVal = histData(end,:)'; - else - histVal = []; - end - else - error('Second Input must be of class nspikeTrain'); - end - end - - val = [stimVal;histVal;gamma]; - outVal = CIF.evalFunctionWithVectorArgs(cifObj.lambdaDeltaGammaFunction,val); - end - - function outVal = evalLogLDGamma(cifObj,stimVal,time_index,nst,gamma) - % outVal = evalLambdaDelta(cifObj,stimVal,nst) - % scalar value of lambda*delta where lambda is evaluated at the - % values in stimVal. If there this CIF has history dependence - % the nspikeTrain nst is used to compute the history effect - - if(nargin<3) - time_index=[]; - histVal = []; - end - - if(nargin<4 || isempty(nst)) - if(~isempty(time_index) && ~isempty(cifObj.historyMat)) - histVal=cifObj.historyMat(time_index,:)'; - end - else - if(isa(nst,'nspikeTrain')) - if(~isempty(cifObj.history)) - histData=cifObj.history.computeHistory(nst).dataToMatrix; - histVal = histData(end,:)'; - else - histVal = []; - end - else - error('Second Input must be of class nspikeTrain'); - end - end - - val = [stimVal;histVal;gamma]; - outVal = CIF.evalFunctionWithVectorArgs(cifObj.LogLambdaDeltaGammaFunction,val); - end - - - function outVal = evalGradientLDGamma(cifObj,stimVal,time_index,nst,gamma) - % outVal = evalGradient(cifObj,stimVal,nst) - % row vector of the gradient of log(lambda*delta) with respect - % to the stimulus variables. - % The gradient is evaluated at the - % values in stimVal. If there this CIF has history dependence - % the nspikeTrain nst is used to compute the history effect - if(nargin<3) - time_index=[]; - histVal = []; - end - - if(nargin<4 || isempty(nst)) - if(~isempty(time_index) && ~isempty(cifObj.historyMat)) - histVal=cifObj.historyMat(time_index,:)'; - end - else - if(isa(nst,'nspikeTrain')) - if(~isempty(cifObj.history)) - histData=cifObj.history.computeHistory(nst).dataToMatrix; - histVal = histData(end,:)'; - else - histVal = []; - end - else - error('Second Input must be of class nspikeTrain'); - end - end - - val = [stimVal;histVal;gamma]; - outVal = CIF.evalFunctionWithVectorArgs(cifObj.gradientFunctionGamma,val); - - end - function outVal = evalGradientLogLDGamma(cifObj,stimVal,time_index,nst,gamma) - % outVal = evalGradient(cifObj,stimVal,nst) - % row vector of the gradient of log(lambda*delta) with respect - % to the stimulus variables. - % The gradient is evaluated at the - % values in stimVal. If there this CIF has history dependence - % the nspikeTrain nst is used to compute the history effect - if(nargin<3) - time_index=[]; - histVal = []; - end - - if(nargin<4 || isempty(nst)) - if(~isempty(time_index) && ~isempty(cifObj.historyMat)) - histVal=cifObj.historyMat(time_index,:)'; - end - else - if(isa(nst,'nspikeTrain')) - if(~isempty(cifObj.history)) - histData=cifObj.history.computeHistory(nst).dataToMatrix; - histVal = histData(end,:)'; - else - histVal = []; - end - else - error('Second Input must be of class nspikeTrain'); - end - end - - - val = [stimVal;histVal;gamma]; - outVal = CIF.evalFunctionWithVectorArgs(cifObj.gradientLogFunctionGamma,val); - - end - - - - function outVal = evalJacobianLogLDGamma(cifObj,stimVal,time_index,nst,gamma) - - % outVal = evalJacobian(cifObj,stimVal,nst) - % matrix vector of the jacobian of log(lambda*delta) with - % to the stimulus variables. The gradient is evaluated at the - % values in stimVal. If there this CIF has history dependence - % the nspikeTrain nst is used to compute the history effect - - if(nargin<3) - time_index=[]; - histVal = []; - end - - if(nargin<4 || isempty(nst)) - if(~isempty(time_index) && ~isempty(cifObj.historyMat)) - histVal=cifObj.historyMat(time_index,:)'; - end - else - if(isa(nst,'nspikeTrain')) - if(~isempty(cifObj.history)) - histData=cifObj.history.computeHistory(nst).dataToMatrix; - histVal = histData(end,:)'; - else - histVal = []; - end - else - error('Second Input must be of class nspikeTrain'); - end - end - val = [stimVal;histVal;gamma]; - outVal = CIF.evalFunctionWithVectorArgs(cifObj.jacobianLogFunctionGamma,val); - end - function outVal = evalJacobianLDGamma(cifObj,stimVal,time_index,nst,gamma) - - % outVal = evalJacobian(cifObj,stimVal,nst) - % matrix vector of the jacobian of log(lambda*delta) with - % to the stimulus variables. The gradient is evaluated at the - % values in stimVal. If there this CIF has history dependence - % the nspikeTrain nst is used to compute the history effect - - if(nargin<3) - time_index=[]; - histVal = []; - end - - if(nargin<4 || isempty(nst)) - if(~isempty(time_index) && ~isempty(cifObj.historyMat)) - histVal=cifObj.historyMat(time_index,:)'; - end - else - if(isa(nst,'nspikeTrain')) - if(~isempty(cifObj.history)) - histData=cifObj.history.computeHistory(nst).dataToMatrix; - histVal = histData(end,:)'; - else - histVal = []; - end - else - error('Second Input must be of class nspikeTrain'); - end - end - val = [stimVal;histVal;gamma]; - outVal = CIF.evalFunctionWithVectorArgs(cifObj.jacobianFunctionGamma,val); - end - - function ans = isSymBeta(cifObj) - if(isa(cifObj.b,'sym')) - ans=1; - else - ans=0; - end - end - - end - - methods (Static) - function spikeTrainColl=simulateCIFByThinningFromLambda(lambda,numRealizations,maxTimeRes)%,histCoeffs,histObj) - % spikeTrainColl=simulateCIFByThinning(lambda,numRealizations,maxTimeRes) - % Returns a nstColl with numRealization distinct nspikeTrains - % corresponding to realizations of the point process specified - % by the conditional intensity function lambda. - % - % lambda: a SignalObj or Covariate that is the CIF time series. - % numRealizations: number of realizations to return of the - % point process specified by lambda. - % maxTimeRes: makes sure that only there is only one spike - % occurs within the time maxTimeRes. - % - % Note: Currently assumes no history dependence. Needs to be - % modified so that a new lambda is determined at each - % time step which includes the current spiking activity - % in a given realization. - -% if(nargin<5) -% histObj = []; -% end -% -% if(nargin<4) -% histCoeffs = []; -% end - - if(nargin<3) - maxTimeRes =[]; - end - Tmax = lambda.maxTime; - lambdaBound = max(lambda); - N=ceil(lambdaBound*(1.5*Tmax)); %Expected number of arrivals in interval 1.5*Tmax - nst=cell(1,numRealizations); - - - for i=1:numRealizations - u = rand(1,N); %N samples U(0,1) - w = -log(u)./(lambdaBound); %Exponential rate lambdaBound - tSpikes = cumsum(w); %time of the spikes - tSpikes = tSpikes(tSpikes<=Tmax); %keep only in interval of interest - - % Thinning - -% if(and(~isempty(histObj),~isempty(histCoeffs))) -% tempnst = nspikeTrain(tSpikes); tempnst.setMinTime(lambda.minTime); -% tempnst.setMaxTime(lambda.maxTime); -% tempnst.resample(lambda.sampleRate); -% histData = histObj.computeHistory(tempnst); -% lambdaHist = SignalObj(lambda.time,exp(histData.dataToMatrix * histCoeffs)); % Assumes poisson lambda -% lambdaProd = lambda.*lambdaHist; -% lambdaBound = max(lambdaProd); -% lambdaRatio = lambdaProd.getValueAt(tSpikes)./lambdaBound; -% else - lambdaRatio = lambda.getValueAt(tSpikes)./lambdaBound; - -% end - u2 = rand(length(lambdaRatio),1); - %If lambdaRatio is greater than u2 keep spike otherwise throw - %away - - if(~isempty(lambdaRatio)) - - tSpikesThin = tSpikes(lambdaRatio>=u2); - else - tSpikesThin =[]; - end - if(isempty(maxTimeRes)) - nst{i} = nspikeTrain(tSpikesThin); - nst{i}.setName(num2str(1)); - else - tSpikesThin = unique(ceil(tSpikesThin./maxTimeRes)*maxTimeRes); - nst{i} = nspikeTrain(tSpikesThin); - nst{i}.setName(num2str(1)); - end - - end - spikeTrainColl=nstColl(nst); - spikeTrainColl.setMinTime(lambda.minTime); - spikeTrainColl.setMaxTime(lambda.maxTime); - end - - function [spikeTrainColl, lambda]=simulateCIFByThinning(mu,hist,stim,ens,inputStimSignal,inputEnsSignal,numRealizations,simType) - % spikeTrainColl=simulateCIF(mu,hist,stim,inputStimSignal,inputEnsSignal,numRealizations) - % Returns a nstColl with numRealization different nspikeTrain - % objects. Each nspikeTrain object is one particular - % realization of the point process defined the input parameters - % in the following way: - % lambda*delta = exp(inputTerms)./(1+exp(inputTerms) - % where inputTerms = (mu + stim*inputStimSignal + - % hist*spikeTrain + ens*inputEnsSignal) - % - % mu: double the indicates the mean rate of the point process - % hist: a transfer function (tf) object that is convolved with - % process spiking activity to determine the history - % effect. - % stim: a transfer function (tf) object that is convolved with - % inputStimSignal to determine the stimulus effect - % - % ens : a transfer function (tf) object that is convolved with - % the inputEnsSignal to determine the ensemble effect - % - % inputStimSignal: a SignalObj specifying the stimulation time - % series. - % inputEnsSignal: a SignalObj specifying the ensemble activity - % - % numRealizations: number of nspikeTrains to return. The - % the conditional intensity function will be - % simulated this number of times to generated - % distinct realizations of the point process. - % Example use of simulateCIF - % - - if(nargin<8 || isempty(simType)) - simType='binomial'; - end - if(nargin<7) - numRealizations =1; - end - Ts=hist.Ts; - if(1/inputStimSignal.sampleRate == hist.Ts && 1/inputStimSignal.sampleRate ==stim.Ts) - assignin('base','S',stim); - assignin('base','H',hist); - assignin('base','E',ens); - assignin('base','mu',mu); - assignin('base','Ts',hist.Ts/100); - assignin('base','TsInt',hist.Ts); - if(strcmp(simType,'poisson')) - simTypeSelect = 1; - elseif(strcmp(simType,'binomial')) - simTypeSelect = 0; - else - error('simType must be either poisson or binomial'); - end - assignin('base','simTypeSelect',simTypeSelect); - - options = simget; - thinningModelName = CIF.resolveSimulinkModelName('PointProcessSimulationThinning'); - lambdaData = zeros(length(inputStimSignal.time),numRealizations); - t=inputStimSignal.time; - u=[inputStimSignal.data, inputEnsSignal.data]; - assignin('base','t',t); - assignin('base','u',u); -% options.T - for i=1:numRealizations - - simOut = sim(thinningModelName,'SimulationMode','normal','AbsTol','1e-5',... - 'SaveState','on','StateSaveName','xout',... - 'SaveOutput','on','OutputSaveName','yout',... - 'SaveTime','on','TimeSaveName','tout',... - 'SaveFormat','StructureWithTime',... - 'StopTime', num2str(inputStimSignal.maxTime),... - 'StartTime', num2str(inputStimSignal.minTime)); - - yout = simOut.get('yout'); - tout = yout.time; -% [tout,~,yout] = sim('PointProcessSimulationThinning',[inputStimSignal.minTime inputStimSignal.maxTime],options,inputStimSignal.dataToStructure, inputEnsSignal.dataToStructure); - spikeTimes = tout(yout.signals(1).values>.5); - nst{i} = nspikeTrain(spikeTimes); - nst{i}.setName(num2str(1)); - lambdaData(:,i) = interp1(tout, yout.signals(2).values./Ts,inputStimSignal.time); - end - spikeTrainColl=nstColl(nst); - spikeTrainColl.setMinTime(inputStimSignal.minTime); - spikeTrainColl.setMaxTime(inputStimSignal.maxTime); - lambda = Covariate(inputStimSignal.time,lambdaData,'\lambda(t|H_t)','time','s','Hz'); - else - error('History and Stimulus Transfer functions be discrete and have ''Ts'' equal to 1/inputStimSignal.sampleRate'); - end - - end - - function [spikeTrainColl, lambda]=simulateCIF(mu,hist,stim,ens,inputStimSignal,inputEnsSignal,numRealizations,simType) - % spikeTrainColl=simulateCIF(mu,hist,stim,inputStimSignal,inputEnsSignal,numRealizations) - % Returns a nstColl with numRealization different nspikeTrain - % objects. Each nspikeTrain object is one particular - % realization of the point process defined the input parameters - % in the following way: - % lambda*delta = exp(inputTerms)./(1+exp(inputTerms) - % where inputTerms = (mu + stim*inputStimSignal + - % hist*spikeTrain + ens*inputEnsSignal) - % - % mu: double the indicates the mean rate of the point process - % hist: a transfer function (tf) object that is convolved with - % process spiking activity to determine the history - % effect. - % stim: a transfer function (tf) object that is convolved with - % inputStimSignal to determine the stimulus effect - % - % ens : a transfer function (tf) object that is convolved with - % the inputEnsSignal to determine the ensemble effect - % - % inputStimSignal: a SignalObj specifying the stimulation time - % series. - % inputEnsSignal: a SignalObj specifying the ensemble activity - % - % numRealizations: number of nspikeTrains to return. The - % the conditional intensity function will be - % simulated this number of times to generated - % distinct realizations of the point process. - % Example use of simulateCIF - % - - if(nargin<8 || isempty(simType)) - simType='binomial'; - end - - if(nargin<7) - numRealizations =1; - end - if(1/inputStimSignal.sampleRate == hist.Ts && 1/inputStimSignal.sampleRate ==stim.Ts) - assignin('base','S',stim); - assignin('base','H',hist); - assignin('base','E',ens); - assignin('base','mu',mu); - assignin('base','Ts',stim.Ts); - if(strcmp(simType,'poisson')) - simTypeSelect = 1; - elseif(strcmp(simType,'binomial')) - simTypeSelect = 0; - else - error('simType must be either poisson or binomial'); - end - assignin('base','simTypeSelect',simTypeSelect); - - options = simget; - simModelName = CIF.resolveSimulinkModelName('PointProcessSimulation'); - lambdaData = zeros(length(inputStimSignal.time),numRealizations); - for i=1:numRealizations - try - [tout,~,yout] = sim(simModelName,[inputStimSignal.minTime inputStimSignal.maxTime],options,inputStimSignal.dataToStructure, inputEnsSignal.dataToStructure); - catch simErr - error('CIF:PointProcessSimulationFailed',... - ['PointProcessSimulation failed (model: %s). In MATLAB 2025b run Simulink Upgrade Advisor for this model ',... - 'and verify model dependencies are on path. Original error: %s'], simModelName, simErr.message); - end - spikeTimes = tout(yout(:,1)>.5); - nst{i} = nspikeTrain(spikeTimes); - nst{i}.setName(num2str(1)); -% lambdaData(:,i) = yout(:,2); - lambdaData(:,i) = interp1(tout, yout(:,2),inputStimSignal.time); - end - spikeTrainColl=nstColl(nst); - spikeTrainColl.setMinTime(inputStimSignal.minTime); - spikeTrainColl.setMaxTime(inputStimSignal.maxTime); - lambda = Covariate(inputStimSignal.time,lambdaData,'\lambda(t|H_t)','time','s','Hz'); - else - error('History and Stimulus Transfer functions be discrete and have ''Ts'' equal to 1/inputStimSignal.sampleRate'); - end - - end - end - - methods (Static, Access = private) - function outVal = evalFunctionWithVectorArgs(funHandle,val) - if(isempty(funHandle)) - error('CIF:EmptyFunctionHandle','CIF function handle is empty and cannot be evaluated.'); - end - args = num2cell(val(:).'); - outVal = funHandle(args{:}); - end - - function modelName = resolveSimulinkModelName(baseModelName) - modelPath = which([baseModelName '.slx']); - if(isempty(modelPath)) - modelPath = which([baseModelName '.mdl']); - end - - if(~isempty(modelPath)) - modelPath = char(modelPath); - else - legacyModelPath = which([baseModelName '.mdl.r2011a']); - if(isempty(legacyModelPath)) - error('CIF:MissingSimulinkModel',... - 'Simulink model %s (.slx/.mdl) was not found on the MATLAB path.',baseModelName); - end - - compatDir = fullfile(tempdir,'nstat_compat_models'); - if(exist(compatDir,'dir') ~= 7) - mkdir(compatDir); - end - modelPath = fullfile(compatDir,[baseModelName '.mdl']); - legacyModelPath = char(legacyModelPath); - copyfile(legacyModelPath,modelPath,'f'); - end - - try - modelHandle = load_system(modelPath); - modelName = get_param(modelHandle,'Name'); - catch modelErr - error('CIF:SimulinkModelLoadFailed',... - ['Could not load Simulink model %s. In MATLAB 2025b run Simulink Upgrade Advisor for this model. ',... - 'Original error: %s'],baseModelName,modelErr.message); - end - end - end -end diff --git a/ConfidenceInterval.m b/ConfidenceInterval.m deleted file mode 100644 index c4070ce9..00000000 --- a/ConfidenceInterval.m +++ /dev/null @@ -1,88 +0,0 @@ -classdef ConfidenceInterval < SignalObj -%ConfidenceInterval-represents the confidence interval for a time -%series or Covariate. -% methods -% Reference page in Help browser -% doc ConfidenceInterval - -% -% nSTAT v1 Copyright (C) 2012 Masschusetts Institute of Technology -% Cajigas, I, Malik, WQ, Brown, EN -% This program is free software; you can redistribute it and/or -% modify it under the terms of the GNU General Public License as published -% by the Free Software Foundation; either version 2 of the License, or -% (at your option) any later version. -% -% This program is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -% See the GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with this program; if not, write to the Free Software Foundation, -% Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - properties - color - value % percent of the CI .eg. 1-alpha - default 95% - end - - methods - function ciObj = ConfidenceInterval(varargin) - ciObj@SignalObj(varargin{:}); - ciObj.color = 'b'; - ciObj.value = .95; - end - function setColor(ciObj,color) - ciObj.color = color; - - end - function setValue(ciObj,value) - ciObj.value = value; - end - - function plot(ciObj,color,alphaVal,drawPatches) - if(nargin<4) - drawPatches=0; - end - if(nargin<3) - alphaVal=.2; - end - if(nargin<2) - color = ciObj.color; - end - ciData = ciObj.dataToMatrix; - ciHigh=ciData(:,2); - ciLow=ciData(:,1); - time = ciObj.time; - - hold on; - if(drawPatches==1) - if(isa(color,'char')) - p=patch([reshape(time,[1 length(time)]) reshape(fliplr(time'),[1 length(time)])],... - [reshape(ciLow',[1 length(time)]) reshape(fliplr(ciHigh'),[1,length(time)])],strcat('',color,'')); - set(p,'facecolor',color,'edgecolor','none'); - elseif(isa(color,'double')) - p=patch([reshape(time,[1 length(time)]) reshape(fliplr(time'),[1 length(time)])],... - [reshape(ciLow',[1 length(time)]) reshape(fliplr(ciHigh'),[1,length(time)])],color); - set(p,'facecolor',color,'edgecolor','none'); - end - alpha(alphaVal); - else - if(isa(color,'char')) - p=plot(time, ciData); - elseif(isa(color,'double')) - p=plot(time, ciData); - set(p,'Color',color); - - end - alpha(alphaVal); - end - end - end - methods (Static) - function ciObj = fromStructure(structure) - ciObj=ConfidenceInterval(structure.time, structure.signals.values, structure.name, structure.xlabelval, structure.xunits, structure.yunits, structure.dataLabels, structure.plotProps); - end - end -end - diff --git a/ConfigColl.m b/ConfigColl.m deleted file mode 100644 index 91f82280..00000000 --- a/ConfigColl.m +++ /dev/null @@ -1,181 +0,0 @@ -classdef ConfigColl < handle -%CONFIGCOLL - a collection of different configurations -% methods -% ConfigColl Examples -% -% see also TrialConfig, Trial, Analysis -% -% Reference page in Help browser -% doc ConfigColl - - -% -% nSTAT v1 Copyright (C) 2012 Masschusetts Institute of Technology -% Cajigas, I, Malik, WQ, Brown, EN -% This program is free software; you can redistribute it and/or -% modify it under the terms of the GNU General Public License as published -% by the Free Software Foundation; either version 2 of the License, or -% (at your option) any later version. -% -% This program is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -% See the GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with this program; if not, write to the Free Software Foundation, -% Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - properties - numConfigs % number of configurations in this collection - configNames% names of the configurations - end - - properties (Hidden) - configArray - end - - methods - function tcColl = ConfigColl(tcObj) - % tcColl = ConfigColl(tcObj) - % creates a ConfigColl object from a TrialConfig objects - % tcObj can be a cell of TrialConfigs, a cell of strings (just - % names) - if(nargin<1) - tcObj = []; - end - tcColl.numConfigs = 0; - tcColl.configArray=[]; - tcColl.addConfig(tcObj); - end - function addConfig(tcColl,tcObj) - if(~isempty(tcObj)) - if(isa(tcObj,'cell')) - if(isa(tcObj{1},'TrialConfig')) - for i=1:length(tcObj) - tcColl.addConfig(tcObj{i}); - end - elseif(isa(tcObj{1},'char')) - for i=1:length(tcObj) - tcColl.addConfig(tcObj{i}); - end - elseif(isempty(tcObj{1})) - for i=1:length(tcObj) - tcColl.addConfig(tcObj{i}); - end - end - - elseif(isa(tcObj,'TrialConfig')) - tcColl.numConfigs = tcColl.numConfigs+1; - tcColl.setConfigNames(tcObj.name,tcColl.numConfigs); - tcColl.configArray{tcColl.numConfigs} = tcObj; - elseif(isa(tcObj,'char')) - tcColl.numConfigs = tcColl.numConfigs+1; - tcColl.setConfigNames(tcObj.name,tcColl.numConfigs); - tcColl.configArray{tcColl.numConfigs} = tcObj; - end - else - tcColl.numConfigs = tcColl.numConfigs+1; - tcColl.setConfigNames('Empty Config',tcColl.numConfigs); - tcColl.configArray{tcColl.numConfigs} = {'Empty Config'}; - end - end - function config = getConfig(tcColl,index) - %config = getConfig(tcColl,index) - % retunrs the TrialConfig specified by index only if index is - % within 0 to numConfigs. Otherwise returns an error 'Index out - % of bounds' - if(index>0 && index<=tcColl.numConfigs) - config = tcColl.configArray{index}; - else - error('Index Out of Bounds'); - end - end - function setConfig(tcColl,trial,index) - % setConfig(tcColl,trial,index) - % Set the configuration specified by the index to Trial - config=tcColl.getConfig(index); - if(isa(config,'TrialConfig')) - config.setConfig(trial); - else - error('Cannot Set Empty Configs'); - end - end - function cArray = getConfigNames(tcColl,index) - % cArray = getConfigNames(tcColl,index) - % returns a cell array of strings with the names of the - % TrialConfigs specified by index. - if(nargin<2) - index=1:tcColl.numConfigs; - end - cArray=cell(1,length(index)); - for i=1:length(cArray) - tempName=tcColl.configNames{index(i)}; - if(isempty(tempName)) - cArray{i} = ['Fit ' num2str(i)]; - else - cArray{i} = tempName; - end - - end - - end - function setConfigNames(tcColl, names, index) - % setConfigNames(tcColl, names, index) - % sets the TrialConfigs specified by index to have the names - % specified in names. - % if names is a string, then index must be length 1 - % if names is a cell array with n string entries, then index - % must be length n. - if(nargin<3) - index=1:tcColl.numConfigs; - end - if((max(index)<=tcColl.numConfigs) && min(index)>0) - if(isa(names,'char') && length(index)==1) - if(isempty(names)) - tcColl.configNames{index} = ['Fit ' num2str(tcColl.numConfigs)]; - else - tcColl.configNames{index} = names; - end - elseif(isa(names,'cell') && isa(names{1},'char')) - if(length(index)==length(names)) - for i=1:length(names) - tcColl.configNames{index(i)} = names{i}; - end - else - error('If specifying multiple names, either names must be the same size as numConfigs or and index specified'); - end - end - end - end - function subsetConfigs=getSubsetConfigs(tcColl, subset) - for i=1:length(subset) - tempconfigs{i} = tcColl.getConfig(subset(i)); - end - subsetConfigs=ConfigColl(tempconfigs); - end - function structure = toStructure(tcColl) - fNames = fieldnames(tcColl); - for i=1:length(fNames) - structure.(fNames{i}) = tcColl.(fNames{i}); - end - for i=1:tcColl.numConfigs - structure.configArray{i} = tcColl.configArray{i}.toStructure; - end - - end - - end - methods (Static) - function tcColl = fromStructure(structure) - c=cell(1,structure.numConfigs); - for i=1:structure.numConfigs - c{i} = TrialConfig.fromStructure(structure.configArray{i}); - end - tcColl = ConfigColl(c); - end - - end - -end diff --git a/CovColl.m b/CovColl.m deleted file mode 100644 index 6cd7b9d5..00000000 --- a/CovColl.m +++ /dev/null @@ -1,976 +0,0 @@ -classdef CovColl methods -% CovColl Examples -% -% see also SignalObj, Covariate -% -% Reference page in Help browser -% doc CovColl -% - -% -% nSTAT v1 Copyright (C) 2012 Masschusetts Institute of Technology -% Cajigas, I, Malik, WQ, Brown, EN -% This program is free software; you can redistribute it and/or -% modify it under the terms of the GNU General Public License as published -% by the Free Software Foundation; either version 2 of the License, or -% (at your option) any later version. -% -% This program is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -% See the GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with this program; if not, write to the Free Software Foundation, -% Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - properties (SetAccess = private) - covArray; %An array of covariate objects - covDimensions; % at each position has the number of dimensions of each covariate - numCov; % a running count of how many covariates are in object - minTime; % Time data occurs - maxTime; % Time last data point occurs in object - covMask; % covariates that are currently selected - covShift;% time lag for covariates - sampleRate % sampleRate for all covariates - end - - properties (Hidden) - originalSampleRate; - originalMinTime; - originalMaxTime; - - end - - - methods - function ccObj=CovColl(cov,varargin) - % ccObj=CovColl(cov,varargin) - % Creates a collection of covariates from a cell array of - % objects of the class Covariate Covariate - if(nargin<1) - cov=[]; - end - ccObj.numCov = 0; - ccObj.minTime=inf; - ccObj.maxTime=-inf; - ccObj.originalSampleRate=[]; - ccObj.originalMinTime = []; - ccObj.originalMaxTime = []; - ccObj.covArray=[]; - ccObj.covDimensions=[]; - ccObj.covMask = []; - ccObj.covShift = 0; - ccObj.addToColl(cov); - if(nargin>1) - for i=1:length(varargin) - ccObj.addToColl(varargin{i}); - end - end - end - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %Set functions - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - function setMinTime(ccObj,minTime) - % setMinTime(ccObj,minTime) - % sets the minimum time for all the covariates in the - % collection to minTime - if(nargin<2 || isempty(minTime)) - minTime=ccObj.findMinTime; - end - if(isempty(ccObj.originalMinTime)) - ccObj.originalMinTime=ccObj.minTime; - end -% for i=1:ccObj.numCov -% tempC = ccObj.covArray{i}; -% tempC.setMinTime(minTime); -% end - ccObj.minTime=minTime; - end - function setMaxTime(ccObj,maxTime) - % setMaxTime(ccObj,maxTime) - % sets the maximum time for all the covariates in the - % collection to maxTime - - if(nargin<2 || isempty(maxTime)) - maxTime=ccObj.findMaxTime; - end - if(isempty(ccObj.originalMaxTime)) - ccObj.originalMaxTime=ccObj.maxTime; - end -% for i=1:ccObj.numCov -% tempC =ccObj.covArray{i}; -% tempC.setMaxTime(maxTime); -% end - ccObj.maxTime = maxTime; - end - function setSampleRate(ccObj, sampleRate) - % setSampleRate(ccObj, sampleRate) - % resample all of the covariates to the specified sampleRate - if(isempty(ccObj.originalSampleRate)) - ccObj.originalSampleRate=ccObj.sampleRate; - end -% minTime = ccObj.minTime; -% maxTime = ccObj.maxTime; - - ccObj.sampleRate = sampleRate; - ccObj.enforceSampleRate; -% ccObj.restrictToTimeWindow(minTime,maxTime); - - end - function setMask(ccObj,cellInput) - % setMask(ccObj,cellInput) - % specify which covariates are to be used - - selectorCell = ccObj.generateSelectorCell(cellInput); - ccObj.setMasksFromSelector(selectorCell); - for i=1:ccObj.numCov - cov=ccObj.getCov(i); - cov.setMask(ccObj.covMask{i}) - end - end - function dataMask=getCovDataMask(ccObj,identifier) - % dataMask=getCovDataMask(ccObj,identifier) - % returns the dataMask for the covariate specified by - % indentifier - cov=ccObj.covArray{identifier}; - dataMask = cov.dataMask; - end - function answer=isCovMaskSet(ccObj) - % answer=isCovMaskSet(ccObj) - % returns 1 if any Covariate has any component that is masked - % away, otherwise returns 0. - answer =0; - for i=1:ccObj.numCov - if(any(ccObj.covMask{i}==0)) - answer =1; - break; - end - end - end - function n=nActCovar(ccObj) - % n=nActCovar(ccObj) - % Returns the effective number of a covariates. Any - % covariate with at least one unmasked component - % contributes to n. Any covariate with all components - % masked away is not counted. - selectorArray = ccObj.getSelectorFromMasks; - n=numActCov(selectorArray); - end - - function maskAwayCov(ccObj,identifier) - % maskAwayCov(ccObj,identifier) - % masks away all the components of the covariates specified by - % indentifier - cov=ccObj.getCov(identifier); - if(isa(cov,'Covariate')) - cov = {cov}; % make it a cell even if just one - end - for j=1:length(cov) - covIndex = ccObj.getCovIndicesFromNames(cov{j}.name); - newMask = cell(1,ccObj.numCov); - for i=1:ccObj.numCov - if(i==covIndex) - newMask{i} = zeros(1,length(ccObj.covMask{i})); - else - newMask{i} = ccObj.covMask{i}; - end - end - ccObj.setMask(ccObj.getSelectorFromMasks(newMask)); - end - end - - function ccObj2 = copy(ccObj) - cov = cell(length(ccObj.numCov),1); - for i=1:ccObj.numCov - cov{i} = ccObj.getCov(i).copySignal; - end - ccObj2 = CovColl(cov); - - - end - function maskAwayOnlyCov(ccObj,identifier) - % maskAwayOnlyCov(ccObj,identifier) - % makes all components of all covariates visible and then masks - % away the covariates specified by indentifier. - ccObj.resetMask; - ccObj.maskAwayCov(identifier); - end - - function maskAwayAllExcept(ccObj, identifier) - % maskAwayAllExcept(ccObj, identifier) - % masks away all covariates except that specified by - % identifier - offset=0; - maskList = zeros(1,ccObj.numCov - length(identifier)); - for i =1:ccObj.numCov - if(~any(i==identifier))% i is not in any element of identifier - offset=offset+1; - maskList(offset) = i; - end - end - ccObj.maskAwayOnlyCov(maskList); - end - - - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % Get Functions - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - function cov = getCov(ccObj, identifier) - % cov = getCov(ccObj, identifier) - % returns a single covariate if only one is requested. - % Otherwise returns a cell array of covariates, one for each - % identifier. - % The identifier can be: - % doubles: specifying the number of the covariate in the - % collection - % strings: specifying the name of the covariate - % cell array of strings: specifying multiple covariates by - % their name. - holdVals=1; - if(isa(identifier,'double')) - if(length(identifier)==1) - cov=ccObj.covArray{identifier}.copySignal; - cov.setMask(ccObj.covMask{identifier}); - if(ccObj.covShift~=0) - cov=cov.shift(ccObj.covShift); - end - if(cov.minTime~=ccObj.minTime || cov.maxTime~=ccObj.maxTime) - cov=cov.getSigInTimeWindow(ccObj.minTime,ccObj.maxTime,holdVals); - end -% cov=cov.resample(ccObj.sampleRate); - - else - cov=cell(1,length(identifier)); - for i=1:length(identifier) - cov{i}=ccObj.getCov(identifier(i)); - %cov{i}=ccObj.covArray{identifier(i)}; - end - end - elseif(isa(identifier,'char')) - %cov=ccObj.covArray{ccObj.getCovIndFromName(identifier)}; - cov=ccObj.getCov(ccObj.getCovIndFromName(identifier)); - elseif(isa(identifier,'cell')) - cov=cell(1,length(identifier)); - if(isa(identifier{1},'char')) - for i=1:length(identifier) - %cov{i}=ccObj.covArray{ccObj.getCovIndFromName(identifier{i})}; - cov{i}=ccObj.getCov(identifier{i}); - end - else - error('Identifier cells must contain strings!'); - end - end - end - function ind = getCovIndicesFromNames(ccObj,name) - % ind = getCovIndicesFromNames(ccObj,name) - % returns a vector of indices for each covariate name - % specified. - if(isa(name,'cell')) - if(isa(name{1},'char')) - ind=zeros(1,length(name)); - for i=1:length(name) - ind(i)=ccObj.getCovIndFromName(name{i}); - end - else - error('Cell must contain strings!'); - end - elseif(isa(name,'char')) - ind=ccObj.getCovIndFromName(name); - else - error('Need either cells with strings or a single string!'); - end - - end - function dim = getCovDimension(ccObj,identifier) - % dim = getCovDimension(ccObj,identifier) - % returns a vector with the dimension of covariate i at - % position i. - covs = ccObj.getCov(identifier); - dim = zeros(1,length(covs)); - for i=1:length(covs) - dim(i)=covs{i}.dimension; - end - end - function l = getAllCovLabels(ccObj) - % l = getAllCovLabels(ccObj) - % returns a cell array of strings with the covariate names - offset=0; - l=cell(1,length(ccObj.flattenCovMask)); - for i=1:ccObj.numCov - tempCov = ccObj.getCov(i); - for j=1:tempCov.dimension - l{j+offset} = tempCov.dataLabels{j}; - end - offset=offset+tempCov.dimension; - end - end - - function l = getCovLabelsFromMask(ccObj) - % l = getCovLabelsFromMask(ccObj) - % returns a list of all the the dataLabels that are currently - % visible (i.e. unmasked). - offset=0; - l={}; - for i=1:ccObj.numCov - tempCov = ccObj.getCov(i); - for j=1:tempCov.dimension - if(ccObj.covMask{i}(j)==1) - offset=offset+1; - l{offset} = tempCov.dataLabels{j}; - end - end - end - - end - - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %Utility Functions - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - function structure = toStructure(ccObj) - fnames = fieldnames(ccObj); - ccObj.resetMask; %otherwise masked data will not get saved!! - for i=1:length(fnames) - currObj = ccObj.(fnames{i}); - if(isa(currObj,'double')||isa(currObj,'cell')) - if(strcmp(fnames{i},'covArray')) - for j=1:ccObj.numCov - structure.(fnames{i}){j} = ccObj.(fnames{i}){j}.toStructure; - end - else - structure.(fnames{i}) = currObj; - end - end - end - - end - - function minTime = findMinTime(ccObj) - % minTime = findMinTime(ccObj) - % finds the minimum minTime from all covariates - minTime=inf; - for i=1:ccObj.numCov - minTime = min(ccObj.covArray{i}.minTime,minTime); - end - minTime = minTime+ccObj.covShift; - end - function maxTime = findMaxTime(ccObj) - % maxTime = findMaxTime(ccObj) - % finds that maximum maxTime from all covariates. - - maxTime=-inf; - for i=1:ccObj.numCov - maxTime = max(ccObj.covArray{i}.maxTime+ccObj.covShift,maxTime); - end - maxTime = maxTime+ccObj.covShift; - end - - function addToColl(ccObj,cov) - % addToColl(ccObj,cov) - % add one or several covariates to the current collection. - % can specify cell of covariates, a single covariate, or a - % covariate CovColl. - if(~isempty(cov)) - if(isa(cov,'cell')) - ccObj.addCovCellToColl(cov); - elseif(isa(cov,'Covariate')) - ccObj.addSingleCovToColl(cov); - elseif(isa(cov,'CovColl')); - ccObj.addCovCollection(cov); - else - error('Can only add covariates to CovColl'); - end - end - ccObj.enforceSampleRate; - end - function addCovCollection(ccObj,cov) - % addCovCollection(ccObj,cov) - % adds a CovColl to the current collection - covCell=cov.covArray; - ccObj.addCovCellToColl(covCell); - end - - - function answer = isCovPresent(ccObj,cov) - % answer = isCovPresent(ccObj,cov) - % returns 1 if covariate is present in the CovColl. - % inputs can be a covariate, a string corresponding to the name - % of the covariate, or the number of the covariate in the - % collection. - if(isa(cov,'Covariate')) - if(strcmp(cov.name,'')) - display('Covariate does not have name'); - answer=0; - else - index=ccObj.getCovIndFromName(cov.name); - if(isempty(index)) - answer = 0; - else - answer = 1; - end - end - elseif(isa(cov,'char')) - covar=ccObj.getCov(cov); - answer=ccObj.isCovPresent(covar); - elseif(isa(cov,'double')) - if((cov>0)&&(cov1 && max(selectorCell{i})==1) - cMask{i}(selectorCell{i}==1)=1; - else - cMask{i}(selectorCell{i})=1; - end - end - end - end - function selectorArray = getSelectorFromMasks(ccObj,covMask) - if(nargin<2) - covMask=ccObj.covMask; - end - - selectorArray=cell(1,ccObj.numCov); - for i=1:ccObj.numCov - ind=find(covMask{i}==1); - if(~isempty(ind)) - selectorArray{i} = ind; - else - selectorArray{i} = []; - end - end - end - - function answer=isaSelectorCell(ccObj,dataSelector) - if(length(dataSelector)==ccObj.numCov && ~containsChars(dataSelector)) - answer=1; - else - answer=0; - end - end - function selectorCell = generateSelectorCell(ccObj, dataSelector) - %dataSelector must be in the following format - %dataSelector{1} = {'Position','x','y'}; - %dataSelector{2} = {'Force','fx','fy','fz'}; - selectorCell=cell(1,ccObj.numCov); - if(isempty(dataSelector)) - for i = 1:length(selectorCell); - selectorCell{i} =[]; %zeros(1,ccObj.getCov(i).dimension); - end - else - if(isa(dataSelector{1},'char')) - covName=dataSelector{1}; - covLabels=cell(1,length(dataSelector)-1); - for i =1:length(covLabels) - covLabels{i}=dataSelector{i+1}; - end - covIndex=ccObj.getCovIndFromName(covName); - currCov = ccObj.getCov(covIndex); - selectorCell{covIndex}=currCov.getIndicesFromLabels(covLabels); - elseif(isa(dataSelector{1},'cell')) - for i=1:length(dataSelector) - [covName, covLabels] = parseDataSelectorArray(dataSelector{i}); - covIndex=ccObj.getCovIndFromName(covName); - currCov = ccObj.getCov(covIndex); - if(~isempty(currCov)) - selectorCell{covIndex}=currCov.getIndicesFromLabels(covLabels); - else - error(['Covariate ' covName ' not found!']); - end - end - elseif(isa(dataSelector{1},'double')) - selectorCell=dataSelector; - else - error('dataSelector specified incorrectly!'); - end - end - - end - function addCovCellToColl(ccObj,cov) - [~, ncolumns]=size(cov); - for i=1:ncolumns - if(isa(cov{i},'Covariate')) - ccObj.addSingleCovToColl(cov{i}); - else - error('CovColl requires a cell array of Covariate class elements'); - end - end - end - function addSingleCovToColl(ccObj,cov) - if(~ccObj.isCovPresent(cov)) - ccObj.covArray{ccObj.numCov+1}= cov; - ccObj.updateTimes(cov); - ccObj.covDimensions(ccObj.numCov+1) = cov.dimension; - ccObj.covMask{ccObj.numCov+1} = cov.dataMask; - ccObj.numCov = ccObj.numCov + 1; - %ccObj.sampleRate - %cov.sampleRate - if(isempty(ccObj.sampleRate)) %this is our first element - ccObj.sampleRate = cov.sampleRate; - ccObj.originalSampleRate = ccObj.sampleRate; - elseif(ccObj.sampleRate==cov.sampleRate) - %Do nothing - just add - elseif(ccObj.sampleRate>cov.sampleRate) %Upsample Covariate - cov.setSampleRate(ccObj.sampleRate); - elseif(ccObj.sampleRateccObj.maxTime) - ccObj.setMaxTime(maxTime); - end - end - function ind = getCovIndFromName(ccObj,name) - ind=[]; - for i=1:ccObj.numCov - if(strcmp(ccObj.getCov(i).name,name)) - ind=i; - break; - end - end - end - function removeFromColl(ccObj,identifier) - covs = ccObj.getCov(identifier); - ind = zeros(1,length(covs)); - if(length(ind)>1) - for i = 1:length(ind) - ind(i) = ccObj.getCovIndFromName(covs{i}.name); - end - else - ind=ccObj.getCovIndFromName(covs.name); - end - - ccObj.removeFromCollByIndices(ind); - - end - function removeFromCollByIndices(ccObj,ind) - remaining = ccObj.generateRemainingIndex(ind); - covArray = cell(1,length(remaining)); - covMask = cell(1,length(remaining)); - covDimensions = zeros(1,length(remaining)); - for i=1:length(remaining) - cov = ccObj.getCov(remaining(i)); - covMask{i} = ccObj.covMask{remaining(i)}; - covArray{i} = cov; - covDimensions(i) = cov.dimension; - end - numCov = length(remaining); - ccObj.covArray = covArray; - ccObj.covMask = covMask; - ccObj.numCov = numCov; - ccObj.covDimensions = covDimensions; - minTime=ccObj.findMinTime; - maxTime=ccObj.findMaxTime; - ccObj.setMinTime(minTime); - ccObj.setMaxTime(maxTime); - if(numCov==0) - ccObj.sampleRate =[]; - ccObj.originalSampleRate = []; - end - - end - function remain = generateRemainingIndex(ccObj,ind) - remain=zeros(1,ccObj.numCov-length(ind)); - count=1; - for i=1:ccObj.numCov - if(sum(i==ind)>0) %then this is one of the indices we are removing - % do nothing - else - remain(count) = i; - count=count+1; - end - end - end - end - methods (Static) - function ccObj = fromStructure(structure) - if(isa(structure,'struct')) - cov = cell(1,structure.numCov); - for i=1:structure.numCov; - cov{i} = Covariate.fromStructure(structure.covArray{i}); - end - ccObj = CovColl(cov); - % covMask = structure.covMask; - % ccObj.setMask(covMask); - %% Need to fix how mask is set!!! - ccObj.setMinTime(structure.minTime); - ccObj.setMaxTime(structure.maxTime); - elseif(isa(structure,'cell')) - ccObj= cell(length(structure),1); - for i=1:length(structure) - ccObj{i} = CovColl.fromStructure(structure{i}); - end - - end - end - - end - - - -end - -%Helper functions - -function ind = covIndFromSelector(selectorCell) - ind=zeros(1,numActCov(selectorCell)); - count=1; - for i=1:length(selectorCell) - if(~isempty(selectorCell{i})) - ind(count)=i; - count=count+1; - end - end -end -function n = numActCov(selectorCell) - n=0; - for i=1:length(selectorCell) - if(~isempty(selectorCell{i})) - n=n+1; - end - end -end - -function dimTot = sumDimensions(selectorCell,index) - if(nargin<2) - index=length(selectorCell); - end - - dimTot=0; - if(index>0 && index<=length(selectorCell)) - for i=1:index - dimTot=dimTot+length(selectorCell{i}); - end - end -end -function [covName, covLabels] = parseDataSelectorArray(entry) - covName = entry{1}; - covLabels = cell(1,length(entry)-1); - for i =1:length(covLabels) - covLabels{i} = entry{i+1}; - end -end -function answer=containsChars(x) - if(isa(x,'cell')) - for i=1:length(x) - if(isa(x{i},'char')) - answer=1; - break; - end - end - answer=0; - elseif(isa(x,'char')) - answer =1; - else - answer=0; - end - end - - - - - diff --git a/Covariate.m b/Covariate.m deleted file mode 100644 index d525b790..00000000 --- a/Covariate.m +++ /dev/null @@ -1,253 +0,0 @@ -classdef Covariate < SignalObj -% COVARIATE Covariates are signals (of class SignalObj) with a mean mu and a standard -% deviation sigma. -% -% cov = Covariate(time, data, name, xlabelval, xunits, yunits, dataLabels, plotProps) -% All inputs are passed to the superclass SignalObj. -% -% Each dimenion of a covariate signal has a mean. -% cov.mu - SignalObj reprenting mean of each component over time -% cov.sigma - SignalObj reprenting standard deviation of each component -% over time. -% -% cov.getSigRep('standard') or cov.getSigRep is the original data -% can also just use cov for the standard representation -% cov.getSigRep('zero-mean') is a zero mean version of the Signal -% -% methods -% Covariate Examples -% -% see also SignalObj, CovColl -% -% Reference page in Help browser -% doc Covariate - -% -% nSTAT v1 Copyright (C) 2012 Masschusetts Institute of Technology -% Cajigas, I, Malik, WQ, Brown, EN -% This program is free software; you can redistribute it and/or -% modify it under the terms of the GNU General Public License as published -% by the Free Software Foundation; either version 2 of the License, or -% (at your option) any later version. -% -% This program is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -% See the GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with this program; if not, write to the Free Software Foundation, -% Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - properties (Dependent = true) - mu %SignalObj representing the mean of each component of the Covariate across time - sigma %Standard deviation of the covariate across time - - end - properties - ci %a Confidence Interval object for the covariate - end - - methods - function cov = Covariate(varargin) - %cov = Covariate(time, data, name, xlabelval, xunits, yunits, - %dataLabels, plotProps) - cov@SignalObj(varargin{:}); - - end - function newCov = computeMeanPlusCI(covObj,alphaVal) - if(nargin<2) - alphaVal=.05; - end - for k=1:length(covObj.time) - [f,x] = ecdf(squeeze(covObj.data(k,:))); - CIs(k,1) = x(find(f(1-alphaVal/2),1,'first')); - end - confInt = ConfidenceInterval(covObj.time,CIs,'CI','time','s',''); - newCov = mean(covObj,2); - newCov.setConfInterval(confInt); - end - function h = plot(covObj,varargin) - h=plot@SignalObj(covObj,varargin{:}); - if(covObj.isConfIntervalSet) - handles = get(gca,'Children'); -% actHandles = []; -% for k=1:length(handles); -% if(strcmp(get(handles(k),'type'),'line'))%&& ~isempty(get(handles(k),'DisplayName'))) -% actHandles = [actHandles;handles(k)]; -% end -% end - actHandles = handles(strcmp('line',get(get(gca,'Children'),'type'))); - s=get(actHandles); - - selectorArray = find(covObj.dataMask==1); - for i=1:length(selectorArray) - actIndex = length(selectorArray)-(i-1); - TempColor=s(actIndex).Color; - covObj.ci{selectorArray(i)}.plot(TempColor); - - end - axis tight; - end - - end - function cov = getSubSignal(covObj,varargin) - cov = getSubSignal@SignalObj(covObj,varargin); - if(covObj.isConfIntervalSet) - origIndex = zeros(1,cov.dimension); - for i=1:cov.dimension - origIndex(i) = find(strcmp(cov.dataLabels{i},covObj.dataLabels)); - end - cov.setConfInterval(covObj.ci(origIndex)); - end - end - function cSig = getSigRep(covObj,repType) - % cSig = getSigRep(covObj,repType) - % repType: 'standard' - original representation - % 'zero-mean' - zero mean representation - if(nargin<2) - repType = 'standard'; - end - if(strcmp(repType, 'zero-mean')) - cSig = covObj-covObj.mu; - elseif(strcmp(repType,'standard')) - cSig = covObj; - else - error('repType must be either ''zero-mean'' or ''standard'' '); - end - end - function mu = get.mu(covObj) - mu = mean(covObj); - end - function sigma = get.sigma(covObj) - sigma = std(covObj); - end - - function cov = filtfilt(covObj,varargin) - cov=filtfilt@SignalObj(covObj,varargin{:}); - end - - - function structure = toStructure(covObj) - fNames = fieldnames(covObj); - for i=1:length(fNames) - currObj = covObj.(fNames{i}); - - if(strcmp(fNames{i},'ci')) - if(covObj.isConfIntervalSet) - if(isa(covObj.ci,'ConfidenceInterval')) - structure.ci = covObj.ci.dataToStructure; - elseif(isa(covObj.ci,'cell')) - for j=1:length(covObj.ci) - ciTemp = covObj.ci{j}; - structure.ci{j} = ciTemp.dataToStructure; - end - end - end - elseif(isa(currObj,'double')||isa(currObj,'cell')||isa(currObj,'char')) - structure.(fNames{i}) = currObj; - elseif(isa(currObj,'Covariate')) - structure.(fNames{i}) = currObj.dataToStructure; - end - end - - - - end - - function ans = isConfIntervalSet(covObj) - ans = ~isempty(covObj.ci); - end - function setConfInterval(covObj, ciObj) - if(isa(ciObj,'cell')) - covObj.ci = ciObj; - elseif(isa(ciObj,'ConfidenceInterval')) - covObj.ci = {ciObj}; - end - end - function covOut = copySignal(covObj) - covOut=copySignal@SignalObj(covObj); - if(covObj.isConfIntervalSet) - covOut.setConfInterval(covObj.ci); - end - end - - function covOut = plus(covObj,covObj2) - covOut=plus@SignalObj(covObj,covObj2); - - if(isa(covObj,'Covariate')&&isa(covObj2,'Covariate')) - if(covObj.isConfIntervalSet && ~covObj2.isConfIntervalSet) - for i=1:covObj.dimension - tempCi{i} = covObj.ci{i} + covObj2.getSubSignal(i); - end - covOut.setConfInterval(tempCi); - elseif(covObj.isConfIntervalSet && covObj2.isConfIntervalSet) - for i=1:covObj.dimension - tempCi{i} = covObj.ci{i} + covObj2.ci{i}; - end - covOut.setConfInterval(tempCi); - elseif(~covObj.isConfIntervalSet && covObj2.isConfIntervalSet) - for i=1:covObj2.dimension - tempCi{i} = covObj2.ci{i} + covObj.getSubSignal(i); - end - covOut.setConfInterval(tempCi); - end - end - - end - - function covOut = minus(covObj,covObj2) - covOut=minus@SignalObj(covObj,covObj2); - - if(isa(covObj,'Covariate')&&isa(covObj2,'Covariate')) - if(covObj.isConfIntervalSet && ~covObj2.isConfIntervalSet) - for i=1:covObj.dimension - tempCi{i} = covObj.ci{i} - covObj2.getSubSignal(i); - end - covOut.setConfInterval(tempCi); - elseif(covObj.isConfIntervalSet && covObj2.isConfIntervalSet) - for i=1:covObj.dimension - tempCi{i} = covObj.ci{i} - covObj2.ci{i}; - end - covOut.setConfInterval(tempCi); - elseif(~covObj.isConfIntervalSet && covObj2.isConfIntervalSet) - for i=1:covObj2.dimension - tempCi{i} = -covObj2.ci{i} + covObj.getSubSignal(i); - end - covOut.setConfInterval(tempCi); - end - end - - end - - - function covOut = dataToStructure(covObj) - covOut=dataToStructure@SignalObj(covObj); - end - - end - methods (Static) - function cov = fromStructure(structure) - - cov=Covariate(structure.time, structure.data, structure.name, structure.xlabelval, structure.xunits, structure.yunits, structure.dataLabels, structure.plotProps); - fnames = fields(structure); - if(any(strcmp('ci',fnames))) - if(~isempty(structure.ci)) - if(isa(structure.ci,'cell')) - for i=1:length(structure.ci) - ciTemp{i} = ConfidenceInterval.fromStructure(structure.ci{i}); - end - cov.setConfInterval(ciTemp); - elseif(isa(structure.ci,'struct')) - cov.setConfInterval(ConfidenceInterval.fromStructure(structure.ci)); - end - end - end - - end - - end - -end - diff --git a/DecodingAlgorithms.m b/DecodingAlgorithms.m deleted file mode 100644 index ec571a6f..00000000 --- a/DecodingAlgorithms.m +++ /dev/null @@ -1,10763 +0,0 @@ -classdef DecodingAlgorithms -% DECODINGALGORITHMS A class that contains static functions for -% decoding the hidden states of linear discrete stochastic systems or -% hybrid linear discrete stochastic systems subject to gaussian noise. -% The observations can come from either a gaussian observation model -% or via a point process observation model. -% -% methods -% Reference page in Help browser -% doc DecodingAlgorithms - - -% -% nSTAT v1 Copyright (C) 2012 Masschusetts Institute of Technology -% Cajigas, I, Malik, WQ, Brown, EN -% This program is free software; you can redistribute it and/or -% modify it under the terms of the GNU General Public License as published -% by the Free Software Foundation; either version 2 of the License, or -% (at your option) any later version. -% -% This program is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -% See the GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with this program; if not, write to the Free Software Foundation, -% Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - properties - end - - methods (Static) - - %% Point Process Adaptive Filter - %PPDecodeFilter takes an object of class CIF describing the - %conditional intensity function. This routine is more generic since - %all of the computations for the PPAF are done symbolically based - %on the CIF object. However, it also means that this version is - %must slower than the linear version below. - function [x_p, W_p, x_u, W_u, x_uT,W_uT,x_pT, W_pT, WConvIter] = PPDecodeFilter(A, Q, Px0, dN,lambdaCIFColl,binwidth,x0,Pi0, yT,PiT,estimateTarget,Wconv) - % A can be static or can be a different matrix for each time N - if(nargin<13||isempty(Wconv)) - Wconv =[]; - end - [C,N] = size(dN); % N time samples, C cells - - ns=size(A,1); % number of states - - - if(nargin<12 || isempty(estimateTarget)) - estimateTarget=0; - end - - if(nargin<11 || isempty(PiT)) - if(estimateTarget==1) - PiT = zeros(size(Q)); - else - PiT = 0*diag(ones(ns,1))*1e-6; - end - end - if(nargin<9 || isempty(Pi0)) - Pi0 = zeros(ns,ns); - end - if(nargin<10 || isempty(yT)) - yT=[]; - Amat = A; - Qmat = Q; - ft = zeros(size(Amat,2),N); - PiT = zeros(size(Q)); - - else - - - PitT= zeros(ns,ns,N); % Pi(t,T) in Srinivasan et al. - QT = zeros(ns,ns,N); % The noise covaraince given target observation (Q_t) - if(estimateTarget==1) - PitT(:,:,N)=Q; % Pi(T,T)=Pi_T + Q_T, setting PiT=0 - else - PitT(:,:,N)=PiT+Q; - end - PhitT = zeros(ns,ns,N);% phi(t,T) - transition matrix from time T to t - % PhiTt = zeros(ns,ns,N);% phi(T,t) - transition matrix from time t to T - PhitT(:,:,N) = eye(ns,ns); % phi(T,T) = I - B = zeros(ns,ns,N); % See Equation 2.21 in Srinivasan et. al - - for n=N:-1:2 - invA=eye(size(A))/A; - % state transition matrix - PhitT(:,:,n-1)= invA*PhitT(:,:,n); - % PhiTt(:,:,n)= A^(N-n); - - % Equation 2.16 in Srinivasan et al. Note there is a typo in the paper. - % This is the correct expression. The term Q_t-1 does not - % need to be mulitplied by phi(t-1,t) - - PitT(:,:,n-1) = invA*PitT(:,:,n)*invA'+Q; - - - - if(n<=N) - B(:,:,n) = A-(Q/PitT(:,:,n))*A; %Equation 2.21 in Srinivasan et. al - QT(:,:,n) = Q-(Q/PitT(:,:,n))*Q'; - end - end - % PhiTt(:,:,1)= A^(N-1); - B(:,:,1) = A-(Q/PitT(:,:,1))*A; - QT(:,:,1) = Q-(Q/PitT(:,:,1))*Q'; - % See Equations 2.23 through 2.26 in Srinivasan et. al - if(estimateTarget==1) - % beta = [beta ;zeros(ns,C)]; - for n=1:N - psi = B(:,:,n); - if(n==N) - gammaMat = eye(ns,ns); - else - gammaMat = (Q/PitT(:,:,n))*PhitT(:,:,n); - end - Amat(:,:,n) = [psi,gammaMat; - zeros(ns,ns), eye(ns,ns)]; - % if(n>1) - % tUnc(:,:,n) = tUnc(:,:,n-1)+PhiTt(:,:,n)*Q*PhiTt(:,:,n)'; - % else - % tUnc(:,:,n) = PhiTt(:,:,n)*Q*PhiTt(:,:,n)'; - % end - Qmat(:,:,n) = [QT(:,:,n), zeros(ns,ns); - zeros(ns,ns) zeros(ns,ns)]; - end - else - - Amat = B; - Qmat = QT; - for n=1:N - ft(:,n) = (Q/PitT(:,:,n))*PhitT(:,:,n)*yT; - end - - end - - end - - if(nargin<8 || isempty(x0)) - x0=zeros(size(A,2),1); - end - - if(nargin<7) - binwidth = .001; % in seconds - end - - %% - % Return values are - % x_p: state estimates given the past x_k|k-1 - % W_p: error covariance estimates given the past - % x_u: state updates given the data - x_k|k - % W_u: error covariance updates given the data - - [C,N] = size(dN); % N time samples, C cells - - %% Initialize the PPAF - x_p = zeros( size(Amat,2), N+1 ); - x_u = zeros( size(Amat,2), N ); - W_p = zeros( size(Amat,2),size(Amat,2), N+1 ); - W_u = zeros( size(Amat,2),size(Amat,2), N ); - - - - - if(~isempty(yT)) - if(det(Pi0)==0) % Assume x0 is known exactly - - else %else - invPi0 = pinv(Pi0); - invPitT= pinv(PitT(:,:,1)); - Pi0New = pinv(invPi0+invPitT); - Pi0New(isnan(Pi0New))=0; - x0New = Pi0New*(invPi0*x0+invPitT*PhitT(:,:,1)*yT); - x0=x0New; Pi0 = Pi0New; - end - end - if(~isempty(yT) && estimateTarget==1) - x0= [x0;yT]; %simultaneous estimation of target requires state augmentation - - end - - - if((estimateTarget==1 && ~isempty(yT)) || isempty(yT)) - x_p(:,1)= Amat(:,:,1)*x0; - - else - invPitT = pinv(PitT(:,:,1)); - % invPhitT = pinv(PhitT(:,:,1)); - invA = pinv(A); - invPhi0T = pinv(invA*PhitT(:,:,1)); - ut(:,1) = (Q*invPitT)*PhitT(:,:,1)*(yT-invPhi0T*x0); - [x_p(:,1), W_p(:,:,1)] = DecodingAlgorithms.PPDecode_predict(x0, Pi0, Amat(:,:,min(size(Amat,3),n)), Qmat(:,:,min(size(Qmat,3)))); - x_p(:,1) = x_p(:,1)+ut(:,1); - W_p(:,:,1) = W_p(:,:,1) + (Q*invPitT)*A*Pi0*A'*(Q*invPitT)'; - - % x_p(:,1)= Amat(:,:,1)*x0 + ft(:,1); - - - end - if(estimateTarget==1 && ~isempty(yT)) - Pi0New = [Pi0, zeros(ns,ns); - zeros(ns,ns) , zeros(ns,ns)]; - W_p(:,:,1) = Amat(:,:,1)*Pi0New*Amat(:,:,1)'+Qmat(:,:,1); - elseif(estimateTarget==0 && isempty(yT)) - - W_p(:,:,1) = Amat(:,:,1)*Pi0*Amat(:,:,1)'+Qmat(:,:,1); - end %Otherwise we computed it above. - - - for n=1:N - [x_u(:,n), W_u(:,:,n)] = DecodingAlgorithms.PPDecode_update( x_p(:,n), W_p(:,:,n), dN(:,1:n),lambdaCIFColl, binwidth,n); - % [x_p(:,n+1), W_p(:,:,n+1)] = DecodingAlgorithms.PPDecode_predict(x_u(:,n), W_u(:,:,n), Amat(:,:,min(size(A,3),n)), Qmat(:,:,min(size(Qmat,3)))); - - if((estimateTarget==1 && ~isempty(yT)) || isempty(yT)) - [x_p(:,n+1), W_p(:,:,n+1)] = DecodingAlgorithms.PPDecode_predict(x_u(:,n), W_u(:,:,n), Amat(:,:,min(size(A,3),n)), Qmat(:,:,min(size(Qmat,3)))); - else - %ut= Q_{t}\Pi(t,T)^{-1}\phi(t,T)(y_{T}-phi(T,t-1)x_{t-1} - if(n1 && isempty(Wconv)) - diffWun = abs(trace(W_u(:,:,n))-W_u(:,:,n-1)); - mAbsdiffWun = max(max(diffWun)); - if(mAbsdiffWun<1e-6) - Wconv=W_u(:,:,n); - WConvIter = n; - else - WConvIter=[]; - end - - end - - - end - if(~isempty(yT) && estimateTarget==1) - %decompose the augmented state space into estimates of the state - %vector and the target position - x_uT = x_u(ns+1:2*ns,:); - W_uT = W_u(ns+1:2*ns,ns+1:2*ns,:); - x_pT = x_p(ns+1:2*ns,:); - W_pT = W_p(ns+1:2*ns,ns+1:2*ns,:); - - x_u = x_u(1:ns,:); - W_u = W_u(1:ns,1:ns,:); - x_p = x_p(1:ns,:); - W_p = W_p(1:ns,1:ns,:); - - else - x_uT = []; - W_uT = []; - x_pT = []; - W_pT = []; - - end - - - end - %PPDecodeFilterLinear takes in a linear representation of the - %conditional intensity terms. These are the terms that are inside - %the exponential in a Poisson or Binomial description of the CIF. - %If such a representation is available, use of this routine is - %recommended because it is much faster. - function [x_p, W_p, x_u, W_u, x_uT,W_uT,x_pT, W_pT] = PPDecodeFilterLinear(A, Q, dN,mu,beta,fitType,delta,gamma,windowTimes,x0, Pi0, yT,PiT,estimateTarget,Wconv) - % [x_p, W_p, x_u, W_u] = PPDecodeFilterLinear(CIFType,A, Q, dN,beta,gamma,x0, xT) - % Point process adaptive filter with the assumption of linear - % expresion for the conditional intensity functions (see below). If - % the terms in the conditional intensity function include - % polynomial powers of a variable for example, these expressions do - % not hold. Use the PPDecodeFilter instead since it will compute - % these expressions symbolically. However, because of the matlab - % symbolic toolbox, it runs much slower than this version. - % - % If a final value for xT is given then the approach of Srinivasan - % et. al (2006) is used for concurrent estimate of the state and - % the target. This involves state augmentation of the original - % state space model. If a final value is not specified then the - % standard Point Process Adaptive Filter of Eden et al (2004) is - % used instead. - % - % Assumes in both cases that - % x_t = A*x_{t-1} + w_{t} w_{t} ~ Normal with zero me and - % covariance Q - % - % - % Paramerters: - % - % A: The state transition matrix from the x_{t-1} to x_{t} - % - % Q: The covariance of the process noise w_t - % - % dN: A C x N matrix of ones and zeros corresponding to the - % observed spike trains. N is the number of time steps in - % my code. C is the number of cells - % - % mu: Cx1 vector of baseline firing rates for each cell. In - % the CIF expression in 'fitType' description - % mu_c=mu(c); - % - % beta: nsxC matrix of coefficients for the conditional - % intensity function. ns is the number of states in x_t - % In the conditional intesity function description below - % beta_c = beta(:,c)'; - % - % fitType: 'poisson' or 'binomial'. Determines how the beta and - % gamma coefficients are used to compute the conditional - % intensity function. - % For the cth cell: - % If poisson: lambda*delta = exp(mu_c+beta_c*x + gamma_c*hist_c) - % If binomial: logit(lambda*delta) = mu_c+beta_c*x + gamma_c*hist_c - % - % delta: The number of seconds per time step. This is used to compute - % th history effect for each spike train using the input - % windowTimes and gamma - % - % gamma: length(windowTimes)-1 x C matrix of the history - % coefficients for each window in windowTimes. In the 'fitType' - % expression above: - % gamma_c = gamma(:,c)'; - % If gamma is a length(windowTimes)-1x1 vector, then the - % same history coefficients are used for each cell. - % - % windowTimes: Defines the distinct windows of time (in seconds) - % that will be computed for each spike train. - % - % xT: Target Position - % - % PiT: Target Uncertainty - % - % estimateTarget: By default (==0), it is assumed that that the - % initial target information is fixed. Set to 1 in order to - % simultaneously estimate the target location via - % state augmentation - % - % - % - % Code for reaching to final target adapted from: - % L. Srinivasan, U. T. Eden, A. S. Willsky, and E. N. Brown, - % "A state-space analysis for reconstruction of goal-directed - % movements using neural signals.," - % Neural computation, vol. 18, no. 10, pp. 2465?2494, Oct. 2006. - % - % Point Process Adaptive Filter from - % U. T. Eden, L. M. Frank, R. Barbieri, V. Solo, and E. N. Brown, - % "Dynamic analysis of neural encoding by point process adaptive - % filtering.," - % Neural computation, vol. 16, no. 5, pp. 971?998, May. 2004. - - if(nargin<15||isempty(Wconv)) - Wconv =[]; - end - [C,N] = size(dN); % N time samples, C cells - ns=size(A,1); % number of states - - if(nargin<14 || isempty(estimateTarget)) - estimateTarget=0; - end - if(nargin<10 || isempty(x0)) - x0=zeros(ns,1); - - end - if(nargin<9 || isempty(windowTimes)) - windowTimes=[]; - end - if(nargin<8 || isempty(gamma)) - gamma=0; - end - if(nargin<7 || isempty(delta)) - delta = .001; - end - - if(nargin<13 || isempty(PiT)) - if(estimateTarget==1) - PiT = zeros(size(Q)); - else - PiT = 0*diag(ones(ns,1))*1e-6; - end - end - if(nargin<11 || isempty(Pi0)) - Pi0 = zeros(ns,ns); - end - if(nargin<12 || isempty(yT)) - yT=[]; - Amat = A; - Qmat = Q; - ft = zeros(size(Amat,2),N); - PiT = zeros(size(Q)); - - else - - - PitT= zeros(ns,ns,N); % Pi(t,T) in Srinivasan et al. - QT = zeros(ns,ns,N); % The noise covaraince given target observation (Q_t) - QN =Q(:,:,min(size(Q,3),N)); - if(estimateTarget==1) - - PitT(:,:,N)=QN; % Pi(T,T)=Pi_T + Q_T, setting PiT=0 - else - PitT(:,:,N)=PiT+QN; - end - PhitT = zeros(ns,ns,N);% phi(t,T) - transition matrix from time T to t - % PhiTt = zeros(ns,ns,N);% phi(T,t) - transition matrix from time t to T - PhitT(:,:,N) = eye(ns,ns); % phi(T,T) = I - B = zeros(ns,ns,N); % See Equation 2.21 in Srinivasan et. al - - for n=N:-1:2 - An =A(:,:,min(size(A,3),n)); - Qn =Q(:,:,min(size(Q,3),n)); - - invA=pinv(An); - % state transition matrix - PhitT(:,:,n-1)= invA*PhitT(:,:,n); - % PhiTt(:,:,n)= A^(N-n); - - % Equation 2.16 in Srinivasan et al. Note there is a typo in the paper. - % This is the correct expression. The term Q_t-1 does not - % need to be mulitplied by phi(t-1,t) - - PitT(:,:,n-1) = invA*PitT(:,:,n)*invA'+Qn; - - - - if(n<=N) - - B(:,:,n) = An-(Qn*pinv(PitT(:,:,n)))*An; %Equation 2.21 in Srinivasan et. al - QT(:,:,n) = Qn-(Qn*pinv(PitT(:,:,n)))*Qn'; - end - end - A1=A(:,:,min(size(A,3),1)); - Q1=Q(:,:,min(size(Q,3),1)); - B(:,:,1) = A1-(Q1*pinv(PitT(:,:,1)))*A1; - QT(:,:,1) = Q1-(Q1*pinv(PitT(:,:,1)))*Q1'; - - % See Equations 2.23 through 2.26 in Srinivasan et. al - if(estimateTarget==1) - beta = [beta ;zeros(ns,C)]; - for n=1:N - An =A(:,:,min(size(A,3),n)); - Qn =Q(:,:,min(size(Q,3),n)); - psi = B(:,:,n); - if(n==N) - gammaMat = eye(ns,ns); - else - gammaMat = (Qn*pinv(PitT(:,:,n)))*PhitT(:,:,n); - end - Amat(:,:,n) = [psi,gammaMat; - zeros(ns,ns), eye(ns,ns)]; - Qmat(:,:,n) = [QT(:,:,n), zeros(ns,ns); - zeros(ns,ns) zeros(ns,ns)]; - end - else - - Amat = B; - Qmat = QT; - for n=1:N - An =A(:,:,min(size(A,3),n)); - Qn =Q(:,:,min(size(Q,3),n)); - ft(:,n) = (Qn*pinv(PitT(:,:,n)))*PhitT(:,:,n)*yT; - end - - end - - end - - - minTime=0; - maxTime=(size(dN,2)-1)*delta; - - C=size(dN,1); - if(~isempty(windowTimes)) - histObj = History(windowTimes,minTime,maxTime); - HkAll = zeros(size(dN,2),length(windowTimes)-1,C); - for c=1:C - nst{c} = nspikeTrain( (find(dN(c,:)==1)-1)*delta); - nst{c}.setMinTime(minTime); - nst{c}.setMaxTime(maxTime); - nst{c}=nst{c}.resample(1/delta); - HkAll(:,:,c) = histObj.computeHistory(nst{c}).dataToMatrix; - % HkAll{c} = histObj.computeHistory(nst{c}).dataToMatrix; - end - if(size(gamma,2)==1 && C>1) % if more than 1 cell but only 1 gamma - gammaNew(:,c) = gamma; - else - gammaNew=gamma; - end - gamma = gammaNew; - - else - for c=1:C - % HkAll{c} = zeros(N,1); - HkAll(:,:,c) = zeros(N,1); - gammaNew(c)=0; - end - gamma=gammaNew; - - end - if(size(gamma,2)~=C) - gamma=gamma'; - end - - - - % Initialize the PPAF - x_p = zeros( size(Amat,2), N+1 ); - x_u = zeros( size(Amat,2), N ); - W_p = zeros( size(Amat,2),size(Amat,2), N+1 ); - W_u = zeros( size(Amat,2),size(Amat,2), N ); - - - - - if(~isempty(yT)) - if(det(Pi0)==0) % Assume x0 is known exactly - - else %else - invPi0 = pinv(Pi0); - invPitT= pinv(PitT(:,:,1)); - Pi0New = pinv(invPi0+invPitT); - Pi0New(isnan(Pi0New))=0; - x0New = Pi0New*(invPi0*x0+invPitT*PhitT(:,:,1)*yT); - x0=x0New; Pi0 = Pi0New; - end - end - if(~isempty(yT) && estimateTarget==1) - x0= [x0;yT]; %simultaneous estimation of target requires state augmentation - - end - - - if((estimateTarget==1 && ~isempty(yT)) || isempty(yT)) - x_p(:,1)= Amat(:,:,1)*x0; - - else - invPitT = pinv(PitT(:,:,1)); - % invPhitT = pinv(PhitT(:,:,1)); - A1 = A(:,:,min(size(A,3),1)); - Q1 = Q(:,:,min(size(Q,3),1)); - invA = pinv(A1); - invPhi0T = pinv(invA*PhitT(:,:,1)); - ut(:,1) = (Q1*invPitT)*PhitT(:,:,1)*(yT-invPhi0T*x0); - [x_p(:,1), W_p(:,:,1)] = DecodingAlgorithms.PPDecode_predict(x0, Pi0, Amat(:,:,min(size(Amat,3),n)), Qmat(:,:,min(size(Qmat,3)))); - x_p(:,1) = x_p(:,1)+ut(:,1); - W_p(:,:,1) = W_p(:,:,1) + (Q1*invPitT)*A1*Pi0*A1'*(Q1*invPitT)'; - - % x_p(:,1)= Amat(:,:,1)*x0 + ft(:,1); - - - end - if(estimateTarget==1 && ~isempty(yT)) - Pi0New = [Pi0, zeros(ns,ns); - zeros(ns,ns) , zeros(ns,ns)]; - W_p(:,:,1) = Amat(:,:,1)*Pi0New*Amat(:,:,1)'+Qmat(:,:,1); - elseif(estimateTarget==0 && isempty(yT)) - - W_p(:,:,1) = Amat(:,:,1)*Pi0*Amat(:,:,1)'+Qmat(:,:,1); - end %Otherwise we computed it above. - - HkPerm = permute(HkAll,[2 3 1]); - clear t; - for n=1:N - - - [x_u(:,n), W_u(:,:,n)] = DecodingAlgorithms.PPDecode_updateLinear(x_p(:,n), W_p(:,:,n), dN,mu,beta,fitType,gamma,HkPerm,n,Wconv); - % The prediction step is identical to the symbolic implementation since - % it is independent of the CIF - - if((estimateTarget==1 && ~isempty(yT)) || isempty(yT)) - [x_p(:,n+1), W_p(:,:,n+1)] = DecodingAlgorithms.PPDecode_predict(x_u(:,n), W_u(:,:,n), Amat(:,:,min(size(Amat,3),n)), Qmat(:,:,min(size(Qmat,3))),Wconv); - else - %ut= Q_{t}\Pi(t,T)^{-1}\phi(t,T)(y_{T}-phi(T,t-1)x_{t-1} - if(n1) % if more than 1 cell but only 1 gamma - gammaNew(:,c) = gamma; - else - gammaNew=gamma; - end - gamma = gammaNew; - - else - for c=1:C -% HkAll{c} = zeros(N,1); - HkAll(:,:,c) = zeros(N,1); - gammaNew(c)=0; - end - gamma=gammaNew; - - end - if(size(gamma,2)~=C) - gamma=gamma'; - end - - %% Initialize the PPAF - x_p = zeros( size(A,2), N+1 ); - x_u = zeros( size(A,2), N ); - W_p = zeros( size(A,2),size(A,2), N+1 ); - W_u = zeros( size(A,2),size(A,2), N ); - - % Assumes that the dynamics only start at time 1 so that A(:,:,0)=I - x_p(:,1) = x0; - W_p(:,:,1) = Pi0; - - HkPerm = permute(HkAll,[2 3 1]); - x_uLag = zeros(size(x_u)); - W_uLag = zeros(size(W_u)); - x_pLag = zeros(size(x_p)); - W_pLag = zeros(size(W_p)); - for n=1:N - [x_u(:,n), W_u(:,:,n)] = DecodingAlgorithms.PPDecode_updateLinear(x_p(:,n), W_p(:,:,n), dN,mu,beta,fitType,gamma,HkPerm,n); - [x_p(:,n+1), W_p(:,:,n+1)] = DecodingAlgorithms.PPDecode_predict(x_u(:,n), W_u(:,:,n), A(:,:,min(size(A,3),n)), Q(:,:,min(size(Q,3),n))); - x_K=zeros(ns, lags); - W_K=zeros(ns,ns,lags); - LnMinusk=zeros(ns, ns, lags); - if(n>(lags)) - for k=1:lags - - LnMinusk(:,:,k)=W_u(:,:,n-k)*A(:,:,min(size(A,3),n-k))'/W_p(:,:,n+1-k); - if(k==1) - x_K(:,k) = x_u(:,n-k)+LnMinusk(:,:,k)*(x_u(:,n+1-k)-x_p(:,n+1-k)); - W_K(:,:,k)=W_u(:,:,n-k)+LnMinusk(:,:,k)*(W_u(:,:,n+1-k)-W_p(:,:,n+1-k))*LnMinusk(:,:,k)'; - else - x_K(:,k) = x_u(:,n-k)+LnMinusk(:,:,k)*(x_K(:,k-1)-x_p(:,n+1-k)); - W_K(:,:,k)=W_u(:,:,n-k)+LnMinusk(:,:,k)*(W_K(:,:,k-1)-W_p(:,:,n+1-k))*LnMinusk(:,:,k)'; - end - W_K(:,:,k) = 0.5*(W_K(:,:,k)+W_K(:,:,k)'); - end - - end - - x_uLag(:,n)=x_K(:,lags); - W_uLag(:,:,n)=W_K(:,:,lags); - if(lags>1) - x_pLag(:,n+1)=x_K(:,lags-1); - W_pLag(:,:,n+1)=W_K(:,:,lags); - else - x_pLag(:,n+1)=x_u(:,n); - W_pLag(:,:,n+1)=W_u(:,:,n); - end - - end - - end - % PPAF Prediction Step - function [x_p, W_p] = PPDecode_predict(x_u, W_u, A, Q,Wconv) - if((nargin<5)||isempty(Wconv)) - Wconv=[]; - end - % The PPDecode prediction step - x_p = A * x_u; - - if(isempty(Wconv)) - W_p = A * W_u * A' + Q; - condNum=rcond(W_p); - if(condNum1))=1; - sumValMat = (repmat(tempVec,size(beta,1),1).*beta)*beta'; - elseif(strcmp(fitType,'poisson')) - Histterm = HkAll(:,:,time_index); - - if(~any(gamma~=0)) - Histterm = Histterm'; - end - if(size(Histterm,2)~=size(mu,1)) - Histterm=Histterm'; - end - linTerm = mu+beta'*x_p + diag(gamma'*Histterm); - lambdaDeltaMat = exp(linTerm); - if(any(isnan(lambdaDeltaMat))||any(isinf(lambdaDeltaMat))) - indNan = isnan(lambdaDeltaMat); - indInf = isinf(lambdaDeltaMat); - lambdaDeltaMat(indNan)=1; - lambdaDeltaMat(indInf)=1; - end - sumValVec=sum(repmat(((dN(:,time_index)-lambdaDeltaMat(:,1)))',size(beta,1),1).*beta,2); - sumValMat = (repmat(lambdaDeltaMat(:,1)',size(beta,1),1).*beta)*beta'; - end - if(isempty(WuConv)) - usePInv=0; - if(usePInv==1) - % Use pinv so that we do a SVD and ignore the zero singular values - % Sometimes because of the state space model definition and how information - % is integrated from distinct CIFs the sumValMat is very sparse. This - % allows us to prevent inverting singular matrices - I=eye(size(W_p)); - Wu=W_p*(I-(I+sumValMat*W_p)\(sumValMat*W_p)); - condNum=rcond(Wu); - if(condNum1) - % tUnc(:,:,n) = tUnc(:,:,n-1)+PhiTt(:,:,n)*Q*PhiTt(:,:,n)'; - % else - % tUnc(:,:,n) = PhiTt(:,:,n)*Q*PhiTt(:,:,n)'; - % end - Qmat{s}(:,:,n) = [QT{s}(:,:,n), zeros(ns(s),ns(s)); - zeros(ns(s),ns(s)) zeros(ns(s),ns(s))]; - - - - end - - Pi0new{s} = [Pi0{s}, zeros(ns(s),ns(s)); - zeros(ns(s),ns(s)) zeros(ns(s),ns(s))]; - - else - - Amat{s} = B{s}; - Qmat{s} = QT{s}; - for n=1:N - ft{s}(:,n) = (Q{s}*pinv(PitT{s}(:,:,n)))*PhitT{s}(:,:,n)*yT{s}; - end - - end - - end - if(estimateTarget==1) - Pi0 = Pi0new; - - end - beta = betaNew; - end - - if(nargin<12 || isempty(x0)) - for s=1:nmodels - x0{s}=zeros(size(Amat{s},2),1); - end - end - - if(nargin<9) - binwidth=0.001; %1 msec - end - - if(isa(A,'cell')) - dimMat = zeros(1,length(Amat)); - X_u = cell(1,length(Amat)); - W_u = cell(1,length(Amat)); - X_p = cell(1,length(Amat)); - W_p = cell(1,length(Amat)); - ind = cell(1,length(Amat)); - ut = cell(1,length(Amat)); - - for i=1:length(Amat) - lambdaDeltaMat{i} = zeros(size(dN)); - X_u{i} = zeros(size(Amat{i},1), size(dN,2)); - X_p{i} = zeros(size(Amat{i},1), size(dN,2)+1); - W_u{i} = zeros(size(Amat{i},1), size(Amat{i},1), size(dN,2)); - W_p{i} = zeros(size(Amat{i},1), size(Amat{i},1), size(dN,2)+1); - dimMat(i) = size(Amat{i},2); - W_u{i}(:,:,1) =Pi0{i}; - ind{i} = 1:dimMat(i); - ut{i} = zeros(size(Amat{i},1), size(dN,2)); - end - end - - maxDim = max(dimMat); - % nmodels = length(Amat); - % lambdaCIFColl = CIFColl(lambda); - - minTime=0; - maxTime=(size(dN,2)-1)*binwidth; - - C=size(dN,1); - - if(nargin<11 || isempty(windowTimes)) - for c=1:C - HkAll(:,:,c) = zeros(N,1); - gammaNew(c)=0; - end - gamma=gammaNew; - else - histObj = History(windowTimes,minTime,maxTime); - for c=1:C - nst{c} = nspikeTrain( (find(dN(c,:)==1)-1)*binwidth); - nst{c}.setMinTime(minTime); - nst{c}.setMaxTime(maxTime); - nst{c}=nst{c}.resample(1/delta); - HkAll(:,:,c) = histObj.computeHistory(nst{c}).dataToMatrix; - end - if(size(gamma,2)==1 && C>1) % if more than 1 cell but only 1 gamma - gammaNew(:,c) = gamma; - end - gamma = gammaNew; - - end - % Overall estimates of Hybrid filter - X = zeros(maxDim, size(dN,2)); % Estimated Trajectories - W = zeros(maxDim, maxDim, size(dN,2)); % Covariance of estimate - % Individual Model Estimates - for i=1:nmodels - X_s{i} = X; % Individual Model Estimates - W_s{i} = W; % Individual Model Covariances - end - % Model probabilities - MU_u = zeros(nmodels,size(dN,2)); % P(s_k | H_k+1) % updated state probabilities - MU_p = zeros(nmodels,size(dN,2)); % P(s_k | H_k) % prediction state probabilities - pNGivenS = zeros(nmodels,size(dN,2)); - - - %mu_0|1 = mu_0|0; - if(isempty(Mu0)) - Mu0 = ones(nmodels,1)*1/nmodels; - elseif(size(Mu0,1)==nmodels && size(Mu0,2)==1) - Mu0 = Mu0; - elseif(size(Mu0,1)==1 && size(Mu0,2)==nmodels) - Mu0 = Mu0'; - else - error('Mu0 must be a column or row vector with the same number of dimensions as the number of states'); - end - for s=1:nmodels - [X_p{s}(ind{s},1),W_p{s}(ind{s},ind{s},1)] = DecodingAlgorithms.PPDecode_predict(x0{s}(ind{s}), Pi0{s}(ind{s},ind{s}), Amat{s}(ind{s},ind{s},min(size(Amat{s},3),1)), Qmat{s}(:,:,min(size(Qmat{s},3)))); - - if((estimateTarget==0 && ~isempty(yT{s}))) - invA= pinv(Amat{s}(:,:,min(size(Amat,3),1))); - ut{s}(:,1) = (Q{s}*pinv(PitT{s}(:,:,1)))*PhitT{s}(:,:,1)*(yT{s}-pinv(invA*PhitT{s}(:,:,1))*x0{s}); - X_p{s}(ind{s},1) = X_p{s}(ind{s},1)+ut{s}(:,1); - W_p{s}(ind{s},ind{s},1) =W_p{s}(ind{s},ind{s},1) + (Q{s}*pinv(PitT{s}(:,:,1)))*A{s}*Pi0{s}*A{s}'*(Q{s}*pinv(PitT{s}(:,:,1)))'; - end - end - - % [~, S_est(1)] = max(MU_p(:,1)); %Most likely current state - - %State transition Probabilities must integrate to 1 - sumVal = sum(p_ij,2); - if(any(sumVal~=1)) - error('State Transition probability matrix must sum to 1 along each row'); - end - %% 9 Steps - % Filtering steps. - HkPerm=permute(HkAll,[2 3 1]); - for k = 1:(size(dN,2)) - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % Step 1 - p(s_k | H_k) = Sum(p(s_k|s_k-1)*p(s_k-1|H_k)) - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %MU(:,k)_p= [ p(s_k=1 | H_k)] is a vector of the probabilities - % [ p(s_k=2 | H_k)] - % . - % . - % . - % [ p(s_k=N | H_k)] - % thus it is an prediction of the discrete state at time k given all - % of the neural firing up to k-1 as summarized in H_k - % - % Whereas - % MU_u(:,k)=[ p(s_k=1 | H_k+1)] is a vector of the probabilities - % [ p(s_k=2 | H_k+1)] - % . - % . - % . - % [ p(s_k=N | H_k+1)] - % The s suffix indicates that this is a "smoothed" estimate of - % the state given the firing up to time k summarized in H_k+1 - if k==1 - MU_p(:,k) = p_ij'*Mu0; %state probability prediction equation - else - MU_p(:,k) = p_ij'*MU_u(:,k-1); - end - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % Step 2 - p(s_k-1 | s_k, H_k) - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % This is a matrix with i,j entry indicating the probability that - % s_k-1 = j given than s_k = i - % - % MU_p is the normalization factor. The first column of the - % matrix of probabilities is: - % - % P(s_k-1=1 | s_k=1,H_k) ~ P(s_k=1|s_k-1=1,H_k)*P(s_k-1=1|H_k) - % P(s_k-1=1 | s_k=2,H_k) ~ P(s_k=2|s_k-1=1,H_k)*P(s_k-1=1|H_k) - % - % And the second columns ... etc - % - % - % P(s_k-1=2 | s_k=1,H_k) ~ P(s_k=1|s_k-1=2,H_k)*P(s_k-1=1|H_k) - % P(s_k-1=2 | s_k=2,H_k) ~ P(s_k=2|s_k-1=2,H_k)*P(s_k-1=1|H_k) - - if(k==1) - p_ij_s= p_ij.*(Mu0*ones(1,nmodels));%.*(ones(nmodels,1)*(1./MU_p(:,k))'); - else - p_ij_s= p_ij.*(MU_u(:,k-1)*ones(1,nmodels));%.*(ones(nmodels,1)*(1./MU_p(:,k))'); - end - % - % To avoid any numerical issues with roundoff, we normalize to - % 1 again - normFact = repmat(sum(p_ij_s,1),[nmodels 1]); %Every column must sum to 1 - - p_ij_s = p_ij_s./normFact; - % for i=1:length(normFact) - % if(normFact(i)~=0) - % p_ij_s(:,i) = p_ij_s(:,i)./normFact(i); - % else %reset all the states to be equally likely (each row must sum to 1) - % p_ij_s(:,i) = 1/nmodels*ones(nmodels,1); - % end - % end - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % Step 3 - Approximate p(x_k-1 | s_k, H_k) with Gaussian - % approximation to Mixtures of Gaussians - % Calculate the mixed state mean for each filter - % This will be the initial states for the update step of the - % Point Process Adaptive Filter - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - - - for j = 1:nmodels - for i = 1:nmodels - if(k>1) - X_s{j}(ind{i},k) = X_s{j}(ind{i},k) + X_u{i}(ind{i},k-1)*p_ij_s(i,j); - else - X_s{j}(ind{i},k) = X_s{j}(ind{i},k) + x0{i}(ind{i})*p_ij_s(i,j); - end - end - end - - % Calculate the mixed state covariance for each filter - - for j = 1:nmodels - for i = 1:nmodels - if(k>1) - W_s{j}(ind{i},ind{i},k) = W_s{j}(ind{i},ind{i},k) + (W_u{i}(ind{i},ind{i},k-1) + (X_u{i}(ind{i},k-1)-X_s{j}(ind{i},k))*(X_u{i}(ind{i},k-1)-X_s{j}(ind{i},k))')*p_ij_s(i,j); - else - W_s{j}(ind{i},ind{i},k) = W_s{j}(ind{i},ind{i},k) + (Pi0{i}(ind{i},ind{i})+ (x0{i}(ind{i})-X_s{j}(ind{i},k))*(x0{i}(ind{i})-X_s{j}(ind{i},k))')*p_ij_s(i,j); - end - end - end - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % Step 4 - Approximate p(x_k+1 |s_k+1,n_k+1,H_k+1) - % Uses a bank of nmodel point process filters - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % k - - for s=1:nmodels - - % Prediction Step - [X_p{s}(ind{s},k),W_p{s}(ind{s},ind{s},k)] = DecodingAlgorithms.PPDecode_predict(X_s{s}(ind{s},k), W_s{s}(ind{s},ind{s},k), Amat{s}(:,:,min(size(Amat,3),k)), Qmat{s}(:,:,min(size(Qmat{s},3)))); - - if(estimateTarget==0 && ~isempty(yT{s})) - if(k>1) - ut{s}(:,k) = (Q{s}*pinv(PitT{s}(:,:,k)))*PhitT{s}(:,:,k)*(yT{s}-pinv(PhitT{s}(:,:,k-1))*X_s{s}(ind{s},k)); - else - invA = pinv(A{s}(:,:,min(size(A{s},3),1))); - ut{s}(:,k) = (Q{s}*pinv(PitT{s}(:,:,1)))*PhitT{s}(:,:,1)*(yT{s}-pinv(invA*PhitT{s}(:,:,1))*X_s{s}(ind{s},k)); - end - X_p{s}(ind{s},k) = X_p{s}(ind{s},k)+ut{s}(:,k); - W_p{s}(ind{s},ind{s},k) =W_p{s}(ind{s},ind{s},k) + (Q{s}*pinv(PitT{s}(:,:,k)))*A{s}*W_s{s}(ind{s},ind{s},k)*A{s}'*(Q{s}*pinv(PitT{s}(:,:,k)))'; - - end - - % Update Step - % Fold in the neural firing in the current time step - [X_u{s}(ind{s},k),W_u{s}(ind{s},ind{s},k),lambdaDeltaMat{s}(:,k)] = DecodingAlgorithms.PPDecode_updateLinear(X_p{s}(ind{s},k),squeeze(W_p{s}(ind{s},ind{s},k)),dN,mu,beta{s}(ind{s},:),fitType,gamma,HkPerm,k); - - - end - % pause; - % close all; plot(lambdaDeltaMat{1}(:,k),'k.'); hold on; plot(lambdaDeltaMat{2}(:,k),'b*'); - % - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % Step 5 - p(n_k | s_k, H_k) using Laplace approximation - % See General-purpose filter design for neural prosthetic devices. - % Srinivasan L, Eden UT, Mitter SK, Brown EN. - % J Neurophysiol. 2007 Oct;98(4):2456-75. Epub 2007 May 23. - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - - - for s=1:nmodels - - tempPdf = sqrt(det(W_u{s}(:,:,k)))./sqrt(det(W_p{s}(:,:,k)))*prod(exp(dN(:,k).*log(lambdaDeltaMat{s}(:,k))-lambdaDeltaMat{s}(:,k))); - pNGivenS(s,k) = tempPdf; - end - tempData = pNGivenS(:,k); - tempData(isinf(tempData))=0; - pNGivenS(:,k) = tempData; - - normFact = sum(pNGivenS(:,k)); - if(normFact~=0 && ~isnan(normFact)) - pNGivenS(:,k)=pNGivenS(:,k)./sum(pNGivenS(:,k)); - else - - if(k>1) - pNGivenS(:,k) = pNGivenS(:,k-1); - else - pNGivenS(:,k) = .5*ones(nmodels,1); - end - end - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % Step 6 - Calculate p(s_k | n_k, H_k) = p(s_k | H_k+1) - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - pSGivenN(:,k) = MU_p(:,k).*pNGivenS(:,k); - - - - %Normalization Factor - normFact = sum(pSGivenN(:,k)); - if(normFact~=0 && ~isnan(normFact)) - pSGivenN(:,k) = pSGivenN(:,k)./sum(pSGivenN(:,k)); - else - if(k>1) - pSGivenN(:,k) = pSGivenN(:,k-1); - else - pSGivenN(:,k) = Mu0; - end - - end - - - MU_u(:,k) = pSGivenN(:,k); %estimate of s_k given data up to k - - - [~, S_est(k)] = max(MU_u(:,k)); %Most likely current state - - if(MinClassificationError==1) - - s= S_est(k); - X(ind{s},k) = X_u{s}(ind{s},k); - W(ind{s},ind{s},k) = W_u{s}(ind{s},ind{s},k); - - else %Minimize the mean squared error - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % Step 7 - Calculate p(x_k | n_k, H_k) - using gaussian - % approximation to mixture of gaussians - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - for s=1:nmodels - X(ind{s},k) = X(ind{s},k)+MU_u(s,k)*X_u{s}(ind{s},k); - end - for s=1:nmodels - W(ind{s},ind{s},k) = W(ind{s},ind{s},k) +MU_u(s,k)*(W_u{s}(ind{s},ind{s},k) + (X_u{s}(ind{s},k)-X(ind{s},k))*(X_u{s}(ind{s},k)-X(ind{s},k))'); - end - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - end - end - - - %Solution to the known target problem. Run the Hybrid Filter - %Forward to determine the most likely states.... this is the - %sequence of the A dynamics matrices to use in the computation of - %the Target Reach Model of Srinivasan et al. Compute PiT - - end - function [S_est, X, W, MU_s, X_s, W_s,pNGivenS] = PPHybridFilter(A, Q, p_ij,Mu0,dN,lambdaCIFColl,binwidth,x0,Pi0, yT,PiT,estimateTarget,MinClassificationError) - - - % General-purpose filter design for neural prosthetic devices. - % Srinivasan L, Eden UT, Mitter SK, Brown EN. - % J Neurophysiol. 2007 Oct;98(4):2456-75. Epub 2007 May 23. - - [C,N] = size(dN); % N time samples, C cells - nmodels = length(A); - for s=1:nmodels - ns(s)=size(A{s},1); % number of states - end - nsMax = max(ns); - if(nargin<13 || isempty(MinClassificationError)) - MinClassificationError=0; %Minimum mean square error state estimate. By default do maximum likelihood - end - if(nargin<12 || isempty(estimateTarget)) - estimateTarget=0; - end - - if(nargin<11 || isempty(PiT)) - for s=1:nmodels - if(estimateTarget==1) - PiT{s} = zeros(size(Q{s})); - else - PiT{s} = 0*diag(ones(ns(s),1))*1e-6; - end - end - end - if(nargin<9 || isempty(Pi0)) - for s=1:nmodels - Pi0{s}(:,:) = zeros(ns(s),ns(s)); - end - end - if(nargin<10 || isempty(yT)) - for s=1:nmodels - yT{s}=[]; - Amat{s} = A{s}; - Qmat{s} = Q{s}; - ft{s} = zeros(size(Amat{s},2),N); - PiT{s} = zeros(size(Q{s})); - end - - else - Pi0new=cell(1,nmodels); - for s=1:nmodels - - PitT{s}= zeros(ns(s),ns(s),N); % Pi(t,T) in Srinivasan et al. - QT{s} = zeros(ns(s),ns(s),N); % The noise covaraince given target observation (Q_t) - if(estimateTarget==1) - PitT{s}(:,:,N)=Q{s}; % Pi(T,T)=Pi_T + Q_T, setting PiT=0 - else - PitT{s}(:,:,N)=PiT{s}+Q{s}; - end - PhitT{s} = zeros(ns(s),ns(s),N);% phi(t,T) - transition matrix from time T to t - % PhiTt = zeros(ns,ns,N);% phi(T,t) - transition matrix from time t to T - PhitT{s}(:,:,N) = eye(ns(s),ns(s)); % phi(T,T) = I - B{s} = zeros(ns(s),ns(s),N); % See Equation 2.21 in Srinivasan et. al - - for n=N:-1:2 - if(rcond(A{s})<1000*eps) - invA=pinv(A{s}); - else - invA=eye(size(A{s}))/A{s}; - end - % state transition matrix - PhitT{s}(:,:,n-1)= invA*PhitT{s}(:,:,n); - % PhiTt(:,:,n)= A^(N-n); - - % Equation 2.16 in Srinivasan et al. Note there is a typo in the paper. - % This is the correct expression. The term Q_t-1 does not - % need to be mulitplied by phi(t-1,t) - - PitT{s}(:,:,n-1) = invA*PitT{s}(:,:,n)*invA'+Q{s}; - - - if(n<=N) - B{s}(:,:,n) = A{s}-(Q{s}*pinv(PitT{s}(:,:,n)))*A{s}; %Equation 2.21 in Srinivasan et. al - QT{s}(:,:,n) = Q{s}-(Q{s}*pinv(PitT{s}(:,:,n)))*Q{s}'; - end - end - % PhiTt(:,:,1)= A^(N-1); - B{s}(:,:,1) = A{s}-(Q{s}*pinv(PitT{s}(:,:,1)))*A{s}; - QT{s}(:,:,1) = Q{s}-(Q{s}*pinv(PitT{s}(:,:,1)))*Q{s}'; - % See Equations 2.23 through 2.26 in Srinivasan et. al - if(estimateTarget==1) - - - for n=1:N - psi = B{s}(:,:,n); - if(n==N) - gammaMat = eye(ns(s),ns(s)); - else - gammaMat = (Q{s}*pinv(PitT{s}(:,:,n)))*PhitT{s}(:,:,n); - end - Amat{s}(:,:,n) = [psi,gammaMat; - zeros(ns(s),ns(s)), eye(ns(s),ns(s))]; - - Qmat{s}(:,:,n) = [QT{s}(:,:,n), zeros(ns(s),ns(s)); - zeros(ns(s),ns(s)) zeros(ns(s),ns(s))]; - - - end - - Pi0new{s} = [Pi0{s}, zeros(ns(s),ns(s)); - zeros(ns(s),ns(s)) zeros(ns(s),ns(s))]; - - else - - Amat{s} = B{s}; - Qmat{s} = QT{s}; - for n=1:N - ft{s}(:,n) = (Q{s}*pinv(PitT{s}(:,:,n)))*PhitT{s}(:,:,n)*yT{s}; - end - - end - - end - if(estimateTarget==1) - Pi0 = Pi0new; - - end - end - - if(nargin<8 || isempty(x0)) - for s=1:nmodels - x0{s}=zeros(size(Amat{s},2),1); - end - end - - if(nargin<7) - binwidth=0.001; %1 msec - end - - if(isa(A,'cell')) - dimMat = zeros(1,length(Amat)); - X_u = cell(1,length(Amat)); - W_u = cell(1,length(Amat)); - X_p = cell(1,length(Amat)); - W_p = cell(1,length(Amat)); - ind = cell(1,length(Amat)); - ut = cell(1,length(Amat)); - - for i=1:length(Amat) - lambdaDeltaMat{i} = zeros(size(dN)); - X_u{i} = zeros(size(Amat{i},1), size(dN,2)); - X_p{i} = zeros(size(Amat{i},1), size(dN,2)+1); - W_u{i} = zeros(size(Amat{i},1), size(Amat{i},1), size(dN,2)); - W_p{i} = zeros(size(Amat{i},1), size(Amat{i},1), size(dN,2)+1); - dimMat(i) = size(Amat{i},2); - W_u{i}(:,:,1) =Pi0{i}; - ind{i} = 1:dimMat(i); - ut{i} = zeros(size(Amat{i},1), size(dN,2)); - end - end - - maxDim = max(dimMat); - % nmodels = length(Amat); - % lambdaCIFColl = CIFColl(lambda); - - minTime=0; - maxTime=(size(dN,2)-1)*binwidth; - - C=size(dN,1); - - % Overall estimates of Hybrid filter - X = zeros(maxDim, size(dN,2)); % Estimated Trajectories - W = zeros(maxDim, maxDim, size(dN,2)); % Covariance of estimate - % Individual Model Estimates - for i=1:nmodels - X_s{i} = X; % Individual Model Estimates - W_s{i} = W; % Individual Model Covariances - end - % Model probabilities - MU_u = zeros(nmodels,size(dN,2)); % P(s_k | H_k+1) % updated state probabilities - MU_p = zeros(nmodels,size(dN,2)); % P(s_k | H_k) % prediction state probabilities - pNGivenS = zeros(nmodels,size(dN,2)); - - - %mu_0|1 = mu_0|0; - if(isempty(Mu0)) - Mu0 = ones(nmodels,1)*1/nmodels; - elseif(size(Mu0,1)==nmodels && size(Mu0,2)==1) - Mu0 = Mu0; - elseif(size(Mu0,1)==1 && size(Mu0,2)==nmodels) - Mu0 = Mu0'; - else - error('Mu0 must be a column or row vector with the same number of dimensions as the number of states'); - end - for s=1:nmodels - [X_p{s}(ind{s},1),W_p{s}(ind{s},ind{s},1)] = DecodingAlgorithms.PPDecode_predict(x0{s}(ind{s}), Pi0{s}(ind{s},ind{s}), Amat{s}(ind{s},ind{s},min(size(Amat{s},3),1)), Qmat{s}(:,:,min(size(Qmat{s},3)))); - - if((estimateTarget==0 && ~isempty(yT{s}))) - invA= pinv(Amat{s}(:,:,min(size(Amat,3),1))); - ut{s}(:,1) = (Q{s}*pinv(PitT{s}(:,:,1)))*PhitT{s}(:,:,1)*(yT{s}-pinv(invA*PhitT{s}(:,:,1))*x0{s}); - X_p{s}(ind{s},1) = X_p{s}(ind{s},1)+ut{s}(:,1); - W_p{s}(ind{s},ind{s},1) =W_p{s}(ind{s},ind{s},1) + (Q{s}*pinv(PitT{s}(:,:,1)))*A{s}*Pi0{s}*A{s}'*(Q{s}*pinv(PitT{s}(:,:,1)))'; - end - end - - % [~, S_est(1)] = max(MU_p(:,1)); %Most likely current state - - %State transition Probabilities must integrate to 1 - sumVal = sum(p_ij,2); - if(any(sumVal~=1)) - error('State Transition probability matrix must sum to 1 along each row'); - end - %% 9 Steps - % Filtering steps. - for k = 1:(size(dN,2)) - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % Step 1 - p(s_k | H_k) = Sum(p(s_k|s_k-1)*p(s_k-1|H_k)) - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %MU(:,k)_p= [ p(s_k=1 | H_k)] is a vector of the probabilities - % [ p(s_k=2 | H_k)] - % . - % . - % . - % [ p(s_k=N | H_k)] - % thus it is an prediction of the discrete state at time k given all - % of the neural firing up to k-1 as summarized in H_k - % - % Whereas - % MU_u(:,k)=[ p(s_k=1 | H_k+1)] is a vector of the probabilities - % [ p(s_k=2 | H_k+1)] - % . - % . - % . - % [ p(s_k=N | H_k+1)] - % The s suffix indicates that this is a "smoothed" estimate of - % the state given the firing up to time k summarized in H_k+1 - if k==1 - MU_p(:,k) = p_ij'*Mu0; %state probability prediction equation - else - MU_p(:,k) = p_ij'*MU_u(:,k-1); - end - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % Step 2 - p(s_k-1 | s_k, H_k) - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % This is a matrix with i,j entry indicating the probability that - % s_k-1 = j given than s_k = i - % - % MU_p is the normalization factor. The first column of the - % matrix of probabilities is: - % - % P(s_k-1=1 | s_k=1,H_k) ~ P(s_k=1|s_k-1=1,H_k)*P(s_k-1=1|H_k) - % P(s_k-1=1 | s_k=2,H_k) ~ P(s_k=2|s_k-1=1,H_k)*P(s_k-1=1|H_k) - % - % And the second columns ... etc - % - % - % P(s_k-1=2 | s_k=1,H_k) ~ P(s_k=1|s_k-1=2,H_k)*P(s_k-1=1|H_k) - % P(s_k-1=2 | s_k=2,H_k) ~ P(s_k=2|s_k-1=2,H_k)*P(s_k-1=1|H_k) - - if(k==1) - p_ij_s= p_ij.*(Mu0*ones(1,nmodels));%.*(ones(nmodels,1)*(1./MU_p(:,k))'); - else - p_ij_s= p_ij.*(MU_u(:,k-1)*ones(1,nmodels));%.*(ones(nmodels,1)*(1./MU_p(:,k))'); - end - % - % To avoid any numerical issues with roundoff, we normalize to - % 1 again - normFact = repmat(sum(p_ij_s,1),[nmodels 1]); %Every column must sum to 1 - - p_ij_s = p_ij_s./normFact; - % for i=1:length(normFact) - % if(normFact(i)~=0) - % p_ij_s(:,i) = p_ij_s(:,i)./normFact(i); - % else %reset all the states to be equally likely (each row must sum to 1) - % p_ij_s(:,i) = 1/nmodels*ones(nmodels,1); - % end - % end - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % Step 3 - Approximate p(x_k-1 | s_k, H_k) with Gaussian - % approximation to Mixtures of Gaussians - % Calculate the mixed state mean for each filter - % This will be the initial states for the update step of the - % Point Process Adaptive Filter - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - - - for j = 1:nmodels - for i = 1:nmodels - if(k>1) - X_s{j}(ind{i},k) = X_s{j}(ind{i},k) + X_u{i}(ind{i},k-1)*p_ij_s(i,j); - else - X_s{j}(ind{i},k) = X_s{j}(ind{i},k) + x0{i}(ind{i})*p_ij_s(i,j); - end - end - end - - % Calculate the mixed state covariance for each filter - - for j = 1:nmodels - for i = 1:nmodels - if(k>1) - W_s{j}(ind{i},ind{i},k) = W_s{j}(ind{i},ind{i},k) + (W_u{i}(ind{i},ind{i},k-1) + (X_u{i}(ind{i},k-1)-X_s{j}(ind{i},k))*(X_u{i}(ind{i},k-1)-X_s{j}(ind{i},k))')*p_ij_s(i,j); - else - W_s{j}(ind{i},ind{i},k) = W_s{j}(ind{i},ind{i},k) + (Pi0{i}(ind{i},ind{i})+ (x0{i}(ind{i})-X_s{j}(ind{i},k))*(x0{i}(ind{i})-X_s{j}(ind{i},k))')*p_ij_s(i,j); - end - end - end - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % Step 4 - Approximate p(x_k+1 |s_k+1,n_k+1,H_k+1) - % Uses a bank of nmodel point process filters - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % k - for s=1:nmodels - - % Prediction Step - [X_p{s}(ind{s},k),W_p{s}(ind{s},ind{s},k)] = DecodingAlgorithms.PPDecode_predict(X_s{s}(ind{s},k), W_s{s}(ind{s},ind{s},k), Amat{s}(:,:,min(size(Amat,3),k)), Qmat{s}(:,:,min(size(Qmat{s},3)))); - - if(estimateTarget==0 && ~isempty(yT{s})) - if(k>1) - ut{s}(:,k) = (Q{s}*pinv(PitT{s}(:,:,k)))*PhitT{s}(:,:,k)*(yT{s}-pinv(PhitT{s}(:,:,k-1))*X_s{s}(ind{s},k)); - else - invA = pinv(A{s}(:,:,min(size(A{s},3),1))); - ut{s}(:,k) = (Q{s}*pinv(PitT{s}(:,:,1)))*PhitT{s}(:,:,1)*(yT{s}-pinv(invA*PhitT{s}(:,:,1))*X_s{s}(ind{s},k)); - end - X_p{s}(ind{s},k) = X_p{s}(ind{s},k)+ut{s}(:,k); - W_p{s}(ind{s},ind{s},k) =W_p{s}(ind{s},ind{s},k) + (Q{s}*pinv(PitT{s}(:,:,k)))*A{s}*W_s{s}(ind{s},ind{s},k)*A{s}'*(Q{s}*pinv(PitT{s}(:,:,k)))'; - - end - - % Update Step - % Fold in the neural firing in the current time step - [X_u{s}(ind{s},k),W_u{s}(ind{s},ind{s},k),lambdaDeltaMat{s}(:,k)] = DecodingAlgorithms.PPDecode_update(X_p{s}(ind{s},k),squeeze(W_p{s}(ind{s},ind{s},k)),dN(:,1:k),lambdaCIFColl,binwidth,k); - - - end - - % - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % Step 5 - p(n_k | s_k, H_k) using Laplace approximation - % See General-purpose filter design for neural prosthetic devices. - % Srinivasan L, Eden UT, Mitter SK, Brown EN. - % J Neurophysiol. 2007 Oct;98(4):2456-75. Epub 2007 May 23. - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - - - for s=1:nmodels - - tempPdf = sqrt(det(W_u{s}(:,:,k)))./sqrt(det(W_p{s}(:,:,k)))*prod(exp(dN(:,k).*log(lambdaDeltaMat{s}(:,k))-lambdaDeltaMat{s}(:,k))); - pNGivenS(s,k) = tempPdf; - end - tempData = pNGivenS(:,k); - tempData(isinf(tempData))=0; - pNGivenS(:,k) = tempData; - - normFact = sum(pNGivenS(:,k)); - if(normFact~=0 && ~isnan(normFact)) - pNGivenS(:,k)=pNGivenS(:,k)./sum(pNGivenS(:,k)); - else - - if(k>1) - pNGivenS(:,k) = pNGivenS(:,k-1); - else - pNGivenS(:,k) = .5*ones(nmodels,1); - end - end - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % Step 6 - Calculate p(s_k | n_k, H_k) = p(s_k | H_k+1) - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - pSGivenN(:,k) = MU_p(:,k).*pNGivenS(:,k); - - - - %Normalization Factor - normFact = sum(pSGivenN(:,k)); - if(normFact~=0 && ~isnan(normFact)) - pSGivenN(:,k) = pSGivenN(:,k)./sum(pSGivenN(:,k)); - else - if(k>1) - pSGivenN(:,k) = pSGivenN(:,k-1); - else - pSGivenN(:,k) = Mu0; - end - - end - - - MU_u(:,k) = pSGivenN(:,k); %estimate of s_k given data up to k - - - [~, S_est(k)] = max(MU_u(:,k)); %Most likely current state - - if(MinClassificationError==1) - - s= S_est(k); - X(ind{s},k) = X_u{s}(ind{s},k); - W(ind{s},ind{s},k) = W_u{s}(ind{s},ind{s},k); - - else %Minimize the mean squared error - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % Step 7 - Calculate p(x_k | n_k, H_k) - using gaussian - % approximation to mixture of gaussians - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - for s=1:nmodels - X(ind{s},k) = X(ind{s},k)+MU_u(s,k)*X_u{s}(ind{s},k); - end - for s=1:nmodels - W(ind{s},ind{s},k) = W(ind{s},ind{s},k) +MU_u(s,k)*(W_u{s}(ind{s},ind{s},k) + (X_u{s}(ind{s},k)-X(ind{s},k))*(X_u{s}(ind{s},k)-X(ind{s},k))'); - end - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - end - end - - - - end - - %%Unscented Transform - function [x,P]=ukf(fstate,x,P,hmeas,z,Q,R) - % UKF Unscented Kalman Filter for nonlinear dynamic systems - % [x, P] = ukf(f,x,P,h,z,Q,R) returns state estimate, x and state covariance, P - % for nonlinear dynamic system (for simplicity, noises are assumed as additive): - % x_k+1 = f(x_k) + w_k - % z_k = h(x_k) + v_k - % where w ~ N(0,Q) meaning w is gaussian noise with covariance Q - % v ~ N(0,R) meaning v is gaussian noise with covariance R - % Inputs: f: function handle for f(x) - % x: "a priori" state estimate - % P: "a priori" estimated state covariance - % h: function handle for h(x) - % z: current measurement - % Q: process noise covariance - % R: measurement noise covariance - % Output: x: "a posteriori" state estimate - % P: "a posteriori" state covariance - % - % Example: - %{ - n=3; %number of state - q=0.1; %std of process - r=0.1; %std of measurement - Q=q^2*eye(n); % covariance of process - R=r^2; % covariance of measurement - f=@(x)[x(2);x(3);0.05*x(1)*(x(2)+x(3))]; % nonlinear state equations - h=@(x)x(1); % measurement equation - s=[0;0;1]; % initial state - x=s+q*randn(3,1); %initial state % initial state with noise - P = eye(n); % initial state covraiance - N=20; % total dynamic steps - xV = zeros(n,N); %estmate % allocate memory - sV = zeros(n,N); %actual - zV = zeros(1,N); - for k=1:N - z = h(s) + r*randn; % measurments - sV(:,k)= s; % save actual state - zV(k) = z; % save measurment - [x, P] = ukf_example(f,x,P,h,z,Q,R); % ekf - xV(:,k) = x; % save estimate - s = f(s) + q*randn(3,1); % update process - end - for k=1:3 % plot results - subplot(3,1,k) - plot(1:N, sV(k,:), '-', 1:N, xV(k,:), '--') - end - %} - % Reference: Julier, SJ. and Uhlmann, J.K., Unscented Filtering and - % Nonlinear Estimation, Proceedings of the IEEE, Vol. 92, No. 3, - % pp.401-422, 2004. - % - % By Yi Cao at Cranfield University, 04/01/2008 - % - L=numel(x); %numer of states - m=numel(z); %numer of measurements - alpha=1e-3; %default, tunable - ki=0; %default, tunable - beta=2; %default, tunable - lambda=alpha^2*(L+ki)-L; %scaling factor - c=L+lambda; %scaling factor - Wm=[lambda/c 0.5/c+zeros(1,2*L)]; %weights for means - Wc=Wm; - Wc(1)=Wc(1)+(1-alpha^2+beta); %weights for covariance - c=sqrt(c); - X=DecodingAlgorithms.ukf_sigmas(x,P,c); %sigma points around x - [x1,X1,P1,X2]=DecodingAlgorithms.ukf_ut(fstate,X,Wm,Wc,L,Q); %unscented transformation of process - % X1=sigmas(x1,P1,c); %sigma points around x1 - % X2=X1-x1(:,ones(1,size(X1,2))); %deviation of X1 - [z1,Z1,P2,Z2]=DecodingAlgorithms.ukf_ut(hmeas,X1,Wm,Wc,m,R); %unscented transformation of measurments - P12=X2*diag(Wc)*Z2'; %transformed cross-covariance - K=P12/(P2); - x=x1+K*(z-z1); %state update - P=P1-K*P12'; %covariance update - - end - function [y,Y,P,Y1]=ukf_ut(f,X,Wm,Wc,n,R) - %Unscented Transformation - %Input: - % f: nonlinear map - % X: sigma points - % Wm: weights for mean - % Wc: weights for covraiance - % n: numer of outputs of f - % R: additive covariance - %Output: - % y: transformed mean - % Y: transformed smapling points - % P: transformed covariance - % Y1: transformed deviations - - L=size(X,2); - y=zeros(n,1); - Y=zeros(n,L); - for k=1:L - Y(:,k)=f(X(:,k)); - y=y+Wm(k)*Y(:,k); - end - Y1=Y-y(:,ones(1,L)); - P=Y1*diag(Wc)*Y1'+R; - end - function X=ukf_sigmas(x,P,c) - %Sigma points around reference point - %Inputs: - % x: reference point - % P: covariance - % c: coefficient - %Output: - % X: Sigma points - - A = c*chol(P)'; - Y = x(:,ones(1,numel(x))); - X = [x Y+A Y-A]; - end - - %% Kalman Filter - function [x_p, Pe_p, x_u, Pe_u,Gn,GnConvIter] = kalman_filter(A, C, Pv, Pw, Px0, x0,y, GnConv) - %% DT Kalman Filter - % This implements the DT Kalman filter for the system described by - % - % x(:,n+1) = A(:,:,n)x(:,n) + v(:,n) - % y(:,n) = C(:,:,n)x(:,n) + w(:,n) - % - % where Pv(:,:,n), Pw(:,:,n) are the covariances of v(:,n) and w(:,n) - % and Px0 is the initial state covariance. - % - % v(:,n), w(:,n), x(:,1) are assumed to be zero-mean. - % - % Return values are - % x_p: state estimates given the past - % Pe_p: error covariance estimates given the past - % x_u: state updates given the data - % Pe_u: error covariance updates given the data - - if(nargin<8||isempty(GnConv)) - GnConv = []; - end - N = size(y,2); % number of time samples in the data - x_p = zeros( size(A,2), N+1 ); - x_u = zeros( size(A,2), N ); - Pe_p = zeros( size(A,2), size(A,2), N+1 ); - Gn = zeros( size(A,2), size(C,1), N ); - Pe_u = zeros( size(A,2), size(A,2), N ); - x_p(:,1)= x0; - Pe_p(:,:,1) = Px0; - - for n=1:N - [x_u(:,n), Pe_u(:,:,n), Gn(:,:,n)] = kalman_update( x_p(:,n), Pe_p(:,:,n), C(:,:,min(size(C,3),n)), Pw(:,:,min(size(Pw,3),n)), y(:,n),GnConv); - [x_p(:,n+1), Pe_p(:,:,n+1)] = kalman_predict(x_u(:,n), Pe_u(:,:,n), A(:,:,min(size(A,3),n)), Pv(:,:,min(size(Pv,3),n)),GnConv); - if(n>1 && isempty(GnConv)) - diffGn = abs(Gn(:,:,n)-Gn(:,:,n-1)); - mAbsdiffGn = max(max(diffGn)); - if(mAbsdiffGn<1e-6) - GnConv=Gn(:,:,n); - GnConvIter = n; - else - GnConvIter=[]; - end - - end - end - - - - - %% Kalman Filter Update Equation - function [x_u, Pe_u, G] = kalman_update(x_p, Pe_p, C, Pw, y, GnConv) - % The Kalman update step that finds the state estimate based on new - % data - if(nargin<6 || isempty(GnConv)) - G = (Pe_p * C')/(C * Pe_p * C' + Pw); - else - G = GnConv; - end - x_u = x_p + G * (y - C * x_p); - Pe_u = Pe_p - G * C * Pe_p; - Pe_u = 0.5*(Pe_u + Pe_u'); - -% figure(10); subplot(1,3,1);imagesc(Pe_u); pause(0.005); - end - %% Kalman Filter Prediction Step - function [x_p, Pe_p] = kalman_predict(x_u, Pe_u, A, Pv,GnConv) - % The Kalman prediction step that implements the tracking system - x_p = A * x_u; - if(isempty(GnConv)) - Pe_p = A * Pe_u * A' + Pv; - else - Pe_p = Pe_u; - end - Pe_p = 0.5*(Pe_p + Pe_p'); - end - end - - %% Kalman Fixed-Interval Smoother - function [x_pLag, Pe_pLag, x_uLag, Pe_uLag] = kalman_fixedIntervalSmoother(A, C, Pv, Pw, Px0, x0,y,lags) - %y should be zero mean gaussian - N = size(y,2); - nStates = size(A,2); - nObs = size(C,1); - Alag = zeros((lags+1)*nStates,(lags+1)*nStates,N); - Pvlag = zeros((lags+1)*nStates,(lags+1)*nStates,N); - Clag = zeros(nObs,(lags+1)*nStates,N); - Pwlag = zeros(nObs,nObs,N); - x0lag = zeros(length(x0)*(lags+1),1); - Px0lag = zeros((lags+1)*nStates,(lags+1)*nStates); - Px0lag((1:nStates),(1:nStates))=Px0; - x0lag(1:nStates,1)=x0; - for n=1:N - offset = 0; - for i=1:(lags+1) - if(i==1) - Alag((1:nStates)+offset,(1:nStates)+offset,n)=A(:,:,min(size(A,3),n)); - Pvlag((1:nStates)+offset,(1:nStates)+offset,n)=Pv(:,:,min(size(Pv,3),n)); - Clag((1:nObs),(1:nStates)+offset,n)=C(:,:,min(size(C,3),n)); - Pwlag((1:nObs),(1:nObs),n) = Pw(:,:,min(size(Pw,3),n)); - else - Alag((1:nStates)+offset,(1:nStates)+(offset-nStates),n)=eye(nStates,nStates); - Pvlag((1:nStates)+offset,(1:nStates)+offset,n)=zeros(nStates,nStates); - Clag((1:nObs),(1:nStates)+offset,n)=zeros(nObs,nStates); - end - offset=offset+nStates; - end - end - - [x_p, Pe_p, x_u, Pe_u] = DecodingAlgorithms.kalman_filter(Alag, Clag, Pvlag, Pwlag, Px0lag, x0lag,y); - - x_pLag = x_p((lags*nStates+1):(lags+1)*nStates,:); - Pe_pLag = Pe_p((lags*nStates+1):(lags+1)*nStates,(lags*nStates+1):(lags+1)*nStates,:); - x_uLag = x_u((lags*nStates+1):(lags+1)*nStates,:); - Pe_uLag = Pe_u((lags*nStates+1):(lags+1)*nStates,(lags*nStates+1):(lags+1)*nStates,:); - end - %% Kalman Smoother - function [x_N, P_N,Ln] = kalman_smootherFromFiltered(A, x_p, Pe_p, x_u, Pe_u) - N=size(x_u,2); - - x_N=zeros(size(x_u)); - P_N=zeros(size(Pe_u)); - Ln = zeros(size(P_N,1),size(P_N,2),size(P_N,3)-1); - j=fliplr(1:N-1); - x_N(:,N) = x_u(:,N); - P_N(:,:,N) = Pe_u(:,:,N); -% LnConv = []; - for n=j -% if(n1e1) - % gamma_newTemp = sign(gamma_newTemp)*1e1; - end - mabsDiff = max(abs(gamma_newTemp - gamma_new)); - if(mabsDiff<10^-2) - converged=1; - end - gamma_new=gamma_newTemp; - iter=iter+1; - end - %Keep gamma from getting too large since this effect is - %exponentiated - gamma_new(gamma_new>1e2)=1e1; - gamma_new(gamma_new<-1e2)=-1e1; - end - - % pause; - end - function fitResults=prepareEMResults(fitType,neuronNumber,dN,HkAll,xK,WK,Q,gamma,windowTimes,delta,informationMatrix,logll) - - - [numBasis, K] =size(xK); - SE = sqrt(abs(diag(inv(informationMatrix)))); - xKbeta = reshape(xK,[numel(xK) 1]); - seXK=[]; - for k=1:K - seXK = [seXK; sqrt(diag(WK(:,:,k)))]; - end - statsStruct.beta=[xKbeta;(Q(:,end));gamma(end,:)']; - statsStruct.se =[seXK;SE]; - covarianceLabels = cell(1,numBasis); - for r=1:numBasis - if(r<10) - covarianceLabels{r} = ['Q0' num2str(r)]; - else - covarianceLabels{r} = ['Q' num2str(r)]; - end - end - - minTime=0; - maxTime=(size(dN,2)-1)*delta; - if(~isempty(numBasis)) - basisWidth = (maxTime-minTime)/numBasis; - sampleRate=1/delta; - unitPulseBasis=nstColl.generateUnitImpulseBasis(basisWidth,minTime,maxTime,sampleRate); - basisMat = unitPulseBasis.data; - end - - nst = cell(1,K); - if(~isempty(windowTimes)) - histObj{1} = History(windowTimes,minTime,maxTime); - else - histObj{1} = []; - end - - if(isnumeric(neuronNumber)) - name=num2str(neuronNumber); - if(neuronNumber>0 && neuronNumber<10) - name = strcat(num2str(0),name); - end - name = ['N' name]; - else - name = neuronNumber; - end - - for k=1:K - nst{k} = nspikeTrain( (find(dN(k,:)==1)-1)*delta,name); - nst{k}.setMinTime(minTime); - nst{k}.setMaxTime(maxTime); - - end - - nCopy = nstColl(nst); - nCopy = nCopy.toSpikeTrain; - lambdaData=[]; - cnt=1; - - for k=1:K - Hk=HkAll{k}; - stimK=basisMat*xK(:,k); - - - if(strcmp(fitType,'poisson')) - histEffect=exp(gamma(end,:)*Hk')'; - stimEffect=exp(stimK); - lambdaDelta = histEffect.*stimEffect; - lambdaData = [lambdaData;lambdaDelta/delta]; - elseif(strcmp(fitType,'binomial')) - histEffect=exp(gamma(end,:)*Hk')'; - stimEffect=exp(stimK); - lambdaDelta = histEffect.*stimEffect; - lambdaDelta = lambdaDelta./(1+lambdaDelta); - lambdaData = [lambdaData;lambdaDelta/delta]; - end - - - for r=1:numBasis - if(r<10) - otherLabels{cnt} = ['b0' num2str(r) '_{' num2str(k) '}']; - else - otherLabels{cnt} = ['b' num2str(r) '_{' num2str(k) '}']; - end - cnt=cnt+1; - end - end - - lambdaTime = minTime:delta:(length(lambdaData)-1)*delta; - nCopy.setMaxTime(max(lambdaTime)); - nCopy.setMinTime(min(lambdaTime)); - - numLabels = length(otherLabels); - if(~isempty(windowTimes)) - histLabels = histObj{1}.computeHistory(nst{1}).getCovLabelsFromMask; - else - histLabels = []; - end - otherLabels((numLabels+1):(numLabels+length(covarianceLabels)))=covarianceLabels; - numLabels = length(otherLabels); - - tc{1} = TrialConfig(otherLabels,sampleRate,histObj,[]); - numBasisStr=num2str(numBasis); - numHistStr = num2str(length(windowTimes)-1); - if(~isempty(histObj)) - tc{1}.setName(['SSGLM(N_{b}=', numBasisStr,')+Hist(N_{h}=' ,numHistStr,')']); - else - tc{1}.setName(['SSGLM(N_{b}=', numBasisStr,')']); - end - configColl= ConfigColl(tc); - - - otherLabels((numLabels+1):(numLabels+length(histLabels)))=histLabels; - - - - - labels{1} = otherLabels; % Labels change depending on presence/absense of History or ensCovHist - if(~isempty(windowTimes)) - numHist{1} = length(histObj{1}.windowTimes)-1; - else - numHist{1}=[]; - end - - ensHistObj{1} = []; - lambdaIndexStr=1; - lambda=Covariate(lambdaTime,lambdaData,... - '\Lambda(t)','time',... - 's','Hz',strcat('\lambda_{',lambdaIndexStr,'}')); - - - AIC = 2*length(otherLabels)-2*logll; - BIC = -2*logll+length(otherLabels)*log(length(lambdaData)); - - dev=-2*logll; - b{1} = statsStruct.beta; - stats{1} = statsStruct; - - distrib{1} =fitType; - currSpikes=nst;%nspikeColl.getNST(tObj.getNeuronIndFromName(neuronNames)); - for n=1:length(currSpikes) - currSpikes{n} = currSpikes{n}.nstCopy; - currSpikes{n}.setName(nCopy.name); - end - XvalData{1} = []; - XvalTime{1} = []; - spikeTraining = currSpikes; - - - fitResults=FitResult(spikeTraining,labels,numHist,histObj,ensHistObj,lambda,b, dev, stats,AIC,BIC,configColl,XvalData,XvalTime,distrib); - DTCorrection=1; - makePlot=0; - Analysis.KSPlot(fitResults,DTCorrection,makePlot); - Analysis.plotInvGausTrans(fitResults,makePlot); - Analysis.plotFitResidual(fitResults,[],makePlot); - end - function [CIs, stimulus] = ComputeStimulusCIs(fitType,xK,Wku,delta,Mc,alphaVal) - if(nargin<6 ||isempty(alphaVal)) - alphaVal =.05; - end - if(nargin<5 ||isempty(Mc)) - Mc=3000; - end - [numBasis,K]=size(xK); - - - for r=1:numBasis - WkuTemp=squeeze(Wku(r,r,:,:)); - % [vec,val]=eig(Wku ); val(val<=0)=eps; - % Wku =vec*val*vec'; - [chol_m,p]=chol(WkuTemp); - if(numel(chol_m)==1) - chol_m = diag(repmat(chol_m,[K 1])); - end - for c=1:Mc % for r-th step function simulate the path of size K - z=zeros(K,1); - z=normrnd(0,1,K,1); - xKDraw(r,:,c)=xK(r,:)+(chol_m'*z)'; - % stimulusDraw(r,:,c) = exp(xKDraw(r,:,c))/delta; - if(strcmp(fitType,'poisson')) - stimulusDraw(r,:,c) = exp(xKDraw(r,:,c))/delta; - elseif(strcmp(fitType,'binomial')) - stimulusDraw(r,:,c) = exp(xKDraw(r,:,c))./(1+exp(xKDraw(r,:,c)))/delta; - end - end - end - - CIs = zeros(size(xK,1),size(xK,2),2); - for r=1:numBasis - for k=1:K - [f,x] = ecdf(squeeze(stimulusDraw(r,k,:))); - CIs(r,k,1) = x(find(f(1-(alphaVal/2)),1,'first')); - end - end - - if(nargout==2) - if(strcmp(fitType,'poisson')) - stimulus = exp(xK)/delta; - elseif(strcmp(fitType,'binomial')) - stimulus = exp(xK)./(1+exp(xK))/delta; - end - end - - - end - function InfoMatrix=estimateInfoMat(fitType,dN,HkAll,A,x0,xK,WK,Wku,Q,gamma,windowTimes,SumXkTerms,delta,Mc) - if(nargin<14) - Mc=500; - end - - [K,N]=size(dN); - if(~isempty(windowTimes)) - J=max(size(gamma(end,:))); - else - J=0; - end - - R=size(Q,1); - numBasis = R; - - % The complete data information matrix - Ic=zeros(J+R,J+R); - Q=(diag(Q)); % Make sure Q is diagonal matrix - - - X=((SumXkTerms)); - Ic(1:R,1:R) = K/2*eye(size(Q))/Q^2 +X'/Q^3; - - - % Compute information of history terms - minTime=0; - maxTime=(size(dN,2)-1)*delta; - % nst = cell(1,K); - % if(~isempty(windowTimes)) - % histObj = History(windowTimes,minTime,maxTime); - % for k=1:K - % nst{k} = nspikeTrain( (find(dN(k,:)==1)-1)*delta); - % nst{k}.setMinTime(minTime); - % nst{k}.setMaxTime(maxTime); - % Hn{k} = histObj.computeHistory(nst{k}).dataToMatrix; - % end - % else - % for k=1:K - % Hn{k} = 0; - % end - % gamma=0; - % end - - if(~isempty(numBasis)) - basisWidth = (maxTime-minTime)/numBasis; - sampleRate=1/delta; - unitPulseBasis=nstColl.generateUnitImpulseBasis(basisWidth,minTime,maxTime,sampleRate); - basisMat = unitPulseBasis.data; - end - - jacQ =zeros(size(gamma,2),size(gamma,2)); - if(strcmp(fitType,'poisson')) - for k=1:K - Hk=HkAll{k}; - - Wk = basisMat*diag(WK(:,:,k)); - stimK=basisMat*(xK(:,k)); - histEffect=exp(gamma*Hk')'; - stimEffect=exp(stimK)+exp(stimK)/2.*Wk; - lambdaDelta = stimEffect.*histEffect; - - jacQ = jacQ - (Hk.*repmat(lambdaDelta,[1 size(Hk,2)]))'*Hk; - end - - elseif(strcmp(fitType,'binomial')) - for k=1:K - Hk=HkAll{k}; - Wk = basisMat*diag(WK(:,:,k)); - stimK=basisMat*(xK(:,k)); - - histEffect=exp(gamma*Hk')'; - stimEffect=exp(stimK); - C = stimEffect.*histEffect; - M = 1./C; - lambdaDelta = exp(stimK+(gamma*Hk')')./(1+exp(stimK+(gamma*Hk')')); - ExpLambdaDelta = lambdaDelta+Wk.*(lambdaDelta.*(1-lambdaDelta).*(1-2*lambdaDelta))/2; - ExpLDSquaredTimesInvExp = (lambdaDelta).^2.*1./C; - ExpLDCubedTimesInvExpSquared = (lambdaDelta).^3.*M.^2 +Wk/2.*(3.*M.^4.*lambdaDelta.^3+12.*lambdaDelta.^3.*M.^3-12.*M.^4.*lambdaDelta.^4); - - jacQ = jacQ - (Hk.*repmat(ExpLDSquaredTimesInvExp.*dN(k,:)',[1,size(Hk,2)]))'*Hk ... - - (Hk.*repmat(ExpLDSquaredTimesInvExp,[1,size(Hk,2)]))'*Hk ... - - (Hk.*repmat(2*ExpLDCubedTimesInvExpSquared,[1,size(Hk,2)]))'*Hk; - - end - - - end - - Ic(1:R,1:R)=K*eye(size(Q))/(2*(Q)^2)+(eye(size(Q))/((Q)^3))*SumXkTerms; - - if(~isempty(windowTimes)) - Ic((R+1):(R+J),(R+1):(R+J)) = -jacQ; - end - xKDraw = zeros(numBasis,K,Mc); - for r=1:numBasis - WkuTemp=squeeze(Wku(r,r,:,:)); - % [vec,val]=eig(Wku ); val(val<=0)=eps; - % Wku =vec*val*vec'; - [chol_m,p]=chol(WkuTemp); - if(numel(chol_m)==1) - chol_m = diag(repmat(chol_m,[K 1])); - end - for c=1:Mc % for r-th step function simulate the path of size K - z=zeros(K,1); - z=normrnd(0,1,K,1); - xKDraw(r,:,c)=xK(r,:)+(chol_m'*z)'; - end - end - - - - Im=zeros(J+R,J+R); - ImMC=zeros(J+R,J+R); - - for c=1:Mc - - gradQGammahat=zeros(size(gamma,2),1); - gradQQhat=zeros(1,R); - if(strcmp(fitType,'poisson')) - for k=1:K - Hk=HkAll{k}; - stimK=basisMat*(xKDraw(:,k,c)); - histEffect=exp(gamma*Hk')'; - stimEffect=exp(stimK); - lambdaDelta = stimEffect.*histEffect; - gradQGammahat = gradQGammahat + Hk'*dN(k,:)' - Hk'*lambdaDelta; - if(k==1) - gradQQhat = ((xKDraw(:,k,c)-A*x0).*(xKDraw(:,k,c)-A*x0)); - else - gradQQhat = gradQQhat+((xKDraw(:,k,c)-A*xKDraw(:,k-1,c)).*(xKDraw(:,k,c)-A*xKDraw(:,k-1,c))); - end - - end - elseif(strcmp(fitType,'binomial')) - for k=1:K - Hk=HkAll{k}; - Wk = basisMat*diag(WK(:,:,k)); - stimK=basisMat*(xKDraw(:,k,c)); - - histEffect=exp(gamma*Hk')'; - stimEffect=exp(stimK); - % - C = stimEffect.*histEffect; - M = 1./C; - lambdaDelta = exp(stimK+(gamma*Hk')')./(1+exp(stimK+(gamma*Hk')')); - ExpLambdaDelta = lambdaDelta+Wk.*(lambdaDelta.*(1-lambdaDelta).*(1-2*lambdaDelta))/2; - ExpLDSquaredTimesInvExp = (lambdaDelta).^2.*1./C; - ExpLDCubedTimesInvExpSquared = (lambdaDelta).^3.*M.^2 +Wk/2.*(3.*M.^4.*lambdaDelta.^3+12.*lambdaDelta.^3.*M.^3-12.*M.^4.*lambdaDelta.^4); - - - gradQGammahat = gradQGammahat + (Hk.*repmat(1-ExpLambdaDelta,[1,size(Hk,2)]))'*dN(k,:)' ... - - (Hk.*repmat(ExpLDSquaredTimesInvExp./lambdaDelta,[1,size(Hk,2)]))'*lambdaDelta; - if(k==1) - gradQQhat = ((xKDraw(:,k,c)-A*x0).*(xKDraw(:,k,c)-A*x0)); - else - gradQQhat = gradQQhat+((xKDraw(:,k,c)-A*xKDraw(:,k-1,c)).*(xKDraw(:,k,c)-A*xKDraw(:,k-1,c))); - end - end - - - end - - gradQQhat = .5*eye(size(Q))/Q*gradQQhat - diag(K/2*eye(size(Q))/Q^2); - ImMC(1:R,1:R)=ImMC(1:R,1:R)+gradQQhat*gradQQhat'; - if(~isempty(windowTimes)) - ImMC((R+1):(R+J),(R+1):(R+J)) = ImMC((R+1):(R+J),(R+1):(R+J))+diag(diag(gradQGammahat*gradQGammahat')); - end - end - Im=ImMC/Mc; - - InfoMatrix=Ic-Im; % Observed information matrix - - - - end - function [spikeRateSig, ProbMat,sigMat]=computeSpikeRateCIs(xK,Wku,dN,t0,tf,fitType,delta,gamma,windowTimes,Mc,alphaVal) - if(nargin<11 ||isempty(alphaVal)) - alphaVal =.05; - end - if(nargin<10 ||isempty(Mc)) - Mc=500; - end - - [numBasis,K]=size(xK); - - minTime=0; - maxTime=(size(dN,2)-1)*delta; - - if(~isempty(numBasis)) - basisWidth = (maxTime-minTime)/numBasis; - sampleRate=1/delta; - unitPulseBasis=nstColl.generateUnitImpulseBasis(basisWidth,minTime,maxTime,sampleRate); - basisMat = unitPulseBasis.data; - end - - - % K=size(dN,1); - if(~isempty(windowTimes)) - histObj = History(windowTimes,minTime,maxTime); - for k=1:K - nst{k} = nspikeTrain( (find(dN(k,:)==1)-1)*delta); - nst{k}.setMinTime(minTime); - nst{k}.setMaxTime(maxTime); - Hk{k} = histObj.computeHistory(nst{k}).dataToMatrix; - end - else - for k=1:K - Hk{k} = 0; - end - gamma=0; - end - - for r=1:numBasis - WkuTemp=squeeze(Wku(r,r,:,:)); - % [vec,val]=eig(Wku ); val(val<=0)=eps; - % Wku =vec*val*vec'; - [chol_m,p]=chol(WkuTemp); - if(numel(chol_m)==1) - chol_m = diag(repmat(chol_m,[K 1])); - end - for c=1:Mc % for r-th step function simulate the path of size K - z=zeros(K,1); - z=normrnd(0,1,K,1); - xKDraw(r,:,c)=xK(r,:)+(chol_m'*z)'; - end - end - - time=minTime:delta:maxTime; - for c=1:Mc - for k=1:K - - if(strcmp(fitType,'poisson')) - stimK=basisMat*xKDraw(:,k,c); - histEffect=exp(gamma*Hk{k}')'; - stimEffect=exp(stimK); - lambdaDelta(:,k,c) =stimEffect.*histEffect; - elseif(strcmp(fitType,'binomial')) - stimK=basisMat*xKDraw(:,k,c); - lambdaDelta(:,k,c)=exp(stimK+(gamma*Hk{k}')')./(1+exp(stimK+(gamma*Hk{k}')')); - end - - - end - lambdaC=Covariate(time,lambdaDelta(:,:,c)/delta,'\Lambda(t)'); - lambdaCInt= lambdaC.integral; - spikeRate(c,:) = (1/(tf-t0))*(lambdaCInt.getValueAt(tf)-lambdaCInt.getValueAt(t0)); - - end - - CIs = zeros(K,2); - for k=1:K - [f,x] = ecdf(spikeRate(:,k)); - CIs(k,1) = x(find(f(1-(alphaVal)),1,'first')); - end - spikeRateSig = Covariate(1:K, mean(spikeRate),['(' num2str(tf) '-' num2str(t0) ')^-1 * \Lambda(' num2str(tf) '-' num2str(t0) ')'],'Trial','k','Hz'); - ciSpikeRate = ConfidenceInterval(1:K,CIs,'CI_{spikeRate}','Trial','k','Hz'); - spikeRateSig.setConfInterval(ciSpikeRate); - - - if(nargout>1) - ProbMat = zeros(K,K); - for k=1:K - for m=(k+1):K - - ProbMat(k,m)=sum(spikeRate(:,m)>spikeRate(:,k))./Mc; - end - end - end - - - if(nargout>2) - sigMat= double(ProbMat>(1-alphaVal)); - end - - - end - function [spikeRateSig, ProbMat,sigMat]=computeSpikeRateDiffCIs(xK,Wku,dN,time1,time2,fitType,delta,gamma,windowTimes,Mc,alphaVal) - if(nargin<11 ||isempty(alphaVal)) - alphaVal =.05; - end - if(nargin<10 ||isempty(Mc)) - Mc=500; - end - - [numBasis,K]=size(xK); - - minTime=0; - maxTime=(size(dN,2)-1)*delta; - - if(~isempty(numBasis)) - basisWidth = (maxTime-minTime)/numBasis; - sampleRate=1/delta; - unitPulseBasis=nstColl.generateUnitImpulseBasis(basisWidth,minTime,maxTime,sampleRate); - basisMat = unitPulseBasis.data; - end - - - % K=size(dN,1); - if(~isempty(windowTimes)) - histObj = History(windowTimes,minTime,maxTime); - for k=1:K - nst{k} = nspikeTrain( (find(dN(k,:)==1)-1)*delta); - nst{k}.setMinTime(minTime); - nst{k}.setMaxTime(maxTime); - Hk{k} = histObj.computeHistory(nst{k}).dataToMatrix; - end - else - for k=1:K - Hk{k} = 0; - end - gamma=0; - end - - for r=1:numBasis - WkuTemp=squeeze(Wku(r,r,:,:)); - % [vec,val]=eig(Wku ); val(val<=0)=eps; - % Wku =vec*val*vec'; - [chol_m,p]=chol(WkuTemp); - if(numel(chol_m)==1) - chol_m = diag(repmat(chol_m,[K 1])); - end - for c=1:Mc % for r-th step function simulate the path of size K - z=zeros(K,1); - z=normrnd(0,1,K,1); - xKDraw(r,:,c)=xK(r,:)+(chol_m'*z)'; - end - end - - timeWindow=minTime:delta:maxTime; - for c=1:Mc - for k=1:K - - if(strcmp(fitType,'poisson')) - stimK=basisMat*xKDraw(:,k,c); - histEffect=exp(gamma*Hk{k}')'; - stimEffect=exp(stimK); - lambdaDelta(:,k,c) =stimEffect.*histEffect; - elseif(strcmp(fitType,'binomial')) - stimK=basisMat*xKDraw(:,k,c); - lambdaDelta(:,k,c)=exp(stimK+(gamma*Hk{k}')')./(1+exp(stimK+(gamma*Hk{k}')')); - end - - - end - lambdaC=Covariate(timeWindow,lambdaDelta(:,:,c)/delta,'\Lambda(t)'); - lambdaCInt= lambdaC.integral; - spikeRate(c,:) = (1/(max(time1)-min(time1)))*(lambdaCInt.getValueAt(max(time1))-lambdaCInt.getValueAt(min(time1))) ... - - (1/(max(time2)-min(time2)))*(lambdaCInt.getValueAt(max(time2))-lambdaCInt.getValueAt(min(time2))); - - - end - - CIs = zeros(K,2); - for k=1:K - [f,x] = ecdf(spikeRate(:,k)); - CIs(k,1) = x(find(f(1-(alphaVal)),1,'first')); - end - spikeRateSig = Covariate(1:K, mean(spikeRate),['(t_{1f}-t_{1o})^-1 * \Lambda(t_{1f}-t_{1o}) - (t_{2f}-t_{2o})^-1 * \Lambda(t_{2f}-t_{2o}) '],'Trial','k','Hz'); - ciSpikeRate = ConfidenceInterval(1:K,CIs,'CI_{spikeRate}','Trial','k','Hz'); - spikeRateSig.setConfInterval(ciSpikeRate); - - - if(nargout>1) - ProbMat = zeros(K,K); - for k=1:K - for m=(k+1):K - - ProbMat(k,m)=sum(spikeRate(:,m)>spikeRate(:,k))./Mc; - end - end - end - - - if(nargout>2) - sigMat= double(ProbMat>(1-alphaVal)); - end - - - end - - %% Kalman Filter EM - function C = KF_EMCreateConstraints(EstimateA, AhatDiag,QhatDiag,QhatIsotropic,RhatDiag,RhatIsotropic,Estimatex0,EstimatePx0, Px0Isotropic,mcIter,EnableIkeda) - %By default, all parameters are estimated. To empose diagonal - %structure on the EM parameter results must pass in the - %constraints element - if(nargin<11 || isempty(EnableIkeda)) - EnableIkeda=0; - end - if(nargin<10 || isempty(mcIter)) - mcIter=1000; - end - if(nargin<9 || isempty(Px0Isotropic)) - Px0Isotropic=0; - end - if(nargin<8 || isempty(EstimatePx0)) - EstimatePx0=1; - end - if(nargin<7 || isempty(Estimatex0)) - Estimatex0=1; - end - if(nargin<6 || isempty(RhatIsotropic)) - RhatIsotropic=0; - end - if(nargin<5 || isempty(RhatDiag)) - RhatDiag=1; - end - if(nargin<4 || isempty(QhatIsotropic)) - QhatIsotropic=0; - end - if(nargin<3 || isempty(QhatDiag)) - QhatDiag=1; - end - if(nargin<2) - AhatDiag=0; - end - if(nargin<1) - EstimateA=1; - end - C.EstimateA = EstimateA; - C.AhatDiag = AhatDiag; - C.QhatDiag = QhatDiag; - if(QhatDiag && QhatIsotropic) - C.QhatIsotropic=1; - else - C.QhatIsotropic=0; - end - C.RhatDiag = RhatDiag; - if(RhatDiag && RhatIsotropic) - C.RhatIsotropic=1; - else - C.RhatIsotropic=0; - end - C.Estimatex0 = Estimatex0; - C.EstimatePx0 = EstimatePx0; - if(EstimatePx0 && Px0Isotropic) - C.Px0Isotropic=1; - else - C.Px0Isotropic=0; - end - C.mcIter = mcIter; - C.EnableIkeda = EnableIkeda; - end - function [xKFinal,WKFinal,Ahat, Qhat, Chat, Rhat,alphahat, x0hat, Px0hat, IC, SE, Pvals, nIter]=KF_EM(y, Ahat0, Qhat0, Chat0, Rhat0, alphahat0, x0, Px0,KFEM_Constraints) - numStates = size(Ahat0,1); - - if(nargin<9 || isempty(KFEM_Constraints)) - KFEM_Constraints=DecodingAlgorithms.KF_EMCreateConstraints; - end - if(nargin<8 || isempty(Px0)) - Px0=10e-10*eye(numStates,numStates); - end - if(nargin<7 || isempty(x0)) - x0=zeros(numStates,1); - end - - % tol = 1e-3; %absolute change; - tolAbs = 1e-3; - tolRel = 1e-3; - llTol = 1e-3; - cnt=1; - - maxIter = 100; - - - A0 = Ahat0; - Q0 = Qhat0; - C0 = Chat0; - R0 = Rhat0; - alpha0 = alphahat0; - - - Ahat{1} = A0; - Qhat{1} = Q0; - Chat{1} = C0; - Rhat{1} = R0; - x0hat{1} = x0; - Px0hat{1} = Px0; - alphahat{1} = alpha0; - yOrig=y; - numToKeep=10; - scaledSystem=1; - - if(scaledSystem==1) - Tq = eye(size(Qhat{1}))/(chol(Qhat{1})); - Tr = eye(size(Rhat{1}))/(chol(Rhat{1})); - Ahat{1}= Tq*Ahat{1}/Tq; - Chat{1}= Tr*Chat{1}/Tq; - Qhat{1}= Tq*Qhat{1}*Tq'; - Rhat{1}= Tr*Rhat{1}*Tr'; - y= Tr*y; - x0hat{1} = Tq*x0; - Px0hat{1} = Tq*Px0*Tq'; - alphahat{1}= Tr*alphahat{1}; - end - - cnt=1; - dLikelihood(1)=inf; - negLL=0; - IkedaAcc=KFEM_Constraints.EnableIkeda; - %Forward EM - stoppingCriteria =0; - - disp(' Kalman Filter/Gaussian Observation EM Algorithm '); - while(stoppingCriteria~=1 && cnt<=maxIter) - storeInd = mod(cnt-1,numToKeep)+1; %make zero-based then mod, then add 1 - storeIndP1= mod(cnt,numToKeep)+1; - storeIndM1= mod(cnt-2,numToKeep)+1; - disp('--------------------------------------------------------------------------------------------------------'); - disp(['Iteration #' num2str(cnt)]); - disp('--------------------------------------------------------------------------------------------------------'); - - - [x_K{storeInd},W_K{storeInd},ll(cnt),ExpectationSums{storeInd}]=... - DecodingAlgorithms.KF_EStep(Ahat{storeInd},Qhat{storeInd},Chat{storeInd},Rhat{storeInd}, y, alphahat{storeInd}, x0hat{storeInd}, Px0hat{storeInd}); - - [Ahat{storeIndP1}, Qhat{storeIndP1}, Chat{storeIndP1}, Rhat{storeIndP1}, alphahat{storeIndP1},x0hat{storeIndP1},Px0hat{storeIndP1}] ... - = DecodingAlgorithms.KF_MStep(y,x_K{storeInd},x0hat{storeInd}, Px0hat{storeInd},ExpectationSums{storeInd},KFEM_Constraints); - - if(IkedaAcc==1) - disp(['****Ikeda Acceleration Step****']); - %y=Cx+alpha+wk wk~Normal with covariance Rk - ykNew = mvnrnd((Chat{storeIndP1}*x_K{storeInd}+alphahat{storeIndP1}*ones(1,size(x_K{storeInd},2)))',Rhat{storeIndP1})'; - - - [x_KNew,W_KNew,llNew,ExpectationSumsNew]=... - DecodingAlgorithms.KF_EStep(Ahat{storeInd},Qhat{storeInd},Chat{storeInd},Rhat{storeInd}, ykNew, alphahat{storeInd},x0, Px0); - - [AhatNew, QhatNew, ChatNew, RhatNew, alphahatNew,x0new,Px0new] ... - = DecodingAlgorithms.KF_MStep(ykNew,x_KNew, x0hat{storeInd}, Px0hat{storeInd}, ExpectationSumsNew,KFEM_Constraints); - - Ahat{storeIndP1} = 2*Ahat{storeIndP1}-AhatNew; - Qhat{storeIndP1} = 2*Qhat{storeIndP1}-QhatNew; - Qhat{storeIndP1} = (Qhat{storeIndP1}+Qhat{storeIndP1}')/2; - Chat{storeIndP1} = 2*Chat{storeIndP1}-ChatNew; - Rhat{storeIndP1} = 2*Rhat{storeIndP1}-RhatNew; - Rhat{storeIndP1} = (Rhat{storeIndP1}+Rhat{storeIndP1}')/2; - alphahat{storeIndP1}=2*alphahat{storeIndP1}-alphahatNew; - -% x0hat{storeIndP1} = 2*x0hat{storeIndP1} - x0new; -% Px0hat{storeIndP1} = 2*Px0hat{storeIndP1}- Px0new; -% [V,D] = eig(Px0hat{storeIndP1}); -% D(D<0)=1e-9; -% Px0hat{storeIndP1} = V*D*V'; -% Px0hat{storeIndP1} = (Px0hat{storeIndP1}+Px0hat{storeIndP1}')/2; - - - end - if(KFEM_Constraints.EstimateA==0) - Ahat{storeIndP1}=Ahat{storeInd}; - end - if(cnt==1) - dLikelihood(cnt+1)=inf; - else - dLikelihood(cnt+1)=(ll(cnt)-ll(cnt-1));%./abs(logll(cnt-1)); - end - if(cnt==1) - QhatInit = Qhat{1}; - RhatInit = Rhat{1}; - xKInit = x_K{1}; - end - %Plot the progress -% if(mod(cnt,2)==0) - if(cnt==1) - scrsz = get(0,'ScreenSize'); - h=figure('OuterPosition',[scrsz(3)*.01 scrsz(4)*.04 scrsz(3)*.98 scrsz(4)*.95]); - end - figure(h); - time = 0:(size(y,2)-1); - - subplot(2,5,[1 2 6 7]); plot(1:cnt,ll,'k','Linewidth', 2); hy=ylabel('Log Likelihood'); hx=xlabel('Iteration'); axis auto; - set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - subplot(2,5,3:5); hNew=plot(time, x_K{storeInd}','Linewidth', 2); hy=ylabel('States'); hx=xlabel('time [s]'); - set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - hold on; hOrig=plot(time, xKInit','--','Linewidth', 2); - legend([hOrig(1) hNew(1)],'Initial','Current'); - - subplot(2,5,8); hNew=plot(diag(Qhat{storeInd}),'o','Linewidth', 2); hy=ylabel('Q'); hx=xlabel('Diagonal Entry'); - set(gca, 'XTick' , 1:1:length(diag(Qhat{storeInd}))); - set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - hold on; hOrig=plot(diag(QhatInit),'r.','Linewidth', 2); - legend([hOrig(1) hNew(1)],'Initial','Current'); - - subplot(2,5,9); hNew=plot(diag(Rhat{storeInd}),'o','Linewidth', 2); hy=ylabel('R'); hx=xlabel('Diagonal Entry'); - set(gca, 'XTick' , 1:1:length(diag(Rhat{storeInd}))); - set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - hold on; hOrig=plot(diag(RhatInit),'r.','Linewidth', 2); - legend([hOrig(1) hNew(1)],'Initial','Current'); - - - subplot(2,5,10); imagesc(Rhat{storeInd}); ht=title('R Matrix Image'); - set(gca, 'XTick' , 1:1:length(diag(Rhat{storeInd})), 'YTick', 1:1:length(diag(Rhat{storeInd}))); - set(ht,'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - drawnow; - hold off; -% end - - if(cnt==1) - dMax=inf; - else - dQvals = max(max(abs(sqrt(Qhat{storeInd})-sqrt(Qhat{storeIndM1})))); - dRvals = max(max(abs(sqrt(Rhat{storeInd})-sqrt(Rhat{storeIndM1})))); - dAvals = max(max(abs((Ahat{storeInd})-(Ahat{storeIndM1})))); - dCvals = max(max(abs((Chat{storeInd})-(Chat{storeIndM1})))); - dAlphavals = max(abs((alphahat{storeInd})-(alphahat{storeIndM1}))); - dMax = max([dQvals,dRvals,dAvals,dCvals,dAlphavals]); - end - -% -% dQRel = max(abs(dQvals./sqrt(Qhat(:,storeIndM1)))); -% dGammaRel = max(abs(dGamma./gammahat(storeIndM1,:))); -% dMaxRel = max([dQRel,dGammaRel]); - - if(cnt==1) - disp(['Max Parameter Change: N/A']); - else - disp(['Max Parameter Change: ' num2str(dMax)]); - end - cnt=(cnt+1); - - if(dMax10) - [SE, Pvals]=DecodingAlgorithms.KF_ComputeParamStandardErrors(y, xKFinal, WKFinal, Ahat, Qhat, Chat, Rhat, alphahat, x0hat, Px0hat, ExpectationSumsFinal, KFEM_Constraints); - end - %Compute number of parameters - if(KFEM_Constraints.EstimateA==1 && KFEM_Constraints.AhatDiag==1) - n1=size(Ahat,1); - elseif(KFEM_Constraints.EstimateA==1 && KFEM_Constraints.AhatDiag==0) - n1=numel(Ahat); - else - n1=0; - end - if(KFEM_Constraints.QhatDiag==1 && KFEM_Constraints.QhatIsotropic==1) - n2=1; - elseif(KFEM_Constraints.QhatDiag==1 && KFEM_Constraints.QhatIsotropic==0) - n2=size(Qhat,1); - else - n2=numel(Qhat); - end - - n3=numel(Chat); - if(KFEM_Constraints.RhatDiag==1 && KFEM_Constraints.RhatIsotropic==1) - n4=1; - elseif(KFEM_Constraints.QhatDiag==1 && KFEM_Constraints.QhatIsotropic==0) - n4=size(Rhat,1); - else - n4=numel(Rhat); - end - - if(KFEM_Constraints.EstimatePx0==1 && KFEM_Constraints.Px0Isotropic==1) - n5=1; - elseif(KFEM_Constraints.EstimatePx0==1 && KFEM_Constraints.Px0Isotropic==0) - n5=size(Px0hat,1); - else - n5=0; - end - - if(KFEM_Constraints.Estimatex0==1) - n6=size(x0hat,1); - else - n6=0; - end - - n7=size(alphahat,1); - - nTerms=n1+n2+n3+n4+n5+n6+n7; - K = size(y,2); - Dx = size(Ahat,2); - sumXkTerms = ExpectationSums{maxLLIndMod}.sumXkTerms; - llobs = ll + Dx*K/2*log(2*pi)+K/2*log(det(Qhat))... - + 1/2*trace(Qhat\sumXkTerms)... - + Dx/2*log(2*pi)+1/2*log(det(Px0hat)) ... - + 1/2*Dx; - AIC = 2*nTerms - 2*llobs; - AICc= AIC+ 2*nTerms*(nTerms+1)/(K-nTerms-1); - BIC = -2*llobs+nTerms*log(K); - IC.AIC = AIC; - IC.AICc= AICc; - IC.BIC = BIC; - IC.llobs = llobs; - IC.llcomp=ll; - - - - end - function [SE,Pvals,nTerms] = KF_ComputeParamStandardErrors(y, xKFinal, WKFinal, Ahat, Qhat, Chat, Rhat, alphahat, x0hat, Px0hat, ExpectationSumsFinal, KFEM_Constraints) - % Use inverse observed information matrix to estimate the standard errors of the estimated model parameters - % Requires computation of the complete information matrix and an estimate of the missing information matrix - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % Complete Information Matrices - % Recall from McLachlan and Krishnan Eq. 4.7 - % Io(theta;y) = Ic(theta;y) - Im(theta;y) - % Io(theta;y) = Ic(theta;y) - cov(Sc(X;theta)Sc(X;theta)') - % where Sc(X;theta) is the score vector of the complete log likelihood - % function evaluated at theta. We first compute Ic term by term and then - % approximate the covariance term using Monte Carlo approximation - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - - if(nargin<12 || isempty(KFEM_Constraints)) - KFEM_Constraints=DecodingAlgorithms.KF_EMCreateConstraints; - end - - if(KFEM_Constraints.AhatDiag==1) - IAComp=zeros(numel(diag(Ahat)),numel(diag(Ahat))); - else - IAComp=zeros(numel(Ahat),numel(Ahat)); - end - [n1,n2] =size(Ahat); - el=(eye(n1,n1)); - em=(eye(n2,n2)); - cnt=1; - N=size(y,2); - - if(KFEM_Constraints.AhatDiag==1) - for l=1:n1 - for m=l - termMat=Qhat\el(:,l)*em(:,m)'*ExpectationSumsFinal.Sxkm1xkm1.*eye(n1,n2); - termvec = diag(termMat); - IAComp(:,cnt)=termvec; - cnt=cnt+1; - end - end - else - for l=1:n1 - for m=1:n2 - termMat=(inv(Qhat))*el(:,l)*em(:,m)'*ExpectationSumsFinal.Sxkm1xkm1; - termvec=reshape(termMat',1,numel(Ahat)); - IAComp(:,cnt)=termvec'; - cnt=cnt+1; - end - end - end - - - ICComp=zeros(numel(Chat),numel(Chat)); - [n1,n2] =size(Chat); - el=(eye(n1,n1)); - em=(eye(n2,n2)); - cnt=1; - for l=1:n1 - for m=1:n2 - termMat=Rhat\el(:,l)*em(:,m)'*ExpectationSumsFinal.Sxkxk; - termvec=reshape(termMat',1,numel(Chat)); - ICComp(:,cnt)=termvec'; - cnt=cnt+1; - end - end - - [n1,n2] =size(Rhat); - ei=(eye(n1,n1)); - ej=(eye(n2,n2)); - cnt=1; - [dy,N]=size(y); - dx=size(xKFinal,1); - - % if(KFEM_Constraints.RhatDiag==1) - % if(KFEM_Constraints.RhatIsotropic) - % IRinvComp=zeros(1,1); - % IRinvComp = 0.5*N*dy*Rhat(1,1)^2; - % else - % IRinvComp=zeros(numel(diag(Rhat)),numel(diag(Rhat))); - % for i=1:n1 - % for j=i - % termMat= N/2*(Rhat)\ei(:,i)*ej(:,j)'/(Rhat); - % termvec=diag(termMat); - % % termvec=reshape(termMat',1,numel(Rhat)); - % IRinvComp(cnt,:)=termvec'; - % cnt=cnt+1; - % end - % end - % end - % else - % IRinvComp=zeros(numel(Rhat),numel(Rhat)); - % for i=1:n1 - % for j=1:n2 - % termMat= N/2*(Rhat)\ei(:,i)*ej(:,j)'/(Rhat); - % termvec=reshape(termMat',1,numel(Rhat)); - % IRinvComp(cnt,:)=termvec; - % cnt=cnt+1; - % end - % end - % end - - [n1,n2] =size(Rhat); - el=(eye(n1,n1)); - em=(eye(n2,n2)); - cnt=1; - N=size(y,2); - if(KFEM_Constraints.RhatDiag==1) - if(KFEM_Constraints.RhatIsotropic==1) - IRComp = 0.5*N*dy*Rhat(1,1)^(-2); - else - IRComp=zeros(numel(diag(Rhat)),numel(diag(Rhat))); - for l=1:n1 - for m=l - termMat= N/2*(Rhat)\em(:,m)*el(:,l)'/(Rhat); - termvec=diag(termMat); - IRComp(:,cnt)=termvec; - cnt=cnt+1; - end - end - end - else - IRComp=zeros(numel((Rhat)),numel((Rhat))); - for l=1:n1 - for m=1:n2 - termMat= N/2*(Rhat)\em(:,m)*el(:,l)'/(Rhat); - termvec=reshape(termMat',1,numel(Rhat)); - IRComp(:,cnt)=termvec; - cnt=cnt+1; - end - end - end - - % [n1,n2] =size(Qhat); - % ei=(eye(n1,n1)); - % ej=(eye(n2,n2)); - % cnt=1; - % N=size(y,2); - % dx=size(xKFinal,1); - % if(KFEM_Constraints.QhatDiag==1) - % if(KFEM_Constraints.QhatIsotropic==1) - % IQinvComp=zeros(1,1); - % IQinvComp = 0.5*N*dx*Qhat(1,1)^2; - % - % else - % IQinvComp=zeros(numel(diag(Qhat)),numel(diag(Qhat))); - % for i=1:n1 - % for j=i - % termMat= N/2*(Qhat)\ei(:,i)*ej(:,j)'/(Qhat); - % termvec=diag(termMat); - % % termvec=reshape(termMat',1,numel(Qhat)); - % IQinvComp(cnt,:)=termvec'; - % cnt=cnt+1; - % end - % end - % end - % else - % IQinvComp=zeros(numel(Qhat),numel(Qhat)); - % for i=1:n1 - % for j=1:n2 - % termMat= N/2*(Qhat)\ei(:,i)*ej(:,j)'/(Qhat); - % termvec=reshape(termMat',1,numel(Qhat)); - % IQinvComp(cnt,:)=termvec'; - % cnt=cnt+1; - % end - % end - % end - - [n1,n2] =size(Qhat); - el=(eye(n1,n1)); - em=(eye(n2,n2)); - cnt=1; - N=size(y,2); - if(KFEM_Constraints.QhatDiag==1) - if(KFEM_Constraints.QhatIsotropic==1) - IQComp=zeros(1,1); - IQComp = 0.5*N*dx*Qhat(1,1)^(-2); - else - IQComp=zeros(numel(diag(Qhat)),numel(diag(Qhat))); - for l=1:n1 - for m=l - termMat= N/2*(Qhat)\em(:,m)*el(:,l)'/(Qhat); - termvec=diag(termMat); - IQComp(:,cnt)=termvec; - cnt=cnt+1; - end - end - end - else - IQComp=zeros(numel(Qhat),numel(Qhat)); - for l=1:n1 - for m=1:n2 - termMat= N/2*(Qhat)\em(:,m)*el(:,l)'/(Qhat); - termvec=reshape(termMat',1,numel(Qhat)); - IQComp(:,cnt)=termvec; - cnt=cnt+1; - end - end - end - - if(KFEM_Constraints.EstimatePx0==1) - if(KFEM_Constraints.Px0Isotropic==1) - % ISinvComp = 0.5*dx*Px0hat(1,1)^2; - ISComp = 0.5*dx*Px0hat(1,1)^(-2); - else - % ISinvComp=zeros(numel(diag(Px0hat)),numel(diag(Px0hat))); - % [n1,n2] =size(Px0hat); - % ei=(eye(n1,n1)); - % ej=(eye(n2,n2)); - % cnt=1; - % for i=1:n1 - % for j=i - % termMat= 1/2*(Px0hat)\ei(:,i)*ej(:,j)'/(Px0hat); - % % termvec=reshape(termMat',1,numel(Px0hat)); - % termvec=diag(termMat); - % ISinvComp(cnt,:)=termvec'; - % cnt=cnt+1; - % end - % end - - ISComp=zeros(numel(diag(Px0hat)),numel(diag(Px0hat))); - [n1,n2] =size(Px0hat); - el=(eye(n1,n1)); - em=(eye(n2,n2)); - cnt=1; - for l=1:n1 - for m=l - termMat= 1/2*(Px0hat)\em(:,m)*el(:,l)'/(Px0hat); - termvec=diag(termMat); - % termvec=reshape(termMat',1,numel(Rhat)); - ISComp(:,cnt)=termvec; - cnt=cnt+1; - end - end - end - end - - if(KFEM_Constraints.Estimatex0==1) - Ix0Comp=eye(size(Px0hat))/Px0hat+(Ahat'/Qhat)*Ahat; - end - - IAlphaComp = N*eye(size(Rhat))/Rhat; - if(KFEM_Constraints.EstimateA==1) - n1=size(IAComp,1); - else - n1=0; - end - n2=size(IQComp,1); n3=size(ICComp,1); - n4=size(IRComp,1); - if(KFEM_Constraints.EstimatePx0==1) - n5=size(ISComp,1); - else - n5=0; - end - if(KFEM_Constraints.Estimatex0==1) - n6=size(Ix0Comp,1); - else - n6=0; - end - n7=size(IAlphaComp,1); - nTerms=n1+n2+n3+n4+n5+n6+n7; - IComp = zeros(nTerms,nTerms); - if(KFEM_Constraints.EstimateA==1) - IComp(1:n1,1:n1)=IAComp; - end - offset=n1+1; - IComp(offset:(n1+n2),offset:(n1+n2))=IQComp; - offset=n1+n2+1; - IComp(offset:(n1+n2+n3),offset:(n1+n2+n3))=ICComp; - offset=n1+n2+n3+1; - IComp(offset:(n1+n2+n3+n4),offset:(n1+n2+n3+n4))=IRComp; - offset=n1+n2+n3+n4+1; - if(KFEM_Constraints.EstimatePx0==1); - IComp(offset:(n1+n2+n3+n4+n5),offset:(n1+n2+n3+n4+n5))=ISComp; - end - offset=n1+n2+n3+n4+n5+1; - if(KFEM_Constraints.Estimatex0==1) - IComp(offset:(n1+n2+n3+n4+n5+n6),offset:(n1+n2+n3+n4+n5+n6))=Ix0Comp; - end - offset=n1+n2+n3+n4+n5+n6+1; - IComp(offset:(n1+n2+n3+n4+n5+n6+n7),offset:(n1+n2+n3+n4+n5+n6+n7))=IAlphaComp; - - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %Missing Information Matrix - %Approximate cov(Sc(X;theta)Sc(X;theta)') - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - K=size(y,2); - Mc=KFEM_Constraints.mcIter; - xKDraw = zeros(size(xKFinal,1),N,Mc); - % IMissing = zeros(nTerms,nTerms); - % - % if(KFEM_Constraints.AhatDiag==1) - % ScoreAMc = zeros(numel(diag(Ahat)),Mc); - % IAMissing=zeros(numel(diag(Ahat)),numel(diag(Ahat))); - % else - % ScoreAMc = zeros(numel(Ahat),Mc); - % IAMissing=zeros(numel(Ahat),numel(Ahat)); - % end - % - % ScoreCMc = zeros(numel(Chat),Mc); - % if(KFEM_Constraints.RhatDiag==1) - % if(KFEM_Constraints.RhatIsotropic==1) - % ScoreRinvMc = zeros(1,Mc); - % ScoreRMc = zeros(1,Mc); - % IRinvMissing=zeros(1,1); - % IRMissing=zeros(1,1); - % else - % ScoreRinvMc = zeros(numel(diag(Rhat)),Mc); - % ScoreRMc = zeros(numel(diag(Rhat)),Mc); - % IRinvMissing=zeros(numel(diag(Rhat)),numel(diag(Rhat))); - % IRMissing=zeros(numel(diag(Rhat)),numel(diag(Rhat))); - % end - % else - % ScoreRMc = zeros(numel(Rhat),Mc); - % ScoreRinvMc = zeros(numel(Rhat),Mc); - % IRMissing=zeros(numel(Rhat),numel(Rhat)); - % IRinvMissing=zeros(numel(Rhat),numel(Rhat)); - % end - % - % if(KFEM_Constraints.QhatDiag==1) - % if(KFEM_Constraints.QhatIsotropic==1) - % ScoreQinvMc = zeros(1,Mc); - % ScoreQMc = zeros(1,Mc); - % else - % ScoreQinvMc = zeros(numel(diag(Qhat)),Mc); - % ScoreQMc = zeros(numel(diag(Qhat)),Mc); - % end - % else - % ScoreQMc = zeros(numel(Qhat),Mc); - % end - % ScoreAlphaMc = zeros(numel(alphahat),Mc); - - % Generate the Monte Carlo samples for the unobserved data - for n=1:N - WuTemp=(WKFinal(:,:,n)); - [chol_m,p]=chol(WuTemp); - z=normrnd(0,1,size(xKFinal,1),Mc); - xKDraw(:,n,:)=repmat(xKFinal(:,n),[1 Mc])+(chol_m*z); - end - - - if(KFEM_Constraints.EstimatePx0|| KFEM_Constraints.Estimatex0) - [chol_m,p]=chol(Px0hat); - z=normrnd(0,1,size(xKFinal,1),Mc); - x0Draw=repmat(x0hat,[1 Mc])+(chol_m*z); - else - x0Draw=repmat(x0hat, [1 Mc]); - - end - - IMc = zeros(nTerms,nTerms,Mc); - % Emperically estimate the covariance of the score - % if matlabpool('size') == 0 % checking to see if my pool is already open - % matlabpool; - % end -% pools = matlabpool('size'); %number of parallel workers -pools=0; - if(pools==0) % parallel toolbox is not enabled; - for c=1:Mc - x_K=xKDraw(:,:,c); - x_0=x0Draw(:,c); - - Dx=size(x_K,1); - Dy=size(y,1); - Sxkm1xk = zeros(Dx,Dx); - Sxkm1xkm1 = zeros(Dx,Dx); - Sxkxk = zeros(Dx,Dx); - Sykyk = zeros(Dy,Dy); - Sxkyk = zeros(Dx,Dy); - - for k=1:K - if(k==1) - Sxkm1xk = Sxkm1xk+x_0*x_K(:,k)'; - Sxkm1xkm1 = Sxkm1xkm1+x_0*x_0'; - else - Sxkm1xk = Sxkm1xk+x_K(:,k-1)*x_K(:,k)'; - Sxkm1xkm1= Sxkm1xkm1+x_K(:,k-1)*x_K(:,k-1)'; - end - Sxkxk = Sxkxk+x_K(:,k)*x_K(:,k)'; - Sykyk = Sykyk+(y(:,k)-alphahat)*(y(:,k)-alphahat)'; - Sxkyk = Sxkyk+x_K(:,k)*(y(:,k)-alphahat)'; - - end - Sx0x0 = x_0*x_0'; - Sxkxk = 0.5*(Sxkxk+Sxkxk'); - Sykyk = 0.5*(Sykyk+Sykyk'); - sumXkTerms = Sxkxk-Ahat*Sxkm1xk-Sxkm1xk'*Ahat'+Ahat*Sxkm1xkm1*Ahat'; - sumYkTerms = Sykyk - Chat*Sxkyk - Sxkyk'*Chat' + Chat*Sxkxk*Chat'; - Sxkxkm1 = Sxkm1xk'; - Sykxk = Sxkyk'; - - - sumXkTerms=0.5*(sumXkTerms+sumXkTerms'); - sumYkTerms=0.5*(sumYkTerms+sumYkTerms'); - if(KFEM_Constraints.EstimateA==1) - ScorA=Qhat\(Sxkxkm1-Ahat*Sxkm1xkm1); - if(KFEM_Constraints.AhatDiag==1) - ScoreAMc=diag(ScorA); - else - ScoreAMc=reshape(ScorA',numel(Ahat),1); - end - end - - ScorC=Rhat\(Sykxk-Chat*Sxkxk); - ScoreCMc=reshape(ScorC',numel(ScorC),1); - - if(KFEM_Constraints.QhatDiag) - if(KFEM_Constraints.QhatIsotropic) - ScoreQ =-.5*(K*Dx*Qhat(1,1)^(-1) - Qhat(1,1)^(-2)*trace(sumXkTerms)); - else - ScoreQ =(-.5*(Qhat\(K*eye(size(Qhat)) - sumXkTerms/Qhat))); - end - ScoreQMc = diag(ScoreQ); - else - ScoreQ =-.5*(Qhat\(K*eye(size(Qhat)) - sumXkTerms/Qhat)); - ScoreQMc =reshape(ScoreQ',numel(ScoreQ),1); - end - - - ScoreAlphaMc = sum(Rhat\(y-Chat*x_K-alphahat*ones(1,N)),2); - if(KFEM_Constraints.RhatDiag) - if(KFEM_Constraints.RhatIsotropic) - ScoreR =-.5*(K*Dy*Rhat(1,1)^(-1) - Rhat(1,1)^(-2)*trace(sumYkTerms)); - else - ScoreR =(-.5*(Rhat\(K*eye(size(Rhat)) - sumYkTerms/Rhat))); - end - ScoreRMc = diag(ScoreR); - else - ScoreR =-.5*(Rhat\(K*eye(size(Rhat)) - sumYkTerms/Rhat)); - ScoreRMc =reshape(ScoreR',numel(ScoreR),1); - end - - - if(KFEM_Constraints.Px0Isotropic==1) - ScoreSMc=-.5*(Dx*Px0hat(1,1)^(-1) - Px0hat(1,1)^(-2)*trace((x_0-x0hat)*(x_0-x0hat)')); - else - ScorS =-.5*(Px0hat\(eye(size(Px0hat)) - (x_0-x0hat)*(x_0-x0hat)'/Px0hat)); - ScoreSMc = diag(ScorS); - end - - Scorx0=(-Px0hat\(x_0-x0hat))+Ahat'/Qhat*(x_K(:,1)-Ahat*x_0); - Scorex0Mc=reshape(Scorx0',numel(Scorx0),1); - - if(KFEM_Constraints.EstimateA==1) - ScoreVec = ScoreAMc; - else - ScoreVec = []; - end - ScoreVec = [ScoreVec; ScoreQMc; ScoreCMc; ScoreRMc]; - if(KFEM_Constraints.EstimatePx0==1) - ScoreVec = [ScoreVec; ScoreSMc]; - end - if(KFEM_Constraints.Estimatex0==1) - ScoreVec = [ScoreVec; Scorex0Mc]; - end - ScoreVec = [ScoreVec; ScoreAlphaMc]; - IMc(:,:,c)=ScoreVec*ScoreVec'; - end - else %Use the parallel toolbox - for c=1:Mc - x_K=xKDraw(:,:,c); - x_0=x0Draw(:,c); - - Dx=size(x_K,1); - Dy=size(y,1); - Sxkm1xk = zeros(Dx,Dx); - Sxkm1xkm1 = zeros(Dx,Dx); - Sxkxk = zeros(Dx,Dx); - Sykyk = zeros(Dy,Dy); - Sxkyk = zeros(Dx,Dy); - - for k=1:K - if(k==1) - Sxkm1xk = Sxkm1xk+x_0*x_K(:,k)'; - Sxkm1xkm1 = Sxkm1xkm1+x_0*x_0'; - else - Sxkm1xk = Sxkm1xk+x_K(:,k-1)*x_K(:,k)'; - Sxkm1xkm1= Sxkm1xkm1+x_K(:,k-1)*x_K(:,k-1)'; - end - Sxkxk = Sxkxk+x_K(:,k)*x_K(:,k)'; - Sykyk = Sykyk+(y(:,k)-alphahat)*(y(:,k)-alphahat)'; - Sxkyk = Sxkyk+x_K(:,k)*(y(:,k)-alphahat)'; - - end - Sx0x0 = x_0*x_0'; - Sxkxk = 0.5*(Sxkxk+Sxkxk'); - Sykyk = 0.5*(Sykyk+Sykyk'); - sumXkTerms = Sxkxk-Ahat*Sxkm1xk-Sxkm1xk'*Ahat'+Ahat*Sxkm1xkm1*Ahat'; - sumYkTerms = Sykyk - Chat*Sxkyk - Sxkyk'*Chat' + Chat*Sxkxk*Chat'; - Sxkxkm1 = Sxkm1xk'; - Sykxk = Sxkyk'; - - - sumXkTerms=0.5*(sumXkTerms+sumXkTerms'); - sumYkTerms=0.5*(sumYkTerms+sumYkTerms'); - if(KFEM_Constraints.EstimateA==1) - ScorA=Qhat\(Sxkxkm1-Ahat*Sxkm1xkm1); - if(KFEM_Constraints.AhatDiag==1) - ScoreAMc=diag(ScorA); - else - ScoreAMc=reshape(ScorA',numel(Ahat),1); - end - else - ScoreAMc=[]; - end - - ScorC=Rhat\(Sykxk-Chat*Sxkxk); - ScoreCMc=reshape(ScorC',numel(ScorC),1); - - if(KFEM_Constraints.QhatDiag) - if(KFEM_Constraints.QhatIsotropic) - ScoreQ =-.5*(K*Dx*Qhat(1,1)^(-1) - Qhat(1,1)^(-2)*trace(sumXkTerms)); - else - ScoreQ =(-.5*(Qhat\(K*eye(size(Qhat)) - sumXkTerms/Qhat))); - end - ScoreQMc = diag(ScoreQ); - else - ScoreQ =-.5*(Qhat\(K*eye(size(Qhat)) - sumXkTerms/Qhat)); - ScoreQMc =reshape(ScoreQ',numel(ScoreQ),1); - end - - - ScoreAlphaMc = sum(Rhat\(y-Chat*x_K-alphahat*ones(1,N)),2); - if(KFEM_Constraints.RhatDiag) - if(KFEM_Constraints.RhatIsotropic) - ScoreR =-.5*(K*Dy*Rhat(1,1)^(-1) - Rhat(1,1)^(-2)*trace(sumYkTerms)); - else - ScoreR =(-.5*(Rhat\(K*eye(size(Rhat)) - sumYkTerms/Rhat))); - end - ScoreRMc = diag(ScoreR); - else - ScoreR =-.5*(Rhat\(K*eye(size(Rhat)) - sumYkTerms/Rhat)); - ScoreRMc =reshape(ScoreR',numel(ScoreR),1); - end - - - if(KFEM_Constraints.Px0Isotropic==1) - ScoreSMc=-.5*(Dx*Px0hat(1,1)^(-1) - Px0hat(1,1)^(-2)*trace((x_0-x0hat)*(x_0-x0hat)')); - else - ScorS =-.5*(Px0hat\(eye(size(Px0hat)) - (x_0-x0hat)*(x_0-x0hat)'/Px0hat)); - ScoreSMc = diag(ScorS); - end - - Scorx0=(-Px0hat\(x_0-x0hat))+Ahat'/Qhat*(x_K(:,1)-Ahat*x_0); - Scorex0Mc=reshape(Scorx0',numel(Scorx0),1); - ScoreVec = [ScoreAMc; ScoreQMc; ScoreCMc; ScoreRMc]; - if(KFEM_Constraints.EstimatePx0==1) - ScoreVec = [ScoreVec; ScoreSMc]; - end - if(KFEM_Constraints.Estimatex0==1) - ScoreVec = [ScoreVec; Scorex0Mc]; - end - ScoreVec = [ScoreVec; ScoreAlphaMc]; - IMc(:,:,c)=ScoreVec*ScoreVec'; - end - - end - IMissing = 1/Mc*sum(IMc,3); - IObs = IComp-IMissing; - invIObs = eye(size(IObs))/IObs; - % figure(1); subplot(1,2,1); imagesc(invIObs); subplot(1,2,2); imagesc(nearestSPD(invIObs)); - invIObs = nearestSPD(invIObs); % Find the nearest positive semidefinite approximation for the variance matrix - VarVec = (diag(invIObs)); - SEVec = sqrt(VarVec); - SEAterms = SEVec(1:n1); - SEQterms = SEVec(n1+1:(n1+n2)); - SECterms = SEVec(n1+n2+1:(n1+n2+n3)); - SERterms = SEVec(n1+n2+n3+1:(n1+n2+n3+n4)); - SEPx0terms=SEVec(n1+n2+n3+n4+1:(n1+n2+n3+n4+n5)); - SEx0terms=SEVec(n1+n2+n3+n4+n5+1:(n1+n2+n3+n4+n5+n6)); - SEAlphaterms=SEVec(n1+n2+n3+n4+n5+n6+1:(n1+n2+n3+n4+n5+n6+n7)); - - % matlabpool close; - - % figure(1); - % subplot(1,3,1); image(IObs); subplot(1,3,2); image(IComp); subplot(1,3,3); image(IMissing); - if(KFEM_Constraints.EstimatePx0==1) - SES = diag(SEPx0terms); - end - if(KFEM_Constraints.Estimatex0==1) - SEx0=SEx0terms; - end - if(KFEM_Constraints.EstimateA==1) - if(KFEM_Constraints.AhatDiag==1) - SEA=diag(SEAterms); - else - SEA=reshape(SEAterms,size(Ahat,1),size(Ahat,2))'; - end - end - SEC=reshape(SECterms,size(Chat,2),size(Chat,1))'; - SEAlpha=reshape(SEAlphaterms,size(alphahat,1),size(alphahat,2)); - - if(KFEM_Constraints.RhatDiag==1) - SER=diag(SERterms); - else - SER=reshape(SERterms,size(Rhat,1),size(Rhat,2))'; - end - if(KFEM_Constraints.QhatDiag==1) - SEQ=diag(SEQterms); - else - SEQ=reshape(SEQterms,size(Qhat,1),size(Qhat,2))'; - end - if(KFEM_Constraints.EstimateA==1) - SE.A = SEA; - end - SE.Q = SEQ; - SE.C = SEC; - SE.R = SER; - SE.alpha = SEAlpha; - - if(KFEM_Constraints.EstimatePx0==1) - SE.Px0=SES; - end - if(KFEM_Constraints.Estimatex0==1) - SE.x0=SEx0; - end - % Compute parameter p-values - if(KFEM_Constraints.EstimateA==1) - clear h p; - if(KFEM_Constraints.AhatDiag==1) - VecParams = diag(Ahat); - VecSE = diag(SEA); - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pA = diag(p); - else - VecParams = reshape(Ahat,[numel(Ahat) 1]); - VecSE = reshape(SEA, [numel(Ahat) 1]); - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pA = reshape(p, [size(Ahat,1) size(Ahat,2)]); - end - end - %C matrix - clear h p; - VecParams = reshape(Chat,[numel(Chat) 1]); - VecSE = reshape(SEC, [numel(Chat) 1]); - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pC = reshape(p, [size(Chat,1) size(Chat,2)]); - - %R matrix - clear h p; - if(KFEM_Constraints.RhatDiag==1) - if(KFEM_Constraints.RhatIsotropic==1) - VecParams = Rhat(1,1); - VecSE = SER(1,1); - [h p] = ztest(VecParams,0,VecSE); - pR = diag(p); - else - VecParams = diag(Rhat); - VecSE = diag(SER); - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pR = diag(p); - end - else - VecParams = reshape(Rhat,[numel(Rhat) 1]); - VecSE = reshape(SER, [numel(Rhat) 1]); - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pR = reshape(p, [size(Rhat,1) size(Rhat,2)]); - end - - %Q matrix - clear h p; - if(KFEM_Constraints.QhatDiag==1) - if(KFEM_Constraints.QhatIsotropic==1) - VecParams = Qhat(1,1); - VecSE = SEQ(1,1); - [h p] = ztest(VecParams,0,VecSE); - pQ = diag(p); - else - VecParams = diag(Qhat); - VecSE = diag(SEQ); - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pQ = diag(p); - end - else - VecParams = reshape(Qhat,[numel(Qhat) 1]); - VecSE = reshape(SEQ, [numel(Qhat) 1]); - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pQ = reshape(p, [size(Qhat,1) size(Qhat,2)]); - end - %Px0 - if(KFEM_Constraints.EstimatePx0==1) - clear h p; - if(KFEM_Constraints.Px0Isotropic==1) - VecParams = Px0hat(1,1); - VecSE = SES(1,1); - [h p] = ztest(VecParams,0,VecSE); - pPX0 = diag(p); - else - VecParams = diag(Px0hat); - VecSE = diag(SES); - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pPX0 = diag(p); - end - end - - clear h p; - VecParams = alphahat; - VecSE = SEAlpha; - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pAlpha = p'; - - if(KFEM_Constraints.Estimatex0==1) - clear h p; - VecParams = x0hat; - VecSE = SEx0; - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pX0 = p'; - end - if(KFEM_Constraints.EstimateA==1) - Pvals.A = pA; - end - Pvals.Q = pQ; - Pvals.C = pC; - Pvals.R = pR; - Pvals.alpha = pAlpha; - if(KFEM_Constraints.EstimatePx0==1) - Pvals.Px0 = pPX0; - end - if(KFEM_Constraints.Estimatex0==1) - Pvals.x0 = pX0; - end - - end - function [x_K,W_K,logll,ExpectationSums]=KF_EStep(A,Q,C,R, y, alpha, x0, Px0) - DEBUG = 0; - - Dx = size(A,2); - Dy = size(C,1); - K=size(y,2); - [x_p, W_p, x_u, W_u] = DecodingAlgorithms.kalman_filter(A, C, Q, R,Px0, x0, y-alpha*ones(1,size(y,2))); - - [x_K, W_K,Lk] = DecodingAlgorithms.kalman_smootherFromFiltered(A, x_p, W_p, x_u, W_u); - - %Best estimates of initial states given the data - W1G0 = A*Px0*A' + Q; - L0=Px0*A'/W1G0; - - Ex0Gy = x0+L0*(x_K(:,1)-x_p(:,1)); - Px0Gy = Px0+L0*(eye(size(W_K(:,:,1)))/(W_K(:,:,1))-eye(size(W1G0))/W1G0)*L0'; - Px0Gy = (Px0Gy+Px0Gy')/2; - numStates = size(x_K,1); - Wku=zeros(numStates,numStates,K,K); - Tk = zeros(numStates,numStates,K-1); - for k=1:K - Wku(:,:,k,k)=W_K(:,:,k); - end - - for u=K:-1:2 - for k=(u-1):-1:(u-1) - Tk(:,:,k)=A; -% Dk(:,:,k)=W_u(:,:,k)*Tk(:,:,k)'*pinv(W_p(:,:,k)); %From deJong and MacKinnon 1988 - Dk(:,:,k)=W_u(:,:,k)*Tk(:,:,k)'/(W_p(:,:,k+1)); %From deJong and MacKinnon 1988 - Wku(:,:,k,u)=Dk(:,:,k)*Wku(:,:,k+1,u); - Wku(:,:,u,k)=Wku(:,:,k,u)'; - end - end - - %All terms - Sxkm1xk = zeros(Dx,Dx); - Sxkxkm1 = zeros(Dx,Dx); - Sxkm1xkm1 = zeros(Dx,Dx); - Sxkxk = zeros(Dx,Dx); - Sykyk = zeros(Dy,Dy); - Sxkyk = zeros(Dx,Dy); - for k=1:K - if(k==1) - Sxkm1xk = Sxkm1xk+Px0*A'/W_p(:,:,1)*Wku(:,:,1,1); - Sxkm1xkm1 = Sxkm1xkm1+Px0+x0*x0'; - else - Sxkm1xk = Sxkm1xk+Wku(:,:,k-1,k)+x_K(:,k-1)*x_K(:,k)'; - Sxkm1xkm1= Sxkm1xkm1+Wku(:,:,k-1,k-1)+x_K(:,k-1)*x_K(:,k-1)'; - end - Sxkxk = Sxkxk+Wku(:,:,k,k)+x_K(:,k)*x_K(:,k)'; - Sykyk = Sykyk+(y(:,k)-alpha)*(y(:,k)-alpha)'; - Sxkyk = Sxkyk+x_K(:,k)*(y(:,k)-alpha)'; - - end - Sx0x0 = Px0+x0*x0'; - Sxkxk = 0.5*(Sxkxk+Sxkxk'); - Sykyk = 0.5*(Sykyk+Sykyk'); - sumXkTerms = Sxkxk-A*Sxkm1xk-Sxkm1xk'*A'+A*Sxkm1xkm1*A'; - sumYkTerms = Sykyk - C*Sxkyk - Sxkyk'*C' + C*Sxkxk*C'; - Sxkxkm1 = Sxkm1xk'; - - - - logll = -Dx*K/2*log(2*pi)-K/2*log(det(Q))-Dy*K/2*log(2*pi)... - -K/2*log(det(R))- Dx/2*log(2*pi) -1/2*log(det(Px0)) ... - -1/2*trace((eye(size(Q))/Q)*sumXkTerms) ... - -1/2*trace((eye(size(R))/R)*sumYkTerms) ... - -Dx/2; - string0 = ['logll: ' num2str(logll)]; - disp(string0); - if(DEBUG==1) - string1 = ['-K/2*log(det(Q)):' num2str(-K/2*log(det(Q)))]; - string11 = ['-K/2*log(det(R)):' num2str(-K/2*log(det(R)))]; - string12= ['Constants: ' num2str(-Dx*K/2*log(2*pi)-Dy*K/2*log(2*pi)- Dx/2*log(2*pi) -Dx/2 -1/2*log(det(Px0)))]; - string3 = ['-.5*trace(Q\sumXkTerms): ' num2str(-.5*trace(Q\sumXkTerms))]; - string4 = ['-.5*trace(R\sumYkTerms): ' num2str(-.5*trace(R\sumYkTerms))]; - - disp(string1); - disp(['Q=' num2str(diag(Q)')]); - disp(string11); - disp(['R=' num2str(diag(R)')]); - disp(string12); - disp(string3); - disp(string4); - end - - ExpectationSums.Sxkm1xkm1=Sxkm1xkm1; - ExpectationSums.Sxkm1xk=Sxkm1xk; - ExpectationSums.Sxkxkm1=Sxkxkm1; - ExpectationSums.Sxkxk=Sxkxk; - ExpectationSums.Sxkyk=Sxkyk; - ExpectationSums.Sykyk=Sykyk; - ExpectationSums.sumXkTerms=sumXkTerms; - ExpectationSums.sumYkTerms=sumYkTerms; - ExpectationSums.Sx0 = Ex0Gy; - ExpectationSums.Sx0x0 = Px0Gy + Ex0Gy*Ex0Gy'; - - end - function [Ahat, Qhat, Chat, Rhat, alphahat, x0hat, Px0hat] = KF_MStep(y,x_K,x0, Px0, ExpectationSums,KFEM_Constraints) - if(nargin<6 || isempty(KFEM_Constraints)) - KFEM_Constraints = DecodingAlgorithms.KF_EMCreateConstraints; - end - Sxkm1xkm1=ExpectationSums.Sxkm1xkm1; - Sxkxkm1=ExpectationSums.Sxkxkm1; - Sxkxk=ExpectationSums.Sxkxk; - Sxkyk=ExpectationSums.Sxkyk; - sumXkTerms = ExpectationSums.sumXkTerms; - sumYkTerms = ExpectationSums.sumYkTerms; - Sx0 = ExpectationSums.Sx0; - Sx0x0 = ExpectationSums.Sx0x0; - - [N,K] = size(x_K); - - - if(KFEM_Constraints.AhatDiag==1) - I=eye(N,N); - Ahat = (Sxkxkm1.*I)/(Sxkm1xkm1.*I); - else - Ahat = Sxkxkm1/Sxkm1xkm1; - end - - -% [V,D] = eig(Px0hat); -% D(D<0)=1e-9; -% Px0hat = V*D*V'; - - - Chat = Sxkyk'/Sxkxk; - alphahat = sum(y - Chat*x_K,2)/K; - - if(KFEM_Constraints.QhatDiag==1) - if(KFEM_Constraints.QhatIsotropic==1) - Qhat=1/(N*K)*trace(sumXkTerms)*eye(N,N); - else - I=eye(N,N); - Qhat=1/K*(sumXkTerms.*I); - Qhat = (Qhat + Qhat')/2; - end - else - Qhat=1/K*sumXkTerms; - Qhat = (Qhat + Qhat')/2; - end - dy=size(sumYkTerms,1); - if(KFEM_Constraints.RhatDiag==1) - if(KFEM_Constraints.RhatIsotropic==1) - I=eye(dy,dy); - Rhat = 1/(dy*K)*trace(sumYkTerms)*I; - else - - I=eye(dy,dy); - Rhat = 1/K*(sumYkTerms.*I); - Rhat = (Rhat + Rhat')/2; - end - else - Rhat = 1/K*(sumYkTerms); - Rhat = (Rhat + Rhat')/2; - end - if(KFEM_Constraints.Estimatex0) - x0hat = (inv(Px0)+Ahat'/Qhat*Ahat)\(Ahat'/Qhat*x_K(:,1)+Px0\x0); - else - x0hat = x0; - end - - if(KFEM_Constraints.EstimatePx0==1) - if(KFEM_Constraints.Px0Isotropic==1) - Px0hat=(trace(x0hat*x0hat' - x0*x0hat' - x0hat*x0' +(x0*x0'))/(N*K))*eye(N,N); - else - I=eye(N,N); - Px0hat =(x0hat*x0hat' - x0*x0hat' - x0hat*x0' +(x0*x0')).*I; - Px0hat = (Px0hat+Px0hat')/2; - [V,Lambda]=eig(Px0hat); - Lambda = diag(Lambda); - if(min(Lambda)1) % if more than 1 cell but only 1 gamma - gammaNew(:,c) = gamma; - else - gammaNew=gamma; - end - gamma = gammaNew; - - else - for c=1:numCells - % HkAll{c} = zeros(N,1); - HkAll(:,:,c) = zeros(N,1); - gammaNew(c)=0; - end - gamma=gammaNew; - - end - if(size(gamma,2)~=numCells) - gamma=gamma'; - end - - - Alag = zeros((lags+1)*nStates,(lags+1)*nStates,N); - Qlag = zeros((lags+1)*nStates,(lags+1)*nStates,N); - Clag = zeros(nObs,(lags+1)*nStates,N); - Rlag = zeros(nObs,nObs,N); - x0lag = zeros(length(x0)*(lags+1),1); - Px0lag = zeros((lags+1)*nStates,(lags+1)*nStates); - Px0lag((1:nStates),(1:nStates))=Px0; - x0lag(1:nStates,1)=x0; - for n=1:N - offset = 0; - for i=1:(lags+1) - if(i==1) - Alag((1:nStates)+offset,(1:nStates)+offset,n)=A(:,:,min(size(A,3),n)); - Qlag((1:nStates)+offset,(1:nStates)+offset,n)=Q(:,:,min(size(Q,3),n)); - Clag((1:nObs),(1:nStates)+offset,n)=C(:,:,min(size(C,3),n)); - Rlag((1:nObs),(1:nObs),n) = R(:,:,min(size(R,3),n)); - - else - Alag((1:nStates)+offset,(1:nStates)+(offset-nStates),n)=eye(nStates,nStates); - Qlag((1:nStates)+offset,(1:nStates)+offset,n)=zeros(nStates,nStates); - Clag((1:nObs),(1:nStates)+offset,n)=zeros(nObs,nStates); - - end - offset=offset+nStates; - end - end - - betaLag = zeros((lags+1)*nStates, numCells); - betaLag(1:nStates,1:numCells)=beta; - [x_p, W_p, x_u, W_u] = DecodingAlgorithms.mPPCODecodeLinear(Alag, Qlag, Clag, Rlag, y, alpha, dN,mu,betaLag,fitType,delta,gamma,windowTimes,x0lag,Px0lag,HkAll); - - - x_pLag = x_p((lags*nStates+1):(lags+1)*nStates,:); - W_pLag = W_p((lags*nStates+1):(lags+1)*nStates,(lags*nStates+1):(lags+1)*nStates,:); - x_uLag = x_u((lags*nStates+1):(lags+1)*nStates,:); - W_uLag = W_u((lags*nStates+1):(lags+1)*nStates,(lags*nStates+1):(lags+1)*nStates,:); - - end - function [x_p, W_p, x_u, W_u] = mPPCODecodeLinear(A, Q, C, R, y, alpha, dN,mu,beta,fitType,delta,gamma,windowTimes,x0,Px0,HkAll) - % [x_p, W_p, x_u, W_u] = mPPCODecodeLinear(A, Q, C, R, y, dN, mu, beta,fitType, delta, gamma,windowTimes, x0) - % Point process adaptive filter with the assumption of linear - % expresion for the conditional intensity functions (see below). If - % the terms in the conditional intensity function include - % polynomial powers of a variable for example, these expressions do - % not hold. Use the PPDecodeFilter instead since it will compute - % these expressions symbolically. However, because of the matlab - % symbolic toolbox, it runs much slower than this version. - % - % Assumes in both cases that - % x_t = A*x_{t-1} + v_{t} w_{t} ~ Normal with zero me and - % covariance Q - % - % y_t = C*x_{t} + w_{t} w_{t} ~ Normal with zero me and - % covariance R - % - % Paramerters: - % - % A: The state transition matrix from the x_{t-1} to x_{t} - % - % Q: The covariance of the process noise v_t - % - % C: The observation matrix - % - % R: The covariance of the observation noise w_t - % - % y: The continuous observations - % - % alpha: Offset for the observations - % - % dN: A C x N matrix of ones and zeros corresponding to the - % observed spike trains. N is the number of time steps in - % my code. C is the number of cells - % - % mu: Cx1 vector of baseline firing rates for each cell. In - % the CIF expression in 'fitType' description - % mu_c=mu(c); - % - % beta: nsxC matrix of coefficients for the conditional - % intensity function. ns is the number of states in x_t - % In the conditional intesity function description below - % beta_c = beta(:,c)'; - % - % fitType: 'poisson' or 'binomial'. Determines how the beta and - % gamma coefficients are used to compute the conditional - % intensity function. - % For the cth cell: - % If poisson: lambda*delta = exp(mu_c+beta_c*x + gamma_c*hist_c) - % If binomial: logit(lambda*delta) = mu_c+beta_c*x + gamma_c*hist_c - % - % delta: The number of seconds per time step. This is used to compute - % th history effect for each spike train using the input - % windowTimes and gamma - % - % gamma: length(windowTimes)-1 x C matrix of the history - % coefficients for each window in windowTimes. In the 'fitType' - % expression above: - % gamma_c = gamma(:,c)'; - % If gamma is a length(windowTimes)-1x1 vector, then the - % same history coefficients are used for each cell. - % - % windowTimes: Defines the distinct windows of time (in seconds) - % that will be computed for each spike train. - % - % x0: The initial state - % - % Px0: The initial state covariance - - - - [numCells,N] = size(dN); % N time samples, C cells - ns=size(A,1); % number of states - if(nargin<16 || isempty(HkAll)) - HkAll=[]; - end - if(nargin<15 || isempty(Px0)) - Px0=zeros(ns,ns); - end - if(nargin<14 || isempty(x0)) - x0=zeros(ns,1); - - end - if(nargin<13 || isempty(windowTimes)) - windowTimes=[]; - end - if(nargin<12 || isempty(gamma)) - gamma=0; - end - if(nargin<11 || isempty(delta)) - delta = .001; - end - - - minTime=0; - maxTime=(size(dN,2)-1)*delta; - -% numCells=size(dN,1); - if(~isempty(HkAll)) - if(~isempty(windowTimes)) - histObj = History(windowTimes,minTime,maxTime); - for c=1:numCells - nst{c} = nspikeTrain( (find(dN(c,:)==1)-1)*delta); - nst{c}.setMinTime(minTime); - nst{c}.setMaxTime(maxTime); - nst{c}=nst{c}.resample(1/delta); -% HkAll{c} = histObj.computeHistory(nst{c}).dataToMatrix; - HkAll(:,:,c) = histObj.computeHistory(nst{c}).dataToMatrix; - end - if(size(gamma,2)==1 && numCells>1) % if more than 1 cell but only 1 gamma - gammaNew(:,c) = gamma; - else - gammaNew = gamma; - end - gamma = gammaNew; - end - - else - for c=1:numCells -% HkAll{c} = zeros(N,1); - HkAll(:,:,c) = zeros(N,1); - gammaNew(c)=0; - end - gamma=gammaNew; - - end - - - - %% Initialize the numCells - x_p = zeros( size(A,2), N+1 ); - x_u = zeros( size(A,2), N ); - W_p = zeros( size(A,2),size(A,2), N+1 ); - W_u = zeros( size(A,2),size(A,2), N ); - A1=A(:,:,min(size(A,3),1)); - x_p(:,1) = A1*x0; - W_p(:,:,1) = A1 * Px0 * A1' +Q(:,:,min(size(Q,3),1)); - Histtermperm = permute(HkAll,[2 3 1]); -% WuConv = []; - for n=1:N -% [x_u, W_u,lambdaDeltaMat] = mPPCODecode_update(x_p, W_p, C, R, y, alpha, dN,mu,beta,fitType,gamma,HkAll,time_index,WuConv) - [x_u(:,n), W_u(:,:,n)] = DecodingAlgorithms.mPPCODecode_update(x_p(:,n), W_p(:,:,n), C(:,:,min(size(C,3),n)), R(:,:,min(size(R,3),n)), y(:,n), alpha(:,min(size(alpha,3),n)),dN,mu,beta,fitType,gamma,Histtermperm,n,[]); %expects History with time on 3rd index - if(n1 && isempty(WuConv)) -% diffWu = abs(W_u(:,:,n)-W_u(:,:,n-1)); -% maxWu = max(max(diffWu)); -% if(maxWu<5e-4) -% WuConv = W_u(:,:,n); -% WuConvIter = n; -% end -% end - end - - - end - function [x_p, W_p] = mPPCODecode_predict(x_u, W_u, A, Q) - x_p = A * x_u; - W_p = A * W_u * A' + Q; -% if(rcond(W_p)<1000*eps) -% W_p=W_u; % See Srinivasan et al. 2007 pg. 529 -% end - W_p = .5*(W_p + W_p'); %To help with symmetry of matrix; - - end - function [x_u, W_u,lambdaDeltaMat] = mPPCODecode_update(x_p, W_p, C, R, y, alpha, dN,mu,beta,fitType,gamma,HkAll,time_index,WuConv) - [numCells,N] = size(dN); % N time samples, C cells - if(nargin<13 || isempty(WuConv)) - WuConv=[]; - end - if(nargin<12 || isempty(time_index)) - time_index=1; - end - if(nargin<11 || isempty(HkAll)) - HkAll = zeros(numCells,1); - end - if(nargin<10 || isempty(gamma)) - gamma=zeros(1,numCells); - end - if(nargin<9 || isempty(fitType)) - fitType = 'poisson'; - end - - - sumValVec=zeros(size(W_p,1),1); - sumValMat=zeros(size(W_p,2),size(W_p,2)); - lambdaDeltaMat = zeros(numCells,1); - - if(numel(gamma)==1 && gamma==0) - gamma = zeros(size(mu))'; - end - if(strcmp(fitType,'binomial')) - Histterm = HkAll(:,:,time_index); - if(size(Histterm,1)~=numCells) %make sure Histterm has proper orientation - Histterm = Histterm'; - end - - if(size(gamma,2)~=size(mu,1)) - if(size(gamma,1)==size(Histterm,1)) %All cells have same history - gamma = repmat(gamma,[1 numCells]); - end - end - linTerm = mu+beta'*x_p + diag(gamma'*Histterm'); - lambdaDeltaMat = exp(linTerm)./(1+exp(linTerm)); - if(any(isnan(lambdaDeltaMat))||any(isinf(lambdaDeltaMat))) - indNan = isnan(lambdaDeltaMat); - indInf = isinf(lambdaDeltaMat); - lambdaDeltaMat(indNan)=1; - lambdaDeltaMat(indInf)=1; - end - sumValVec=sum(repmat(((dN(:,time_index)-lambdaDeltaMat(:,1)).*(1-lambdaDeltaMat(:,1)))',size(beta,1),1).*beta,2); - tempVec = ((dN(:,time_index)+(1-2*(lambdaDeltaMat(:,1)))).*(1-(lambdaDeltaMat(:,1))).*(lambdaDeltaMat(:,1)))'; -% tempVec((tempVec<0))=0; -% tempVec((tempVec>1))=1; - sumValMat = (repmat(tempVec,size(beta,1),1).*beta)*beta'; - elseif(strcmp(fitType,'poisson')) - Histterm = HkAll(:,:,time_index); - if(size(Histterm,1)~=numCells) %make sure Histterm has proper orientation - Histterm = Histterm'; - end - - if(size(gamma,2)~=size(mu,1)) - if(size(gamma,1)==size(Histterm,1)) %All cells have same history - gamma = repmat(gamma,[1 numCells]); - end - end - - linTerm = mu+beta'*x_p + diag(gamma'*Histterm'); - lambdaDeltaMat = exp(linTerm); - if(any(isnan(lambdaDeltaMat))||any(isinf(lambdaDeltaMat))) - indNan = isnan(lambdaDeltaMat); - indInf = isinf(lambdaDeltaMat); - lambdaDeltaMat(indNan)=1; - lambdaDeltaMat(indInf)=1; - end - sumValVec=sum(repmat(((dN(:,time_index)-lambdaDeltaMat(:,1)))',size(beta,1),1).*beta,2); - sumValMat = (repmat(lambdaDeltaMat(:,1)',size(beta,1),1).*beta)*beta'; - end - if(isempty(WuConv)) - sumValMat = sumValMat+C'*(R\C); - I=eye(size(W_p)); - Wu=W_p*(I-(I+sumValMat*W_p)\(sumValMat*W_p)); - if(any(any(isnan(Wu)))||any(any(isinf(Wu)))) - Wu=W_p; - end - % Make sure that the update covariance is positive definite. - W_u = Wu; - W_u = .5*(W_u + W_u'); %To help with symmetry of matrix; - else - W_u = WuConv; - end - x_u = x_p + W_u*(sumValVec)+((W_u*C')/R)*(y-C*x_p -alpha); - - - end - function C = mPPCO_EMCreateConstraints(EstimateA, AhatDiag,QhatDiag,QhatIsotropic,RhatDiag,RhatIsotropic,Estimatex0,EstimatePx0, Px0Isotropic,mcIter,EnableIkeda) - %By default, all parameters are estimated. To empose diagonal - %structure on the EM parameter results must pass in the - %constraints element - if(nargin<11 || isempty(EnableIkeda)) - EnableIkeda=0; - end - if(nargin<10 || isempty(mcIter)) - mcIter=1000; - end - if(nargin<9 || isempty(Px0Isotropic)) - Px0Isotropic=0; - end - if(nargin<8 || isempty(EstimatePx0)) - EstimatePx0=1; - end - if(nargin<7 || isempty(Estimatex0)) - Estimatex0=1; - end - if(nargin<6 || isempty(RhatIsotropic)) - RhatIsotropic=0; - end - if(nargin<5 || isempty(RhatDiag)) - RhatDiag=1; - end - if(nargin<4 || isempty(QhatIsotropic)) - QhatIsotropic=0; - end - if(nargin<3 || isempty(QhatDiag)) - QhatDiag=1; - end - if(nargin<2) - AhatDiag=0; - end - if(nargin<1) - EstimateA=1; - end - C.EstimateA= EstimateA; - C.AhatDiag = AhatDiag; - C.QhatDiag = QhatDiag; - if(QhatDiag && QhatIsotropic) - C.QhatIsotropic=1; - else - C.QhatIsotropic=0; - end - C.RhatDiag = RhatDiag; - if(RhatDiag && RhatIsotropic) - C.RhatIsotropic=1; - else - C.RhatIsotropic=0; - end - C.Estimatex0 = Estimatex0; - C.EstimatePx0 = EstimatePx0; - if(EstimatePx0 && Px0Isotropic) - C.Px0Isotropic=1; - else - C.Px0Isotropic=0; - end - C.mcIter = mcIter; - C.EnableIkeda = EnableIkeda; - end - function [SE,Pvals,nTerms] = mPPCO_ComputeParamStandardErrors(y, dN, xKFinal, WKFinal, Ahat, Qhat, Chat, Rhat, alphahat, x0hat, Px0hat, ExpectationSumsFinal, fitType, muhat, betahat, gammahat, windowTimes, HkAll, mPPCOEM_Constraints) - - % Use inverse observed information matrix to estimate the standard errors of the estimated model parameters - % Requires computation of the complete information matrix and an estimate of the missing information matrix - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % Complete Information Matrices - % Recall from McLachlan and Krishnan Eq. 4.7 - % Io(theta;y) = Ic(theta;y) - Im(theta;y) - % Io(theta;y) = Ic(theta;y) - cov(Sc(X;theta)Sc(X;theta)') - % where Sc(X;theta) is the score vector of the complete log likelihood - % function evaluated at theta. We first compute Ic term by term and then - % approximate the covariance term using Monte Carlo approximation - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - - if(nargin<19 || isempty(mPPCOEM_Constraints)) - mPPCOEM_Constraints=DecodingAlgorithms.mPPCO_EMCreateConstraints; - end - - if(mPPCOEM_Constraints.EstimateA==1) - if(mPPCOEM_Constraints.AhatDiag==1) - IAComp=zeros(numel(diag(Ahat)),numel(diag(Ahat))); - else - IAComp=zeros(numel(Ahat),numel(Ahat)); - end - [n1,n2] =size(Ahat); - el=(eye(n1,n1)); - em=(eye(n2,n2)); - cnt=1; - N=size(y,2); - - if(mPPCOEM_Constraints.AhatDiag==1) - for l=1:n1 - for m=l - termMat=Qhat\el(:,l)*em(:,m)'*ExpectationSumsFinal.Sxkm1xkm1.*eye(n1,n2); - termvec = diag(termMat); - IAComp(:,cnt)=termvec; - cnt=cnt+1; - end - end - else - for l=1:n1 - for m=1:n2 - termMat=(inv(Qhat))*el(:,l)*em(:,m)'*ExpectationSumsFinal.Sxkm1xkm1; - termvec=reshape(termMat',1,numel(Ahat)); - IAComp(:,cnt)=termvec'; - cnt=cnt+1; - end - end - end - end - - - ICComp=zeros(numel(Chat),numel(Chat)); - [n1,n2] =size(Chat); - el=(eye(n1,n1)); - em=(eye(n2,n2)); - cnt=1; - for l=1:n1 - for m=1:n2 - termMat=Rhat\el(:,l)*em(:,m)'*ExpectationSumsFinal.Sxkxk; - termvec=reshape(termMat',1,numel(Chat)); - ICComp(:,cnt)=termvec'; - cnt=cnt+1; - end - end - - [n1,n2] =size(Rhat); - ei=(eye(n1,n1)); - ej=(eye(n2,n2)); - cnt=1; - [dy,N]=size(y); - dx=size(xKFinal,1); - - [n1,n2] =size(Rhat); - el=(eye(n1,n1)); - em=(eye(n2,n2)); - cnt=1; - N=size(y,2); - if(mPPCOEM_Constraints.RhatDiag==1) - if(mPPCOEM_Constraints.RhatIsotropic==1) - IRComp = 0.5*N*dy*Rhat(1,1)^(-2); - else - IRComp=zeros(numel(diag(Rhat)),numel(diag(Rhat))); - for l=1:n1 - for m=l - termMat= N/2*(Rhat)\em(:,m)*el(:,l)'/(Rhat); - termvec=diag(termMat); - IRComp(:,cnt)=termvec; - cnt=cnt+1; - end - end - end - else - IRComp=zeros(numel(diag(Rhat)),numel(diag(Rhat))); - for l=1:n1 - for m=1:n2 - termMat= N/2*(Rhat)\em(:,m)*el(:,l)'/(Rhat); - termvec=reshape(termMat',1,numel(Rhat)); - IRComp(:,cnt)=termvec; - cnt=cnt+1; - end - end - end - - [n1,n2] =size(Qhat); - el=(eye(n1,n1)); - em=(eye(n2,n2)); - cnt=1; - N=size(y,2); - if(mPPCOEM_Constraints.QhatDiag==1) - if(mPPCOEM_Constraints.QhatIsotropic==1) - IQComp=zeros(1,1); - IQComp = 0.5*N*dx*Qhat(1,1)^(-2); - else - IQComp=zeros(numel(diag(Qhat)),numel(diag(Qhat))); - for l=1:n1 - for m=l - termMat= N/2*(Qhat)\em(:,m)*el(:,l)'/(Qhat); - termvec=diag(termMat); - IQComp(:,cnt)=termvec; - cnt=cnt+1; - end - end - end - else - IQComp=zeros(numel(Qhat),numel(Qhat)); - for l=1:n1 - for m=1:n2 - termMat= N/2*(Qhat)\em(:,m)*el(:,l)'/(Qhat); - termvec=reshape(termMat',1,numel(Qhat)); - IQComp(:,cnt)=termvec; - cnt=cnt+1; - end - end - end - - if(mPPCOEM_Constraints.EstimatePx0==1) - if(mPPCOEM_Constraints.Px0Isotropic==1) - ISComp = 0.5*dx*Px0hat(1,1)^(-2); - else - ISComp=zeros(numel(diag(Px0hat)),numel(diag(Px0hat))); - [n1,n2] =size(Px0hat); - el=(eye(n1,n1)); - em=(eye(n2,n2)); - cnt=1; - for l=1:n1 - for m=l - termMat= 1/2*(Px0hat)\em(:,m)*el(:,l)'/(Px0hat); - termvec=diag(termMat); - ISComp(:,cnt)=termvec; - cnt=cnt+1; - end - end - end - end - - if(mPPCOEM_Constraints.Estimatex0==1) - Ix0Comp=eye(size(Px0hat))/Px0hat+(Ahat'/Qhat)*Ahat; - end - - IAlphaComp = N*eye(size(Rhat))/Rhat; - K=size(y,2); - numCells=size(betahat,2); -% McExp=500; - McExp=mPPCOEM_Constraints.mcIter; - xKDrawExp = zeros(size(xKFinal,1),K,McExp); - - - % Generate the Monte Carlo - for k=1:K -% WuTemp=squeeze(WKFinal(:,:,k)); - WuTemp=(WKFinal(:,:,k)); - [chol_m,p]=chol(WuTemp); - z=normrnd(0,1,size(xKFinal,1),McExp); - xKDrawExp(:,k,:)=repmat(xKFinal(:,k),[1 McExp])+(chol_m*z); - end - - IBetaComp =zeros(size(xKFinal,1)*numCells,size(xKFinal,1)*numCells); - xkPerm = permute(xKDrawExp,[1 3 2]); - pools = matlabpool('size'); %number of parallel workers - if(pools==0) - if(strcmp(fitType,'poisson')) - for c=1:numCells - HessianTerm = zeros(size(xKFinal,1),size(xKFinal,1)); - for k=1:K - % Hk = squeeze(HkAll(:,:,c)); - Hk = (HkAll(k,:,c)); - Wk = WKFinal(:,:,k); - - % xk = squeeze(xKDrawExp(:,k,:)); - xk=xkPerm(:,:,k); - if(size(Hk,1)==numCells) - Hk = Hk'; - end - - if(numel(gammahat)==1) - gammaC=gammahat; - % gammaC=repmat(gammaC,[1 numCells]); - else - gammaC=gammahat(:,c); - end - - terms =muhat(c)+betahat(:,c)'*xk+gammaC'*Hk'; - ld=exp(terms); - - HessianTerm=HessianTerm-1/McExp*(repmat(ld,[size(xk,1),1]).*xk)*xk'; - end - startInd = size(betahat,1)*(c-1)+1; endInd = size(betahat,1)*c; - IBetaComp(startInd:endInd,startInd:endInd)=-HessianTerm; - end - else - for c=1:numCells - HessianTerm = zeros(size(xKFinal,1),size(xKFinal,1)); - for k=1:K - % Hk = squeeze(HkAll(:,:,c)); - Hk = (HkAll(k,:,c)); - Wk = WKFinal(:,:,k); - % xk = squeeze(xKDrawExp(:,k,:)); - xk = (xkPerm(:,:,k)); - if(size(Hk,1)==numCells) - Hk = Hk'; - end - - if(numel(gammahat)==1) - gammaC=gammahat; - % gammaC=repmat(gammaC,[1 numCells]); - else - gammaC=gammahat(:,c); - end - terms =muhat(c)+betahat(:,c)'*xk+gammaC'*Hk'; - ld=exp(terms)./(1+exp(terms)); - ExplambdaDeltaXkXk=1/McExp*(repmat(ld,[size(xk,1),1]).*xk)*xk'; - ExplambdaDeltaSqXkXkT=1/McExp*(repmat(ld.^2,[size(xk,1),1]).*xk)*xk'; - ExplambdaDeltaCubeXkXkT=1/McExp*(repmat(ld.^3,[size(xk,1),1]).*xk)*xk'; - HessianTerm=HessianTerm+ExplambdaDeltaXkXk+ExplambdaDeltaSqXkXkT-2*ExplambdaDeltaCubeXkXkT; - - end - startInd = size(betahat,1)*(c-1)+1; endInd = size(betahat,1)*c; - IBetaComp(startInd:endInd,startInd:endInd)=-HessianTerm; - end - end - else - if(strcmp(fitType,'poisson')) - for c=1:numCells - HessianTerm = zeros(size(xKFinal,1),size(xKFinal,1),K); - for k=1:K - % Hk = squeeze(HkAll(:,:,c)); - Hk = (HkAll(k,:,c)); - Wk = WKFinal(:,:,k); - - % xk = squeeze(xKDrawExp(:,k,:)); - xk=xkPerm(:,:,k); - if(size(Hk,1)==numCells) - Hk = Hk'; - end - - if(numel(gammahat)==1) - gammaC=gammahat; - % gammaC=repmat(gammaC,[1 numCells]); - else - gammaC=gammahat(:,c); - end - - terms =muhat(c)+betahat(:,c)'*xk+gammaC'*Hk'; - ld=exp(terms); - - HessianTerm(:,:,k)=-1/McExp*(repmat(ld,[size(xk,1),1]).*xk)*xk'; - end - startInd = size(betahat,1)*(c-1)+1; endInd = size(betahat,1)*c; - IBetaComp(startInd:endInd,startInd:endInd)=-sum(HessianTerm,3); - end - else - for c=1:numCells - HessianTerm = zeros(size(xKFinal,1),size(xKFinal,1),K); - for k=1:K - % Hk = squeeze(HkAll(:,:,c)); - Hk = (HkAll(k,:,c)); - Wk = WKFinal(:,:,k); - % xk = squeeze(xKDrawExp(:,k,:)); - xk = (xkPerm(:,:,k)); - if(size(Hk,1)==numCells) - Hk = Hk'; - end - - if(numel(gammahat)==1) - gammaC=gammahat; - % gammaC=repmat(gammaC,[1 numCells]); - else - gammaC=gammahat(:,c); - end - terms =muhat(c)+betahat(:,c)'*xk+gammaC'*Hk'; - ld=exp(terms)./(1+exp(terms)); - ExplambdaDeltaXkXk=1/McExp*(repmat(ld,[size(xk,1),1]).*xk)*xk'; - ExplambdaDeltaSqXkXkT=1/McExp*(repmat(ld.^2,[size(xk,1),1]).*xk)*xk'; - ExplambdaDeltaCubeXkXkT=1/McExp*(repmat(ld.^3,[size(xk,1),1]).*xk)*xk'; - HessianTerm(:,:,k)=+ExplambdaDeltaXkXk+ExplambdaDeltaSqXkXkT-2*ExplambdaDeltaCubeXkXkT; - - end - startInd = size(betahat,1)*(c-1)+1; endInd = size(betahat,1)*c; - IBetaComp(startInd:endInd,startInd:endInd)=-sum(HessianTerm,3); - end - - end - end - - - %CIF means - IMuComp=zeros(numel(muhat),numel(muhat)); - xkPerm = permute(xKDrawExp,[1 3 2]); - if(pools==0) - for c=1:numCells - if(strcmp(fitType,'poisson')) - HessianTerm = 0; - for k=1:K - % Hk = squeeze(HkAll(:,:,c)); - Hk = (HkAll(:,:,c)); - if(size(Hk,1)==numCells) - Hk = Hk'; - end - % xk = squeeze(xKDrawExp(:,k,:)); - xk = xkPerm(:,:,k); - Wk = WKFinal(:,:,k); - if(numel(gammahat)==1) - gammaC=gammahat; - else - gammaC=gammahat(:,c); - end - terms=muhat(c)+betahat(:,c)'*xk+gammaC'*Hk(k,:)'; - ld = exp(terms); - HessianTerm=HessianTerm-1/McExp*sum(ld,2); - end - elseif(strcmp(fitType,'binomial')) - HessianTerm = 0; - for k=1:K - % Hk = squeeze(HkAll(:,:,c)); - Hk = (HkAll(:,:,c)); - if(size(Hk,1)==numCells) - Hk = Hk'; - end - % xk = squeeze(xKDrawExp(:,k,:)); - xk = xkPerm(:,:,k); - Wk = WKFinal(:,:,k); - if(numel(gammahat)==1) - gammaC=gammahat; - else - gammaC=gammahat(:,c); - end - terms=muhat(c)+betahat(:,c)'*xk+gammaC'*Hk(k,:)'; - ld = exp(terms)./(1+exp(terms)); - ExplambdaDelta = 1/McExp*sum(ld,2); - ExplambdaDeltaSquare = 1/McExp*sum(ld.^2,2); - ExplambdaDeltaCubed = 1/McExp*sum(ld.^3,2); - HessianTerm = HessianTerm -(dN(c,k)+1)*ExplambdaDelta ... - +(dN(c,k)+3)*ExplambdaDeltaSquare-3*ExplambdaDeltaCubed; - end - end - IMuComp(c,c) = -HessianTerm; - end - else - for c=1:numCells - if(strcmp(fitType,'poisson')) - HessianTerm = zeros(K,1); - for k=1:K - % Hk = squeeze(HkAll(:,:,c)); - Hk = (HkAll(k,:,c)); - if(size(Hk,1)==numCells) - Hk = Hk'; - end - % xk = squeeze(xKDrawExp(:,k,:)); - xk = xkPerm(:,:,k); - Wk = WKFinal(:,:,k); - if(numel(gammahat)==1) - gammaC=gammahat; - else - gammaC=gammahat(:,c); - end - terms=muhat(c)+betahat(:,c)'*xk+gammaC'*Hk'; - ld = exp(terms); - HessianTerm(k)=-1/McExp*sum(ld,2); - end - elseif(strcmp(fitType,'binomial')) - HessianTerm = zeros(K,1); - for k=1:K - % Hk = squeeze(HkAll(:,:,c)); - Hk = (HkAll(k,:,c)); - if(size(Hk,1)==numCells) - Hk = Hk'; - end - % xk = squeeze(xKDrawExp(:,k,:)); - xk = xkPerm(:,:,k); - Wk = WKFinal(:,:,k); - if(numel(gammahat)==1) - gammaC=gammahat; - else - gammaC=gammahat(:,c); - end - terms=muhat(c)+betahat(:,c)'*xk+gammaC'*Hk'; - ld = exp(terms)./(1+exp(terms)); - ExplambdaDelta = 1/McExp*sum(ld,2); - ExplambdaDeltaSquare = 1/McExp*sum(ld.^2,2); - ExplambdaDeltaCubed = 1/McExp*sum(ld.^3,2); - HessianTerm(k) = -(dN(c,k)+1)*ExplambdaDelta ... - +(dN(c,k)+3)*ExplambdaDeltaSquare-3*ExplambdaDeltaCubed; - end - end - IMuComp(c,c) = -sum(HessianTerm); - end - end - - - % Gamma Information Matrix - IGammaComp = zeros(numel(gammahat),numel(gammahat)); - if(~isempty(windowTimes) && any(any(gammahat~=0))) - xkPerm = permute(xKDrawExp,[1 3 2]); - if(pools==0) - for c=1:numCells - if(strcmp(fitType,'poisson')) - HessianTerm = zeros(size(HkAll,2),size(HkAll,2)); - for k=1:K - % Hk = squeeze(HkAll(:,:,c)); - Hk = (HkAll(:,:,c)); - if(size(Hk,1)==numCells) - Hk = Hk'; - end - % xk = squeeze(xKDrawExp(:,k,:)); - xk = xkPerm(:,:,k); - Wk = WKFinal(:,:,k); - if(numel(gammahat)==1) - gammaC=gammahat; - else - gammaC=gammahat(:,c); - end - terms=muhat(c)+betahat(:,c)'*xk+gammaC'*Hk(k,:)'; - ld = exp(terms); - ExplambdaDelta = 1/McExp*sum(ld,2); - HessianTerm=HessianTerm-Hk(k,:)'*Hk(k,:)*ExplambdaDelta; - end - elseif(strcmp(fitType,'binomial')) - HessianTerm = zeros(size(HkAll,2),size(HkAll,2)); - for k=1:K - Hk = (HkAll(:,:,c)); - if(size(Hk,1)==numCells) - Hk = Hk'; - end - % xk = squeeze(xKDrawExp(:,k,:)); - xk = xkPerm(:,:,k); - Wk = WKFinal(:,:,k); - if(numel(gammahat)==1) - gammaC=gammahat; - else - gammaC=gammahat(:,c); - end - terms=muhat(c)+betahat(:,c)'*xk+gammaC'*Hk(k,:)'; - ld = exp(terms)./(1+exp(terms)); - ExplambdaDelta = 1/McExp*sum(ld,2); - ExplambdaDeltaSquare = 1/McExp*sum(ld.^2,2); - ExplambdaDeltaCubed = 1/McExp*sum(ld.^2,2); - HessianTerm=HessianTerm+(-ExplambdaDelta*(dN(c,k)+1)... - +ExplambdaDeltaSquare*(dN(c,k)+3)... - -2*ExplambdaDeltaCubed)*Hk(k,:)'*Hk(:,k); - end - end - startInd=size(HkAll,2)*(c-1)+1; endInd = size(HkAll,2)*c; - IGammaComp(startInd:endInd,startInd:endInd) = -HessianTerm; - end - - else - - for c=1:numCells - if(strcmp(fitType,'poisson')) - HessianTerm = zeros(size(HkAll,2),size(HkAll,2),K); - for k=1:K - % Hk = squeeze(HkAll(:,:,c)); - Hk = (HkAll(k,:,c)); - if(size(Hk,1)==numCells) - Hk = Hk'; - end - % xk = squeeze(xKDrawExp(:,k,:)); - xk = xkPerm(:,:,k); - Wk = WKFinal(:,:,k); - if(numel(gammahat)==1) - gammaC=gammahat; - else - gammaC=gammahat(:,c); - end - terms=muhat(c)+betahat(:,c)'*xk+gammaC'*Hk'; - ld = exp(terms); - ExplambdaDelta = 1/McExp*sum(ld,2); - HessianTerm(:,:,k)=-Hk'*Hk*ExplambdaDelta; - end - elseif(strcmp(fitType,'binomial')) - HessianTerm = zeros(size(HkAll,2),size(HkAll,2),K); - - for k=1:K - Hk = (HkAll(k,:,c)); - if(size(Hk,1)==numCells) - Hk = Hk'; - end - % xk = squeeze(xKDrawExp(:,k,:)); - xk = xkPerm(:,:,k); - Wk = WKFinal(:,:,k); - if(numel(gammahat)==1) - gammaC=gammahat; - else - gammaC=gammahat(:,c); - end - terms=muhat(c)+betahat(:,c)'*xk+gammaC'*Hk'; - ld = exp(terms)./(1+exp(terms)); - ExplambdaDelta = 1/McExp*sum(ld,2); - ExplambdaDeltaSquare = 1/McExp*sum(ld.^2,2); - ExplambdaDeltaCubed = 1/McExp*sum(ld.^2,2); - HessianTerm(:,:,k)=+(-ExplambdaDelta*(dN(c,k)+1)... - +ExplambdaDeltaSquare*(dN(c,k)+3)... - -2*ExplambdaDeltaCubed)*Hk'*Hk; - end - end - startInd=size(HkAll,2)*(c-1)+1; endInd = size(HkAll,2)*c; - IGammaComp(startInd:endInd,startInd:endInd) = -sum(HessianTerm,3); - end - - end - end - - - - if(mPPCOEM_Constraints.EstimateA==1) - n1=size(IAComp,1); - else - n1=0; - end - n2=size(IQComp,1); n3=size(ICComp,1); n4=size(IRComp,1); - if(mPPCOEM_Constraints.EstimatePx0==1) - n5=size(ISComp,1); - else - n5=0; - end - if(mPPCOEM_Constraints.Estimatex0==1) - n6=size(Ix0Comp,1); - else - n6=0; - end - n7=size(IAlphaComp,1); - n8=size(IMuComp,1); - n9=size(IBetaComp,1); - if(numel(gammahat)==1) - if(gammahat==0) - n10=0; - end - else - n10=size(IGammaComp,1); - end - nTerms=n1+n2+n3+n4+n5+n6+n7+n8+n9+n10; - IComp = zeros(nTerms,nTerms); - if(mPPCOEM_Constraints.EstimateA==1) - IComp(1:n1,1:n1)=IAComp; - end - offset=n1+1; - IComp(offset:(n1+n2),offset:(n1+n2))=IQComp; - offset=n1+n2+1; - IComp(offset:(n1+n2+n3),offset:(n1+n2+n3))=ICComp; - offset=n1+n2+n3+1; - IComp(offset:(n1+n2+n3+n4),offset:(n1+n2+n3+n4))=IRComp; - offset=n1+n2+n3+n4+1; - if(mPPCOEM_Constraints.EstimatePx0==1); - IComp(offset:(n1+n2+n3+n4+n5),offset:(n1+n2+n3+n4+n5))=ISComp; - end - offset=n1+n2+n3+n4+n5+1; - if(mPPCOEM_Constraints.Estimatex0==1) - IComp(offset:(n1+n2+n3+n4+n5+n6),offset:(n1+n2+n3+n4+n5+n6))=Ix0Comp; - end - offset=n1+n2+n3+n4+n5+n6+1; - IComp(offset:(n1+n2+n3+n4+n5+n6+n7),offset:(n1+n2+n3+n4+n5+n6+n7))=IAlphaComp; - offset=n1+n2+n3+n4+n5+n6+n7+1; - IComp(offset:(n1+n2+n3+n4+n5+n6+n7+n8),offset:(n1+n2+n3+n4+n5+n6+n7+n8))=IMuComp; - offset=n1+n2+n3+n4+n5+n6+n7+n8+1; - IComp(offset:(n1+n2+n3+n4+n5+n6+n7+n8+n9),offset:(n1+n2+n3+n4+n5+n6+n7+n8+n9))=IBetaComp; - offset=n1+n2+n3+n4+n5+n6+n7+n8+n9+1; - IComp(offset:(n1+n2+n3+n4+n5+n6+n7+n8+n9+n10),offset:(n1+n2+n3+n4+n5+n6+n7+n8+n9+n10))=IGammaComp; - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %Missing Information Matrix - %Approximate cov(Sc(X;theta)Sc(X;theta)') - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - - Mc=mPPCOEM_Constraints.mcIter; - xKDraw = zeros(size(xKFinal,1),N,Mc); - - % Generate the Monte Carlo samples for the unobserved data - for n=1:N - WuTemp=(WKFinal(:,:,n)); - [chol_m,p]=chol(WuTemp); - z=normrnd(0,1,size(xKFinal,1),Mc); - xKDraw(:,n,:)=repmat(xKFinal(:,n),[1 Mc])+(chol_m*z); - end - - - if(mPPCOEM_Constraints.EstimatePx0|| mPPCOEM_Constraints.Estimatex0) - [chol_m,p]=chol(Px0hat); - z=normrnd(0,1,size(xKFinal,1),Mc); - x0Draw=repmat(x0hat,[1 Mc])+(chol_m*z); - else - x0Draw=repmat(x0hat, [1 Mc]); - - end - - IMc = zeros(nTerms,nTerms,Mc); - % Emperically estimate the covariance of the score - pools = matlabpool('size'); %number of parallel workers - if(pools==0) % parallel toolbox is not enabled; - for c=1:Mc - x_K=xKDraw(:,:,c); - x_0=x0Draw(:,c); - - Dx=size(x_K,1); - Dy=size(y,1); - Sxkm1xk = zeros(Dx,Dx); - Sxkm1xkm1 = zeros(Dx,Dx); - Sxkxk = zeros(Dx,Dx); - Sykyk = zeros(Dy,Dy); - Sxkyk = zeros(Dx,Dy); - - for k=1:K - if(k==1) - Sxkm1xk = Sxkm1xk+x_0*x_K(:,k)'; - Sxkm1xkm1 = Sxkm1xkm1+x_0*x_0'; - else - Sxkm1xk = Sxkm1xk+x_K(:,k-1)*x_K(:,k)'; - Sxkm1xkm1= Sxkm1xkm1+x_K(:,k-1)*x_K(:,k-1)'; - end - Sxkxk = Sxkxk+x_K(:,k)*x_K(:,k)'; - Sykyk = Sykyk+(y(:,k)-alphahat)*(y(:,k)-alphahat)'; - Sxkyk = Sxkyk+x_K(:,k)*(y(:,k)-alphahat)'; - - end - Sx0x0 = x_0*x_0'; - Sxkxk = 0.5*(Sxkxk+Sxkxk'); - Sykyk = 0.5*(Sykyk+Sykyk'); - sumXkTerms = Sxkxk-Ahat*Sxkm1xk-Sxkm1xk'*Ahat'+Ahat*Sxkm1xkm1*Ahat'; - sumYkTerms = Sykyk - Chat*Sxkyk - Sxkyk'*Chat' + Chat*Sxkxk*Chat'; - Sxkxkm1 = Sxkm1xk'; - Sykxk = Sxkyk'; - - - - sumXkTerms=0.5*(sumXkTerms+sumXkTerms'); - sumYkTerms=0.5*(sumYkTerms+sumYkTerms'); - if(mPPCOEM_Constraints.EstimateA==1) - ScorA=Qhat\(Sxkxkm1-Ahat*Sxkm1xkm1); - if(mPPCOEM_Constraints.AhatDiag==1) - ScoreAMc=diag(ScorA); - else - ScoreAMc=reshape(ScorA',numel(Ahat),1); - end - else - ScoreAMc=[]; - end - - ScorC=Rhat\(Sykxk-Chat*Sxkxk); - ScoreCMc=reshape(ScorC',numel(ScorC),1); - - if(mPPCOEM_Constraints.QhatDiag) - if(mPPCOEM_Constraints.QhatIsotropic) - ScoreQ =-.5*(K*Dx*Qhat(1,1)^(-1) - Qhat(1,1)^(-2)*trace(sumXkTerms)); - else - ScoreQ =(-.5*(Qhat\(K*eye(size(Qhat)) - sumXkTerms/Qhat))); - end - ScoreQMc = diag(ScoreQ); - else - ScoreQ =-.5*(Qhat\(K*eye(size(Qhat)) - sumXkTerms/Qhat)); - ScoreQMc =reshape(ScoreQ',numel(ScoreQ),1); - end - - - ScoreAlphaMc = sum(Rhat\(y-Chat*x_K-alphahat*ones(1,N)),2); - if(mPPCOEM_Constraints.RhatDiag) - if(mPPCOEM_Constraints.RhatIsotropic) - ScoreR =-.5*(K*Dy*Rhat(1,1)^(-1) - Rhat(1,1)^(-2)*trace(sumYkTerms)); - else - ScoreR =(-.5*(Rhat\(K*eye(size(Rhat)) - sumYkTerms/Rhat))); - end - ScoreRMc = diag(ScoreR); - else - ScoreR =-.5*(Rhat\(K*eye(size(Rhat)) - sumYkTerms/Rhat)); - ScoreRMc =reshape(ScoreR',numel(ScoreR),1); - end - - - if(mPPCOEM_Constraints.Px0Isotropic==1) - ScoreSMc=-.5*(Dx*Px0hat(1,1)^(-1) - Px0hat(1,1)^(-2)*trace((x_0-x0hat)*(x_0-x0hat)')); - else - ScorS =-.5*(Px0hat\(eye(size(Px0hat)) - (x_0-x0hat)*(x_0-x0hat)'/Px0hat)); - ScoreSMc = diag(ScorS); - end - - Scorx0=(-Px0hat\(x_0-x0hat))+Ahat'/Qhat*(x_K(:,1)-Ahat*x_0); - Scorex0Mc=reshape(Scorx0',numel(Scorx0),1); - ScoreMuMc=zeros(numCells,1); - ScoreBetaMc=[]; - ScoreGammaMc=[]; - % Cell Scores - for nc=1:numCells - if(strcmp(fitType,'poisson')) - Hk = (HkAll(:,:,nc)); - if(size(Hk,1)==numCells) - Hk = Hk'; - end - nHist = size(Hk,2); - if(numel(gammahat)==1) - gammaC=gammahat; - else - gammaC=gammahat(:,nc); - end - terms=muhat(nc)+betahat(:,nc)'*x_K+gammaC'*Hk'; - ld = exp(terms); - ScoreMuMc(nc) = sum(dN(nc,:)-ld,2); - ScoreBetaMc = [ScoreBetaMc; sum(repmat((dN(nc,:)-ld),[Dx 1]).*x_K,2)]; - ScoreGammaMc= [ScoreGammaMc;sum(repmat(dN(nc,:)-ld,[nHist 1]).*Hk',2)]; - elseif(strcmp(fitType,'binomial')) - Hk = (HkAll(:,:,nc)); - if(size(Hk,1)==numCells) - Hk = Hk'; - end - nHist = size(Hk,2); - - if(numel(gammahat)==1) - gammaC=gammahat; - else - gammaC=gammahat(:,nc); - end - terms=muhat(nc)+betahat(:,nc)'*x_K+gammaC'*Hk'; - ld = exp(terms)./(1+exp(terms)); - ScoreMuMc(nc) = sum(dN(nc,:)-(dN(nc,:)+1).*ld+ld.^2,2); - ScoreBetaMc = [ScoreBetaMc;sum(repmat(dN(nc,:).*(1-ld) - ld.*(1-ld),[Dx,1]).*x_K,2)]; - ScoreGammaMc= [ScoreGammaMc;sum(repmat(dN(nc,:)-(dN(nc,:)+1).*ld+ld.^2,[nHist 1]).*Hk',2)]; - end - - end - ScoreVec = [ScoreAMc; ScoreQMc; ScoreCMc; ScoreRMc]; - if(mPPCOEM_Constraints.EstimatePx0==1) - ScoreVec = [ScoreVec; ScoreSMc]; - end - if(mPPCOEM_Constraints.Estimatex0==1) - ScoreVec = [ScoreVec; Scorex0Mc]; - end - ScoreVec = [ScoreVec; ScoreAlphaMc]; - ScoreVec = [ScoreVec; ScoreMuMc; ScoreBetaMc]; - if((numel(gammahat)==1 && gammahat~=0) || numel(gammahat)>1) - ScoreVec=[ScoreVec;ScoreGammaMc]; - end - - IMc(:,:,c)=ScoreVec*ScoreVec'; - end - else %Use the parallel toolbox - for c=1:Mc - x_K=xKDraw(:,:,c); - x_0=x0Draw(:,c); - - Dx=size(x_K,1); - Dy=size(y,1); - Sxkm1xk = zeros(Dx,Dx); - Sxkm1xkm1 = zeros(Dx,Dx); - Sxkxk = zeros(Dx,Dx); - Sykyk = zeros(Dy,Dy); - Sxkyk = zeros(Dx,Dy); - - for k=1:K - if(k==1) - Sxkm1xk = Sxkm1xk+x_0*x_K(:,k)'; - Sxkm1xkm1 = Sxkm1xkm1+x_0*x_0'; - else - Sxkm1xk = Sxkm1xk+x_K(:,k-1)*x_K(:,k)'; - Sxkm1xkm1= Sxkm1xkm1+x_K(:,k-1)*x_K(:,k-1)'; - end - Sxkxk = Sxkxk+x_K(:,k)*x_K(:,k)'; - Sykyk = Sykyk+(y(:,k)-alphahat)*(y(:,k)-alphahat)'; - Sxkyk = Sxkyk+x_K(:,k)*(y(:,k)-alphahat)'; - - end - Sx0x0 = x_0*x_0'; - Sxkxk = 0.5*(Sxkxk+Sxkxk'); - Sykyk = 0.5*(Sykyk+Sykyk'); - sumXkTerms = Sxkxk-Ahat*Sxkm1xk-Sxkm1xk'*Ahat'+Ahat*Sxkm1xkm1*Ahat'; - sumYkTerms = Sykyk - Chat*Sxkyk - Sxkyk'*Chat' + Chat*Sxkxk*Chat'; - Sxkxkm1 = Sxkm1xk'; - Sykxk = Sxkyk'; - - - - sumXkTerms=0.5*(sumXkTerms+sumXkTerms'); - sumYkTerms=0.5*(sumYkTerms+sumYkTerms'); - if(mPPCOEM_Constraints.EstimateA==1) - ScorA=Qhat\(Sxkxkm1-Ahat*Sxkm1xkm1); - if(mPPCOEM_Constraints.AhatDiag==1) - ScoreAMc=diag(ScorA); - else - ScoreAMc=reshape(ScorA',numel(Ahat),1); - end - else - ScoreAMc=[]; - end - - ScorC=Rhat\(Sykxk-Chat*Sxkxk); - ScoreCMc=reshape(ScorC',numel(ScorC),1); - - if(mPPCOEM_Constraints.QhatDiag) - if(mPPCOEM_Constraints.QhatIsotropic) - ScoreQ =-.5*(K*Dx*Qhat(1,1)^(-1) - Qhat(1,1)^(-2)*trace(sumXkTerms)); - else - ScoreQ =(-.5*(Qhat\(K*eye(size(Qhat)) - sumXkTerms/Qhat))); - end - ScoreQMc = diag(ScoreQ); - else - ScoreQ =-.5*(Qhat\(K*eye(size(Qhat)) - sumXkTerms/Qhat)); - ScoreQMc =reshape(ScoreQ',numel(ScoreQ),1); - end - - - ScoreAlphaMc = sum(Rhat\(y-Chat*x_K-alphahat*ones(1,N)),2); - if(mPPCOEM_Constraints.RhatDiag) - if(mPPCOEM_Constraints.RhatIsotropic) - ScoreR =-.5*(K*Dy*Rhat(1,1)^(-1) - Rhat(1,1)^(-2)*trace(sumYkTerms)); - else - ScoreR =(-.5*(Rhat\(K*eye(size(Rhat)) - sumYkTerms/Rhat))); - end - ScoreRMc = diag(ScoreR); - else - ScoreR =-.5*(Rhat\(K*eye(size(Rhat)) - sumYkTerms/Rhat)); - ScoreRMc =reshape(ScoreR',numel(ScoreR),1); - end - - - if(mPPCOEM_Constraints.Px0Isotropic==1) - ScoreSMc=-.5*(Dx*Px0hat(1,1)^(-1) - Px0hat(1,1)^(-2)*trace((x_0-x0hat)*(x_0-x0hat)')); - else - ScorS =-.5*(Px0hat\(eye(size(Px0hat)) - (x_0-x0hat)*(x_0-x0hat)'/Px0hat)); - ScoreSMc = diag(ScorS); - end - - Scorx0=(-Px0hat\(x_0-x0hat))+Ahat'/Qhat*(x_K(:,1)-Ahat*x_0); - Scorex0Mc=reshape(Scorx0',numel(Scorx0),1); - ScoreMuMc=zeros(numCells,1); - ScoreBetaMc=[]; - ScoreGammaMc=[]; - % Cell Scores - for nc=1:numCells - if(strcmp(fitType,'poisson')) - Hk = (HkAll(:,:,nc)); - if(size(Hk,1)==numCells) - Hk = Hk'; - end - nHist = size(Hk,2); - if(numel(gammahat)==1) - gammaC=gammahat; - else - gammaC=gammahat(:,nc); - end - terms=muhat(nc)+betahat(:,nc)'*x_K+gammaC'*Hk'; - ld = exp(terms); - ScoreMuMc(nc) = sum(dN(nc,:)-ld,2); - ScoreBetaMc = [ScoreBetaMc; sum(repmat((dN(nc,:)-ld),[Dx 1]).*x_K,2)]; - ScoreGammaMc= [ScoreGammaMc;sum(repmat(dN(nc,:)-ld,[nHist 1]).*Hk',2)]; - elseif(strcmp(fitType,'binomial')) - Hk = (HkAll(:,:,nc)); - if(size(Hk,1)==numCells) - Hk = Hk'; - end - nHist = size(Hk,2); - - if(numel(gammahat)==1) - gammaC=gammahat; - else - gammaC=gammahat(:,nc); - end - terms=muhat(nc)+betahat(:,nc)'*x_K+gammaC'*Hk'; - ld = exp(terms)./(1+exp(terms)); - ScoreMuMc(nc) = sum(dN(nc,:)-(dN(nc,:)+1).*ld+ld.^2,2); - ScoreBetaMc = [ScoreBetaMc;sum(repmat(dN(nc,:).*(1-ld) - ld.*(1-ld),[Dx,1]).*x_K,2)]; - ScoreGammaMc= [ScoreGammaMc;sum(repmat(dN(nc,:)-(dN(nc,:)+1).*ld+ld.^2,[nHist 1]).*Hk',2)]; - end - - end - ScoreVec = [ScoreAMc; ScoreQMc; ScoreCMc; ScoreRMc]; - if(mPPCOEM_Constraints.EstimatePx0==1) - ScoreVec = [ScoreVec; ScoreSMc]; - end - if(mPPCOEM_Constraints.Estimatex0==1) - ScoreVec = [ScoreVec; Scorex0Mc]; - end - ScoreVec = [ScoreVec; ScoreAlphaMc]; - ScoreVec = [ScoreVec; ScoreMuMc; ScoreBetaMc]; - if((numel(gammahat)==1 && gammahat~=0) || numel(gammahat)>1) - ScoreVec=[ScoreVec;ScoreGammaMc]; - end - - IMc(:,:,c)=ScoreVec*ScoreVec'; - end - end - IMissing = 1/Mc*sum(IMc,3); - IObs = IComp-IMissing; - invIObs = eye(size(IObs))/IObs; -% figure(1); subplot(1,2,1); imagesc(invIObs); subplot(1,2,2); imagesc(nearestSPD(invIObs)); - invIObs = nearestSPD(invIObs); % Find the nearest positive semidefinite approximation for the variance matrix - VarVec = (diag(invIObs)); - SEVec = sqrt(VarVec); - SEAterms = SEVec(1:n1); - SEQterms = SEVec(n1+1:(n1+n2)); - SECterms = SEVec(n1+n2+1:(n1+n2+n3)); - SERterms = SEVec(n1+n2+n3+1:(n1+n2+n3+n4)); - SEPx0terms=SEVec(n1+n2+n3+n4+1:(n1+n2+n3+n4+n5)); - SEx0terms=SEVec(n1+n2+n3+n4+n5+1:(n1+n2+n3+n4+n5+n6)); - SEAlphaterms=SEVec(n1+n2+n3+n4+n5+n6+1:(n1+n2+n3+n4+n5+n6+n7)); - SEMuTerms = SEVec(n1+n2+n3+n4+n5+n6+n7+1:(n1+n2+n3+n4+n5+n6+n7+n8)); - SEBetaTerms = SEVec(n1+n2+n3+n4+n5+n6+n7+n8+1:(n1+n2+n3+n4+n5+n6+n7+n8+n9)); - SEGammaTerms = SEVec(n1+n2+n3+n4+n5+n6+n7+n8+n9+1:(n1+n2+n3+n4+n5+n6+n7+n8+n9+n10)); - if(mPPCOEM_Constraints.EstimatePx0==1) - SES = diag(SEPx0terms); - end - if(mPPCOEM_Constraints.Estimatex0==1) - SEx0=SEx0terms; - end - - if(mPPCOEM_Constraints.EstimateA==1) - if(mPPCOEM_Constraints.AhatDiag==1) - SEA=diag(SEAterms); - else - SEA=reshape(SEAterms,size(Ahat,2),size(Ahat,1))'; - end - end - SEC=reshape(SECterms,size(Chat,2),size(Chat,1))'; - SEAlpha=reshape(SEAlphaterms,size(alphahat,2),size(alphahat,1))'; - - if(mPPCOEM_Constraints.RhatDiag==1) - SER=diag(SERterms); - else - SER=reshape(SERterms,size(Rhat,2),size(Rhat,1))'; - end - if(mPPCOEM_Constraints.QhatDiag==1) - SEQ=diag(SEQterms); - else - SEQ=reshape(SEQterms,size(Qhat,2),size(Qhat,1))'; - end - if(mPPCOEM_Constraints.EstimateA==1) - SE.A = SEA; - end - SE.Q = SEQ; - SE.C = SEC; - SE.R = SER; - SE.alpha = SEAlpha; - - if(mPPCOEM_Constraints.EstimatePx0==1) - SE.Px0=SES; - end - if(mPPCOEM_Constraints.Estimatex0==1) - SE.x0=SEx0; - end - - SEMu = SEMuTerms; - SEBeta=reshape(SEBetaTerms,size(betahat,2),size(betahat,1))'; - - SE.mu = SEMu; - SE.beta = SEBeta; - if((numel(gammahat)==1 && gammahat~=0) || numel(gammahat)>1) - SEGamma=reshape(SEGammaTerms,size(gammahat,2),size(gammahat,1))'; - SE.gamma = SEGamma; - end - % Compute parameter p-values - if(mPPCOEM_Constraints.EstimateA==1) - clear h p; - if(mPPCOEM_Constraints.AhatDiag==1) - VecParams = diag(Ahat); - VecSE = diag(SEA); - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pA = diag(p); - else - VecParams = reshape(Ahat,[numel(Ahat) 1]); - VecSE = reshape(SEA, [numel(Ahat) 1]); - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pA = reshape(p, [size(Ahat,1) size(Ahat,2)]); - end - end - - %C matrix - clear h p; - VecParams = reshape(Chat,[numel(Chat) 1]); - VecSE = reshape(SEC, [numel(Chat) 1]); - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pC = reshape(p, [size(Chat,1) size(Chat,2)]); - - %R matrix - clear h p; - if(mPPCOEM_Constraints.RhatDiag==1) - if(mPPCOEM_Constraints.RhatIsotropic==1) - VecParams = Rhat(1,1); - VecSE = SER(1,1); - [h p] = ztest(VecParams,0,VecSE); - pR = diag(p); - else - VecParams = diag(Rhat); - VecSE = diag(SER); - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pR = diag(p); - end - else - VecParams = reshape(Rhat,[numel(Rhat) 1]); - VecSE = reshape(SER, [numel(Rhat) 1]); - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pR = reshape(p, [size(Rhat,1) size(Rhat,2)]); - end - - %Q matrix - clear h p; - if(mPPCOEM_Constraints.QhatDiag==1) - if(mPPCOEM_Constraints.QhatIsotropic==1) - VecParams = Qhat(1,1); - VecSE = SEQ(1,1); - [h p] = ztest(VecParams,0,VecSE); - pQ = diag(p); - else - VecParams = diag(Qhat); - VecSE = diag(SEQ); - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pQ = diag(p); - end - else - VecParams = reshape(Qhat,[numel(Qhat) 1]); - VecSE = reshape(SEQ, [numel(Qhat) 1]); - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pQ = reshape(p, [size(Qhat,1) size(Qhat,2)]); - end - %Px0 - if(mPPCOEM_Constraints.EstimatePx0==1) - clear h p; - if(mPPCOEM_Constraints.Px0Isotropic==1) - VecParams = Px0hat(1,1); - VecSE = SES(1,1); - [h p] = ztest(VecParams,0,VecSE); - pPX0 = diag(p); - else - VecParams = diag(Px0hat); - VecSE = diag(SES); - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pPX0 = diag(p); - end - end - - clear h p; - VecParams = alphahat; - VecSE = SEAlpha; - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pAlpha = p'; - - if(mPPCOEM_Constraints.Estimatex0==1) - clear h p; - VecParams = x0hat; - VecSE = SEx0; - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pX0 = p'; - end - - %Mu - clear h p; - VecParams = muhat; - VecSE = SEMu; - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pMu = p'; - - %Beta - clear h p; - VecParams = reshape(betahat,[numel(betahat),1]); - VecSE = reshape(SEBeta, [numel(SEBeta),1]); - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pBeta = reshape(p, [size(betahat,1) size(betahat,2)]); - - %Gamma - clear h p; - if((numel(gammahat)==1 && gammahat~=0) || numel(gammahat)>1) - VecParams = reshape(gammahat,[numel(gammahat),1]); - VecSE = reshape(SEGamma, [numel(gammahat),1]); - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pGamma = reshape(p, [size(gammahat,1) size(gammahat,2)]); - end - if(mPPCOEM_Constraints.EstimateA==1) - Pvals.A = pA; - end - Pvals.Q = pQ; - Pvals.C = pC; - Pvals.R = pR; - Pvals.alpha = pAlpha; - if(mPPCOEM_Constraints.EstimatePx0==1) - Pvals.Px0 = pPX0; - end - if(mPPCOEM_Constraints.Estimatex0==1) - Pvals.x0 = pX0; - end - Pvals.mu = pMu; - Pvals.beta = pBeta; - - if(numel(gammahat)==1) - if(gammahat~=0) - Pvals.gamma = pGamma; - end - else - Pvals.gamma = pGamma; - end - - end - function [xKFinal,WKFinal,Ahat, Qhat, Chat, Rhat,alphahat, muhat, betahat, gammahat, x0hat, Px0hat, IC, SE, Pvals]=mPPCO_EM(y,dN, Ahat0, Qhat0, Chat0, Rhat0, alphahat0, mu, beta, fitType,delta, gamma, windowTimes, x0, Px0,mPPCOEM_Constraints,MstepMethod) - numStates = size(Ahat0,1); - if(nargin<17 || isempty(MstepMethod)) - MstepMethod='GLM'; %or NewtonRaphson - end - if(nargin<16 || isempty(mPPCOEM_Constraints)) - mPPCOEM_Constraints = DecodingAlgorithms.mPPCO_EMCreateConstraints; - end - if(nargin<15 || isempty(Px0)) - Px0=10e-10*eye(numStates,numStates); - end - if(nargin<14 || isempty(x0)) - x0=zeros(numStates,1); - end - - if(nargin<13 || isempty(windowTimes)) - if(isempty(gamma)) - windowTimes =[]; - else - % numWindows =length(gamma0)+1; - windowTimes = 0:delta:(length(gamma)+1)*delta; - end - end - if(nargin<12) - gamma=[]; - end - if(nargin<11 || isempty(delta)) - delta = .001; - end - if(nargin<10) - fitType = 'poisson'; - end - - minTime=0; - maxTime=(size(dN,2)-1)*delta; - K=size(dN,1); - if(~isempty(windowTimes)) - histObj = History(windowTimes,minTime,maxTime); - for k=1:K - nst{k} = nspikeTrain( (find(dN(k,:)==1)-1)*delta); - nst{k}.setMinTime(minTime); - nst{k}.setMaxTime(maxTime); -% HkAll{k} = histObj.computeHistory(nst{k}).dataToMatrix; - HkAll(:,:,k) = histObj.computeHistory(nst{k}).dataToMatrix; - end - else - for k=1:K -% HkAll{k} = 0; - HkAll(:,:,k) = 0; - end - gamma=0; - end - - - - % tol = 1e-3; %absolute change; - tolAbs = 1e-3; - tolRel = 1e-3; - llTol = 1e-3; - cnt=1; - - maxIter = 100; - - - A0 = Ahat0; - Q0 = Qhat0; - C0 = Chat0; - R0 = Rhat0; - alpha0 = alphahat0; - - Ahat{1} = A0; - Qhat{1} = Q0; - Chat{1} = C0; - Rhat{1} = R0; - x0hat{1} = x0; - Px0hat{1} = Px0; - alphahat{1} = alpha0; - muhat{1} = mu; - betahat{1} = beta; - gammahat{1} = gamma; - yOrig=y; - numToKeep=10; - scaledSystem=1; - - if(scaledSystem==1) - Tq = eye(size(Qhat{1}))/(chol(Qhat{1})); - Tr = eye(size(Rhat{1}))/(chol(Rhat{1})); - Ahat{1}= Tq*Ahat{1}/Tq; - Chat{1}= Tr*Chat{1}/Tq; - Qhat{1}= Tq*Qhat{1}*Tq'; - Rhat{1}= Tr*Rhat{1}*Tr'; - y= Tr*y; - x0hat{1} = Tq*x0; - Px0hat{1} = Tq*Px0*Tq'; - alphahat{1}= Tr*alphahat{1}; - betahat{1}=(betahat{1}'/Tq)'; - end - - cnt=1; - dLikelihood(1)=inf; -% x0hat = x0; - negLL=0; - IkedaAcc=mPPCOEM_Constraints.EnableIkeda; - %Forward EM - stoppingCriteria =0; -% logllNew= -inf; - - disp(' Joint Point-Process/Gaussian Observation EM Algorithm '); - while(stoppingCriteria~=1 && cnt<=maxIter) - storeInd = mod(cnt-1,numToKeep)+1; %make zero-based then mod, then add 1 - storeIndP1= mod(cnt,numToKeep)+1; - storeIndM1= mod(cnt-2,numToKeep)+1; - disp('--------------------------------------------------------------------------------------------------------'); - disp(['Iteration #' num2str(cnt)]); - disp('--------------------------------------------------------------------------------------------------------'); - - - [x_K{storeInd},W_K{storeInd},ll(cnt),ExpectationSums{storeInd}]=... - DecodingAlgorithms.mPPCO_EStep(Ahat{storeInd},Qhat{storeInd},Chat{storeInd},Rhat{storeInd}, y, alphahat{storeInd},dN, muhat{storeInd}, betahat{storeInd},fitType,delta,gammahat{storeInd},HkAll, x0hat{storeInd}, Px0hat{storeInd}); - - [Ahat{storeIndP1}, Qhat{storeIndP1}, Chat{storeIndP1}, Rhat{storeIndP1}, alphahat{storeIndP1}, muhat{storeIndP1}, betahat{storeIndP1}, gammahat{storeIndP1},x0hat{storeIndP1},Px0hat{storeIndP1}] ... - = DecodingAlgorithms.mPPCO_MStep(dN, y,x_K{storeInd},W_K{storeInd},x0hat{storeInd}, Px0hat{storeInd}, ExpectationSums{storeInd}, fitType,muhat{storeInd},betahat{storeInd}, gammahat{storeInd},windowTimes,HkAll,mPPCOEM_Constraints,MstepMethod); - - if(IkedaAcc==1) - disp(['****Ikeda Acceleration Step****']); - %y=Cx+alpha+wk wk~Normal with covariance Rk - ykNew = mvnrnd((Chat{storeIndP1}*x_K{storeInd}+alphahat{storeIndP1}*ones(1,size(x_K{storeInd},2)))',Rhat{storeIndP1})'; - -% if(gammahat{storeIndP1}==0)% No history effect -% dataMat = [ones(size(y,2),1) x_K{storeInd}']; % design matrix: X -% coeffsMat = [muhat{storeIndP1} betahat{storeIndP1}']; % coefficient vector: beta -% minTime=0; -% maxTime=(size(dN,2)-1)*delta; -% time=minTime:delta:maxTime; -% clear nstNew; -% for cc=1:length(muhat{storeIndP1}) -% tempData = exp(dataMat*coeffsMat(cc,:)'); -% -% if(strcmp(fitType,'poisson')) -% lambdaData = tempData; -% else -% lambdaData = tempData./(1+tempData); % Conditional Intensity Function for ith cell -% end -% lambda{cc}=Covariate(time,lambdaData./delta, ... -% '\Lambda(t)','time','s','spikes/sec',... -% {strcat('\lambda_{',num2str(cc),'}')},{{' ''b'' '}}); -% lambda{cc}=lambda{cc}.resample(1/delta); -% -% % generate one realization for each cell -% tempSpikeColl{cc} = CIF.simulateCIFByThinningFromLambda(lambda{cc},1); -% nstNew{cc} = tempSpikeColl{cc}.getNST(1); % grab the realization -% nstNew{cc}.setName(num2str(cc)); % give each cell a unique name -% % subplot(4,3,[8 11]); -% % h2=lambda{cc}.plot([],{{' ''k'', ''LineWidth'' ,.5'}}); -% % legend off; hold all; % Plot the CIF -% -% end -% -% spikeColl = nstColl(nstNew); % Create a neural spike train collection -% else -% time; -% end - - dNNew=dN;%spikeColl.dataToMatrix'; - %dNNew(dNNew>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 - % only one spike per bin - - - - [x_KNew,W_KNew,llNew,ExpectationSumsNew]=... - DecodingAlgorithms.mPPCO_EStep(Ahat{storeInd},Qhat{storeInd},Chat{storeInd},Rhat{storeInd}, ykNew, alphahat{storeInd},dNNew, muhat{storeInd}, betahat{storeInd},fitType,delta,gammahat{storeInd},HkAll, x0, Px0); - - - [AhatNew, QhatNew, ChatNew, RhatNew, alphahatNew, muhatNew, betahatNew, gammahatNew,x0new,Px0new] ... - = DecodingAlgorithms.mPPCO_MStep(dNNew, ykNew,x_KNew,W_KNew, x0hat{storeInd}, Px0hat{storeInd}, ExpectationSumsNew, fitType,muhat{storeInd},betahat{storeInd}, gammahat{storeInd},windowTimes,HkAll,mPPCOEM_Constraints,MstepMethod); - - Ahat{storeIndP1} = 2*Ahat{storeIndP1}-AhatNew; - Qhat{storeIndP1} = 2*Qhat{storeIndP1}-QhatNew; - Qhat{storeIndP1} = (Qhat{storeIndP1}+Qhat{storeIndP1}')/2; - Chat{storeIndP1} = 2*Chat{storeIndP1}-ChatNew; - Rhat{storeIndP1} = 2*Rhat{storeIndP1}-RhatNew; - Rhat{storeIndP1} = (Rhat{storeIndP1}+Rhat{storeIndP1}')/2; - alphahat{storeIndP1}=2*alphahat{storeIndP1}-alphahatNew; -% muhat{storeIndP1}= 2*muhat{storeIndP1}-muhatNew; -% betahat{storeIndP1} = 2*betahat{storeIndP1}-betahatNew; -% gammahat{storeIndP1}= 2*gammahat{storeIndP1}-gammahatNew; -% x0hat{storeIndP1} = 2*x0hat{storeIndP1} - x0new; -% Px0hat{storeIndP1} = 2*Px0hat{storeIndP1}- Px0new; -% [V,D] = eig(Px0hat{storeIndP1}); -% D(D<0)=1e-9; -% Px0hat{storeIndP1} = V*D*V'; -% Px0hat{storeIndP1} = (Px0hat{storeIndP1}+Px0hat{storeIndP1}')/2; - - - end - if(mPPCOEM_Constraints.EstimateA==0) - Ahat{storeIndP1}=Ahat{storeInd}; - end - if(cnt==1) - dLikelihood(cnt+1)=inf; - else - dLikelihood(cnt+1)=(ll(cnt)-ll(cnt-1));%./abs(ll(cnt-1)); - end - if(cnt==1) - QhatInit = Qhat{1}; - RhatInit = Rhat{1}; - xKInit = x_K{1}; - end - %Plot the progress -% if(mod(cnt,2)==0) - if(cnt==1) - scrsz = get(0,'ScreenSize'); - h=figure('OuterPosition',[scrsz(3)*.01 scrsz(4)*.04 scrsz(3)*.98 scrsz(4)*.95]); - end - figure(h); - time = linspace(minTime,maxTime,size(x_K{storeInd},2)); - subplot(2,5,[1 2 6 7]); plot(1:cnt,ll,'k','Linewidth', 2); hy=ylabel('Log Likelihood'); hx=xlabel('Iteration'); axis auto; - set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - subplot(2,5,3:5); hNew=plot(time, x_K{storeInd}','Linewidth', 2); hy=ylabel('States'); hx=xlabel('time [s]'); - set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - hold on; hOrig=plot(time, xKInit','--','Linewidth', 2); - legend([hOrig(1) hNew(1)],'Initial','Current'); - - subplot(2,5,8); hNew=plot(diag(Qhat{storeInd}),'o','Linewidth', 2); hy=ylabel('Q'); hx=xlabel('Diagonal Entry'); - set(gca, 'XTick' , 1:1:length(diag(Qhat{storeInd}))); - set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - hold on; hOrig=plot(diag(QhatInit),'r.','Linewidth', 2); - legend([hOrig(1) hNew(1)],'Initial','Current'); - - subplot(2,5,9); hNew=plot(diag(Rhat{storeInd}),'o','Linewidth', 2); hy=ylabel('R'); hx=xlabel('Diagonal Entry'); - set(gca, 'XTick' , 1:1:length(diag(Rhat{storeInd}))); - set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - hold on; hOrig=plot(diag(RhatInit),'r.','Linewidth', 2); - legend([hOrig(1) hNew(1)],'Initial','Current'); - - - subplot(2,5,10); imagesc(Rhat{storeInd}); ht=title('R Matrix Image'); - set(gca, 'XTick' , 1:1:length(diag(Rhat{storeInd})), 'YTick', 1:1:length(diag(Rhat{storeInd}))); - set(ht,'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - drawnow; - hold off; -% end - - if(cnt==1) - dMax=inf; - else - dQvals = max(max(abs(sqrt(Qhat{storeInd})-sqrt(Qhat{storeIndM1})))); - dRvals = max(max(abs(sqrt(Rhat{storeInd})-sqrt(Rhat{storeIndM1})))); - dAvals = max(max(abs((Ahat{storeInd})-(Ahat{storeIndM1})))); - dCvals = max(max(abs((Chat{storeInd})-(Chat{storeIndM1})))); - dMuvals = max(abs((muhat{storeInd})-(muhat{storeIndM1}))); - dAlphavals = max(abs((alphahat{storeInd})-(alphahat{storeIndM1}))); - dBetavals = max(max(abs((betahat{storeInd})-(betahat{storeIndM1})))); - dGammavals = max(max(abs((gammahat{storeInd})-(gammahat{storeIndM1})))); - dMax = max([dQvals,dRvals,dAvals,dCvals,dMuvals,dAlphavals,dBetavals,dGammavals]); - end - -% -% dQRel = max(abs(dQvals./sqrt(Qhat(:,storeIndM1)))); -% dGammaRel = max(abs(dGamma./gammahat(storeIndM1,:))); -% dMaxRel = max([dQRel,dGammaRel]); - if(cnt==1) - disp(['Max Parameter Change: N/A']); - else - disp(['Max Parameter Change: ' num2str(dMax)]); - end - cnt=(cnt+1); - if(dMax13) - [SE, Pvals]=DecodingAlgorithms.mPPCO_ComputeParamStandardErrors(y, dN,... - xKFinal, WKFinal, Ahat, Qhat, Chat, Rhat, alphahat, x0hat, Px0hat, ExpectationSumsFinal,... - fitType, muhat, betahat, gammahat, windowTimes, HkAll,... - mPPCOEM_Constraints); - end - - %Compute number of parameters - if(mPPCOEM_Constraints.EstimateA==1 && mPPCOEM_Constraints.AhatDiag==1) - n1=size(Ahat,1); - elseif(mPPCOEM_Constraints.EstimateA==1 && mPPCOEM_Constraints.AhatDiag==0) - n1=numel(Ahat); - else - n1=0; - end - if(mPPCOEM_Constraints.QhatDiag==1 && mPPCOEM_Constraints.QhatIsotropic==1) - n2=1; - elseif(mPPCOEM_Constraints.QhatDiag==1 && mPPCOEM_Constraints.QhatIsotropic==0) - n2=size(Qhat,1); - else - n2=numel(Qhat); - end - - n3=numel(Chat); - if(mPPCOEM_Constraints.RhatDiag==1 && mPPCOEM_Constraints.RhatIsotropic==1) - n4=1; - elseif(mPPCOEM_Constraints.QhatDiag==1 && mPPCOEM_Constraints.QhatIsotropic==0) - n4=size(Rhat,1); - else - n4=numel(Rhat); - end - - if(mPPCOEM_Constraints.EstimatePx0==1 && mPPCOEM_Constraints.Px0Isotropic==1) - n5=1; - elseif(mPPCOEM_Constraints.EstimatePx0==1 && mPPCOEM_Constraints.Px0Isotropic==0) - n5=size(Px0hat,1); - else - n5=0; - end - - if(mPPCOEM_Constraints.Estimatex0==1) - n6=size(x0hat,1); - else - n6=0; - end - - n7=size(alphahat,1); - n8=size(muhat,1); - n9=numel(betahat); - if(numel(gammahat)==1) - if(gammahat==0) - n10=0; - else - n10=1; - end - else - n10=numel(gammahat); - end - nTerms=n1+n2+n3+n4+n5+n6+n7+n8+n9+n10; - - K = size(y,2); - Dx = size(Ahat,2); - sumXkTerms = ExpectationSums{maxLLIndMod}.sumXkTerms; - llobs = ll + Dx*K/2*log(2*pi)+K/2*log(det(Qhat))... - + 1/2*trace(Qhat\sumXkTerms)... - + Dx/2*log(2*pi)+1/2*log(det(Px0hat)) ... - + 1/2*Dx; - AIC = 2*nTerms - 2*llobs; - AICc= AIC+ 2*nTerms*(nTerms+1)/(K-nTerms-1); - BIC = -2*llobs+nTerms*log(K); - IC.AIC = AIC; - IC.AICc= AICc; - IC.BIC = BIC; - IC.llobs = llobs; - IC.llcomp=ll; - - - end - function [x_K,W_K,logll,ExpectationSums]=mPPCO_EStep(A,Q,C,R, y, alpha,dN, mu, beta,fitType,delta,gamma,HkAll, x0, Px0) - DEBUG = 0; - - minTime=0; - maxTime=(size(dN,2)-1)*delta; - - - - [numCells,K] = size(dN); - Dx = size(A,2); - Dy = size(C,1); - x_p = zeros( size(A,2), K ); - x_u = zeros( size(A,2), K ); - W_p = zeros( size(A,2),size(A,2), K); - W_u = zeros( size(A,2),size(A,2), K ); - - - [x_p, W_p, x_u, W_u] = DecodingAlgorithms.mPPCODecodeLinear(A, Q, C, R, y, alpha, dN,mu,beta,fitType,delta,gamma,[],x0,Px0,HkAll); - - [x_K, W_K,Lk] = DecodingAlgorithms.kalman_smootherFromFiltered(A, x_p, W_p, x_u, W_u); - - %Best estimates of initial states given the data - W1G0 = A*Px0*A' + Q; - L0=Px0*A'/W1G0; - - Ex0Gy = x0+L0*(x_K(:,1)-x_p(:,1)); - Px0Gy = Px0+L0*(eye(size(W_K(:,:,1)))/(W_K(:,:,1))-eye(size(W1G0))/W1G0)*L0'; - Px0Gy = (Px0Gy+Px0Gy')/2; - numStates = size(x_K,1); - Wku=zeros(numStates,numStates,K,K); - Tk = zeros(numStates,numStates,K-1); - for k=1:K - Wku(:,:,k,k)=W_K(:,:,k); - end - - for u=K:-1:2 - for k=(u-1):-1:(u-1) - Tk(:,:,k)=A; -% Dk(:,:,k)=W_u(:,:,k)*Tk(:,:,k)'*pinv(W_p(:,:,k)); %From deJong and MacKinnon 1988 - Dk(:,:,k)=W_u(:,:,k)*Tk(:,:,k)'/(W_p(:,:,k+1)); %From deJong and MacKinnon 1988 - Wku(:,:,k,u)=Dk(:,:,k)*Wku(:,:,k+1,u); - Wku(:,:,u,k)=Wku(:,:,k,u)'; - end - end - - %All terms - Sxkm1xk = zeros(Dx,Dx); - Sxkxkm1 = zeros(Dx,Dx); - Sxkm1xkm1 = zeros(Dx,Dx); - Sxkxk = zeros(Dx,Dx); - Sykyk = zeros(Dy,Dy); - Sxkyk = zeros(Dx,Dy); - for k=1:K - if(k==1) - Sxkm1xk = Sxkm1xk+Px0*A'/W_p(:,:,1)*Wku(:,:,1,1); - Sxkm1xkm1 = Sxkm1xkm1+Px0+x0*x0'; - else -% - Sxkm1xk = Sxkm1xk+Wku(:,:,k-1,k)+x_K(:,k-1)*x_K(:,k)'; - - Sxkm1xkm1= Sxkm1xkm1+Wku(:,:,k-1,k-1)+x_K(:,k-1)*x_K(:,k-1)'; - end - Sxkxk = Sxkxk+Wku(:,:,k,k)+x_K(:,k)*x_K(:,k)'; - Sykyk = Sykyk+(y(:,k)-alpha)*(y(:,k)-alpha)'; - Sxkyk = Sxkyk+x_K(:,k)*(y(:,k)-alpha)'; - - end - Sx0x0 = Px0+x0*x0'; - Sxkxk = 0.5*(Sxkxk+Sxkxk'); - Sykyk = 0.5*(Sykyk+Sykyk'); - sumXkTerms = Sxkxk-A*Sxkm1xk-Sxkm1xk'*A'+A*Sxkm1xkm1*A'; - sumYkTerms = Sykyk - C*Sxkyk - Sxkyk'*C' + C*Sxkxk*C'; - Sxkxkm1 = Sxkm1xk'; - -% if(strcmp(fitType,'poisson')) -% sumPPll=0; -% for c=1:numCells -% Hk=HkAll{c}; -% for k=1:K -% xk = x_K(:,k); -% if(numel(gamma)==1) -% gammaC=gamma; -% else -% gammaC=gamma(:,c); -% end -% terms=mu(c)+beta(:,c)'*xk+gammaC'*Hk(k,:)'; -% Wk = W_K(:,:,k); -% ld = exp(terms); -% bt = beta(:,c); -% ExplambdaDelta =ld+0.5*trace(bt*bt'*ld*Wk); -% ExplogLD = terms; -% sumPPll=sumPPll+dN(c,k).*ExplogLD - ExplambdaDelta; -% end -% -% -% end -% elseif(strcmp(fitType,'binomial')) -% sumPPll=0; -% for c=1:numCells -% Hk=HkAll{c}; -% for k=1:K -% xk = x_K(:,k); -% if(numel(gamma)==1) -% gammaC=gamma; -% else -% gammaC=gamma(:,c); -% end -% terms=mu(c)+beta(:,c)'*xk+gammaC'*Hk(k,:)'; -% Wk = W_K(:,:,k); -% ld = exp(terms)./(1+exp(terms)); -% bt = beta(:,c); -% ExplambdaDelta =ld+0.5*trace(bt*bt'*ld*(1-ld)*(1-2*ld)*Wk); -% ExplogLD = log(ld)+0.5*trace(-(bt*bt'*ld*(1-ld))*Wk); -% sumPPll=sumPPll+dN(c,k).*ExplogLD - ExplambdaDelta; -% end -% -% -% end -% end - %Vectorize for loop over cells - if(strcmp(fitType,'poisson')) - sumPPll=0; - HkPerm =permute(HkAll,[2 3 1]); - for k=1:K -% Hk=squeeze(HkAll(k,:,:)); - Hk = HkPerm(:,:,k); - if(size(Hk,1)==numCells) - Hk = Hk'; - end - xk = x_K(:,k); - if(numel(gamma)==1) - gammaC=repmat(gamma,1,numCells); - else - gammaC=gamma; - end - if(size(gammaC,2)~=numCells) - gammaC = repmat(gammaC,[1 numCells]); - end - terms=mu+beta'*xk+diag(gammaC'*Hk); - Wk = W_K(:,:,k); - ld = exp(terms); - bt = beta; - ExplambdaDelta =ld+0.5*(ld.*diag((bt'*Wk*bt))); - ExplogLD = terms; - sumPPll=sumPPll+sum(dN(:,k).*ExplogLD - ExplambdaDelta); - - end - - %Vectorize over number of cells - elseif(strcmp(fitType,'binomial')) - sumPPll=0; - HkPerm = permute(HkAll,[2 3 1]); - for k=1:K -% Hk=squeeze(HkAll(k,:,:)); - HkPerm = HkPerm(:,:,k); - if(size(Hk,1)==numCells) - Hk = Hk'; - end - xk = x_K(:,k); - if(numel(gamma)==1) - gammaC=repmat(gamma,1,numCells); - else - gammaC=gamma; - end - if(size(gammaC,2)~=numCells) - gammaC = repmat(gammaC,[1 numCells]); - end - terms=mu+beta'*xk+diag(gammaC'*Hk); - Wk = W_K(:,:,k); - ld = exp(terms)./(1+exp(terms)); - bt = beta; - ExplambdaDelta = ld+0.5*(ld.*(1-ld).*(1-2.*ld)).*diag((bt'*Wk*bt)); - ExplogLD = log(ld)+0.5*(-ld.*(1-ld)).*diag(bt'*Wk*bt); - sumPPll=sumPPll+sum(dN(:,k).*ExplogLD - ExplambdaDelta); - - end - - - end - - logll = -Dx*K/2*log(2*pi)-K/2*log(det(Q))-Dy*K/2*log(2*pi) ... - -K/2*log(det(R))- Dx/2*log(2*pi) -1/2*log(det(Px0)) ... - +sumPPll - 1/2*trace((eye(size(Q))/Q)*sumXkTerms) ... - -1/2*trace((eye(size(R))/R)*sumYkTerms) ... - -Dx/2; - string0 = ['logll: ' num2str(logll)]; - disp(string0); - if(DEBUG==1) - string1 = ['-K/2*log(det(Q)):' num2str(-K/2*log(det(Q)))]; - string11 = ['-K/2*log(det(R)):' num2str(-K/2*log(det(R)))]; - string12= ['Constants: ' num2str(-Dx*K/2*log(2*pi)-Dy*K/2*log(2*pi)- Dx/2*log(2*pi) -Dx/2 -1/2*log(det(Px0)))]; - string2 = ['SumPPll: ' num2str(sumPPll)]; - string3 = ['-.5*trace(Q\sumXkTerms): ' num2str(-.5*trace(Q\sumXkTerms))]; - string4 = ['-.5*trace(R\sumYkTerms): ' num2str(-.5*trace(R\sumYkTerms))]; - - disp(string1); - disp(['Q=' num2str(diag(Q)')]); - disp(string11); - disp(['R=' num2str(diag(R)')]); - disp(string12); - disp(string2); - disp(string3); - disp(string4); - end - - ExpectationSums.Sxkm1xkm1=Sxkm1xkm1; - ExpectationSums.Sxkm1xk=Sxkm1xk; - ExpectationSums.Sxkxkm1=Sxkxkm1; - ExpectationSums.Sxkxk=Sxkxk; - ExpectationSums.Sxkyk=Sxkyk; - ExpectationSums.Sykyk=Sykyk; - ExpectationSums.sumXkTerms=sumXkTerms; - ExpectationSums.sumYkTerms=sumYkTerms; - ExpectationSums.sumPPll=sumPPll; - ExpectationSums.Sx0 = Ex0Gy; - ExpectationSums.Sx0x0 = Px0Gy + Ex0Gy*Ex0Gy'; - - end - function [Ahat, Qhat, Chat, Rhat, alphahat, muhat_new, betahat_new, gammahat_new, x0hat, Px0hat] = mPPCO_MStep(dN, y,x_K,W_K,x0, Px0, ExpectationSums,fitType, muhat, betahat,gammahat, windowTimes, HkAll,mPPCOEM_Constraints,MstepMethod) - if(nargin<14 || isempty(MstepMethod)) - MstepMethod = 'GLM'; %GLM or NewtonRaphson - end - if(nargin<13 || isempty(mPPCOEM_Constraints)) - mPPCOEM_Constraints = DecodingAlgorithms.mPPCO_EMCreateConstraints; - end - - Sxkm1xkm1=ExpectationSums.Sxkm1xkm1; - Sxkm1xk=ExpectationSums.Sxkm1xk; - Sxkxkm1=ExpectationSums.Sxkxkm1; - Sxkxk=ExpectationSums.Sxkxk; - Sxkyk=ExpectationSums.Sxkyk; - Sykyk=ExpectationSums.Sykyk; - sumXkTerms = ExpectationSums.sumXkTerms; - sumYkTerms = ExpectationSums.sumYkTerms; - Sx0 = ExpectationSums.Sx0; - Sx0x0 = ExpectationSums.Sx0x0; - [dx,K] = size(x_K); - dy=size(y,1); - numCells=size(dN,1); - - if(mPPCOEM_Constraints.AhatDiag==1) - I=eye(dx,dx); - Ahat = (Sxkxkm1.*I)/(Sxkm1xkm1.*I); - else - Ahat = Sxkxkm1/Sxkm1xkm1; - end - Chat = Sxkyk'/Sxkxk; - alphahat = sum(y - Chat*x_K,2)/K; - - if(mPPCOEM_Constraints.QhatDiag==1) - if(mPPCOEM_Constraints.QhatIsotropic==1) - Qhat=1/(dx*K)*trace(sumXkTerms)*eye(dx,dx); - else - I=eye(dx,dx); - Qhat=1/K*(sumXkTerms.*I); - Qhat = (Qhat + Qhat')/2; - end - else - Qhat=1/K*sumXkTerms; - Qhat = (Qhat + Qhat')/2; - end - dy=size(sumYkTerms,1); - if(mPPCOEM_Constraints.RhatDiag==1) - if(mPPCOEM_Constraints.RhatIsotropic==1) - I=eye(dy,dy); - Rhat = 1/(dy*K)*trace(sumYkTerms)*I; - else - - I=eye(dy,dy); - Rhat = 1/K*(sumYkTerms.*I); - Rhat = (Rhat + Rhat')/2; - end - else - Rhat = 1/K*(sumYkTerms); - Rhat = (Rhat + Rhat')/2; - end - if(mPPCOEM_Constraints.Estimatex0) - x0hat = (inv(Px0)+Ahat'/Qhat*Ahat)\(Ahat'/Qhat*x_K(:,1)+Px0\x0); - else - x0hat = x0; - end - - if(mPPCOEM_Constraints.EstimatePx0==1) - if(mPPCOEM_Constraints.Px0Isotropic==1) - Px0hat=(trace(x0hat*x0hat' - x0*x0hat' - x0hat*x0' +(x0*x0'))/(dx*K))*eye(dx,dx); - else - I=eye(dx,dx); - Px0hat =(x0hat*x0hat' - x0*x0hat' - x0hat*x0' +(x0*x0')).*I; - Px0hat = (Px0hat+Px0hat')/2; - end - - else - Px0hat =Px0; - end - - betahat_new =betahat; - gammahat_new = gammahat; - muhat_new = muhat; - - %Compute the new CIF beta using the GLM - if(strcmp(fitType,'poisson')) - algorithm = 'GLM'; - else - algorithm = 'BNLRCG'; - end - - % Estimate params via GLM - - if(strcmp(MstepMethod,'GLM')) - clear c; close all; - time=(0:length(x_K)-1)*.001; - labels = cell(1,dx); - labels2 = cell(1,dx+1); - labels2{1} = 'vel'; - for i=1:dx - labels{i} = strcat('v',num2str(i)); - labels2{i+1} = strcat('v',num2str(i)); - end - vel = Covariate(time,x_K','vel','time','s','m/s',labels); - baseline = Covariate(time,ones(length(time),1),'Baseline','time','s','',... - {'constant'}); - for i=1:size(dN,1) - spikeTimes = time(find(dN(i,:)==1)); - nst{i} = nspikeTrain(spikeTimes); - end - nspikeColl = nstColl(nst); - cc = CovColl({vel,baseline}); - trial = Trial(nspikeColl,cc); - selfHist = windowTimes ; NeighborHist = []; sampleRate = 1000; - clear c; - - - - if(gammahat==0) - c{1} = TrialConfig({{'Baseline','constant'},labels2},sampleRate,[],NeighborHist); - else - c{1} = TrialConfig({{'Baseline','constant'},labels2},sampleRate,selfHist,NeighborHist); - end - c{1}.setName('Baseline'); - cfgColl= ConfigColl(c); - warning('OFF'); - - results = Analysis.RunAnalysisForAllNeurons(trial,cfgColl,0,algorithm); - temp = FitResSummary(results); - tempCoeffs = squeeze(temp.getCoeffs); - if(gammahat==0) - betahat(1:dx,:) = tempCoeffs(2:(dx+1),:); - muhat = tempCoeffs(1,:)'; - else - betahat(1:dx,:) = tempCoeffs(2:(dx+1),:); - muhat = tempCoeffs(1,:)'; - histTemp = squeeze(temp.getHistCoeffs); - histTemp = reshape(histTemp, [length(windowTimes)-1 numCells]); - histTemp(isnan(histTemp))=0; - gammahat=histTemp; - end - else - - - % Estimate via Newton-Raphson - fprintf(['****M-step for beta**** \n']); - McExp=50; - xKDrawExp = zeros(size(x_K,1),K,McExp); - diffTol = 1e-5; - - % Generate the Monte Carlo samples - for k=1:K - WuTemp=(W_K(:,:,k)); - [chol_m,p]=chol(WuTemp); - z=normrnd(0,1,size(x_K,1),McExp); - xKDrawExp(:,k,:)=repmat(x_K(:,k),[1 McExp])+(chol_m*z); - end - % Stimulus Coefficients - pool = matlabpool('size'); - if(pool==0) - xkPerm = permute(xKDrawExp,[1 3 2]); - for c=1:numCells - converged=0; - iter = 1; - maxIter=100; - fprintf(['neuron:' num2str(c) ' iter: ']); - while(~converged && iter1) - ScoreVec=[ScoreVec;ScoreGammaMc]; - end - - IMc(:,:,c)=ScoreVec*ScoreVec'; - end - else %Use the parallel toolbox - for c=1:Mc - x_K=xKDraw(:,:,c); - x_0=x0Draw(:,c); - - Dx=size(x_K,1); - Sxkm1xk = zeros(Dx,Dx); - Sxkm1xkm1 = zeros(Dx,Dx); - Sxkxk = zeros(Dx,Dx); - - for k=1:K - if(k==1) - Sxkm1xk = Sxkm1xk+x_0*x_K(:,k)'; - Sxkm1xkm1 = Sxkm1xkm1+x_0*x_0'; - else - Sxkm1xk = Sxkm1xk+x_K(:,k-1)*x_K(:,k)'; - Sxkm1xkm1= Sxkm1xkm1+x_K(:,k-1)*x_K(:,k-1)'; - end - Sxkxk = Sxkxk+x_K(:,k)*x_K(:,k)'; - - end - Sxkxk = 0.5*(Sxkxk+Sxkxk'); - sumXkTerms = Sxkxk-Ahat*Sxkm1xk-Sxkm1xk'*Ahat'+Ahat*Sxkm1xkm1*Ahat'; - Sxkxkm1 = Sxkm1xk'; - sumXkTerms=0.5*(sumXkTerms+sumXkTerms'); - ScorA=Qhat\(Sxkxkm1-Ahat*Sxkm1xkm1); - if(PPEM_Constraints.EstimateA==1) - ScorA=Qhat\(Sxkxkm1-Ahat*Sxkm1xkm1); - if(PPEM_Constraints.AhatDiag==1) - ScoreAMc=diag(ScorA); - else - ScoreAMc=reshape(ScorA',numel(Ahat),1); - end - else - ScoreAMc=[]; - end - - - - if(PPEM_Constraints.QhatDiag) - if(PPEM_Constraints.QhatIsotropic) - ScoreQ =-.5*(K*Dx*Qhat(1,1)^(-1) - Qhat(1,1)^(-2)*trace(sumXkTerms)); - else - ScoreQ =(-.5*(Qhat\(K*eye(size(Qhat)) - sumXkTerms/Qhat))); - end - ScoreQMc = diag(ScoreQ); - else - ScoreQ =-.5*(Qhat\(K*eye(size(Qhat)) - sumXkTerms/Qhat)); - ScoreQMc =reshape(ScoreQ',numel(ScoreQ),1); - end - - if(PPEM_Constraints.Px0Isotropic==1) - ScoreSMc=-.5*(Dx*Px0hat(1,1)^(-1) - Px0hat(1,1)^(-2)*trace((x_0-x0hat)*(x_0-x0hat)')); - else - ScorS =-.5*(Px0hat\(eye(size(Px0hat)) - (x_0-x0hat)*(x_0-x0hat)'/Px0hat)); - ScoreSMc = diag(ScorS); - end - - Scorx0=(-Px0hat\(x_0-x0hat))+Ahat'/Qhat*(x_K(:,1)-Ahat*x_0); - Scorex0Mc=reshape(Scorx0',numel(Scorx0),1); - ScoreMuMc=zeros(numCells,1); - ScoreBetaMc=[]; - ScoreGammaMc=[]; - % Cell Scores - for nc=1:numCells - if(strcmp(fitType,'poisson')) - Hk = (HkAll(:,:,nc)); - nHist = size(Hk,2); - if(numel(gammahat)==1) - gammaC=gammahat; - else - gammaC=gammahat(:,nc); - end - terms=muhat(nc)+betahat(:,nc)'*x_K+gammaC'*Hk'; - ld = exp(terms); - ScoreMuMc(nc) = sum(dN(nc,:)-ld,2); - ScoreBetaMc = [ScoreBetaMc; sum(repmat((dN(nc,:)-ld),[Dx 1]).*x_K,2)]; - ScoreGammaMc= [ScoreGammaMc;sum(repmat(dN(nc,:)-ld,[nHist 1]).*Hk',2)]; - elseif(strcmp(fitType,'binomial')) - Hk = (HkAll(:,:,nc)); - nHist = size(Hk,2); - if(numel(gammahat)==1) - gammaC=gammahat; - else - gammaC=gammahat(:,nc); - end - terms=muhat(nc)+betahat(:,nc)'*x_K+gammaC'*Hk'; - ld = exp(terms)./(1+exp(terms)); - ScoreMuMc(nc) = sum(dN(nc,:)-(dN(nc,:)+1).*ld+ld.^2,2); - ScoreBetaMc = [ScoreBetaMc;sum(repmat(dN(nc,:).*(1-ld) - ld.*(1-ld),[Dx,1]).*x_K,2)]; - ScoreGammaMc= [ScoreGammaMc;sum(repmat(dN(nc,:)-(dN(nc,:)+1).*ld+ld.^2,[nHist 1]).*Hk',2)]; - end - - end - ScoreVec = [ScoreAMc; ScoreQMc]; - if(PPEM_Constraints.EstimatePx0==1) - ScoreVec = [ScoreVec; ScoreSMc]; - end - if(PPEM_Constraints.Estimatex0==1) - ScoreVec = [ScoreVec; Scorex0Mc]; - end - ScoreVec = [ScoreVec; ScoreMuMc; ScoreBetaMc]; - if((numel(gammahat)==1 && gammahat~=0) || numel(gammahat)>1) - ScoreVec=[ScoreVec;ScoreGammaMc]; - end - - IMc(:,:,c)=ScoreVec*ScoreVec'; - end - - end - IMissing = 1/Mc*sum(IMc,3); - IObs = IComp-IMissing; - invIObs = eye(size(IObs))/IObs; -% figure(1); subplot(1,2,1); imagesc(invIObs); subplot(1,2,2); imagesc(nearestSPD(invIObs)); - invIObs = nearestSPD(invIObs); % Find the nearest positive semidefinite approximation for the variance matrix - VarVec = (diag(invIObs)); - SEVec = sqrt(VarVec); - SEAterms = SEVec(1:n1); - SEQterms = SEVec(n1+1:(n1+n2)); - SEPx0terms=SEVec(n1+n2+1:(n1+n2+n3)); - SEx0terms=SEVec(n1+n2+n3+1:(n1+n2+n3+n4)); - SEMuTerms = SEVec(n1+n2+n3+n4+1:(n1+n2+n3+n4+n5)); - SEBetaTerms = SEVec(n1+n2+n3+n4+n5+1:(n1+n2+n3+n4+n5+n6)); - SEGammaTerms = SEVec(n1+n2+n3+n4+n5+n6+1:(n1+n2+n3+n4+n5+n6+n7)); - if(PPEM_Constraints.EstimatePx0==1) - SES = diag(SEPx0terms); - end - if(PPEM_Constraints.Estimatex0==1) - SEx0=SEx0terms; - end - - if(PPEM_Constraints.EstimateA==1) - if(PPEM_Constraints.AhatDiag==1) - SEA=diag(SEAterms); - else - SEA=reshape(SEAterms,size(Ahat,2),size(Ahat,1))'; - end - end - - if(PPEM_Constraints.QhatDiag==1) - SEQ=diag(SEQterms); - else - SEQ=reshape(SEQterms,size(Qhat,2),size(Qhat,1))'; - end - if(PPEM_Constraints.EstimateA==1) - SE.A = SEA; - end - SE.Q = SEQ; - - if(PPEM_Constraints.EstimatePx0==1) - SE.Px0=SES; - end - if(PPEM_Constraints.Estimatex0==1) - SE.x0=SEx0; - end - - SEMu = SEMuTerms; - SEBeta=reshape(SEBetaTerms,size(betahat,2),size(betahat,1))'; - - SE.mu = SEMu; - SE.beta = SEBeta; - if((numel(gammahat)==1 && gammahat~=0) || numel(gammahat)>1) - SEGamma=reshape(SEGammaTerms,size(gammahat,2),size(gammahat,1))'; - SE.gamma = SEGamma; - end - % Compute parameter p-values - - if(PPEM_Constraints.EstimateA==1) - clear h p; - if(PPEM_Constraints.AhatDiag==1) - VecParams = diag(Ahat); - VecSE = diag(SEA); - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pA = diag(p); - else - VecParams = reshape(Ahat,[numel(Ahat) 1]); - VecSE = reshape(SEA, [numel(Ahat) 1]); - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pA = reshape(p, [size(Ahat,1) size(Ahat,2)]); - end - end - - %Q matrix - clear h p; - if(PPEM_Constraints.QhatDiag==1) - if(PPEM_Constraints.QhatIsotropic==1) - VecParams = Qhat(1,1); - VecSE = SEQ(1,1); - [h p] = ztest(VecParams,0,VecSE); - pQ = diag(p); - else - VecParams = diag(Qhat); - VecSE = diag(SEQ); - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pQ = diag(p); - end - else - VecParams = reshape(Qhat,[numel(Qhat) 1]); - VecSE = reshape(SEQ, [numel(Qhat) 1]); - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pQ = reshape(p, [size(Qhat,1) size(Qhat,2)]); - end - %Px0 - if(PPEM_Constraints.EstimatePx0==1) - clear h p; - if(PPEM_Constraints.Px0Isotropic==1) - VecParams = Px0hat(1,1); - VecSE = SES(1,1); - [h p] = ztest(VecParams,0,VecSE); - pPX0 = diag(p); - else - VecParams = diag(Px0hat); - VecSE = diag(SES); - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pPX0 = diag(p); - end - end - - - if(PPEM_Constraints.Estimatex0==1) - clear h p; - VecParams = x0hat; - VecSE = SEx0; - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pX0 = p'; - end - - %Mu - clear h p; - VecParams = muhat; - VecSE = SEMu; - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pMu = p'; - - %Beta - clear h p; - VecParams = reshape(betahat,[numel(betahat),1]); - VecSE = reshape(SEBeta, [numel(SEBeta),1]); - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pBeta = reshape(p, [size(betahat,1) size(betahat,2)]); - - %Gamma - clear h p; - if((numel(gammahat)==1 && gammahat~=0) || numel(gammahat)>1) - VecParams = reshape(gammahat,[numel(gammahat),1]); - VecSE = reshape(SEGamma, [numel(gammahat),1]); - for i=1:length(VecParams) - [h(i) p(i)] = ztest(VecParams(i),0,VecSE(i)); - end - pGamma = reshape(p, [size(gammahat,1) size(gammahat,2)]); - end - if(PPEM_Constraints.EstimateA==1) - Pvals.A = pA; - end - Pvals.Q = pQ; - - if(PPEM_Constraints.EstimatePx0==1) - Pvals.Px0 = pPX0; - end - if(PPEM_Constraints.Estimatex0==1) - Pvals.x0 = pX0; - end - Pvals.mu = pMu; - Pvals.beta = pBeta; - - if(numel(gammahat)==1) - if(gammahat~=0) - Pvals.gamma = pGamma; - end - else - Pvals.gamma = pGamma; - end - - end - function [xKFinal,WKFinal,Ahat, Qhat, muhat, betahat, gammahat, x0hat, Px0hat, IC, SE, Pvals,nIter]=PP_EM(dN, Ahat0, Qhat0, mu, beta, fitType,delta, gamma, windowTimes, x0, Px0,PPEM_Constraints,MstepMethod) - numStates = size(Ahat0,1); - if(nargin<13 || isempty(MstepMethod)) - MstepMethod='GLM'; %or NewtonRaphson - end - if(nargin<12 || isempty(PPEM_Constraints)) - PPEM_Constraints = DecodingAlgorithms.PP_EMCreateConstraints; - end - if(nargin<11 || isempty(Px0)) - Px0=10e-10*eye(numStates,numStates); - end - if(nargin<10 || isempty(x0)) - x0=zeros(numStates,1); - end - - if(nargin<9 || isempty(windowTimes)) - if(isempty(gamma)) - windowTimes =[]; - else - % numWindows =length(gamma0)+1; - windowTimes = 0:delta:(length(gamma)+1)*delta; - end - end - if(nargin<8) - gamma=[]; - end - if(nargin<7 || isempty(delta)) - delta = .001; - end - if(nargin<6) - fitType = 'poisson'; - end - - minTime=0; - maxTime=(size(dN,2)-1)*delta; - K=size(dN,1); - if(~isempty(windowTimes)) - histObj = History(windowTimes,minTime,maxTime); - for k=1:K - nst{k} = nspikeTrain( (find(dN(k,:)==1)-1)*delta); - nst{k}.setMinTime(minTime); - nst{k}.setMaxTime(maxTime); -% HkAll{k} = histObj.computeHistory(nst{k}).dataToMatrix; - HkAll(:,:,k) = histObj.computeHistory(nst{k}).dataToMatrix; - end - else - for k=1:K -% HkAll{k} = 0; - HkAll(:,:,k) = 0; - end - gamma=0; - end - - - - % tol = 1e-3; %absolute change; - tolAbs = 1e-3; - tolRel = 1e-3; - llTol = 1e-3; - cnt=1; - - maxIter = 100; - - - A0 = Ahat0; - Q0 = Qhat0; - - Ahat{1} = A0; - Qhat{1} = Q0; - x0hat{1} = x0; - Px0hat{1} = Px0; - muhat{1} = mu; - betahat{1} = beta; - gammahat{1} = gamma; - numToKeep=10; - scaledSystem=1; - - if(scaledSystem==1) - Tq = eye(size(Qhat{1}))/(chol(Qhat{1})); - Ahat{1}= Tq*Ahat{1}/Tq; - Qhat{1}= Tq*Qhat{1}*Tq'; - x0hat{1} = Tq*x0; - Px0hat{1} = Tq*Px0*Tq'; - betahat{1}=(betahat{1}'/Tq)'; - end - - cnt=1; - dLikelihood(1)=inf; -% x0hat = x0; - negLL=0; - IkedaAcc=PPEM_Constraints.EnableIkeda; - %Forward EM - stoppingCriteria =0; -% logllNew= -inf; - - disp(' Point-Process Observation EM Algorithm '); - while(stoppingCriteria~=1 && cnt<=maxIter) - storeInd = mod(cnt-1,numToKeep)+1; %make zero-based then mod, then add 1 - storeIndP1= mod(cnt,numToKeep)+1; - storeIndM1= mod(cnt-2,numToKeep)+1; - disp('--------------------------------------------------------------------------------------------------------'); - disp(['Iteration #' num2str(cnt)]); - disp('--------------------------------------------------------------------------------------------------------'); - - - [x_K{storeInd},W_K{storeInd},ll(cnt),ExpectationSums{storeInd}]=... - DecodingAlgorithms.PP_EStep(Ahat{storeInd},Qhat{storeInd},dN, muhat{storeInd}, betahat{storeInd},fitType,gammahat{storeInd},HkAll, x0hat{storeInd}, Px0hat{storeInd}); - - [Ahat{storeIndP1}, Qhat{storeIndP1}, muhat{storeIndP1}, betahat{storeIndP1}, gammahat{storeIndP1},x0hat{storeIndP1},Px0hat{storeIndP1}] ... - = DecodingAlgorithms.PP_MStep(dN,x_K{storeInd},W_K{storeInd},x0hat{storeInd}, Px0hat{storeInd}, ExpectationSums{storeInd}, fitType,muhat{storeInd},betahat{storeInd}, gammahat{storeInd},windowTimes,HkAll,PPEM_Constraints,MstepMethod); - - if(IkedaAcc==1) - disp(['****Ikeda Acceleration Step****']); - - if(gammahat{storeIndP1}==0)% No history effect - dataMat = [ones(size(dN,2),1) x_K{storeInd}']; % design matrix: X - coeffsMat = [muhat{storeIndP1} betahat{storeIndP1}']; % coefficient vector: beta - minTime=0; - maxTime=(size(dN,2)-1)*delta; - time=minTime:delta:maxTime; - clear nstNew; - for cc=1:length(muhat{storeIndP1}) - tempData = exp(dataMat*coeffsMat(cc,:)'); - - if(strcmp(fitType,'poisson')) - lambdaData = tempData; - else - lambdaData = tempData./(1+tempData); % Conditional Intensity Function for ith cell - end - lambda{cc}=Covariate(time,lambdaData./delta, ... - '\Lambda(t)','time','s','spikes/sec',... - {strcat('\lambda_{',num2str(cc),'}')},{{' ''b'' '}}); - lambda{cc}=lambda{cc}.resample(1/delta); - - % generate one realization for each cell - tempSpikeColl{cc} = CIF.simulateCIFByThinningFromLambda(lambda{cc},1); - nstNew{cc} = tempSpikeColl{cc}.getNST(1); % grab the realization - nstNew{cc}.setName(num2str(cc)); % give each cell a unique name -% subplot(4,3,[8 11]); -% h2=lambda{cc}.plot([],{{' ''k'', ''LineWidth'' ,.5'}}); -% legend off; hold all; % Plot the CIF - - end - - spikeColl = nstColl(nstNew); % Create a neural spike train collection - else - time; - end - - dNNew=spikeColl.dataToMatrix'; - dNNew(dNNew>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 - % only one spike per bin - - -% [x_K,W_K,logll,ExpectationSums]=PP_EStep(A,Q,dN, mu, beta,fitType,gamma,HkAll, x0, Px0) - [x_KNew,W_KNew,logllNew,ExpectationSumsNew]=... - DecodingAlgorithms.PP_EStep(Ahat{storeInd},Qhat{storeInd},dNNew, muhat{storeInd}, betahat{storeInd},fitType,gammahat{storeInd},HkAll, x0, Px0); - - - [AhatNew, QhatNew, muhatNew, betahatNew, gammahatNew,x0new,Px0new] ... - = DecodingAlgorithms.PP_MStep(dNNew,x_KNew,W_KNew, x0hat{storeInd}, Px0hat{storeInd}, ExpectationSumsNew, fitType,muhat{storeInd},betahat{storeInd}, gammahat{storeInd},windowTimes,HkAll,PPEM_Constraints,MstepMethod); - - Ahat{storeIndP1} = 2*Ahat{storeIndP1}-AhatNew; - Qhat{storeIndP1} = 2*Qhat{storeIndP1}-QhatNew; - Qhat{storeIndP1} = (Qhat{storeIndP1}+Qhat{storeIndP1}')/2; - muhat{storeIndP1}= 2*muhat{storeIndP1}-muhatNew; - betahat{storeIndP1} = 2*betahat{storeIndP1}-betahatNew; - gammahat{storeIndP1}= 2*gammahat{storeIndP1}-gammahatNew; -% x0hat{storeIndP1} = 2*x0hat{storeIndP1} - x0new; -% Px0hat{storeIndP1} = 2*Px0hat{storeIndP1}- Px0new; -% [V,D] = eig(Px0hat{storeIndP1}); -% D(D<0)=1e-9; -% Px0hat{storeIndP1} = V*D*V'; -% Px0hat{storeIndP1} = (Px0hat{storeIndP1}+Px0hat{storeIndP1}')/2; - - - end - if(PPEM_Constraints.EstimateA==0) - Ahat{storeIndP1}=Ahat{storeInd}; - end - if(cnt==1) - dLikelihood(cnt+1)=inf; - else - dLikelihood(cnt+1)=(ll(cnt)-ll(cnt-1));%./abs(ll(cnt-1)); - end - if(cnt==1) - QhatInit = Qhat{1}; - xKInit = x_K{1}; - end - %Plot the progress -% if(mod(cnt,2)==0) - if(cnt==1) - scrsz = get(0,'ScreenSize'); - h=figure('OuterPosition',[scrsz(3)*.01 scrsz(4)*.04 scrsz(3)*.98 scrsz(4)*.95]); - end - figure(h); - time = linspace(minTime,maxTime,size(x_K{storeInd},2)); - subplot(2,4,[1 2 5 6]); plot(1:cnt,ll,'k','Linewidth', 2); hy=ylabel('Log Likelihood'); hx=xlabel('Iteration'); axis auto; - set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - subplot(2,4,3:4); hNew=plot(time, x_K{storeInd}','Linewidth', 2); hy=ylabel('States'); hx=xlabel('time [s]'); - set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - hold on; hOrig=plot(time, xKInit','--','Linewidth', 2); - legend([hOrig(1) hNew(1)],'Initial','Current'); - - - subplot(2,4,7:8); hNew=plot(diag(Qhat{storeInd}),'o','Linewidth', 2); hy=ylabel('Q'); hx=xlabel('Diagonal Entry'); - set(gca, 'XTick' , 1:1:length(diag(Qhat{storeInd}))); - set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - hold on; hOrig=plot(diag(QhatInit),'r.','Linewidth', 2); - legend([hOrig(1) hNew(1)],'Initial','Current'); - drawnow; - hold off; - - if(cnt==1) - dMax=inf; - else - dQvals = max(max(abs(sqrt(Qhat{storeInd})-sqrt(Qhat{storeIndM1})))); - dAvals = max(max(abs((Ahat{storeInd})-(Ahat{storeIndM1})))); - dMuvals = max(abs((muhat{storeInd})-(muhat{storeIndM1}))); - dBetavals = max(max(abs((betahat{storeInd})-(betahat{storeIndM1})))); - dGammavals = max(max(abs((gammahat{storeInd})-(gammahat{storeIndM1})))); - dMax = max([dQvals,dAvals,dMuvals,dBetavals,dGammavals]); - end - - if(cnt==1) - disp(['Max Parameter Change: N/A']); - else - disp(['Max Parameter Change: ' num2str(dMax)]); - end - - cnt=(cnt+1); - if(dMax10) - [SE, Pvals]=DecodingAlgorithms.PP_ComputeParamStandardErrors(dN,... - xKFinal, WKFinal, Ahat, Qhat, x0hat, Px0hat, ExpectationSumsFinal,... - fitType, muhat, betahat, gammahat, windowTimes, HkAll,... - PPEM_Constraints); - end - - %Compute number of parameters - if(PPEM_Constraints.EstimateA==1 && PPEM_Constraints.AhatDiag==1) - n1=size(Ahat,1); - elseif(PPEM_Constraints.EstimateA==1 && PPEM_Constraints.AhatDiag==0) - n1=numel(Ahat); - else - n1=0; - end - if(PPEM_Constraints.QhatDiag==1 && PPEM_Constraints.QhatIsotropic==1) - n2=1; - elseif(PPEM_Constraints.QhatDiag==1 && PPEM_Constraints.QhatIsotropic==0) - n2=size(Qhat,1); - else - n2=numel(Qhat); - end - - - if(PPEM_Constraints.EstimatePx0==1 && PPEM_Constraints.Px0Isotropic==1) - n3=1; - elseif(PPEM_Constraints.EstimatePx0==1 && PPEM_Constraints.Px0Isotropic==0) - n3=size(Px0hat,1); - else - n3=0; - end - - if(PPEM_Constraints.Estimatex0==1) - n4=size(x0hat,1); - else - n4=0; - end - - n5=size(muhat,1); - n6=numel(betahat); - if(numel(gammahat)==1) - if(gammahat==0) - n7=0; - else - n7=1; - end - else - n7=numel(gammahat); - end - nTerms=n1+n2+n3+n4+n5+n6+n7; - - K = size(xKFinal,2); - Dx = size(Ahat,2); - sumXkTerms = ExpectationSums{maxLLIndMod}.sumXkTerms; - llobs = ll + Dx*K/2*log(2*pi)+K/2*log(det(Qhat))... - + 1/2*trace(Qhat\sumXkTerms)... - + Dx/2*log(2*pi)+1/2*log(det(Px0hat)) ... - + 1/2*Dx; - AIC = 2*nTerms - 2*llobs; - AICc= AIC+ 2*nTerms*(nTerms+1)/(K-nTerms-1); - BIC = -2*llobs+nTerms*log(K); - IC.AIC = AIC; - IC.AICc= AICc; - IC.BIC = BIC; - IC.llobs = llobs; - IC.llcomp=ll; - - - end - % function [xKFinal,WKFinal,Ahat, Qhat, muhat, betahat, gammahat, x0hat, Px0hat, logll,nIter,negLL]=PP_EM(dN, Ahat0, Qhat0, mu, beta, fitType,delta, gamma, windowTimes, x0, Px0,MstepMethod) -% numStates = size(Ahat0,1); -% if(nargin<12 || isempty(MstepMethod)) -% MstepMethod='GLM'; %or NewtonRaphson -% end -% if(nargin<11 || isempty(Px0)) -% Px0=10e-10*eye(numStates,numStates); -% end -% if(nargin<10 || isempty(x0)) -% x0=zeros(numStates,1); -% end -% -% if(nargin<9 || isempty(windowTimes)) -% if(isempty(gamma)||gamma==0) -% windowTimes =[]; -% else -% % numWindows =length(gamma0)+1; -% windowTimes = 0:delta:(length(gamma)+1)*delta; -% end -% end -% if(nargin<8) -% gamma=[]; -% end -% if(nargin<11 || isempty(delta)) -% delta = .001; -% end -% if(nargin<6) -% fitType = 'poisson'; -% end -% -% minTime=0; -% maxTime=(size(dN,2)-1)*delta; -% K=size(dN,1); -% N=size(dN,2); -% if(~isempty(windowTimes)) -% histObj = History(windowTimes,minTime,maxTime); -% for k=1:K -% nst{k} = nspikeTrain( (find(dN(k,:)==1)-1)*delta); -% nst{k}.setMinTime(minTime); -% nst{k}.setMaxTime(maxTime); -% % HkAll{k} = histObj.computeHistory(nst{k}).dataToMatrix; -% HkAll(:,:,k) = histObj.computeHistory(nst{k}).dataToMatrix; -% end -% if(size(gamma,1)==K) -% gamma=gamma'; -% end -% -% else -% for k=1:K -% HkAll(:,:,k) = zeros(N,length(windowTimes)-1); -% end -% gamma=0; -% end -% -% -% -% % tol = 1e-3; %absolute change; -% tolAbs = 1e-3; -% tolRel = 1e-3; -% llTol = 1e-3; -% cnt=1; -% -% maxIter = 100; -% -% -% A0 = Ahat0; -% Q0 = Qhat0; -% -% Ahat{1} = A0; -% Qhat{1} = Q0; -% x0hat{1} = x0; -% Px0hat{1} = Px0; -% muhat{1} = mu; -% betahat{1} = beta; -% gammahat{1} = gamma; -% numToKeep=10; -% scaledSystem=1; -% -% if(scaledSystem==1) -% Tq = eye(size(Qhat{1}))/(chol(Qhat{1})); -% Ahat{1}= Tq*Ahat{1}/Tq; -% Qhat{1}= Tq*Qhat{1}*Tq'; -% x0hat{1} = Tq*x0; -% Px0hat{1} = Tq*Px0*Tq'; -% betahat{1}=(betahat{1}'/Tq)'; -% end -% -% cnt=1; -% dLikelihood(1)=inf; -% negLL=0; -% IkedaAcc=0; -% %Forward EM -% stoppingCriteria =0; -% -% while(stoppingCriteria~=1 && cnt<=maxIter) -% storeInd = mod(cnt-1,numToKeep)+1; %make zero-based then mod, then add 1 -% storeIndP1= mod(cnt,numToKeep)+1; -% storeIndM1= mod(cnt-2,numToKeep)+1; -% disp('---------------'); -% disp(['Iteration #' num2str(cnt)]); -% disp('---------------'); -% -% -% [x_K{storeInd},W_K{storeInd},logll(cnt),ExpectationSums{storeInd}]=... -% DecodingAlgorithms.PP_EStep(Ahat{storeInd},Qhat{storeInd},dN, muhat{storeInd}, betahat{storeInd},fitType,gammahat{storeInd},HkAll, x0hat{storeInd}, Px0hat{storeInd}); -% -% [Ahat{storeIndP1}, Qhat{storeIndP1}, muhat{storeIndP1}, betahat{storeIndP1}, gammahat{storeIndP1},x0hat{storeIndP1},Px0hat{storeIndP1}] ... -% = DecodingAlgorithms.PP_MStep(dN,x_K{storeInd},W_K{storeInd},x0hat{storeInd},ExpectationSums{storeInd}, fitType,muhat{storeInd},betahat{storeInd}, gammahat{storeInd},windowTimes,HkAll,MstepMethod); -% -% if(IkedaAcc==1) -% disp(['****Ikeda Acceleration Step****']); -% -% if(gammahat{storeIndP1}==0)% No history effect -% dataMat = [ones(size(dN,2),1) x_K{storeInd}']; % design matrix: X -% coeffsMat = [muhat{storeIndP1} betahat{storeIndP1}']; % coefficient vector: beta -% minTime=0; -% maxTime=(size(dN,2)-1)*delta; -% time=minTime:delta:maxTime; -% clear nstNew; -% for cc=1:length(muhat{storeIndP1}) -% tempData = exp(dataMat*coeffsMat(cc,:)'); -% -% if(strcmp(fitType,'poisson')) -% lambdaData = tempData; -% else -% lambdaData = tempData./(1+tempData); % Conditional Intensity Function for ith cell -% end -% lambda{cc}=Covariate(time,lambdaData./delta, ... -% '\Lambda(t)','time','s','spikes/sec',... -% {strcat('\lambda_{',num2str(cc),'}')},{{' ''b'' '}}); -% lambda{cc}=lambda{cc}.resample(1/delta); -% -% % generate one realization for each cell -% tempSpikeColl{cc} = CIF.simulateCIFByThinningFromLambda(lambda{cc},1); -% nstNew{cc} = tempSpikeColl{cc}.getNST(1); % grab the realization -% nstNew{cc}.setName(num2str(cc)); % give each cell a unique name -% % subplot(4,3,[8 11]); -% % h2=lambda{cc}.plot([],{{' ''k'', ''LineWidth'' ,.5'}}); -% % legend off; hold all; % Plot the CIF -% -% end -% -% spikeColl = nstColl(nstNew); % Create a neural spike train collection -% else -% time; -% end -% -% dNNew=spikeColl.dataToMatrix'; -% dNNew(dNNew>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 -% % only one spike per bin -% -% -% % [x_K,W_K,logll,ExpectationSums]=PP_EStep(A,Q,dN, mu, beta,fitType,gamma,HkAll, x0, Px0) -% [x_KNew,W_KNew,logllNew,ExpectationSumsNew]=... -% DecodingAlgorithms.PP_EStep(Ahat{storeInd},Qhat{storeInd},dNNew, muhat{storeInd}, betahat{storeInd},fitType,gammahat{storeInd},HkAll, x0, Px0); -% -% -% [AhatNew, QhatNew, muhatNew, betahatNew, gammahatNew,x0new,Px0new] ... -% = DecodingAlgorithms.PP_MStep(dNNew,x_KNew,W_KNew, x0hat{storeInd}, ExpectationSumsNew, fitType,muhat{storeInd},betahat{storeInd}, gammahat{storeInd},windowTimes,HkAll,MstepMethod); -% -% Ahat{storeIndP1} = 2*Ahat{storeIndP1}-AhatNew; -% Qhat{storeIndP1} = 2*Qhat{storeIndP1}-QhatNew; -% Qhat{storeIndP1} = (Qhat{storeIndP1}+Qhat{storeIndP1}')/2; -% muhat{storeIndP1}= 2*muhat{storeIndP1}-muhatNew; -% betahat{storeIndP1} = 2*betahat{storeIndP1}-betahatNew; -% gammahat{storeIndP1}= 2*gammahat{storeIndP1}-gammahatNew; -% % x0hat{storeIndP1} = 2*x0hat{storeIndP1} - x0new; -% % Px0hat{storeIndP1} = 2*Px0hat{storeIndP1}- Px0new; -% % [V,D] = eig(Px0hat{storeIndP1}); -% % D(D<0)=1e-9; -% % Px0hat{storeIndP1} = V*D*V'; -% % Px0hat{storeIndP1} = (Px0hat{storeIndP1}+Px0hat{storeIndP1}')/2; -% -% -% end -% -% if(cnt==1) -% dLikelihood(cnt+1)=inf; -% else -% dLikelihood(cnt+1)=(logll(cnt)-logll(cnt-1));%./abs(logll(cnt-1)); -% end -% if(cnt==1) -% QhatInit = Qhat{1}; -% xKInit = x_K{1}; -% end -% %Plot the progress -% % if(mod(cnt,2)==0) -% if(cnt==1) -% scrsz = get(0,'ScreenSize'); -% h=figure('OuterPosition',[scrsz(3)*.01 scrsz(4)*.04 scrsz(3)*.98 scrsz(4)*.95]); -% end -% figure(h); -% time = linspace(minTime,maxTime,size(x_K{storeInd},2)); -% subplot(2,4,[1 2 5 6]); plot(1:cnt,logll,'k','Linewidth', 2); hy=ylabel('Log Likelihood'); hx=xlabel('Iteration'); axis auto; -% set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); -% subplot(2,4,3:4); hNew=plot(time, x_K{storeInd}','Linewidth', 2); hy=ylabel('States'); hx=xlabel('time [s]'); -% set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); -% hold on; hOrig=plot(time, xKInit','--','Linewidth', 2); -% legend([hOrig(1) hNew(1)],'Initial','Current'); -% -% -% subplot(2,4,7:8); hNew=plot(diag(Qhat{storeInd}),'o','Linewidth', 2); hy=ylabel('Q'); hx=xlabel('Diagonal Entry'); -% set(gca, 'XTick' , 1:1:length(diag(Qhat{storeInd}))); -% set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); -% hold on; hOrig=plot(diag(QhatInit),'r.','Linewidth', 2); -% legend([hOrig(1) hNew(1)],'Initial','Current'); -% drawnow; -% hold off; -% % end -% -% if(cnt==1) -% dMax=inf; -% else -% dQvals = max(max(abs(sqrt(Qhat{storeInd})-sqrt(Qhat{storeIndM1})))); -% dAvals = max(max(abs((Ahat{storeInd})-(Ahat{storeIndM1})))); -% dMuvals = max(abs((muhat{storeInd})-(muhat{storeIndM1}))); -% dBetavals = max(max(abs((betahat{storeInd})-(betahat{storeIndM1})))); -% dGammavals = max(max(abs((gammahat{storeInd})-(gammahat{storeIndM1})))); -% dMax = max([dQvals,dAvals,dMuvals,dBetavals,dGammavals]); -% end -% -% % -% % dQRel = max(abs(dQvals./sqrt(Qhat(:,storeIndM1)))); -% % dGammaRel = max(abs(dGamma./gammahat(storeIndM1,:))); -% % dMaxRel = max([dQRel,dGammaRel]); -% -% -% cnt=(cnt+1); -% if(dMax1 && isempty(WuConv)) -% % diffWu = abs(W_u(:,:,k)-W_u(:,:,k-1)); -% % maxWu = max(max(diffWu)); -% % if(maxWu<5e-2) -% % WuConv = W_u(:,:,k); -% % WuConvIter = k; -% % end -% % end -% end -% -% -% [x_K, W_K,Lk] = DecodingAlgorithms.kalman_smootherFromFiltered(A, x_p, W_p, x_u, W_u); -% -% %Best estimates of initial states given the data -% W1G0 = A*Px0*A' + Q; -% L0=Px0*A'/W1G0; -% -% Ex0Gy = x0+L0*(x_K(:,1)-x_p(:,1)); -% Px0Gy = Px0+L0*(eye(size(W_K(:,:,1)))/(W_K(:,:,1))-eye(size(W1G0))/W1G0)*L0'; -% Px0Gy = (Px0Gy+Px0Gy')/2; -% numStates = size(x_K,1); -% Wku=zeros(numStates,numStates,K,K); -% Tk = zeros(numStates,numStates,K-1); -% for k=1:K -% Wku(:,:,k,k)=W_K(:,:,k); -% end -% -% for u=K:-1:2 -% for k=(u-1):-1:(u-1) -% Tk(:,:,k)=A; -% % Dk(:,:,k)=W_u(:,:,k)*Tk(:,:,k)'*pinv(W_p(:,:,k)); %From deJong and MacKinnon 1988 -% Dk(:,:,k)=W_u(:,:,k)*Tk(:,:,k)'/(W_p(:,:,k+1)); %From deJong and MacKinnon 1988 -% Wku(:,:,k,u)=Dk(:,:,k)*Wku(:,:,k+1,u); -% Wku(:,:,u,k)=Wku(:,:,k,u)'; -% end -% end -% -% %All terms -% Sxkm1xk = zeros(Dx,Dx); -% Sxkxkm1 = zeros(Dx,Dx); -% Sxkm1xkm1 = zeros(Dx,Dx); -% Sxkxk = zeros(Dx,Dx); -% -% for k=1:K -% if(k==1) -% Sxkm1xk = Sxkm1xk+Px0*A'/W_p(:,:,1)*Wku(:,:,1,1); -% Sxkm1xkm1 = Sxkm1xkm1+Px0+x0*x0'; -% else -% % -% Sxkm1xk = Sxkm1xk+Wku(:,:,k-1,k)+x_K(:,k-1)*x_K(:,k)'; -% -% Sxkm1xkm1= Sxkm1xkm1+Wku(:,:,k-1,k-1)+x_K(:,k-1)*x_K(:,k-1)'; -% end -% Sxkxk = Sxkxk+Wku(:,:,k,k)+x_K(:,k)*x_K(:,k)'; -% -% end -% Sx0x0 = Px0+x0*x0'; -% Sxkxk = 0.5*(Sxkxk+Sxkxk'); -% sumXkTerms = Sxkxk-A*Sxkm1xk-Sxkm1xk'*A'+A*Sxkm1xkm1*A'; -% Sxkxkm1 = Sxkm1xk'; -% -% % if(strcmp(fitType,'poisson')) -% % sumPPll=0; -% % for c=1:numCells -% % % Hk=HkAll{c}; -% % Hk=squeeze(HkAll(k,:,c)); -% % for k=1:K -% % xk = x_K(:,k); -% % if(numel(gamma)==1) -% % gammaC=gamma; -% % else -% % gammaC=gamma(:,c); -% % end -% % % terms=mu(c)+beta(:,c)'*xk+gammaC'*Hk(k,:)'; -% % if(numel(Hk)~=1) -% % terms=mu(c)+beta(:,c)'*xk+gammaC'*Hk(k,:)'; -% % else -% % terms=mu(c)+beta(:,c)'*xk+gammaC'*Hk'; -% % end -% % Wk = W_K(:,:,k); -% % ld = exp(terms); -% % bt = beta(:,c); -% % ExplambdaDelta =ld+0.5*trace(bt*bt'*ld*Wk); -% % ExplogLD = terms; -% % sumPPll=sumPPll+dN(c,k).*ExplogLD - ExplambdaDelta; -% % end -% % -% % -% % end -% % elseif(strcmp(fitType,'binomial')) -% % sumPPll=0; -% % for c=1:C -% % for k=1:K -% % Hk=squeeze(HkAll(k,:,c)); -% % xk = x_K(:,k); -% % if(numel(gamma)==1) -% % gammaC=gamma; -% % else -% % gammaC=gamma(:,c); -% % end -% % if(numel(Hk)~=1) -% % terms=mu(c)+beta(:,c)'*xk+gammaC'*Hk(k,:)'; -% % else -% % terms=mu(c)+beta(:,c)'*xk+gammaC'*Hk'; -% % end -% % Wk = W_K(:,:,k); -% % ld = exp(terms)./(1+exp(terms)); -% % bt = beta; -% % ExplambdaDelta =sum(ld+0.5*sum(bt'*bt*repmat(ld.*(1-ld).*(1-2.*ld),1,2)*Wk,2)); -% % ExplogLD = (log(ld)+0.5*sum(bt*bt'*(repmat(ld.*(1-ld),1,size(bt,1))*Wk)')'); -% % sumPPll=sumPPll+dN(:,k)'*ExplogLD - ExplambdaDelta; -% % end -% % end -% % -% % % for c=1:numCells -% % % Hk=HkAll{c}; -% % % for k=1:K -% % % xk = x_K(:,k); -% % % if(numel(gamma)==1) -% % % gammaC=gamma; -% % % else -% % % gammaC=gamma(:,c); -% % % end -% % % if(numel(Hk)~=1) -% % % terms=mu(c)+beta(:,c)'*xk+gammaC'*Hk(k,:)'; -% % % else -% % % terms=mu(c)+beta(:,c)'*xk+gammaC'*Hk'; -% % % end -% % % Wk = W_K(:,:,k); -% % % ld = exp(terms)./(1+exp(terms)); -% % % bt = beta(:,c); -% % % ExplambdaDelta =ld+0.5*trace(bt*bt'*ld*(1-ld)*(1-2*ld)*Wk); -% % % ExplogLD = log(ld)+0.5*trace(-(bt*bt'*ld*(1-ld))*Wk); -% % % sumPPll=sumPPll+dN(c,k).*ExplogLD - ExplambdaDelta; -% % % end -% % % -% % % -% % % end -% % end -% -% %Vectorize for loop over cells -% if(strcmp(fitType,'poisson')) -% sumPPll=0; -% for k=1:K -% Hk=squeeze(HkAll(k,:,:)); -% if(size(Hk,1)==numCells) -% Hk = Hk'; -% end -% xk = x_K(:,k); -% if(numel(gamma)==1) -% gammaC=repmat(gamma,1,numCells); -% else -% gammaC=gamma; -% end -% % if(size(gammaC,1)~=size(mu,1)) -% % gammaC = gammaC'; -% % end -% % if(size(Hk,1)~=size(mu,1)) -% % Hk=Hk'; -% % end -% terms=mu+beta'*xk+diag(gammaC'*Hk); -% Wk = W_K(:,:,k); -% ld = exp(terms); -% bt = beta; -% ExplambdaDelta =ld+0.5*(ld.*diag((bt'*Wk*bt))); -% ExplogLD = terms; -% sumPPll=sumPPll+sum(dN(:,k).*ExplogLD - ExplambdaDelta); -% -% end -% -% %Vectorize over number of cells -% elseif(strcmp(fitType,'binomial')) -% sumPPll=0; -% for k=1:K -% Hk=squeeze(HkAll(k,:,:)); -% if(size(Hk,1)==numCells) -% Hk = Hk'; -% end -% xk = x_K(:,k); -% if(numel(gamma)==1) -% gammaC=repmat(gamma,1,numCells); -% else -% gammaC=gamma; -% end -% % if(size(gammaC,1)~=size(mu,1)) -% % gammaC = gammaC'; -% % end -% % if(size(Hk,1)~=size(mu,1)) -% % Hk=Hk'; -% % end -% terms=mu+beta'*xk+diag(gammaC'*Hk); -% Wk = W_K(:,:,k); -% ld = exp(terms)./(1+exp(terms)); -% bt = beta; -% ExplambdaDelta = ld+0.5*(ld.*(1-ld).*(1-2.*ld)).*diag((bt'*Wk*bt)); -% ExplogLD = log(ld)+0.5*(-ld.*(1-ld)).*diag(bt'*Wk*bt); -% sumPPll=sumPPll+sum(dN(:,k).*ExplogLD - ExplambdaDelta); -% -% end -% -% -% end -% -% logll = -Dx*K/2*log(2*pi)-K/2*log(det(Q)) ... -% - Dx/2*log(2*pi) -1/2*log(det(Px0)) ... -% +sumPPll - 1/2*trace((eye(size(Q))/Q)*sumXkTerms) ... -% -Dx/2; -% string0 = ['logll: ' num2str(logll)]; -% disp(string0); -% if(DEBUG==1) -% string1 = ['-K/2*log(det(Q)):' num2str(-K/2*log(det(Q)))]; -% string12= ['Constants: ' num2str(-Dx*K/2*log(2*pi)-Dx/2*log(2*pi) -Dx/2 -1/2*log(det(Px0)))]; -% string2 = ['SumPPll: ' num2str(sumPPll)]; -% string3 = ['-.5*trace(Q\sumXkTerms): ' num2str(-.5*trace(Q\sumXkTerms))]; -% -% disp(string1); -% disp(['Q=' num2str(diag(Q)')]); -% disp(string12); -% disp(string2); -% disp(string3); -% -% end -% -% ExpectationSums.Sxkm1xkm1=Sxkm1xkm1; -% ExpectationSums.Sxkm1xk=Sxkm1xk; -% ExpectationSums.Sxkxkm1=Sxkxkm1; -% ExpectationSums.Sxkxk=Sxkxk; -% ExpectationSums.sumXkTerms=sumXkTerms; -% ExpectationSums.sumPPll=sumPPll; -% ExpectationSums.Sx0 = Ex0Gy; -% ExpectationSums.Sx0x0 = Px0Gy + Ex0Gy*Ex0Gy'; -% ExpectationSums.A = A; -% ExpectationSums.Q = Q; -% ExpectationSums.mu = mu; -% ExpectationSums.beta = beta; -% ExpectationSums.gamma = gamma; -% -% end - function [Ahat, Qhat, muhat_new, betahat_new, gammahat_new, x0hat, Px0hat] = PP_MStep(dN, x_K,W_K,x0, Px0, ExpectationSums,fitType, muhat, betahat,gammahat, windowTimes, HkAll,PPEM_Constraints,MstepMethod) - if(nargin<14 || isempty(MstepMethod)) - MstepMethod = 'GLM'; %GLM or NewtonRaphson - end - if(nargin<13 || isempty(PPEM_Constraints)) - PPEM_Constraints = DecodingAlgorithms.PP_EMCreateConstraints; - end - - Sxkm1xkm1=ExpectationSums.Sxkm1xkm1; - Sxkxkm1=ExpectationSums.Sxkxkm1; - sumXkTerms = ExpectationSums.sumXkTerms; - [dx,K] = size(x_K); - numCells=size(dN,1); - - if(PPEM_Constraints.AhatDiag==1) - I=eye(dx,dx); - Ahat = (Sxkxkm1.*I)/(Sxkm1xkm1.*I); - else - Ahat = Sxkxkm1/Sxkm1xkm1; - end - - - if(PPEM_Constraints.QhatDiag==1) - if(PPEM_Constraints.QhatIsotropic==1) - Qhat=1/(dx*K)*trace(sumXkTerms)*eye(dx,dx); - else - I=eye(dx,dx); - Qhat=1/K*(sumXkTerms.*I); - Qhat = (Qhat + Qhat')/2; - end - else - Qhat=1/K*sumXkTerms; - Qhat = (Qhat + Qhat')/2; - end - - if(PPEM_Constraints.Estimatex0) - x0hat = (inv(Px0)+Ahat'/Qhat*Ahat)\(Ahat'/Qhat*x_K(:,1)+Px0\x0); - else - x0hat = x0; - end - - if(PPEM_Constraints.EstimatePx0==1) - if(PPEM_Constraints.Px0Isotropic==1) - Px0hat=(trace(x0hat*x0hat' - x0*x0hat' - x0hat*x0' +(x0*x0'))/(dx*K))*eye(dx,dx); - else - I=eye(dx,dx); - Px0hat =(x0hat*x0hat' - x0*x0hat' - x0hat*x0' +(x0*x0')).*I; - Px0hat = (Px0hat+Px0hat')/2; - end - - else - Px0hat =Px0; - end - - betahat_new =betahat; - gammahat_new = gammahat; - muhat_new = muhat; - - %Compute the new CIF beta using the GLM - if(strcmp(fitType,'poisson')) - algorithm = 'GLM'; - else - algorithm = 'BNLRCG'; - end - - % Estimate params via GLM - if(strcmp(MstepMethod,'GLM')) - clear c; close all; - time=(0:length(x_K)-1)*.001; - labels = cell(1,dx); - labels2 = cell(1,dx+1); - labels2{1} = 'vel'; - for i=1:dx - labels{i} = strcat('v',num2str(i)); - labels2{i+1} = strcat('v',num2str(i)); - end - vel = Covariate(time,x_K','vel','time','s','m/s',labels); - baseline = Covariate(time,ones(length(time),1),'Baseline','time','s','',... - {'constant'}); - for i=1:size(dN,1) - spikeTimes = time(find(dN(i,:)==1)); - nst{i} = nspikeTrain(spikeTimes); - end - nspikeColl = nstColl(nst); - cc = CovColl({vel,baseline}); - trial = Trial(nspikeColl,cc); - selfHist = windowTimes ; NeighborHist = []; sampleRate = 1000; - clear c; - - - - if(gammahat==0) - c{1} = TrialConfig({{'Baseline','constant'},labels2},sampleRate,[],NeighborHist); - else - c{1} = TrialConfig({{'Baseline','constant'},labels2},sampleRate,selfHist,NeighborHist); - end - c{1}.setName('Baseline'); - cfgColl= ConfigColl(c); - warning('OFF'); - - results = Analysis.RunAnalysisForAllNeurons(trial,cfgColl,0,algorithm); - temp = FitResSummary(results); - tempCoeffs = squeeze(temp.getCoeffs); - if(gammahat==0) - betahat(1:dx,:) = tempCoeffs(2:(dx+1),:); - muhat = tempCoeffs(1,:)'; - else - betahat(1:dx,:) = tempCoeffs(2:(dx+1),:); - muhat = tempCoeffs(1,:)'; - histTemp = squeeze(temp.getHistCoeffs); - histTemp = reshape(histTemp, [length(windowTimes)-1 numCells]); - histTemp(isnan(histTemp))=0; - gammahat=histTemp; - end - else - - % Estimate via Newton-Raphson - % Estimate via Newton-Raphson - fprintf(['****M-step for beta**** \n']); - McExp=50; - xKDrawExp = zeros(size(x_K,1),K,McExp); - diffTol = 1e-5; - - % Generate the Monte Carlo samples - for k=1:K - WuTemp=(W_K(:,:,k)); - [chol_m,p]=chol(WuTemp); - z=normrnd(0,1,size(x_K,1),McExp); - xKDrawExp(:,k,:)=repmat(x_K(:,k),[1 McExp])+(chol_m*z); - end - - % Stimulus Coefficients - pool = matlabpool('size'); - if(pool==0) - for c=1:numCells - converged=0; - iter = 1; - maxIter=100; - fprintf(['neuron:' num2str(c) ' iter: ']); - while(~converged && itermethods -% Events Examples -% -% Reference page in Help browser -% doc Events - - -% -% nSTAT v1 Copyright (C) 2012 Masschusetts Institute of Technology -% Cajigas, I, Malik, WQ, Brown, EN -% This program is free software; you can redistribute it and/or -% modify it under the terms of the GNU General Public License as published -% by the Free Software Foundation; either version 2 of the License, or -% (at your option) any later version. -% -% This program is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -% See the GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with this program; if not, write to the Free Software Foundation, -% Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - properties - eventTimes; % time of each event - eventLabels;% label of each event - eventColor; % color for plotting event - end - - methods - function e = Events(eventTimes, eventLabels,eventColor) - % e = Events(eventTimes, eventLabels,eventColor) - if(nargin<3) - eventColor = 'r'; - end - - if(length(eventTimes)==length(eventLabels)) - e.eventTimes = eventTimes; - e.eventLabels = eventLabels; - e.eventColor = eventColor; - else - error('Number of eventTimes must equal number of eventLabels'); - end - end - - function h = plot(EObj,handle,colorString) - % h = plot(EObj,handle) - % plots the event on the current on the figure/subplot - % specified by handle. - % If handle is not specified, then handle defaults to the - % current figure window. - if((nargin<3) || isempty(colorString)) - colorString=EObj.eventColor; - end - if((nargin<2) || isempty(handle)) - handle=gca; - end - - - - for j=1:length(handle) %An event can be told to plot itself on multiple axes - set(gcf,'CurrentAxes',handle(j)); - v=axis; -% for k=1:length(EObj.eventTimes) -% times = ones(1,4)*EObj.eventTimes(k) + 4*[-.001 .001 .001 -.001]*(v(2)-v(1)); -% y = [v(3), v(3),v(4),v(4)]; - times = repmat(EObj.eventTimes,[2 1]); - y = [v(3); v(4)]*ones(1,length(EObj.eventTimes)); - hold on; - h=plot(handle(j),times,y,'r','LineWidth',4); - %tcolor(1,1,1:3) = [1 0 0]; -% p=patch(times,y,colorString);%'FaceAlpha',.7,'EdgeAlpha',0) -% set(p,'facecolor',colorString,'edgecolor','none'); -% alpha(.5); -% end - % Create textbox - v=axis; - for i=1:length(EObj.eventTimes) - if( ((EObj.eventTimes(i)-v(1))/(v(2)-v(1))>=0) && (EObj.eventTimes(i)<=v(2))) - text((EObj.eventTimes(i)-v(1))/(v(2)-v(1))-.02,1.03,EObj.eventLabels{i},'rotation',0,'FontSize',10,'Color',[0 0 0],'Units', 'normalized'); %write event labels - %'Interpreter','latex' - end - end - end - end - - function structure = toStructure(EObj) - fNames = fieldnames(EObj); - for i=1:length(fNames) - structure.(fNames{i}) = EObj.(fNames{i}); - end - - - end - - - end - methods (Static) - function EObj = fromStructure(structure) - if(~isempty(structure)) - fNames = fieldnames(structure); - reqNames = {'eventTimes','eventLabels','eventColor'}; - for i=1:length(reqNames) - if(~any(strcmp(reqNames{i},fNames))) - error('Missing field in structure. Cant creats Events object!'); - end - end - EObj=Events(structure.eventTimes,structure.eventLabels,structure.eventColor); - else - EObj = []; - end - end - end - - -end - -function varargout = dsxy2figxy(varargin) -% dsxy2figxy -- Transform point or position from axis to figure coords -% Transforms [axx axy] or [xypos] from axes hAx (data) coords into coords -% wrt GCF for placing annotation objects that use figure coords into data -% space. The annotation objects this can be used for are -% arrow, doublearrow, textarrow -% ellipses (coordinates must be transformed to [x, y, width, height]) -% Note that line, text, and rectangle anno objects already are placed -% on a plot using axes coordinates and must be located within an axes. -% Usage: Compute a position and apply to an annotation, e.g., -% [axx axy] = ginput(2); -% [figx figy] = getaxannopos(gca, axx, axy); -% har = annotation('textarrow',figx,figy); -% set(har,'String',['(' num2str(axx(2)) ',' num2str(axy(2)) ')']) - -%% Obtain arguments (only limited argument checking is performed). -% Determine if axes handle is specified -if length(varargin{1})== 1 && ishandle(varargin{1}) && ... - strcmp(get(varargin{1},'type'),'axes') - hAx = varargin{1}; - varargin = varargin(2:end); -else - hAx = gca; -end; -% Parse either a position vector or two 2-D point tuples -if length(varargin)==1 % Must be a 4-element POS vector - pos = varargin{1}; -else - [x,y] = deal(varargin{:}); % Two tuples (start & end points) -end -%% Get limits -axun = get(hAx,'Units'); -set(hAx,'Units','normalized'); % Need normaized units to do the xform -axpos = get(hAx,'Position'); -axlim = axis(hAx); % Get the axis limits [xlim ylim (zlim)] -axwidth = diff(axlim(1:2)); -axheight = diff(axlim(3:4)); -%% Transform data from figure space to data space -if exist('x','var') % Transform a and return pair of points - varargout{1} = (x-axlim(1))*axpos(3)/axwidth + axpos(1); - varargout{2} = (y-axlim(3))*axpos(4)/axheight + axpos(2); -else % Transform and return a position rectangle - pos(1) = (pos(1)-axlim(1))/axwidth*axpos(3) + axpos(1); - pos(2) = (pos(2)-axlim(3))/axheight*axpos(4) + axpos(2); - pos(3) = pos(3)*axpos(3)/axwidth; - pos(4) = pos(4)*axpos(4)/axheight; - varargout{1} = pos; -end -%% Restore axes units -set(hAx,'Units',axun) -end - - - - \ No newline at end of file diff --git a/FitResSummary.m b/FitResSummary.m deleted file mode 100644 index 3f73bc55..00000000 --- a/FitResSummary.m +++ /dev/null @@ -1,1340 +0,0 @@ -classdef FitResSummary < handle -% FITRESSUMMARY - given a collection of fitResult objects (one for each -% neuron, each containing the results of multiple regressions), computes -% summary statistics across neurons. This is to allows visualization of -% commonalities in the data across multiple neurons. -% -% % methods -% see also FitResult -% -% Reference page in Help browser -% doc FitResSummary - - -% -% nSTAT v1 Copyright (C) 2012 Masschusetts Institute of Technology -% Cajigas, I, Malik, WQ, Brown, EN -% This program is free software; you can redistribute it and/or -% modify it under the terms of the GNU General Public License as published -% by the Free Software Foundation; either version 2 of the License, or -% (at your option) any later version. -% -% This program is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -% See the GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with this program; if not, write to the Free Software Foundation, -% Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - properties - fitResCell %collection of FitResult Objects - fitNames %names of the different fits - numResults %number of fits in each FitResult Object - maxNumIndex %Index into the results that have all of the labels - dev - AIC % AIC matrix (length(neuronNumbers) x numResults) - BIC % BIC matrix (length(neuronNumbers) x numResults) - logLL % logLL matrix (length(neuronNumners) x numResults) - bAct - seAct - sigIndex - covLabels %labels of relevant covariates in fits. - uniqueCovLabels - indicesToUniqueLabels - flatMask - neuronNumbers % neuronNumber(i) is the number of the neuron corresponding to fitResCell{i} - numNeurons % Total number of neurons being summarized - numCoeffs - numResultsCoeffPresent; - KSStats % KSStats matrix (length(neuronNumbers) x numResults) - KSPvalues - withinConfInt - plotParams - coeffRange - end - - methods - function frsObj = FitResSummary(fitResultsCell) - % frsObj = FitResSummary(fitResultsCell) - % Takes a cell array of FitResult objects and returns a - % FitResultSummary object. - if(isa(fitResultsCell,'FitResult')) - frsObj=FitResSummary({fitResultsCell}); - elseif(isa(fitResultsCell,'cell') && ~isempty(fitResultsCell)) - if(isa(fitResultsCell{1},'FitResult')) - frsObj.fitResCell=cell(length(fitResultsCell),1); - maxNumResults = 0; - maxNumIndex=1; - for i=1:length(fitResultsCell) - if(fitResultsCell{i}.numResults>maxNumResults) - maxNumResults = fitResultsCell{i}.numResults; - maxNumIndex = i; - end - - end - frsObj.maxNumIndex = maxNumIndex; - frsObj.dev = nan(length(fitResultsCell),maxNumResults); - frsObj.AIC = nan(length(fitResultsCell),maxNumResults); - frsObj.BIC = nan(length(fitResultsCell),maxNumResults); - frsObj.logLL = nan(length(fitResultsCell),maxNumResults); - frsObj.KSStats = nan(length(fitResultsCell),maxNumResults); - frsObj.KSPvalues = nan(length(fitResultsCell),maxNumResults); - frsObj.withinConfInt = zeros(length(fitResultsCell),maxNumResults); - for i=1:length(fitResultsCell) - frsObj.neuronNumbers(i) = fitResultsCell{i}.neuronNumber; - frsObj.dev(i,1:length(fitResultsCell{i}.dev)) = fitResultsCell{i}.dev(1:end); - frsObj.AIC(i,1:length(fitResultsCell{i}.AIC)) = fitResultsCell{i}.AIC(1:end); - frsObj.BIC(i,1:length(fitResultsCell{i}.BIC)) = fitResultsCell{i}.BIC(1:end); - frsObj.logLL(i,1:length(fitResultsCell{i}.logLL)) = fitResultsCell{i}.logLL(1:end); - frsObj.covLabels{i} = fitResultsCell{i}.uniqueCovLabels; - %flatMask(:,:,i) = fitResultsCell{i}.flatMask; - frsObj.fitResCell{i} = fitResultsCell{i}; - frsObj.KSStats(i,1:length(fitResultsCell{i}.KSStats.ks_stat)) = fitResultsCell{i}.KSStats.ks_stat(1:end); - frsObj.KSPvalues(i,1:length(fitResultsCell{i}.KSStats.pValue)) = fitResultsCell{i}.KSStats.pValue(1:end); - frsObj.withinConfInt(i,1:length(fitResultsCell{i}.KSStats.withinConfInt)) = fitResultsCell{i}.KSStats.withinConfInt(1:end); - end - frsObj.numResults = maxNumResults;%fitResultsCell{1}.numResults; - frsObj.numNeurons = length(frsObj.neuronNumbers); - frsObj.uniqueCovLabels = getUniqueLabels(frsObj.covLabels); - frsObj.mapCovLabelsToUniqueLabels; - %indActCoeffs = find( sum(squeeze(sum(frsObj.flatMask,2)),2)>0); - bAct=nan(length(frsObj.uniqueCovLabels),frsObj.numResults,frsObj.numNeurons); - seAct=nan(length(frsObj.uniqueCovLabels),frsObj.numResults,frsObj.numNeurons); - sigIndex=zeros(length(frsObj.uniqueCovLabels),frsObj.numResults,frsObj.numNeurons); - for n=1:frsObj.numNeurons - for j=1:frsObj.numResults - index=frsObj.indicesToUniqueLabels{j,n}; - if(j<=size(fitResultsCell{n}.flatMask,2)) - % origIndex = find(fitResultsCell{n}.flatMask(:,j)); - origIndex = fitResultsCell{n}.indicesToUniqueLabels{j}; - bAct(index,j,n) = fitResultsCell{n}.getPlotParams.bAct(origIndex,j); - seAct(index,j,n) = fitResultsCell{n}.getPlotParams.seAct(origIndex,j); - sigIndex(index,j,n) = fitResultsCell{n}.getPlotParams.sigIndex(origIndex,j); - end - end - end - frsObj.bAct = bAct; - frsObj.seAct= seAct; - frsObj.sigIndex=sigIndex; - - - frsObj.numResultsCoeffPresent = (sum(sum(frsObj.flatMask,3),2)); - frsObj.numCoeffs = length(frsObj.uniqueCovLabels); - frsObj.coeffRange = []; - frsObj.fitNames= fitResultsCell{maxNumIndex}.configNames; - - frsObj.plotParams.bAct = bAct;%(sum(sum(sigIndex,3),2)>0,:,:); - frsObj.plotParams.seAct = seAct;%(sum(sum(sigIndex,3),2)>0,:,:); - frsObj.plotParams.sigIndex = sigIndex;%(sum(sum(sigIndex,3),2)>0,:,:); - frsObj.plotParams.xLabels = frsObj.uniqueCovLabels;%(sum(sum(sigIndex,3),2)>0); - frsObj.plotParams.numResultsCoeffPresent = frsObj.numResultsCoeffPresent;%(sum(sum(sigIndex,3),2)>0); - - % frsObj.plotParams.bAct = bAct(sum(sum(sigIndex,3),2)>0,:,:); - % frsObj.plotParams.seAct = seAct(sum(sum(sigIndex,3),2)>0,:,:); - % frsObj.plotParams.sigIndex = sigIndex(sum(sum(sigIndex,3),2)>0,:,:); - % frsObj.plotParams.xLabels = frsObj.uniqueCovLabels(sum(sum(sigIndex,3),2)>0); - % frsObj.plotParams.numResultsCoeffPresent = frsObj.numResultsCoeffPresent(sum(sum(sigIndex,3),2)>0); - % - end - end - end - - %% Utility Functions - function mapCovLabelsToUniqueLabels(frsObj) - % mapCovLabelsToUniqueLabels(frsObj) - % from all the covariate labels across all neurons and all - % fits, finds a minimal list of covariate labels to be used in - % summarizing the data. - flatMask = zeros(length(frsObj.uniqueCovLabels),frsObj.numResults,frsObj.numNeurons); - for n=1:frsObj.numNeurons - currFitResult = frsObj.fitResCell{n}; - for j=1:currFitResult.numResults - currLabels = currFitResult.covLabels{j}; - index=zeros(1,length(currLabels)); - for i=1:length(currLabels) - idx = find(strcmp(currLabels{i}, frsObj.uniqueCovLabels),1,'first'); - if(isempty(idx)) - error('FitResSummary:UnknownCovariateLabel',... - 'Unable to map covariate label "%s" to unique labels.',currLabels{i}); - end - index(i)=idx; - end - - frsObj.indicesToUniqueLabels{j,n} = index; - flatMask(index,j,n) = 1; - end - end - frsObj.flatMask = flatMask; - end - - function [dAIC, handle] = getDiffAIC(frsObj,diffIndex,makePlot,h) - % [dAIC, handle] = getDiffAIC(frsObj,diffIndex,makePlot,h) - % Takes the AIC matrix and returns a matrix with N-1 columns - % containing the difference between all columns of the original - % matrix minus the column indicated by diffIndex. The zero - % column corresponding to diffIndex is removed from the orginal - % AIC matrix - if(nargin<4) - h=gca; - end - if(nargin<3 || isempty(makePlot)) - makePlot=1; - end - if(nargin<2 || isempty(diffIndex)) - diffIndex = 1; - end - if(frsObj.numResults>1) - dAIC=computeDiffMat(frsObj.AIC,diffIndex); - else - dAIC=frsObj.AIC; - end - if(makePlot) - handle=frsObj.boxPlot(dAIC,diffIndex,h); - end - end - function [dBIC, handle] = getDiffBIC(frsObj,diffIndex,makePlot,h) - % [dBIC, handle] = getDiffBIC(frsObj,diffIndex,makePlot,h) - % Takes the BIC matrix and returns a matrix with N-1 columns - % containing the difference between all columns of the original - % matrix minus the column indicated by diffIndex. The zero - % column corresponding to diffIndex is removed from the orginal - % BIC matrix - if(nargin<4) - h=gca; - end - if(nargin<3 || isempty(makePlot)) - makePlot=1; - end - if(nargin<2 || isempty(diffIndex)) - diffIndex = 1; - end - if(frsObj.numResults>1) - dBIC=computeDiffMat(frsObj.BIC,diffIndex); - else - dBIC=frsObj.BIC; - end - if(makePlot==1) - handle=frsObj.boxPlot(dBIC,diffIndex,h); - end - - end - - function [dlogLL, handle] = getDifflogLL(frsObj,diffIndex,makePlot,h) - % [dlogLL, handle] = getDifflogLL(frsObj,diffIndex,makePlot,h) - % Takes the logLL matrix and returns a matrix with N-1 columns - % containing the difference between all columns of the original - % matrix minus the column indicated by diffIndex. The zero - % column corresponding to diffIndex is removed from the orginal - % dlogLL matrix - if(nargin<4) - h=gca; - end - if(nargin<3 || isempty(makePlot)) - makePlot=1; - end - if(nargin<2 || isempty(diffIndex)) - diffIndex = 1; - end - if(frsObj.numResults>1) - dlogLL=computeDiffMat(frsObj.logLL,diffIndex); - else - dlogLL=frsObj.logLL; - end - if(makePlot==1) - handle=frsObj.boxPlot(dlogLL,diffIndex,h); - end - - end - - function [N,edges,percentSig] = binCoeffs(frsObj,minVal,maxVal,binSize) - % [N,edges,percentSig] = binCoeffs(frsObj,minVal,maxVal,binSize) - % Does a histogram of the regression coefficients across all - % fits. Also returns an indicator of the percentage of times - % that a coefficient was significantly different than zero out - % of all the times that it was used in a regression. - if(nargin<4) - binSize=.1; - end - if(nargin<3) - if(isempty(frsObj.coeffRange)) - %v=axis; - maxVal=12;%v(4); - frsObj.coeffRange.maxVal = maxVal; - else - %if(exists(frsObj.coeffRange.maxVal)) - maxVal=frsObj.coeffRange.maxVal; - %else - %maxVal = 12; - %end - end - - end - if(nargin<2) - if(isempty(frsObj.coeffRange)) - % v=axis; - minVal=-12;%v(3); - frsObj.coeffRange.minVal = minVal; - else - %if(exists(frsObj.coeffRange.maxVal)) - minVal=frsObj.coeffRange.minVal; - %else - % minVal=-12; - %end - end - - end - - edges=(minVal:binSize:maxVal)'; - sigVals = frsObj.plotParams.bAct;%frsObj.plotParams.sigIndex; - numPlotCoeffs = length(frsObj.plotParams.xLabels); - numSig = zeros(1,numPlotCoeffs); - percentSig=zeros(1,numPlotCoeffs); - sigValArray=[]; - sigGroup=[]; - for i=1:numPlotCoeffs %num coefficients - tempsigVals = squeeze(sigVals(i,:,:)); - tempsigVals = tempsigVals(squeeze(frsObj.plotParams.sigIndex(i,:,:))==1); - %sigValArray = [sigValArray;tempsigVals]; - sigGroup = [sigGroup; repmat(i,[length(tempsigVals),1])]; - Ntemp=histc(tempsigVals,edges); - numSig(i) = sum(Ntemp); - [nr,nc] = size(squeeze(sigVals(i,:,:))); %for this coefficient across all fits - %percentSig(i) = numSig(i)./(nr*nc)*frsObj.numResults./frsObj.plotParams.numResultsCoeffPresent(i); - percentSig(i) = numSig(i)./frsObj.plotParams.numResultsCoeffPresent(i); - N(:,i)=Ntemp./numSig(i); %normalize to 1 (pdf) - end - - end - function setCoeffRange(frsObj,minVal,maxVal) - % setCoeffRange(frsObj,minVal,maxVal) - % Sets the minimum and maximum value for the coeffRange. - frsObj.coeffRange.minVal=max(-100,minVal); - frsObj.coeffRange.maxVal=min(100,maxVal); - end - function sigValMat = getSigCoeffs(frsObj,fitNum) - % sigValMat = getSigCoeffs(frsObj,fitNum) - % if a fitNum is specified, a 2-d matrix (number of rows = - % number of GLM coefficients for that fit, number of columns = - % numer of neurons) - % Otherwise returns a 3-d matrix indicating the significant - % coefficients across all regression coefficient, fits, and - % neurons. - % nUnique params x num regressions x num neurons in size. - sigValMat = frsObj.plotParams.bAct.*frsObj.plotParams.sigIndex; - if(nargin==2 && fitNum>0 && fitNum1) - xticklabel_rotate([],90,[],'Fontsize',10);%rotateticklabel(gca,-90); - end - - end - function handle = plot3dCoeffSummary(frsObj,h) - % handle = plot3dCoeffSummary(frsObj,h) - % x-axis (covariate labels) - % y-axis (coefficient values) - % z-axis (histogram of coefficient values) - if(nargin<2) - h=gca; - end - frsObj.plotAllCoeffs(h); - [N,edges] = frsObj.binCoeffs; - numPlotCoeffs = length(frsObj.plotParams.xLabels); - handle=ribbon(repmat(edges,[1 numPlotCoeffs]),N); - set(handle,'edgecolor','none'); - alpha(.6); - legend off; - view(gca,[71.5 28]); - set(gca,'Box','off', 'Projection','perspective','Color',[0.831372549019608 0.815686274509804 0.784313725490196]); - grid on; axis tight; - end - function handle = plot2dCoeffSummary(frsObj,h) - % handle = plot2dCoeffSummary(frsObj,h) - % histogram of regression coefficients for each unique - % covariate. - if(nargin<2) - h=gca; - end - [N,edges,percentSig] = frsObj.binCoeffs; - offset=0; - numPlotCoeffs = length(frsObj.plotParams.xLabels); - for i=1:numPlotCoeffs - offset=offset+1; - handle(i)=plot(h,edges,N(:,i)+offset); hold on; -% plot(edges,N(:,i)+offset,'.'); - set(gca,'xtick',[],'ytick',[]); - end - % Reset the bottom subplot to have xticks - set(gca,'xtickMode', 'auto'); - set(gca,'ytick',1:length(frsObj.plotParams.xLabels),'ytickLabel',frsObj.plotParams.xLabels,'FontSize',6); - - offset=0; - for i=1:numPlotCoeffs - offset=offset+1; - text(frsObj.coeffRange.maxVal,offset,strcat(num2str(percentSig(i)*100,'%2.f'),'%_{sig}'),'FontSize',6); hold on; - end - - end - function handle = plotKSSummary(frsObj,neurons) - % handle = plotKSSummary(frsObj,neurons) - % For all of the distinct neurons in the the FitResSummary, - % plots the corresponding KS plot with all the differentt fits - % available for each neuron. Each neuron may have different numbers - % of model fits: eg. Neuron j may have 3 fits while - % neuron i may have 6. - if(nargin<2||isempty(neurons)) - neurons = 1:frsObj.numNeurons; - end - if(max(neurons)>frsObj.numNeurons) - error('Indices must be <= numNeurons'); - end - - handle = figure; - numToPlot=length(neurons); - cnt=0; - for i=neurons - cnt=cnt+1; - if(numToPlot==1) - %dont subplot - elseif(numToPlot<=2) - subplot(1,2,cnt); - elseif(numToPlot<=4) - subplot(2,2,cnt) - elseif(numToPlot<=8) - subplot(2,4,cnt) - elseif(numToPlot<=12) - subplot(3,4,cnt) - elseif(numToPlot<=16) - subplot(4,4,cnt) - elseif(numToPlot<=20) - subplot(5,4,cnt) - elseif(numToPlot<=24) - subplot(6,4,cnt) - elseif(numToPlot<=40) - subplot(10,4,cnt) - else - subplot(10,10,cnt) - end - frsObj.fitResCell{i}.KSPlot; - if(i~=neurons(end)) - legend off; ylabel(''); xlabel(''); title(''); - else - h= legend; set(h,'Location','Best'); ylabel(''); xlabel(''); title(''); - end - text(.4,.9,['N' num2str(i)]); - set(gca,'xtick',[0 1],'ytick',[0 1]) - end - - end - function handle = plotAIC(frsObj) - % handle = plotAIC(frsObj) - % Plot mean +/- 1 standard error from the mean for the AIC for - % each fit. - AICdata=frsObj.AIC; - mData=mean(AICdata,1,'omitnan'); - numNeurons = size(AICdata,1); - sData=std(AICdata,0,1,'omitnan')./sqrt(numNeurons); - ciUp = mData+sData; - ciDown = mData-sData; - - x=1:frsObj.numResults; - plot(x,mData,'r','Linewidth',3); hold on; - faceColor='r'; - p=patch([x, fliplr(x)],[ciUp fliplr(ciDown)],faceColor); - set(p,'facecolor',faceColor,'edgecolor','none'); - alpha(.5); -% set(gca,'xticklabelmode','auto','xtickmode','auto'); - set(gca,'xtick',x,'xticklabel',frsObj.fitNames); - if(length(x)>1) - xticklabel_rotate([],90,[],'Fontsize',8);%rotateticklabel(gca,-90); - end - - end - - function handle = plotBIC(frsObj) - % handle = plotBIC(frsObj) - % Plot mean +/- 1 standard error from the mean for the BIC for - % each fit. - BICdata=frsObj.BIC; - mData=mean(BICdata,1,'omitnan'); - numNeurons = size(BICdata,1); - sData=std(BICdata,0,1,'omitnan')./sqrt(numNeurons); - ciUp = mData+sData; - ciDown = mData-sData; - - x=1:frsObj.numResults; - plot(x,mData,'r','Linewidth',3); hold on; - faceColor='r'; - p=patch([x, fliplr(x)],[ciUp fliplr(ciDown)],faceColor); - set(p,'facecolor',faceColor,'edgecolor','none'); - alpha(.5); -% set(gca,'xticklabelmode','auto','xtickmode','auto'); - set(gca,'xtick',x,'xticklabel',frsObj.fitNames); - if(length(x)>1) - xticklabel_rotate([],90,[],'Fontsize',8);%rotateticklabel(gca,-90); - end - end - - function handle = plotlogLL(frsObj) - % handle = plotlogLL(frsObj) - % Plot mean +/- 1 standard error from the mean for the logLL for - % each fit. - logLLdata=frsObj.logLL; - mData=mean(logLLdata,1,'omitnan'); - numNeurons = size(logLLdata,1); - sData=std(logLLdata,0,1,'omitnan')./sqrt(numNeurons); - ciUp = mData+sData; - ciDown = mData-sData; - - x=1:frsObj.numResults; - plot(x,mData,'r','Linewidth',3); hold on; - faceColor='r'; - p=patch([x, fliplr(x)],[ciUp fliplr(ciDown)],faceColor); - set(p,'facecolor',faceColor,'edgecolor','none'); - alpha(.5); -% set(gca,'xticklabelmode','auto','xtickmode','auto'); - set(gca,'xtick',x,'xticklabel',frsObj.fitNames); - if(length(x)>1) - xticklabel_rotate([],90,[],'Fontsize',8);%rotateticklabel(gca,-90); - end - end - - function handle = plotResidualSummary(frsObj) - handle = figure; - for i=1:frsObj.numNeurons - if(frsObj.numNeurons<=4) - subplot(2,2,i) - elseif(frsObj.numNeurons<=8) - subplot(2,4,i) - elseif(frsObj.numNeurons<=12) - subplot(3,4,i) - elseif(frsObj.numNeurons<=16) - subplot(4,4,i) - elseif(frsObj.numNeurons<=20) - subplot(5,4,i) - elseif(frsObj.numNeurons<=24) - subplot(6,4,i) - elseif(frsObj.numNeurons<=40) - subplot(10,4,i) - else - subplot(10,10,i) - end - frsObj.fitResCell{i}.plotResidual; - if(i~=frsObj.numNeurons) - legend off; ylabel(''); xlabel(''); title(''); - else - h= legend; set(h,'Location','BestOutside'); ylabel(''); xlabel(''); title(''); - end - end - end - - function handle = plotSummary(frsObj) - % handle = plotSummary(frsObj) - % - scrsz = get(0,'ScreenSize'); - handle=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.9 scrsz(4)*.9]); - h1=subplot(2,4,[1 2 5 6]);frsObj.plotAllCoeffs(h1); grid off; - title({'GLM Coefficients Across Neurons';'with 95% CIs (* p<0.05)'},'FontWeight','bold','FontSize',11,'FontName','Arial'); - - %subplot(2,4,[2 3]);frsObj.plot3dCoeffSummary; %rotateticklabel(get(gca,'ytickLabels'),0); - subplot(2,4,[3 4]); boxplot(frsObj.KSStats,frsObj.fitNames,'labelorientation','inline'); - ylabel('KS Statistics'); - hx=get(gca,'XLabel'); hy=get(gca,'YLabel'); - set([hx hy],'FontName', 'Arial','FontSize',11,'FontWeight','bold'); - title('KS Statistics Across Neurons','FontWeight','bold','FontSize',11,'FontName','Arial'); -% subplot(2,4,[6 7]);frsObj.plot2dCoeffSummary; %rotateticklabel(get(gca,'ytickLabels'),0); - - subplot(2,4,7); frsObj.getDiffAIC(1); - ylabel('\Delta AIC'); %xticklabel_rotate([],45,[],'Fontsize',6); - hx=get(gca,'XLabel'); hy=get(gca,'YLabel'); - set([hx hy],'FontName', 'Arial','FontSize',11,'FontWeight','bold'); - title('Change in AIC Across Neurons','FontWeight','bold','FontSize',11,'FontName','Arial'); - set(gca,'XTickLabelRotation',90); - - subplot(2,4,8); frsObj.getDiffBIC(1); - ylabel('\Delta BIC'); %xticklabel_rotate([],45,[],'Fontsize',6); - hx=get(gca,'XLabel'); hy=get(gca,'YLabel'); - set([hx hy],'FontName', 'Arial','FontSize',11,'FontWeight','bold'); - title('Change in BIC Across Neurons','FontWeight','bold','FontSize',11,'FontName','Arial'); - set(gca,'XTickLabelRotation',90); - end - function handle = boxPlot(frsObj,X,diffIndex,h,dataLabels,varargin) - if(nargin<3) - h=gca; - end - if(nargin<5 || isempty(dataLabels)) - [~,columns] = size(X); - tempIndex = 1:frsObj.numResults; - actIndex = find(tempIndex~=diffIndex); - - if(~isempty(actIndex)) - for i=1:columns - if(length(actIndex)==columns) - dataLabels{i} = [frsObj.fitNames{actIndex(i)} ' - ' frsObj.fitNames{diffIndex}]; - end - end - else - dataLabels{1}=frsObj.fitNames{diffIndex}; %only put the name of the fit since no other fits - end - - - if(columns>1) - handle = boxplot(X,strvcat(dataLabels)); - else - handle = boxplot(X,dataLabels); % when only one column - end - - - % set(gca,'xticklabelmode','auto','xtickmode','auto'); - % set(gca,'xtick',1:length(dataLabels),'xticklabel',dataLabels); - % hT=rotateticklabel(gca,90); - % FitResSummary.xticklabel_rotate([],45,[],'interpreter','none'); - elseif(nargin>5) - handle = boxplot(h,X,strvcat(dataLabels),varargin{:}); - elseif(nargin==5) - handle = boxplot(h,X,strvcat(dataLabels)); - end - h = get(get(gca,'child'),'child'); - group_name_handle = findobj(h,'type','text'); - group_name_handle = flipud(group_name_handle); %place in correct order - find obj returns backwards - v=axis; - vdiffy = v(4)-v(3); - vdiffx = v(2)-v(1); - for j=1:length(group_name_handle) - text(0,0,get(group_name_handle(j),'string'),'color','k','position',[j-.0*vdiffx v(3)-.02*vdiffy 0],'rotation',-90,'Fontsize',8); - end - delete(group_name_handle); - - end - - function structure = toStructure(frsObj) - fNames = fieldnames(frsObj); - for i=1:length(fNames) - currObj = frsObj.(fNames{i}); - if(isa(currObj,'double')||isa(currObj,'cell')) - if(strcmp(fNames{i},'fitResCell')) - structure.(fNames{i}) = FitResult.CellArrayToStructure(frsObj.(fNames{i})); - else - structure.(fNames{i}) = frsObj.(fNames{i}); - end - end - - end - - end - - function [coeffIndex, epochId,numEpochs] = getCoeffIndex(frsObj,fitNum,sortByEpoch) - if(nargin<3 || isempty(sortByEpoch)) - sortByEpoch=0; - end - if(nargin<2 || isempty(fitNum)) - fitNum = 1:frsObj.numResults; - end - if(isempty(frsObj.plotParams)) - frsObj.computePlotParams; - end - [histIndex, epochId] = frsObj.getHistIndex(fitNum,sortByEpoch); - allIndex = 1:length(frsObj.uniqueCovLabels); - - nonHistIndex = setdiff(allIndex,histIndex); - nonNANIndex = find(sum(~isnan(squeeze(frsObj.plotParams.bAct(:,fitNum,:))),2)>=1); - actCoeffIndex = nonHistIndex(ismember(nonHistIndex, nonNANIndex)); - allCoeffTerms = frsObj.uniqueCovLabels(actCoeffIndex); - epochStartInd=regexp(allCoeffTerms,'_\{\d*\}','start'); - epochEndInd=regexp(allCoeffTerms,'_\{\d*\}','end'); - - allCoeffIndex = []; - epochsExist =0; - nonEpochIndex=[]; - for i=1:length(allCoeffTerms) - if(~isempty(allCoeffTerms{i})) - allCoeffIndex = [allCoeffIndex i]; - if(~isempty(epochStartInd{i})) - epochsExist=1; - actStart = epochStartInd{i}+2; - actEnd = epochEndInd{i}-1; - numEpoch(i) = str2num(allCoeffTerms{i}(actStart:actEnd)); - else - - nonEpochIndex = [nonEpochIndex i]; - numEpoch(i) = 0; % make terms that only appear once part of epoch 0. - - end - end - - end - - - if(epochsExist && ~sortByEpoch) - totalEpochs = unique(numEpoch); - coeffIndex = []; - if(nargout>1) - epochId=[]; - end - for i=1:length(totalEpochs) - coeffIndex = [coeffIndex, find(numEpoch==totalEpochs(i))]; - if(nargout>1) - epochId = [epochId, totalEpochs(i)*ones(size(find(numEpoch==totalEpochs(i))))]; - end - end - coeffIndex = actCoeffIndex(coeffIndex); - elseif(epochsExist && sortByEpoch) - coeffIndex = actCoeffIndex(allCoeffIndex); - if(nargout>1) - epochId = numEpoch; - end - else - coeffIndex = actCoeffIndex(allCoeffIndex); - if(nargout>1) - epochId = zeros(size(allCoeffIndex)); %no epochs exist so just create same index for all; - end - end - - -% nonNANIndex = find(sum(~isnan(frsObj.plotParams.bAct(:,fitNum)),2)>=1); -% coeffIndex = coeffIndex(ismember(coeffIndex, nonNANIndex)); -% - if(nargout>2) - numEpochs = length(unique(epochId)); - end - - end - - function h=plotCoeffsWithoutHistory(frsObj,fitNum,sortByEpoch,plotSignificance) - if(nargin<4 || isempty(plotSignificance)) - plotSignificance=1; - end - if(nargin<3 || isempty(sortByEpoch)) - sortByEpoch = 0; - end - if(nargin<2 || isempty(fitNum)) - fitNum = 1:frsObj.numResults; - end - if(isempty(frsObj.plotParams)) - frsObj.computePlotParams; - end - - - coeffIndex = frsObj.getCoeffIndex(fitNum,sortByEpoch); - h=frsObj.plotAllCoeffs([],fitNum,[],plotSignificance,coeffIndex); - - - - end - - function [histIndex, epochId,numEpochs] = getHistIndex(frsObj,fitNum,sortByEpoch) - %if sortByEpoch==1 then we group all regression terms with the - %same name one next to each other by epoch (time interval). - %Otherwise, we show all epoch one terms, followed by all epoch - %2 terms, etc. - if(nargin<3 || isempty(sortByEpoch)) - sortByEpoch = 0; - end - if(nargin<2 || isempty(fitNum)) - fitNum = 1:frsObj.numResults; - end - if(isempty(frsObj.plotParams)) - frsObj.computePlotParams; - end - - - allHistTerms = regexp(frsObj.uniqueCovLabels,'^[\w*'); - epochStartInd=regexp(frsObj.uniqueCovLabels,'\]_\{\d*\}','start'); - epochEndInd=regexp(frsObj.uniqueCovLabels,'\]_\{\d*\}','end'); - allHistIndex = []; - epochsExist =0; - for i=1:length(allHistTerms) - if(~isempty(allHistTerms{i})) - allHistIndex = [allHistIndex i]; - if(~isempty(epochStartInd{i})) - epochsExist=1; - actStart = epochStartInd{i}+3; - actEnd = epochEndInd{i}-1; - numEpoch(i) = str2num(frsObj.uniqueCovLabels{i}(actStart:actEnd)); - end - end - - end - - if(epochsExist && ~sortByEpoch) - totalEpochs = unique(numEpoch); - histIndex = []; - if(nargout>1) - epochId=[]; - end - for i=1:length(totalEpochs) - histIndex = [histIndex, find(numEpoch==totalEpochs(i))]; - if(nargout>1) - epochId = [epochId, totalEpochs(i)*ones(size(find(numEpoch==totalEpochs(i))))]; - end - end - elseif(epochsExist && sortByEpoch) - histIndex = allHistIndex; - if(nargout>1) - epochId = numEpoch; - end - else - histIndex = allHistIndex; - if(nargout>1) - epochId = zeros(size(allHistIndex)); %no epochs exist so just create same index for all; - end - end - - - nonNANIndex = find(sum(~isnan(frsObj.plotParams.bAct(:,fitNum)),2)>=1); - histIndex = histIndex(ismember(histIndex, nonNANIndex)); - - if(nargout>2) - numEpochs = length(unique(epochId)); - end - - end - function [coeffMat, labels, seMat] = getCoeffs(frsObj, fitNum) - if(nargin<2 || isempty(fitNum)) - fitNum =1:frsObj.numResults; - end - sortByEpoch = 0; % Make sure we have different time series if the history is divided into epochs; - [coeffIndex, epochId, numEpochs] = frsObj.getCoeffIndex(fitNum,sortByEpoch); - epochNums = unique(epochId); - - - coeffStrings = frsObj.uniqueCovLabels(coeffIndex); - baseStringEndIndex =regexp(coeffStrings,'_\{\d*\}','start'); - for i=1:length(baseStringEndIndex) - if(~isempty(baseStringEndIndex{i})) - baseStrings{i} = coeffStrings{i}(1:baseStringEndIndex{i}-1); - else - baseStrings{i} = coeffStrings{i}; - end - end - uniqueCoeffs = unique(baseStrings); - - for i=1:length(uniqueCoeffs) - coeffStrIndex{i} = coeffIndex(strcmp(baseStrings,uniqueCoeffs{i})); - if(min(epochId)==0) - epochIndices{i} = epochId(strcmp(baseStrings,uniqueCoeffs{i}))+1; - else - epochIndices{i} = epochId(strcmp(baseStrings,uniqueCoeffs{i})); - end - end - -% -% for i=1:numEpochs -% epochIndices{i} = find(epochId==epochNums(i)); -% epochLength(i) = length(epochIndices{i}); -% end - - - - coeffIndMat= nan(length(uniqueCoeffs),numEpochs); - labels = cell(size(coeffIndMat)); - for i=1:length(uniqueCoeffs) - coeffIndMat(i,epochIndices{i}) = coeffStrIndex{i}; - labels(i,epochIndices{i}) = frsObj.uniqueCovLabels(coeffStrIndex{i}); - end - - -% for i=1:numEpochs -% coeffIndMat(1:epochLength(i),i) = coeffIndex(epochIndices{i}); -% labels(1:epochLength(i),i) = frsObj.uniqueCovLabels(coeffIndMat(1:epochLength(i),i)); -% end - - - - if(length(fitNum)>1) - coeffMat=cell(1,length(fitNum)); - seMat=cell(1,length(fitNum)); - for i=1:length(fitNum) - coeffMat{i} = nan(size(coeffIndMat,1),size(coeffIndMat,2), frsObj.numNeurons); - seMat{i} = nan(size(coeffIndMat,1),size(coeffIndMat,2), frsObj.numNeurons); - for j=1:length(uniqueCoeffs) - bTemp=squeeze(frsObj.plotParams.bAct(coeffStrIndex{j},i,:)); - seTemp=squeeze(frsObj.plotParams.seAct(coeffStrIndex{j},i,:)); - for k=1:frsObj.numNeurons - if(size(epochIndices,2)==1) - if(size(bTemp,2)==1) - coeffMat(j,epochIndices{1},k) = bTemp(k); - seMat(j,epochIndices{1},k) = seTemp(k); - else - coeffMat(j,epochIndices{1},k) = bTemp(:,k); - seMat(j,epochIndices{1},k) = seTemp(:,k); - end - else - if(size(bTemp,2)==1) - coeffMat{i}(j,epochIndices{j},k) = bTemp(k); - seMat{i}(j,epochIndices{j},k) = seTemp(k); - else - coeffMat{i}(j,epochIndices{j},k) = bTemp(:,k); - seMat{i}(j,epochIndices{j},k) = seTemp(:,k); - end - end - end - end - end - else - coeffMat = nan(size(coeffIndMat,1),size(coeffIndMat,2),frsObj.numNeurons); - seMat = nan(size(coeffIndMat,1),size(coeffIndMat,2),frsObj.numNeurons); - for j=1:length(uniqueCoeffs) - bTemp=squeeze(frsObj.plotParams.bAct(coeffStrIndex{j},fitNum,:)); - seTemp=squeeze(frsObj.plotParams.seAct(coeffStrIndex{j},fitNum,:)); - for k=1:frsObj.numNeurons - if(size(epochIndices,2)==1) - if(size(bTemp,2)==1) - if(numel(bTemp)==numel(epochIndices{1}) && frsObj.numNeurons==1) - coeffMat(j,epochIndices{1},k) = bTemp(:); - seMat(j,epochIndices{1},k) = seTemp(:); - else - coeffMat(j,epochIndices{1},k) = bTemp(k); - seMat(j,epochIndices{1},k) = seTemp(k); - end - else - coeffMat(j,epochIndices{1},k) = bTemp(:,k); - seMat(j,epochIndices{1},k) = seTemp(:,k); - end - else - if(size(bTemp,2)==1) - if(numel(bTemp)==numel(epochIndices{j}) && frsObj.numNeurons==1) - coeffMat(j,epochIndices{j},k) = bTemp(:); - seMat(j,epochIndices{j},k) = seTemp(:); - else - coeffMat(j,epochIndices{j},k) = bTemp(k); - seMat(j,epochIndices{j},k) = seTemp(k); - end - - else - coeffMat(j,epochIndices{j},k) = bTemp(:,k); - seMat(j,epochIndices{j},k) = seTemp(:,k); - end - end - end - end - - end - if(frsObj.numNeurons==1) - coeffMat=coeffMat'; - seMat=seMat'; - end - end - - function [histMat, labels] = getHistCoeffs(frsObj,fitNum) - if(nargin<2 || isempty(fitNum)) - fitNum =1:frsObj.numResults; - end - sortByEpoch = 0; % Make sure we have different time series if the history is divided into epochs; - [histIndex, epochId, numEpochs] = frsObj.getHistIndex(fitNum,sortByEpoch); - epochNums = unique(epochId); - - - histcoeffStrings = frsObj.uniqueCovLabels(histIndex); - baseStringEndIndex =regexp(histcoeffStrings,'_\{\d\}','start'); - for i=1:length(baseStringEndIndex) - if(~isempty(baseStringEndIndex{i})) - baseStrings{i} = histcoeffStrings{i}(1:baseStringEndIndex{i}-1); - else - baseStrings{i} = histcoeffStrings{i}; - end - end - uniqueCoeffs = unique(baseStrings); - - for i=1:length(uniqueCoeffs) - histcoeffStrIndex{i} = histIndex(strcmp(baseStrings,uniqueCoeffs{i})); - if(min(epochId)==0) - epochIndices{i} = epochId(strcmp(baseStrings,uniqueCoeffs{i}))+1; - else - epochIndices{i} = epochId(strcmp(baseStrings,uniqueCoeffs{i})); - end - end - -% -% for i=1:numEpochs -% epochIndices{i} = find(epochId==epochNums(i)); -% epochLength(i) = length(epochIndices{i}); -% end - - - - histcoeffIndMat= nan(length(uniqueCoeffs),numEpochs); - labels = cell(size(histcoeffIndMat)); - for i=1:length(uniqueCoeffs) - histcoeffIndMat(i,epochIndices{i}) = histcoeffStrIndex{i}; - labels(i,epochIndices{i}) = frsObj.uniqueCovLabels(histcoeffStrIndex{i}); - end - - -% for i=1:numEpochs -% coeffIndMat(1:epochLength(i),i) = coeffIndex(epochIndices{i}); -% labels(1:epochLength(i),i) = frsObj.uniqueCovLabels(coeffIndMat(1:epochLength(i),i)); -% end - - - - if(length(fitNum)>1) -% histMat = nan(size(histcoeffIndMat,1),size(histcoeffIndMat,2), length(fitNum)); - histMat = cell(1, length(fitNum)); - for i=fitNum - histMat{i} = nan(size(histcoeffIndMat,1),size(histcoeffIndMat,2), frsObj.numNeurons); - for j=1:length(uniqueCoeffs) - bTemp=squeeze(frsObj.plotParams.bAct(histcoeffStrIndex{j},i,:)); - for k=1:frsObj.numNeurons - histMat{i}(j,epochIndices{j},k) = bTemp(k,:); - end - end - end - else - histMat = nan(size(histcoeffIndMat,1),size(histcoeffIndMat,2),frsObj.numNeurons); - - for j=1:length(uniqueCoeffs) - bTemp=squeeze(frsObj.plotParams.bAct(histcoeffStrIndex{j},fitNum,:)); - for k=1:frsObj.numNeurons - histMat(j,epochIndices{j},k) = bTemp(k,:); - end - end - - end - - - - - end - function h=plotHistCoeffs(frsObj,fitNum,sortByEpoch,plotSignificance) - if(nargin<4 || isempty(plotSignificance)) - plotSignificance=1; - end - if(nargin<3 || isempty(sortByEpoch)) - sortByEpoch=0; - end - if(nargin<2 || isempty(fitNum)) - fitNum = 1:frsObj.numResults; - end - if(isempty(frsObj.plotParams)) - frsObj.computePlotParams; - end - histIndex = frsObj.getHistIndex(fitNum,sortByEpoch); - h=frsObj.plotAllCoeffs([],fitNum,[],plotSignificance,histIndex); - end - - - - - end - - methods (Static) - function frsObj = fromStructure(structure) - resultsCell = FitResult.fromStructure(structure.fitResCell); - frsObj = FitResSummary(resultsCell); - end - - end - -end - -%% Helper Functions -function dMat = computeDiffMat(MAT,diffIndex) - - columns = size(MAT,2); - index = 1:columns; - dMat = MAT(:,index~=diffIndex) - MAT(:,diffIndex)*(ones(1,columns-length(diffIndex))); - -end -function [uniqueLabels, indexIntoOriginal, restoreIndex] = getUniqueLabels(covLabels) - offset = 0; - for i=1:length(covLabels) - currLabels = covLabels{i}; - allLabels((1:length(currLabels))+offset) = currLabels; - offset=length(allLabels); - end - [uniqueLabels, indexIntoOriginal, restoreIndex] = unique(allLabels); -end -function hText = xticklabel_rotate(XTick,rot,varargin) - %hText = xticklabel_rotate(XTick,rot,XTickLabel,varargin) Rotate XTickLabel - % - % Syntax: xticklabel_rotate - % - % Input: - % {opt} XTick - vector array of XTick positions & values (numeric) - % uses current XTick values or XTickLabel cell array by - % default (if empty) - % {opt} rot - angle of rotation in degrees, 90° by default - % {opt} XTickLabel - cell array of label strings - % {opt} [var] - "Property-value" pairs passed to text generator - % ex: 'interpreter','none' - % 'Color','m','Fontweight','bold' - % - % Output: hText - handle vector to text labels - % - % Example 1: Rotate existing XTickLabels at their current position by 90° - % xticklabel_rotate - % - % Example 2: Rotate existing XTickLabels at their current position by 45° and change - % font size - % xticklabel_rotate([],45,[],'Fontsize',14) - % - % Example 3: Set the positions of the XTicks and rotate them 90° - % figure; plot([1960:2004],randn(45,1)); xlim([1960 2004]); - % xticklabel_rotate([1960:2:2004]); - % - % Example 4: Use text labels at XTick positions rotated 45° without tex interpreter - % xticklabel_rotate(XTick,45,NameFields,'interpreter','none'); - % - % Example 5: Use text labels rotated 90° at current positions - % xticklabel_rotate([],90,NameFields); - % - % Note : you can not re-run xticklabel_rotate on the same graph. - % - % - - - % This is a modified version of xticklabel_rotate90 by Denis Gilbert - % Modifications include Text labels (in the form of cell array) - % Arbitrary angle rotation - % Output of text handles - % Resizing of axes and title/xlabel/ylabel positions to maintain same overall size - % and keep text on plot - % (handles small window resizing after, but not well due to proportional placement with - % fixed font size. To fix this would require a serious resize function) - % Uses current XTick by default - % Uses current XTickLabel is different from XTick values (meaning has been already defined) - - % Brian FG Katz - % bfgkatz@hotmail.com - % 23-05-03 - % Modified 03-11-06 after user comment - % Allow for exisiting XTickLabel cell array - - % Other m-files required: cell2mat - % Subfunctions: none - % MAT-files required: none - % - % See also: xticklabel_rotate90, TEXT, SET - - % Based on xticklabel_rotate90 - % Author: Denis Gilbert, Ph.D., physical oceanography - % Maurice Lamontagne Institute, Dept. of Fisheries and Oceans Canada - % email: gilbertd@dfo-mpo.gc.ca Web: http://www.qc.dfo-mpo.gc.ca/iml/ - % February 1998; Last revision: 24-Mar-2003 - - % check to see if xticklabel_rotate has already been here (no other reason for this to happen) - if isempty(get(gca,'XTickLabel')), - error('xticklabel_rotate : can not process, either xticklabel_rotate has already been run or XTickLabel field has been erased') ; - end - - % if no XTickLabel AND no XTick are defined use the current XTickLabel - %if nargin < 3 & (~exist('XTick') | isempty(XTick)), - if (nargin < 3 || isempty(varargin{1})) & (~exist('XTick') | isempty(XTick)), - xTickLabels = get(gca,'XTickLabel') ; % use current XTickLabel - if ~iscell(xTickLabels) - % remove trailing spaces if exist (typical with auto generated XTickLabel) - temp1 = num2cell(xTickLabels,2) ; - for loop = 1:length(temp1), - temp1{loop} = deblank(temp1{loop}) ; - end - xTickLabels = temp1 ; - end - varargin = varargin(2:length(varargin)); - end - - % if no XTick is defined use the current XTick - if (~exist('XTick') | isempty(XTick)), - XTick = get(gca,'XTick') ; % use current XTick - end - - %Make XTick a column vector - XTick = XTick(:); - - if ~exist('xTickLabels'), - % Define the xtickLabels - % If XtickLabel is passed as a cell array then use the text - if (length(varargin)>0) & (iscell(varargin{1})), - xTickLabels = varargin{1}; - varargin = varargin(2:length(varargin)); - else - xTickLabels = num2str(XTick); - end - end - - if length(XTick) ~= length(xTickLabels), - error('xticklabel_rotate : must have same number of elements in "XTick" and "XTickLabel"') ; - end - - %Set the Xtick locations and set XTicklabel to an empty string - set(gca,'XTick',XTick,'XTickLabel','') - - if nargin < 2, - rot = 90 ; - end - - % Determine the location of the labels based on the position - % of the xlabel - hxLabel = get(gca,'XLabel'); % Handle to xlabel - xLabelString = get(hxLabel,'String'); - - % if ~isempty(xLabelString) - % warning('You may need to manually reset the XLABEL vertical position') - % end - - set(hxLabel,'Units','data'); - xLabelPosition = get(hxLabel,'Position'); - y = xLabelPosition(2); - - %CODE below was modified following suggestions from Urs Schwarz - y=repmat(y,size(XTick,1),1); - % retrieve current axis' fontsize - fs = get(gca,'fontsize'); - - % Place the new xTickLabels by creating TEXT objects - hText = text(XTick, y, xTickLabels,'fontsize',fs); - - % Rotate the text objects by ROT degrees - set(hText,'Rotation',rot,'HorizontalAlignment','right',varargin{:}) - - % Adjust the size of the axis to accomodate for longest label (like if they are text ones) - % This approach keeps the top of the graph at the same place and tries to keep xlabel at the same place - % This approach keeps the right side of the graph at the same place - - set(get(gca,'xlabel'),'units','data') ; - labxorigpos_data = get(get(gca,'xlabel'),'position') ; - set(get(gca,'ylabel'),'units','data') ; - labyorigpos_data = get(get(gca,'ylabel'),'position') ; - set(get(gca,'title'),'units','data') ; - labtorigpos_data = get(get(gca,'title'),'position') ; - - set(gca,'units','pixel') ; - set(hText,'units','pixel') ; - set(get(gca,'xlabel'),'units','pixel') ; - set(get(gca,'ylabel'),'units','pixel') ; - - origpos = get(gca,'position') ; - textsizes = cell2mat(get(hText,'extent')) ; - longest = max(textsizes(:,4)) ; - - laborigext = get(get(gca,'xlabel'),'extent') ; - laborigpos = get(get(gca,'xlabel'),'position') ; - - - labyorigext = get(get(gca,'ylabel'),'extent') ; - labyorigpos = get(get(gca,'ylabel'),'position') ; - leftlabdist = labyorigpos(1) + labyorigext(1) ; - - % assume first entry is the farthest left - leftpos = get(hText(1),'position') ; - leftext = get(hText(1),'extent') ; - leftdist = leftpos(1) + leftext(1) ; - if leftdist > 0, leftdist = 0 ; end % only correct for off screen problems - - botdist = origpos(2) + laborigpos(2) ; - newpos = [origpos(1)-leftdist longest+botdist origpos(3)+leftdist origpos(4)-longest+origpos(2)-botdist] ; - set(gca,'position',newpos) ; - - % readjust position of nex labels after resize of plot - set(hText,'units','data') ; - for loop= 1:length(hText), - set(hText(loop),'position',[XTick(loop), y(loop)]) ; - end - - - % adjust position of xlabel and ylabel - laborigpos = get(get(gca,'xlabel'),'position') ; - set(get(gca,'xlabel'),'position',[laborigpos(1) laborigpos(2)-longest 0]) ; - - % switch to data coord and fix it all - set(get(gca,'ylabel'),'units','data') ; - set(get(gca,'ylabel'),'position',labyorigpos_data) ; - set(get(gca,'title'),'position',labtorigpos_data) ; - - set(get(gca,'xlabel'),'units','data') ; - labxorigpos_data_new = get(get(gca,'xlabel'),'position') ; - set(get(gca,'xlabel'),'position',[labxorigpos_data(1) labxorigpos_data_new(2)]) ; - - - % Reset all units to normalized to allow future resizing - set(get(gca,'xlabel'),'units','normalized') ; - set(get(gca,'ylabel'),'units','normalized') ; - set(get(gca,'title'),'units','normalized') ; - set(hText,'units','normalized') ; - set(gca,'units','normalized') ; - - if nargout < 1, - clear hText - end - -end - diff --git a/FitResult.m b/FitResult.m deleted file mode 100644 index b7e731c9..00000000 --- a/FitResult.m +++ /dev/null @@ -1,1747 +0,0 @@ -classdef FitResult < handle -% FITRESULT -% stores results of a fit using the Analysis object -% The results are for a single neuron over a range of configurations -% -% methods -% FitResult Examples -% -% see also Analysis -% -% Reference page in Help browser -% doc FitResult - - -% -% nSTAT v1 Copyright (C) 2012 Masschusetts Institute of Technology -% Cajigas, I, Malik, WQ, Brown, EN -% This program is free software; you can redistribute it and/or -% modify it under the terms of the GNU General Public License as published -% by the Free Software Foundation; either version 2 of the License, or -% (at your option) any later version. -% -% This program is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -% See the GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with this program; if not, write to the Free Software Foundation, -% Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - properties - numResults %Number of results in this FitResult object - lambda %Lambda signal - numCoeffs %Number of coefficients for each fitResult - fitType %Poisson or Binomial - - b %coefficients for each fit - - dev %deviance for each fit - AIC %Akaike's Information Criterion for each fit - BIC %Baysian Information Criterion for each fit - logLL %Log Likelihood - stats %Relevant statistics for each fit - configs % the config collection for the different fits - configNames % names of the the differen fits - neuronNumber % the number of the neuron the data comes from - neuralSpikeTrain % the spike data - covLabels - uniqueCovLabels - indicesToUniqueLabels - numHist % Number of history terms (used for indexing into the regression coefficients) for each fit - histObjects % History object for self firing - ensHistObjects % History object to be applied to the neuron's neigbors to compute ensemble effect - flatMask - Z % Rescaled spike times from the Time-Rescaling theorem, exponential rate 1 - U % Transformed z's -> uniform in [0,1] - X % Transformed u's -> gaussian in [-inf, inf] - Residual %fit residual -% xAxis -% KSSorted -% ks_stat - invGausStats - KSStats %Kolmogorov Smirnov Statistics - plotParams - XvalData % cell array of raw data used for validation - XvalTime % cell array of time vectors for each element of XvalData - validation % a FitResult object with the validation data - minTime % The minTime from the spikeTrain (not necessarily the analysis) - maxTime % The maxTime for the spikeTrain (not necessarily the analysis) - end - properties (Constant,Hidden) - colors={'b','g','r','c','m','y','k'}; - end - - - methods - - function fitObj=FitResult(spikeObj,covLabels,numHist,histObjects,ensHistObj,lambda,b, dev, stats,AIC,BIC,logLL, configColl,XvalData,XvalTime,distribution) - % fitObj=FitResult(spikeObj,covLabels,numHist,histObjects,ensHistObj,lambda,b, dev, stats,AIC,BIC,configColl,XvalData,XvalTime) - % Stores the results of multiple regressions for a single neuron into a accessible structure. - % - % spikeObj: The spike train for the neuron whose results are - % being stored. - % covLabels: A 2-d cell array, the jth row has all the labels for the covariates used in the jth fit - % numHist: The number of history terms in each of the N fits. - % histObjects: The History object for each of the N fits - % ensHistObj: The History object for used to compute the ensemble history effect. - % lambda: The conditional intensity function evaluated usin the - % data. Each dimension of lambda corresponds to the a different - % GLM Fit. - % b: N-component cell array containing the GLM regression - % coefficient of each of the fits. The jth component has all - % the regression coefficients for the jth trial. - % dev: vector of Deviances for each the GLM fits. - % stats: Cell array of the stats parameters for each GLM fit; - % AIC: vector of Akaike's information criteria for each the GLM fits. - % BIC: vector of Bayes Information criteria for each the GLM fits. - % configColl: configCollection object used to generate this - % results - % XvalData: Data to be used for validation. - % XvalTime: Time vector for the data. - - if(nargin< 14) - XvalTime =[]; - end - if(nargin<13) - XvalData =[]; - end - - if(isa(spikeObj,'cell')) - for i=1:length(spikeObj) - if(isnumeric(spikeObj{i}.name)) - nNumber(i) =spikeObj{i}.name; - else - nNumber(i) = str2double(spikeObj{i}.name(~isletter(spikeObj{i}.name))); - end - minTime(i)=spikeObj{i}.minTime; - maxTime(i)=spikeObj{i}.maxTime; - end - nNumber = unique(nNumber); - minTime = unique(minTime); - maxTime = unique(maxTime); - if(length(nNumber)>1) - error('Can only have a FitResults with spike trains from a single neuron'); - end - if(length(minTime)>1 || length(maxTime)>1) - error('Spike Trains are of different lengths'); - end - - elseif(isa(spikeObj,'nspikeTrain')) - if(isnumeric(spikeObj.name)) - nNumber =spikeObj.name; - else - nNumber = str2double(spikeObj.name(~isletter(spikeObj.name))); - end - minTime=spikeObj.minTime; - maxTime=spikeObj.maxTime; - - end - - fitObj.neuronNumber = nNumber; %str2num(spikeObj.name); - fitObj.neuralSpikeTrain = spikeObj; - fitObj.minTime = minTime; - fitObj.maxTime = maxTime; - - fitObj.numResults = 0; - fitObj.configs = configColl; - fitObj.configNames = configColl.getConfigNames; - fitObj.covLabels=covLabels; - fitObj.uniqueCovLabels= getUniqueLabels(covLabels); - - fitObj.mapCovLabelsToUniqueLabels; - fitObj.numHist=numHist; - fitObj.histObjects = histObjects; - fitObj.ensHistObjects = ensHistObj; - fitObj.addParamsToFit(fitObj.neuronNumber,lambda,b, dev, stats,AIC,BIC,logLL,configColl); - fitObj.Z =[]; %rescaled spikes times - exponentially dist. - fitObj.U =[]; %rescaled spike times - uniformly dist. - fitObj.X =[]; %rescaled spike times - gaussian dist. - fitObj.Residual =[]; %fit residual for PP - fitObj.KSStats.xAxis =[]; - fitObj.KSStats.KSSorted =[]; - fitObj.KSStats.ks_stat =[]; - fitObj.invGausStats.rhoSig=[]; - fitObj.invGausStats.confBoundSig=[]; - fitObj.plotParams = []; - fitObj.XvalData = XvalData; - fitObj.XvalTime = XvalTime; - - fitObj.fitType = distribution; - - end - function fitObj = setNeuronName(fitObj,name) - fitObj.neuronNumber = name; - end - function mFitRes = mergeResults(fitObj,newFitObj) - % mFitRes = mergeResults(fitObj,newFitObj) - % mFitRes contains the results from fitObj followed by the - % results of newFitObj in a single new FitResult object - % - % newFitObj can be of class 'FitResult' or a cell array of - % 'FitResult' objects. In the latter case, the results are - % apppended in the order that they appear in each cell array. - if(isa(newFitObj,'FitResult')) -% newFitObj.neuronNumber - if(fitObj.neuronNumber ==newFitObj.neuronNumber) - spikeObj = fitObj.neuralSpikeTrain; - covLabels = fitObj.covLabels(1:fitObj.numResults); - covLabels((fitObj.numResults+1):(fitObj.numResults+newFitObj.numResults)) = newFitObj.covLabels(1:newFitObj.numResults); - numHist = fitObj.numHist(1:fitObj.numResults); - numHist((fitObj.numResults+1):(fitObj.numResults+newFitObj.numResults)) = newFitObj.numHist(1:newFitObj.numResults); - histObjects=fitObj.histObjects(1:fitObj.numResults); - histObjects((fitObj.numResults+1):(fitObj.numResults+newFitObj.numResults)) = newFitObj.histObjects(1:newFitObj.numResults); - ensHistObjects=fitObj.ensHistObjects(1:fitObj.numResults); - ensHistObjects((fitObj.numResults+1):(fitObj.numResults+newFitObj.numResults)) = newFitObj.ensHistObjects(1:newFitObj.numResults); - b=fitObj.b(1:fitObj.numResults); - b((fitObj.numResults+1):(fitObj.numResults+newFitObj.numResults)) = newFitObj.b(1:newFitObj.numResults); - dev = [fitObj.dev newFitObj.dev]; - AIC = [fitObj.AIC newFitObj.AIC]; - BIC = [fitObj.BIC newFitObj.BIC]; - logLL = [fitObj.logLL newFitObj.logLL]; - stats=fitObj.stats(1:fitObj.numResults); - stats((fitObj.numResults+1):(fitObj.numResults+newFitObj.numResults)) = newFitObj.stats(1:newFitObj.numResults); - lambda = fitObj.lambda.merge(newFitObj.lambda); - - for i=1:fitObj.numResults - config{i}=fitObj.configs.getConfig(i); - end - offset=fitObj.numResults; - for i=1:newFitObj.numResults - config{i+offset}=newFitObj.configs.getConfig(i); - end - configColl= ConfigColl(config); - - XvalData = [fitObj.XvalData newFitObj.XvalData]; - XvalTime = [fitObj.XvalTime newFitObj.XvalTime]; - distribution=fitObj.fitType(1:fitObj.numResults); - distribution((fitObj.numResults+1):(fitObj.numResults+newFitObj.numResults)) = newFitObj.fitType(1:newFitObj.numResults); - tempZ = zeros(length(fitObj.Z),size(newFitObj.Z,2)); - tempU = zeros(length(fitObj.U),size(newFitObj.U,2)); - tempZ(1:length(newFitObj.Z),:) = newFitObj.Z; - tempU(1:length(newFitObj.U),:) = newFitObj.U; - Z=[fitObj.Z tempZ]; - U=[fitObj.U tempU]; - [X,rhoSig,confBoundSig] = Analysis.computeInvGausTrans(Z); - - M=fitObj.Residual.merge(newFitObj.Residual); - - origLength = size(fitObj.KSStats.xAxis,1); - currLength = size(newFitObj.KSStats.xAxis,1); - - if(currLength~=origLength) - %we use this because some times the time scales - %dont match up. In particular when spikeTrain is - %segmented by steps or windows and the window sizes - %are normalized to 1. - newX = fitObj.KSStats.xAxis; - oldX = newFitObj.KSStats.xAxis; - oldY = newFitObj.KSStats.KSSorted; - y = interp1(oldX,oldY,newX(:,1),'spline','extrap'); - xAxis = [fitObj.KSStats.xAxis newX(:,1)]; - KSSorted = [fitObj.KSStats.KSSorted y]; - else - - xAxis = [fitObj.KSStats.xAxis newFitObj.KSStats.xAxis]; - KSSorted = [fitObj.KSStats.KSSorted newFitObj.KSStats.KSSorted]; - - end - ks_stat = [fitObj.KSStats.ks_stat newFitObj.KSStats.ks_stat]; - mFitRes=FitResult(spikeObj,covLabels,numHist,histObjects,ensHistObjects,lambda,b, dev, stats,AIC,BIC,logLL,configColl,XvalData,XvalTime,distribution); - mFitRes.setKSStats(Z,U, xAxis, KSSorted, ks_stat); - mFitRes.setInvGausStats(X,rhoSig,confBoundSig); - mFitRes.setFitResidual(M); - - - elseif(isa(newFitObj,'cell')) - if(isa(newFitObj{1},'FitResult')) - for i=1:length(newFitObj) - if(i==1) - mFitRes = fitObj.mergeResults(newFitObj{i}); - else - mFitRes = mFitRes.mergeResults(newFitObj{i}); - end - end - end - end - end - - end - function subsetFit = getSubsetFitResult(fitObj,subfits) - %subfits is a row vector with numbers corresponding to the - %subfits - if(and(min(subfits)>0,max(subfits)<=fitObj.numResults)) - spikeObj = fitObj.neuralSpikeTrain; - covLabels = fitObj.covLabels(subfits); - numHist = fitObj.numHist(subfits); - histObjects = fitObj.histObjects(subfits); - ensHistObj = fitObj.ensHistObjects(subfits); - lambda = fitObj.lambda.getSubSignal(subfits); - b = fitObj.b(subfits); - dev = fitObj.dev(subfits); - stats = fitObj.stats(subfits); - AIC = fitObj.AIC(subfits); - BIC = fitObj.BIC(subfits); - logLL = fitObj.logLL(subfits); - configColl = fitObj.configs.getSubsetConfigs(subfits); - XvalData = fitObj.XvalData; - XvalTime = fitObj.XvalTime; - distribution = fitObj.fitType; - - subsetFit=FitResult(spikeObj,covLabels,numHist,histObjects,ensHistObj,lambda,b, dev, stats,AIC,BIC,logLL,configColl,XvalData,XvalTime,distribution); - Z = fitObj.Z(:,subfits); - U = fitObj.U(:,subfits); - X = fitObj.X(:,subfits); - xAxis= fitObj.KSStats.xAxis(:,subfits); - KSSorted=fitObj.KSStats.KSSorted(:,subfits); - ks_stat=fitObj.KSStats.ks_stat(subfits); - rhoSig=fitObj.invGausStats.rhoSig.getSubSignal(subfits); - confBoundSig=fitObj.invGausStats.confBoundSig; - M = fitObj.Residual.getSubSignal(subfits); - - subsetFit.setKSStats(Z,U, xAxis, KSSorted, ks_stat); - subsetFit.setInvGausStats(X,rhoSig,confBoundSig); - subsetFit.setFitResidual(M); - end - end - function addParamsToFit(fitObj,neuronNum,lambda,b, dev, stats,AIC,BIC,logLL,configColl) - % addParamsToFit(fitObj,neuronNum,lambda,b, dev, stats,AIC,BIC,configColl) - % Add the specified parameters to the current FitResult object - % only if the neuronNum matches the neuronNum of this object - if(fitObj.neuronNumber==neuronNum) - if(isa(lambda,'cell')) - newLambda=lambda{1}; - for i=2:length(lambda) - newLambda = newLambda.merge(lambda{i}); - end - elseif(isa(lambda,'Covariate')||isa(lambda,'SignalObj')) - newLambda = lambda; - end - - numNewResults = newLambda.dimension;%number of new elements - if(nargin<8) - configColl = cell(1,numNewResults); - end - - if(numNewResults==1) - fitObj.b{fitObj.numResults+1} = b{1}; - - fitObj.dev(fitObj.numResults+1) = dev; - fitObj.stats{fitObj.numResults+1}= stats{1}; - if(nargin<7) - fitObj.AIC(fitObj.numResults+1) = 2*length(b)+dev; - fitObj.BIC(fitObj.numResults+1) = length(b)*log(length(newLambda.time))+dev; - delta = 1/newLambda.sampleRate; - fitObj.logLL(fitObj.numResults+1) = sum(y.*log(data*delta)+(1-y).*(1-newLambda.data*delta)); - else - fitObj.AIC(fitObj.numResults+1) = AIC; - fitObj.BIC(fitObj.numResults+1) = BIC; - fitObj.logLL(fitObj.numResults+1) = logLL; - end - - fitObj.numCoeffs(fitObj.numResults+1) = length(b); - else - for i=1:numNewResults - fitObj.b{fitObj.numResults+i} = b{i}; - - fitObj.dev(fitObj.numResults+i) = dev(i); - fitObj.stats{fitObj.numResults+i}= stats{i}; - if(nargin<7) - fitObj.AIC(fitObj.numResults+i) = 2*length(b{i})+dev(i); - fitObj.BIC(fitObj.numResults+i) = length(b{i})*log(length(newLambda.time))+dev(i); - delta=fitObj.neuralSpikeTrain.sampleRate; - y=fitObj.neuralSpikeTrain.getSigRep.dataToMatrix; - - fitObj.logLL(fitObj.numResults+i)= sum(y.*log(newLambda.data*delta)+(1-y).*(1-newLambda.data*delta)); - else - fitObj.AIC(fitObj.numResults+i) = AIC(i); - fitObj.BIC(fitObj.numResults+i) = BIC(i); - fitObj.logLL(fitObj.numResults+i)= logLL(i); - end - fitObj.numCoeffs(fitObj.numResults+i) = length(b{i}); - end - end - if(fitObj.numResults ==0) - fitObj.lambda = newLambda; - else - fitObj.lambda = fitObj.lambda.merge(newLambda); %new lambda - end - - fitObj.numResults = fitObj.numResults+numNewResults; - dataLabels = cell(1,fitObj.numResults); - for i=1:fitObj.numResults - dataLabels{i} = strcat('\lambda_{',num2str(i),'}'); - end - fitObj.lambda.setDataLabels(dataLabels); - - fitObj.configs.addConfig(configColl); - fitObj.configNames = fitObj.configs.getConfigNames; - else - error('Neuron number does not match'); - end - end - function [lambda, logLL] = computeValLambda(fitObj) - % lambda = computeValLambda(fitObj) - % Returns a Covariate object lambda. This is the Conditional - % intensity function evaluated using the validation data - lambdaData = zeros(length(fitObj.XvalTime{1}),fitObj.numResults); - for i=1:fitObj.numResults - lambdaData(:,i) = fitObj.evalLambda(i,fitObj.XvalData{i}); - end - lambda=Covariate(fitObj.XvalTime{1},lambdaData,... - '\lambda(t)',fitObj.lambda.xlabelval,... - fitObj.lambda.xunits,'Hz',fitObj.lambda.dataLabels); - delta = 1/lambda.sampleRate; - y=fitObj.neuralSpikeTrain.getSigRep.dataToMatrix; - logLL =sum(y.*log(lambda.data*delta)+(1-y).*(1-lambda.data*delta)); - end - - function mapCovLabelsToUniqueLabels(fitObj) - % mapCovLabelsToUniqueLabels(fitObj) - % Used internally by the FitResult class generate a matrix that - % maps how covariate labels of the fit object map to unique - % covariate labels. For example, multiple fits that have a - % constant baseline term will be assumed to refer to the same - % "baseline" term and not two separate ones - flatMask = zeros(length(fitObj.uniqueCovLabels),length(fitObj.covLabels)); - for j=1:length(fitObj.covLabels) - currLabels = fitObj.covLabels{j}; - index=zeros(1,length(currLabels)); - for i=1:length(currLabels) - idx = find(strcmp(currLabels{i}, fitObj.uniqueCovLabels),1,'first'); - if(isempty(idx)) - error('FitResult:UnknownCovariateLabel',... - 'Unable to map covariate label "%s" to unique labels.',currLabels{i}); - end - index(i)=idx; - end - - fitObj.indicesToUniqueLabels{j} = index; - flatMask(index,j) = 1; - end - fitObj.flatMask = flatMask; - end - function p=getPlotParams(fitObj) - % p=getPlotParams(fitObj) - if(isempty(fitObj.plotParams)) - fitObj.computePlotParams; - end - p=fitObj.plotParams; - end - function plotValidation(fitObj) - % plotValidation(fitObj) - % calls plotResults on the validation FitResult object if - % validation data is present. Note that the GLM coefficients - % are not recomputed and therefore the same as those obtained - % from the training data. - if(~isempty(fitObj.validation)) - fitObj.validation.plotResults; - else - display('Validation Data not available to plot'); - end - end - function answer = isValDataPresent(fitObj) - % answer = isValDataPresent(fitObj) - % returns 1 if validation data is present. This method is used - % to determine if validation data is available to compute the - % validation results. - answer = 0; - if(~isempty(fitObj.XvalTime) && ~isempty(fitObj.XvalData)) - for i=1:length(fitObj.XvalTime) - currTime = fitObj.XvalTime{i}; - if(~isempty(currTime)) - if(currTime(end)-currTime(1)>0) - answer =1; - break; - end - end - end - - end - - end - function lambdaData = evalLambda(fitObj,lambdaIndex,newData) - % lambdaData = evalLambda(fitObj,lambdaIndex,newData) - % lambdaIndex: the index of the corresponding lambda to be - % evaluated with the new data. - % newData: matrix of covariates in same order as fits without - % constant term in first column -% if(isa(newData,'double')) -% [~,columns] = size(newData); -% tempData = cell(1,columns); -% for i=1:columns -% tempData{i} = newData(:,i); -% end -% newData = tempData; -% end - - if(lambdaIndex>0 && lambdaIndex <= fitObj.numResults) - b=fitObj.b{lambdaIndex}; %coefficient matrix - if(isempty(newData)) - [rows,~] = size(newData); - baseline=ones(rows,1); - lambdaData = exp(b(1)*baseline); - else - if(isa(newData,'double')) %matrix, 1 column per coefficient - baseline=ones(length(newData),1); - [~,columns] = size(newData); - - if(length(b)>=1) - lambdaData = exp(newData*b(1:end)); - if(strcmp(fitObj.fitType{lambdaIndex},'poisson')) -% lambdaData = exp(newData*b(1:end)); -% lambdaData = exp(b(1) + newData*b(2:end)); - else -% lambdaData = exp(b(1) + newData*b(2:end)); - lambdaData = lambdaData./(1+lambdaData); - end -% else -% if(strcmp(fitObj.fitType{lambdaIndex},'poisson')) -% lambdaData = exp(b(1)*baseline); -% -% else -% lambdaData = exp(b(1)*baseline); -% lambdaData = lambdaData./(1+lambdaData); -% end - end - lambdaData = lambdaData*fitObj.neuralSpikeTrain.sampleRate; - elseif(isa(newData,'cell')) % a cell array, each element is matrix of values for each coeff -% baseline=ones(size(newData{1})); %design matrix - runSum=0; - for i=1:(length(newData)) %-fitObj.numHist(lambdaIndex)) -% if(i==1) -% runSum = b(1)*baseline; -% else - if(i<=length(b)) - runSum = runSum+b(i)*newData{i}; - end -% end - end - if(strcmp(fitObj.fitType{lambdaIndex},'poisson')) - lambdaData = exp(runSum); - lambdaData = lambdaData*fitObj.neuralSpikeTrain.sampleRate; - else - lambdaData = exp(runSum); - lambdaData = lambdaData./(1+lambdaData); - lambdaData = lambdaData*fitObj.neuralSpikeTrain.sampleRate; - end - else - error('New data must be cell or a matrix'); - end - - end - else - error('Index into fit params is incorrect'); - end - - end -% function handle = plotHist(fitObj,fitNum) -% % handle = plotHist(fitObj,fitNum) -% % plots the history terms used in this FitResult object -% % if fitNum is not specified then fitNum=1:numResults -% if(nargin<2 || isempty(fitNum)) -% fitNum = 1:fitObj.numResults; -% end -% -% for j=fitNum -% if(j>0 && j <= fitObj.numResults) -% b=fitObj.b{j}; %coefficient matrix -% startHistIndex = length(b)-fitObj.numHist(j)+1; -% if(startHistIndex=windowTimes(i),t<=windowTimes(i+1)); -% histEffect(index)=exp(-bHist(i))-1; %To offset zero coeffs -% end -% end -% else -% t=[0; 0.00001]; -% histEffect =[0;0]; -% end -% if(j==fitNum(1)) -% hSig = SignalObj(t,histEffect,'History','time','s','',fitObj.lambda.dataLabels{j}); -% else -% hSig = hSig.merge(SignalObj(t,histEffect,'History Effect','time','s','',fitObj.lambda.dataLabels{j})); -% end -% end -% end -% N=floor(length(hSig.time)./70); B=ones(1,N)/N; A=1; -% handle=hSig.filtfilt(B,A).plot; -% end - function computePlotParams(fitObj,fitNum) - if(nargin<2) - fitNum = 1:fitObj.numResults; - end - index=find(sum(fitObj.flatMask,2)>0);%1:length(fitObj.flatMask(:,1)); - %Only use the labels that appear in at least one fit - %Otherwise that parameter was not present for any of the - %regressions and just takes up plot real-estate - - sigIndex=zeros(length(index),length(fitNum)); - bAct = nan(length(index),length(fitNum)); - seAct= nan(length(index),length(fitNum)); - - for i=fitNum - %this indexing is to avoid extremely large se's from - %affecting plots - criteria = find(fitObj.stats{i}.se'<100); - %indicesForFit = find(fitObj.flatMask(index,i)==1); - indicesForFit = fitObj.indicesToUniqueLabels{i}; - bVals = fitObj.b{i}(criteria); - bAct(indicesForFit(criteria),i) = bVals; %sorted according to uniqueLabels - seVals = fitObj.stats{i}.se(criteria)'; - seAct(indicesForFit(criteria),i)= seVals; %sorted according to uniqueLabels; - temp = sign([bAct(:,i)-seAct(:,i) bAct(:,i)+seAct(:,i)]); - productOfSigns = temp(:,1).*temp(:,2); %should be positive - sIndex=and(productOfSigns>0,seAct(:,i)~=0); - sigIndex(:,i)=sIndex; - end - fitObj.plotParams.bAct = bAct; - fitObj.plotParams.seAct= seAct; - fitObj.plotParams.sigIndex = sigIndex; - fitObj.plotParams.xLabels = cell(length(index),1); - fitObj.plotParams.xLabels = fitObj.uniqueCovLabels; - -% for i=1:(length(index)) -% if(i==1) -% fitObj.plotParams.xLabels{i} = 'baseline'; -% %text(i, 0,'baseline','interpreter','latex'); -% else -% fitObj.plotParams.xLabels{i} = fitObj.covLabels{index(i)-1}; -% %text(i, 0,fitObj.covLabels{index(i)-1},'interpreter','latex'); -% end -% end - tempVal =sum(fitObj.flatMask,2); - fitObj.plotParams.numResultsCoeffPresent =tempVal(index); - end - - function [coeffIndex, epochId,numEpochs] = getCoeffIndex(fitObj,fitNum,sortByEpoch) - if(nargin<3 || isempty(sortByEpoch)) - sortByEpoch=0; - end - if(nargin<2 || isempty(fitNum)) - fitNum = 1:fitObj.numResults; - end - if(isempty(fitObj.plotParams)) - fitObj.computePlotParams; - end - [histIndex, epochId] = fitObj.getHistIndex(fitNum,sortByEpoch); - allIndex = 1:length(fitObj.uniqueCovLabels); - - nonHistIndex = setdiff(allIndex,histIndex); -% nonNANIndex = find(sum(~isnan(fitObj.plotParams.bAct(:,fitNum)),2)>=1); - nonNANIndex= allIndex; - actCoeffIndex = nonHistIndex(ismember(nonHistIndex, nonNANIndex)); - allCoeffTerms = fitObj.uniqueCovLabels(actCoeffIndex); -% coeffName = cell(size(allCoeffTerms)); - epochStartInd=regexp(allCoeffTerms,'_\{\d*\}','start'); - epochEndInd=regexp(allCoeffTerms,'_\{\d*\}','end'); - - allCoeffIndex = []; - nonEpochIndex=[]; -% nonEmptyCoeffNameInd = []; - epochsExist =0; - for i=1:length(allCoeffTerms) - if(~isempty(allCoeffTerms{i})) - allCoeffIndex = [allCoeffIndex i]; - - if(~isempty(epochStartInd{i})) -% nonEmptyCoeffNameInd = [nonEmptyCoeffNameInd i]; - epochsExist=1; - actStart = epochStartInd{i}+2; - actEnd = epochEndInd{i}-1; - numEpoch(i) = str2num(allCoeffTerms{i}(actStart:actEnd)); -% coeffName{i} = allCoeffTerms{i}(1:actStart-3); - - - else - nonEpochIndex = [nonEpochIndex i]; - numEpoch(i) = 0; % make terms that only appear once part of epoch 0. - - end - end - - end - -% coeffName = coeffName(nonEmptyCoeffNameInd); - if(epochsExist && ~sortByEpoch) - totalEpochs = unique(numEpoch); - coeffIndex = nonEpochIndex; - if(nargout>1) - epochId=zeros(size(nonEpochIndex)); - end - for i=1:length(totalEpochs) - if(totalEpochs(i)~=0) - coeffIndex = [coeffIndex, find(numEpoch==totalEpochs(i))]; - - if(nargout>1) - epochId = [epochId, totalEpochs(i)*ones(size(find(numEpoch==totalEpochs(i))))]; - end - end - end - coeffIndex = actCoeffIndex(coeffIndex); - elseif(epochsExist && sortByEpoch) - coeffIndex = actCoeffIndex(allCoeffIndex); - if(nargout>1) - epochId = numEpoch; - end - else - coeffIndex = actCoeffIndex(allCoeffIndex); - if(nargout>1) - epochId = zeros(size(allCoeffIndex)); %no epochs exist so just create same index for all; - end - end - - -% nonNANIndex = find(sum(~isnan(fitObj.plotParams.bAct(:,fitNum)),2)>=1); - nonNANIndex = allIndex; - coeffIndex = coeffIndex(ismember(coeffIndex, nonNANIndex)); - - if(nargout>2) - numEpochs = length(unique(epochId)); - end - - end - - function h=plotCoeffsWithoutHistory(fitObj,fitNum,sortByEpoch,plotSignificance) - if(nargin<4 || isempty(plotSignificance)) - plotSignificance=1; - end - if(nargin<3 || isempty(sortByEpoch)) - sortByEpoch = 0; - end - if(nargin<2 || isempty(fitNum)) - fitNum = 1:fitObj.numResults; - end - if(isempty(fitObj.plotParams)) - fitObj.computePlotParams; - end - - - coeffIndex = fitObj.getCoeffIndex(fitNum,sortByEpoch); - h=fitObj.plotCoeffs([],fitNum,[],plotSignificance,coeffIndex); - - - - end - - function [histIndex, epochId,numEpochs] = getHistIndex(fitObj,fitNum,sortByEpoch) - %if sortByEpoch==1 then we group all regression terms with the - %same name one next to each other by epoch (time interval). - %Otherwise, we show all epoch one terms, followed by all epoch - %2 terms, etc. - if(nargin<3 || isempty(sortByEpoch)) - sortByEpoch = 0; - end - if(nargin<2 || isempty(fitNum)) - fitNum = 1:fitObj.numResults; - end - if(isempty(fitObj.plotParams)) - fitObj.computePlotParams; - end - - - allHistTerms = regexp(fitObj.uniqueCovLabels,'^[\w*'); - epochStartInd=regexp(fitObj.uniqueCovLabels,'\]_\{\d*\}','start'); - epochEndInd=regexp(fitObj.uniqueCovLabels,'\]_\{\d*\}','end'); - allHistIndex = []; - epochsExist =0; - for i=1:length(allHistTerms) - if(~isempty(allHistTerms{i})) - allHistIndex = [allHistIndex i]; - if(~isempty(epochStartInd{i})) - epochsExist=1; - actStart = epochStartInd{i}+3; - actEnd = epochEndInd{i}-1; - numEpoch(i) = str2num(fitObj.uniqueCovLabels{i}(actStart:actEnd)); - end - end - - end - - if(epochsExist && ~sortByEpoch) - totalEpochs = unique(numEpoch); - histIndex = []; - if(nargout>1) - epochId=[]; - end - for i=1:length(totalEpochs) - histIndex = [histIndex, find(numEpoch==totalEpochs(i))]; - if(nargout>1) - epochId = [epochId, totalEpochs(i)*ones(size(find(numEpoch==totalEpochs(i))))]; - end - end - elseif(epochsExist && sortByEpoch) - histIndex = allHistIndex; - if(nargout>1) - epochId = numEpoch; - end - else - histIndex = allHistIndex; - if(nargout>1) - epochId = zeros(size(allHistIndex)); %no epochs exist so just create same index for all; - end - end - - -% nonNANIndex = find(sum(~isnan(fitObj.plotParams.bAct(:,fitNum)),2)>=1); -% histIndex = histIndex(ismember(histIndex, nonNANIndex)); - - if(nargout>2) - numEpochs = length(unique(epochId)); - end - - end - - function [coeffMat, labels, SEMat] = getCoeffs(fitObj, fitNum) - if(nargin<2 || isempty(fitNum)) - fitNum =1:fitObj.numResults; - end - sortByEpoch = 0; % Make sure we have different time series if the history is divided into epochs; - [coeffIndex, epochId, numEpochs] = fitObj.getCoeffIndex(fitNum,sortByEpoch); - epochNums = unique(epochId); - - - coeffStrings = fitObj.uniqueCovLabels(coeffIndex); - baseStringEndIndex =regexp(coeffStrings,'_\{\d*\}','start'); - - for i=1:length(baseStringEndIndex) - if(~isempty(baseStringEndIndex{i})) - baseStrings{i} = coeffStrings{i}(1:baseStringEndIndex{i}-1); - else - baseStrings{i} = coeffStrings{i}; - end - end - uniqueCoeffs = unique(baseStrings); - - for i=1:length(uniqueCoeffs) - coeffStrIndex{i} = coeffIndex(strcmp(baseStrings,uniqueCoeffs{i})); - if(min(epochId)==0) - epochIndices{i} = epochId(strcmp(baseStrings,uniqueCoeffs{i}))+1; - else - epochIndices{i} = epochId(strcmp(baseStrings,uniqueCoeffs{i})); - end - end - -% -% for i=1:numEpochs -% epochIndices{i} = find(epochId==epochNums(i)); -% epochLength(i) = length(epochIndices{i}); -% end - - - - coeffIndMat= nan(length(uniqueCoeffs),numEpochs); - - labels = cell(size(coeffIndMat)); - for i=1:length(uniqueCoeffs) - coeffIndMat(i,epochIndices{i}) = coeffStrIndex{i}; - labels(i,epochIndices{i}) = fitObj.uniqueCovLabels(coeffStrIndex{i}); - end - - -% for i=1:numEpochs -% coeffIndMat(1:epochLength(i),i) = coeffIndex(epochIndices{i}); -% labels(1:epochLength(i),i) = fitObj.uniqueCovLabels(coeffIndMat(1:epochLength(i),i)); -% end - - - - if(length(fitNum)>1) - coeffMat = nan(size(coeffIndMat,1),size(coeffIndMat,2), length(fitNum)); - SEMat = nan(size(coeffIndMat,1),size(coeffIndMat,2), length(fitNum)); - for i=1:length(fitNum) - for j=1:length(uniqueCoeffs) - bTemp=fitObj.plotParams.bAct(coeffStrIndex{j},i); - seTemp=fitObj.plotParams.seAct(coeffStrIndex{j},i); - coeffMat(j,epochIndices{j},i) = bTemp'; - SEMat(j,epochIndices{j},i) = seTemp'; - end - end - else - coeffMat = nan(size(coeffIndMat,1),size(coeffIndMat,2)); - SEMat = nan(size(coeffIndMat,1),size(coeffIndMat,2)); - for j=1:length(uniqueCoeffs) - bTemp=fitObj.plotParams.bAct(coeffStrIndex{j},fitNum); - seTemp = fitObj.plotParams.seAct(coeffStrIndex{j},fitNum); - coeffMat(j,epochIndices{j}) = bTemp'; - SEMat(j,epochIndices{j}) = seTemp'; - end - - end - - end - - function [histMat, labels, SEMat] = getHistCoeffs(fitObj,fitNum) - if(nargin<2 || isempty(fitNum)) - fitNum =1:fitObj.numResults; - end - sortByEpoch = 0; % Make sure we have different time series if the history is divided into epochs; - [histIndex, epochId, numEpochs] = fitObj.getHistIndex(fitNum,sortByEpoch); - epochNums = unique(epochId); - - - histcoeffStrings = fitObj.uniqueCovLabels(histIndex); - baseStringEndIndex =regexp(histcoeffStrings,'_\{\d*\}','start'); - baseStrings = cell(length(baseStringEndIndex),1); - for i=1:length(baseStringEndIndex) - if(~isempty(baseStringEndIndex{i})) - baseStrings{i} = histcoeffStrings{i}(1:baseStringEndIndex{i}-1); - else - baseStrings{i} = histcoeffStrings{i}; - end - end - uniqueCoeffs = unique(baseStrings); - - for i=1:length(uniqueCoeffs) - histcoeffStrIndex{i} = histIndex(strcmp(baseStrings,uniqueCoeffs{i})); - if(min(epochId)==0) - epochIndices{i} = epochId(strcmp(baseStrings,uniqueCoeffs{i}))+1; - else - epochIndices{i} = epochId(strcmp(baseStrings,uniqueCoeffs{i})); - end - end - -% -% for i=1:numEpochs -% epochIndices{i} = find(epochId==epochNums(i)); -% epochLength(i) = length(epochIndices{i}); -% end - - - - histcoeffIndMat= nan(length(uniqueCoeffs),numEpochs); - labels = cell(size(histcoeffIndMat)); -% SEMat = nan(length(uniqueCoeffs),numEpochs); - for i=1:length(uniqueCoeffs) - histcoeffIndMat(i,epochIndices{i}) = histcoeffStrIndex{i}; - labels(i,epochIndices{i}) = fitObj.uniqueCovLabels(histcoeffStrIndex{i}); -% SEMat(i,epochIndices{i}) = fitObj.se; - end - - -% for i=1:numEpochs -% coeffIndMat(1:epochLength(i),i) = coeffIndex(epochIndices{i}); -% labels(1:epochLength(i),i) = fitObj.uniqueCovLabels(coeffIndMat(1:epochLength(i),i)); -% end - - - - if(length(fitNum)>1) - histMat = nan(size(histcoeffIndMat,1),size(histcoeffIndMat,2), length(fitNum)); - SEMat = nan(size(histcoeffIndMat,1),size(histcoeffIndMat,2), length(fitNum)); - for i=fitNum - for j=1:length(uniqueCoeffs) - bTemp=fitObj.plotParams.bAct(histcoeffStrIndex{j},i); - seTemp = fitObj.plotParams.seAct(histcoeffStrIndex{j},i); - histMat(j,epochIndices{j},i) = bTemp'; - SEMat(j,epochIndices{j},i) = seTemp'; - end - end - else - histMat = nan(size(histcoeffIndMat,1),size(histcoeffIndMat,2)); - SEMat = nan(size(histcoeffIndMat,1),size(histcoeffIndMat,2)); - for j=1:length(uniqueCoeffs) - bTemp=fitObj.plotParams.bAct(histcoeffStrIndex{j},fitNum); - seTemp=fitObj.plotParams.seAct(histcoeffStrIndex{j},fitNum); - histMat(j,epochIndices{j}) = bTemp'; - SEMat(j,epochIndices{j}) = seTemp'; - end - - end - - -% -% if(nargin<2 || isempty(fitNum)) -% fitNum =1:fitObj.numResults; -% end -% sortByEpoch = 0; % Make sure we have different time series if the history is divided into epochs; -% [histIndex, epochId, numEpochs] = fitObj.getHistIndex(fitNum,sortByEpoch); -% epochNums = unique(epochId); -% for i=1:numEpochs -% epochIndices{i} = find(epochId==epochNums(i)); -% epochLength(i) = length(epochIndices{i}); -% end -% -% histIndMat= nan(max(epochLength),numEpochs); -% labels = cell(size(histIndMat)); -% for i=1:numEpochs -% histIndMat(1:epochLength(i),i) = histIndex(epochIndices{i}); -% labels(1:epochLength(i),i) = fitObj.uniqueCovLabels(histIndMat(1:epochLength(i),i)); -% end -% -% -% -% if(length(fitNum)>1) -% histMat = nan(size(histIndMat,1),size(histIndMat,2), length(fitNum)); -% for i=1:length(fitNum) -% for j=1:numEpochs -% bTemp=fitObj.plotParams.bAct(epochIndices{j},i); -% histMat(1:epochLength(j),j,i) = bTemp; -% end -% end -% else -% histMat = nan(size(histIndMat,1),size(histIndMat,2)); -% -% for j=1:numEpochs -% bTemp=fitObj.plotParams.bAct(epochIndices{j},fitNum); -% histMat(1:epochLength(j),j) = bTemp; -% end -% -% end - - end - function h=plotHistCoeffs(fitObj,fitNum,sortByEpoch,plotSignificance) - if(nargin<4 || isempty(plotSignificance)) - plotSignificance=1; - end - if(nargin<3 || isempty(sortByEpoch)) - sortByEpoch=0; - end - if(nargin<2 || isempty(fitNum)) - fitNum = 1:fitObj.numResults; - end - if(isempty(fitObj.plotParams)) - fitObj.computePlotParams; - end - histIndex = fitObj.getHistIndex(fitNum,sortByEpoch); - h=fitObj.plotCoeffs([],fitNum,[],plotSignificance,histIndex); - end - - - function h=plotCoeffs(fitObj,handle,fitNum,plotProps,plotSignificance,subIndex) - % h=plotCoeffs(fitObj,handle,fitNum,plotProps,plotSignificance) - % plots the GLM coefficients for each fit along with the - % confidence intervals. - % fitNum: number of the fit to plot. If not specified, all are - % plotted. - % plotProps: properties to use for the making the plot - % plotSignificance: If 1 then an asterix (*) is place above - % parameters that are statistically different - % from zero with alpha=5%. - - - if(nargin<5 || isempty(plotSignificance)) - plotSignificance = 1; - end - - if(nargin<4 || isempty(plotProps)) - plotProps = []; - end - - if(nargin<3 || isempty(fitNum)) - fitNum = 1:fitObj.numResults; - end - - if(nargin<2 || isempty(handle)) - handle=gca; - end - - if(isempty(fitObj.plotParams)) - fitObj.computePlotParams; - end - - if(nargin<6 || isempty(subIndex)) - subIndex = [fitObj.getHistIndex, fitObj.getCoeffIndex]; - end - - bAct = fitObj.getPlotParams.bAct(subIndex,fitNum); - seAct= fitObj.getPlotParams.seAct(subIndex,fitNum); - sigIndex=fitObj.getPlotParams.sigIndex(subIndex,fitNum); - - if(~isempty(plotProps)) - for i=1:length(fitNum) - h(i)=errorbar(handle,1:length(subIndex),bAct(:,i),seAct(:,i),plotProps{i}); hold on; - set(h(i), 'LineStyle', 'none', 'Marker', '.');%,... -% 'Linewidth',1,'Marker','o','MarkerSize',6); - currColor = get(h(i),'Color'); - set(h(i),'MarkerEdgeColor',currColor,'MarkerFaceColor',currColor); -% hE= get(h(i),'Children'); -% errorbarXData = get(hE(2),'XData'); -% errorbarXData(4:9:end) = errorbarXData(1:9:end) - 0.2; -% errorbarXData(7:9:end) = errorbarXData(1:9:end) - 0.2; -% errorbarXData(5:9:end) = errorbarXData(1:9:end) + 0.2; -% errorbarXData(8:9:end) = errorbarXData(1:9:end) + 0.2; -% set(hE(2), 'XData', errorbarXData); - end - else - Xaxis=repmat(1:length(bAct(:,1)),[length(bAct(1,:)) 1]); - h=errorbar(handle,Xaxis',bAct,seAct,'.');%strcat('.',FitResult.colors{mod(i-1,length(FitResult.colors))+1})); - set(h, 'LineStyle', 'none', 'Marker', '.');%,... - - for n=1:length(h) - currColor = get(h(n),'Color'); - set(h(n),'MarkerEdgeColor',currColor,'MarkerFaceColor',currColor); - - end - end - - hold on; - - - if(plotSignificance==1) - v=axis; - vdiff = .8*v(4); - - for i=1:length(fitNum) - plot(handle,find(sigIndex(:,i)==1),vdiff*ones(length(find(sigIndex(:,i)==1)),1)-i*.1,strcat('*',FitResult.colors{mod(i-1,length(FitResult.colors))+1})); hold on; - end - end - ylabel('GLM Fit Coefficients','Interpreter','none'); - xtickLabels = fitObj.getPlotParams.xLabels(subIndex); - xticks = 1:(length(xtickLabels)); - - set(handle,'xtick',xticks,'xtickLabel',xtickLabels,'FontSize',6); -% axis tight; - if(max(fitObj.numCoeffs)>=1) - xticklabel_rotate([],90,[],'Fontsize',10); - end -% hT=rotateticklabel(gca,-90); - h_legend=legend(handle,fitObj.lambda.dataLabels(fitNum),'Location','NorthEast'); - set(h_legend,'FontSize',14) - pos = get(h_legend,'position'); - set(h_legend, 'position',[pos(1)+.05 pos(2) pos(3:4)]); - -% axis tight; - title({'GLM Coefficients with 95% CIs (* p<0.05)'},'FontWeight','bold',... - 'FontSize',11,... - 'FontName','Arial'); - set(gca,'FontName', 'Arial' ); - set(gca, ... - 'TickLength' , [.02 .02] , ... - 'YGrid' , 'on' , ... - 'LineWidth' , 1 ); - hx=get(gca,'XLabel'); hy=get(gca,'YLabel'); - set([hx hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - - - end - function h=plotResults(fitObj) - % plotResults(fitObj) - % Generates KS plot, auto-correlation function of the inverse - % gaussian transformed rescaled ISIs, the sequential - % correlation coefficient between neigboring pairs of the - % rescaled ISIs (zj vs. zj-1), the GLM regression coefficients, - % and the Point Process Residual. - scrsz = get(0,'ScreenSize'); - h=figure('OuterPosition',[scrsz(3)*.01 scrsz(4)*.04 scrsz(3)*.98 scrsz(4)*.95]); - - subplot(2,4,[1 2]); fitObj.KSPlot; %make the plot - ht=text(.45, .95,strcat('Neuron:',num2str(fitObj.neuronNumber))); - set(ht,'FontName', 'Arial','FontWeight','bold','FontSize',10); - - subplot(2,4,3); fitObj.plotInvGausTrans; - subplot(2,4,4); fitObj.plotSeqCorr; - subplot(2,4,[7 8]); fitObj.plotResidual; - subplot(2,4,[5 6]); fitObj.plotCoeffs; - end - function handle = KSPlot(fitObj,fitNum) - % handle = KSPlot(fitObj) - % computes the K-S plot for each of the the candidate rate - % functions in this FitResult object. These candidate rate - % functions are numbered according to the order in which they - % were added to the FitResult. - if(nargin<2) - fitNum=1:fitObj.numResults; - end - h=gcf; - %h=[]; - figure(h); - % size(xAxis) - % size(KSSorted) - N = length(fitObj.KSStats.KSSorted); - if(~isempty(fitObj.KSStats.xAxis)) - xaxis = fitObj.KSStats.xAxis(:,1); - % Plot the CIs - plot(xaxis,xaxis, 'k-.'); hold on; - plot(xaxis, xaxis+1.36/sqrt(N), 'r','Linewidth',1); - plot(xaxis,xaxis-1.36/sqrt(N), 'r','Linewidth',1 ); - handle=plot(fitObj.KSStats.xAxis(:,fitNum),fitObj.KSStats.KSSorted(:,fitNum),'Linewidth',2); - - %set(gca,'xtick',[],'ytick',[],'ztick', []) - axis( [0 1 0 1] ); -% dataLabels = cell(1,fitObj.lambda.dimension); -% for i=1:fitObj.lambda.dimension - dataLabels = fitObj.lambda.dataLabels(fitNum); -% end - h_legend=legend(handle,dataLabels,'Location','SouthEast'); - set(h_legend,'FontSize',14) - end - hx=xlabel('Ideal Uniform CDF'); - hy=ylabel('Empirical CDF'); - title({'KS Plot of Rescaled ISIs'; 'with 95% Confidence Intervals'},'FontWeight','bold','FontSize',11,'FontName','Arial'); - set([hx, hy],'FontName', 'Arial','FontWeight','bold','FontSize',12); - - set(gca, ... - 'TickLength' , [.02 .02] , ... - 'YTick' , 0:.2:1, ... - 'XTick' , 0:.2:1, ... - 'LineWidth' , 1 ); - end - - function structure = toStructure(fitObj) - % structure = toStructure(fitObj) - % Converts FitResult object to a matlab structure than can then - % be saved. The structure is compatible with the FitResult - % static method FitResult.fromStructure(structure) that returns - % the object corresponding structure passed in. - fnames = fieldnames(fitObj); - - for i=1:length(fnames) - - currObj = fitObj.(fnames{i}); - if(strcmp(fnames{i},'histObjects')||strcmp(fnames{i},'ensHistObjects')) - for j=1:fitObj.numResults - tempObj = fitObj.(fnames{i}){j}; - if(~isempty(tempObj)) - structure.(fnames{i}){j} = tempObj.toStructure; - else - structure.(fnames{i}){j} = tempObj; - end - end - elseif(strcmp(fnames{i},'invGausStats')) - tempNames = fieldnames(fitObj.(fnames{i})); - for j=1:length(tempNames) - tempObj = currObj.(tempNames{j}); - if(~isempty(tempObj)) - structure.(fnames{i}).(tempNames{j})= tempObj.dataToStructure; - else - structure.(fnames{i}).(tempNames{j})= tempObj; - end - - end - - else - - if(isa(currObj,'double')||isa(currObj,'cell')) - structure.(fnames{i}) = currObj; - elseif(isa(currObj,'Covariate') ||isa(currObj,'ConfigColl')||isa(currObj,'nspikeTrain')) - structure.(fnames{i}) = currObj.toStructure; - elseif(isa(currObj,'SignalObj')) - structure.(fnames{i}) = currObj.dataToStructure; - elseif(isa(currObj,'struct')) - structure.(fnames{i}) = currObj; - end - end - end - - end - - - function handle = plotSeqCorr(fitObj) - % handle = plotSeqCorr(fitObj) - % plot zj+1 against zj - - %colors = {'.b','.g','.r','.c','.m','.y','.k'}; - rho=zeros(1,fitObj.numResults); - pval=zeros(1,fitObj.numResults); - dataLabels = fitObj.lambda.dataLabels; - for i=1:fitObj.numResults - handle = plot(fitObj.U(1:end-1,i),fitObj.U(2:end,i),strcat('.',Analysis.colors{mod(i-1,length(Analysis.colors))+1})); hold on; - [rhoTemp,p]= corrcoef(fitObj.U(1:end-1,i),fitObj.U(2:end,i));%handle=scatterhist(fitResults.Z(1:end-1,i),fitResults.Z(2:end,i)) - - [~,columns]=size(rhoTemp); - if(columns>1) - rho(i) = rhoTemp(1,2); - pval(i)= p(1,2); - else - rho(i) = rhoTemp; - pval(i)= p; - end - dataLabels{i} = strcat(dataLabels{i},', \rho=',num2str(rho(i),'%0.2g'),' (p=',num2str(pval(i),'%0.2g'),')'); - %get(h,'AlphaData'); - %set(h,'FaceAlpha',0.2,'EdgeAlpha',0.8,'EdgeColor',color{i}); - end - - - h_legend=legend(dataLabels,'Location','NorthEast'); - set(h_legend,'FontSize',14) - pos = get(h_legend,'position'); - if(~isempty(pos)) - set(h_legend, 'position',[pos(1)+.05 pos(2) pos(3:4)]); - end - - hy=ylabel('u_{j+1}'); hx=xlabel('u_j'); - set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - - axis([0 1 0 1]); - title({'Sequential Correlation of'; 'Rescaled ISIs'},'FontWeight','bold',... - 'FontSize',11,... - 'FontName','Arial'); - - - set(gca, ... - 'TickLength' , [.02 .02] , ... - 'YTick' , 0:.25:1, ... - 'XTick' , 0:.25:1, ... - 'LineWidth' , 1 ); - - - - end - function handle = plotInvGausTrans(fitObj) - % handle = plotInvGausTrans(fitObj) - % Plots the Auto-correlation function of the X_j's where: - % Z_j: rescaled ISI from the Time Rescaling Theorem. - % Exponential Rate 1 under true conditional intensity - % function. - % U_j: 1-exp(-Z_j). Uniform on the interval [0,1) if Z_j's - % are exponential rate 1. - % - % X_j: norminv(U_j,0,1). Gaussian mean 0, stdev 1 if U_j's are - % U([0,1)) - % - - %[rows,colm] = size(fitObj.X); - %index=find(fitObj.invGausStats.lags==1); - %lags=fitObj.invGausStats.lags; - [fitObj.X,rhoSig,confBoundSig] = Analysis.computeInvGausTrans(fitObj.Z); -% rhoSig=fitObj.invGausStats.rhoSig; - n=length(fitObj.X); -% confBoundSig = fitObj.invGausStats.confBoundSig; - handle=[]; -% for i=1:colm -% %i -% htemp=plot(lags',rho(:,i),strcat('.',FitResults.colors{mod(i-1,length(Analysis.colors))+1})); -% handle=[handle,htemp]; -% hold on; -% %labelArray{i} = ['Fit ' num2str(i)]; -% end - if(~isempty(rhoSig)) - rhoSig.plot; - end - h_legend=legend(fitObj.lambda.dataLabels,'Location','NorthEast'); - set(h_legend,'FontSize',14) - pos = get(h_legend,'position'); - if(~isempty(pos)) - set(h_legend, 'position',[pos(1)+.05 pos(2) pos(3:4)]); - end - %legend(h,labelArray); - hold on; - if(~isempty(confBoundSig)) - confBoundSig.plot; - end - title({'Autocorrelation Function';'of Rescaled ISIs'; 'with 95% CIs'},'FontWeight','bold',... - 'FontSize',11,... - 'FontName','Arial'); - hx=get(gca,'XLabel'); hy=get(gca,'YLabel'); - set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - set(gca, ... - 'TickLength' , [.02 .02] , ... - 'LineWidth' , 1 ); - v=axis; - maxY = max(abs(v(3:4)))*(1.1); %add 10% - axis([v(1:2) -maxY maxY]); - end - function handle = plotResidual(fitObj) - % handle = plotResidual(fitObj) - % Plots the Point Process Residual - handle=fitObj.Residual.plot; - legend off; - h_legend=legend(fitObj.lambda.dataLabels,'Location','NorthEast'); - set(h_legend,'FontSize',14) - pos = get(h_legend,'position'); -% set(h_legend, 'position',[.91 .41 pos(3:4)]); - set(h_legend, 'position',[pos(1)+.05 pos(2) pos(3:4)]); - title('Point Process Residual','FontWeight','bold',... - 'FontSize',11,... - 'FontName','Arial'); - xlabel('time [s]','Interpreter','none'); - hx=get(gca,'XLabel'); hy=get(gca,'YLabel'); - set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - v=axis; - maxY = max(abs(v(3:4)))*(1.1); %add 10% - axis([v(1:2) -maxY maxY]); - end - - - function setKSStats(fitObj, Z, U, xAxis, KSSorted, ks_stat) - % setKSStats(fitObj, Z, xAxis, KSSorted, ks_stat) - % Allows KS statistics to be set after object creation - % Z: Rescaled ISIs from the Time Rescaling Theorem - % xAxis: xAxis of the KS plot - % KSSorted: the sorted values of Uj=1-exp(-zj) - % ks_stat: the maximum deviation from the 45 degree line for - % all of the fits. - % - fitObj.Z =Z; - fitObj.U =U; - fitObj.KSStats.xAxis =xAxis; - fitObj.KSStats.KSSorted =KSSorted; - - - for i=1:size(xAxis,2); - [differentDists(i),pVal(i),ks_stat(i)]=kstest2(fitObj.KSStats.xAxis(:,i) ,fitObj.KSStats.KSSorted(:,i)); - end - if(~exist('differentDists')) - differentDists=1; - end - if(~exist('pVal')) - pVal=1; - end - - fitObj.KSStats.ks_stat =ks_stat; -% N = length(fitObj.KSStats.KSSorted); -% fitObj.KSStats.withinConfInt = ks_stat<1.36/sqrt(N); - fitObj.KSStats.withinConfInt = ~differentDists; - fitObj.KSStats.pValue = pVal; - end - function setInvGausStats(fitObj, X,rhoSig,confBoundSig) - % setInvGausStats(fitObj,X,rhoSig,confBoundSig) - % Sets the inverse gaussian transformed rescaled ISIs and the - % confidence bounds after the object has been created. - %fitObj.U=U; - fitObj.X=X; - fitObj.invGausStats.rhoSig=rhoSig; - fitObj.invGausStats.confBoundSig=confBoundSig; - end - function setFitResidual(fitObj,M) - % setFitResidual(fitObj,M). - % Adds the point process residual to the FitResult object - fitObj.Residual = M; - end - - function [paramVals, paramSE, paramSigIndex] = getParam(fitObj,paramNames,fitNum) - % output is a matrix of length equal to the total number of - % paramNames - % and one column for each fit - - if(nargin<3) - fitNum = 1:fitObj.numResults; - end - if(isempty(fitObj.plotParams)) - fitObj.computePlotParams; - end - paramVals = zeros(length(paramNames),length(fitNum)); - - if(nargout>1) - paramSE = zeros(length(paramNames),length(fitNum)); - end - - if(nargout>2) - paramSigIndex = zeros(length(paramNames),length(fitNum)); - end - - for i=1:length(paramNames) - paramIndex=find(strcmp(paramNames(i),fitObj.uniqueCovLabels)); - paramVals(i,:) = fitObj.plotParams.bAct(paramIndex,fitNum); - if(nargout>1) - paramSE(i,:) = fitObj.plotParams.seAct(paramIndex,fitNum); - end - if(nargout>2) - paramSigIndex(i,:) = fitObj.plotParams.sigIndex(paramIndex,fitNum); - end - end - - end - - - end - - methods (Static) - - function fitObj = fromStructure(structure) - % fitObj = fromStructure(structure) - % Returns a FitResult object from the input structure. - % This is used to be able to save and restore FitResult - if(isa(structure,'struct')) - if(isa(structure.neuralSpikeTrain,'cell')) - spikeObj = cell(1,length(structure.neuralSpikeTrain)); - for k=1:length(structure.neuralSpikeTrain) - spikeObj{k} = nspikeTrain.fromStructure(structure.neuralSpikeTrain{k}); - - end - else - spikeObj=nspikeTrain.fromStructure(structure.neuralSpikeTrain); - end - lambda=Covariate.fromStructure(structure.lambda); - rhoSig=SignalObj.signalFromStruct(structure.invGausStats.rhoSig); - confBoundSig = SignalObj.signalFromStruct(structure.invGausStats.confBoundSig); - M = Covariate.fromStructure(structure.Residual); - for i=1:structure.numResults - histObjects{i} = History.fromStructure(structure.histObjects{i}); - ensHistObject{i} = History.fromStructure(structure.ensHistObjects{i}); - end - configColl = ConfigColl.fromStructure(structure.configs); -% fitObj=FitResult(spikeObj,covLabels,numHist,histObjects,ensHistObj,lambda,b, dev, stats,AIC,BIC,logLL, configColl,XvalData,XvalTime,distribution) - fitObj=FitResult(spikeObj,structure.covLabels,structure.numHist,histObjects,ensHistObject,lambda,structure.b, structure.dev, structure.stats,structure.AIC,structure.BIC,structure.logLL,configColl,structure.XvalData,structure.XvalTime,structure.fitType); - fitObj.setKSStats(structure.Z,structure.U, structure.KSStats.xAxis, structure.KSStats.KSSorted, structure.KSStats.ks_stat); - fitObj.setInvGausStats(structure.X,rhoSig,confBoundSig); - fitObj.setFitResidual(M); - fitObj.setNeuronName(structure.neuronNumber); - - elseif(isa(structure,'cell')) %cell array of FitResult objects - fitObj = cell(size(structure)); - for i=1:length(structure) - fitObj{i} = FitResult.fromStructure(structure{i}); - end - end - - end - - function structCell = CellArrayToStructure(fitResObjCell) - % structCell = CellArrayToStructure(fitResObjCell) - % For every FitResult structure in the a cell array, it calls - % FitResults.fromStructure - - if(isa(fitResObjCell,'FitResult')) - structCell = fitResObjCell.toStructure; - elseif(isa(fitResObjCell,'cell')&&~isempty(fitResObjCell)) - if(isa(fitResObjCell{1},'FitResult')) - structCell = cell(size(fitResObjCell)); - for i=1:length(fitResObjCell) - structCell{i} = fitResObjCell{i}.toStructure; - end - end - else - structCell={}; - end - - end - - end - -end - -%Helper functions -function hText = xticklabel_rotate(XTick,rot,varargin) - %hText = xticklabel_rotate(XTick,rot,XTickLabel,varargin) Rotate XTickLabel - % - % Syntax: xticklabel_rotate - % - % Input: - % {opt} XTick - vector array of XTick positions & values (numeric) - % uses current XTick values or XTickLabel cell array by - % default (if empty) - % {opt} rot - angle of rotation in degrees, 90° by default - % {opt} XTickLabel - cell array of label strings - % {opt} [var] - "Property-value" pairs passed to text generator - % ex: 'interpreter','none' - % 'Color','m','Fontweight','bold' - % - % Output: hText - handle vector to text labels - % - % Example 1: Rotate existing XTickLabels at their current position by 90° - % xticklabel_rotate - % - % Example 2: Rotate existing XTickLabels at their current position by 45° and change - % font size - % xticklabel_rotate([],45,[],'Fontsize',14) - % - % Example 3: Set the positions of the XTicks and rotate them 90° - % figure; plot([1960:2004],randn(45,1)); xlim([1960 2004]); - % xticklabel_rotate([1960:2:2004]); - % - % Example 4: Use text labels at XTick positions rotated 45° without tex interpreter - % xticklabel_rotate(XTick,45,NameFields,'interpreter','none'); - % - % Example 5: Use text labels rotated 90° at current positions - % xticklabel_rotate([],90,NameFields); - % - % Note : you can not re-run xticklabel_rotate on the same graph. - % - % - - - % This is a modified version of xticklabel_rotate90 by Denis Gilbert - % Modifications include Text labels (in the form of cell array) - % Arbitrary angle rotation - % Output of text handles - % Resizing of axes and title/xlabel/ylabel positions to maintain same overall size - % and keep text on plot - % (handles small window resizing after, but not well due to proportional placement with - % fixed font size. To fix this would require a serious resize function) - % Uses current XTick by default - % Uses current XTickLabel is different from XTick values (meaning has been already defined) - - % Brian FG Katz - % bfgkatz@hotmail.com - % 23-05-03 - % Modified 03-11-06 after user comment - % Allow for exisiting XTickLabel cell array - - % Other m-files required: cell2mat - % Subfunctions: none - % MAT-files required: none - % - % See also: xticklabel_rotate90, TEXT, SET - - % Based on xticklabel_rotate90 - % Author: Denis Gilbert, Ph.D., physical oceanography - % Maurice Lamontagne Institute, Dept. of Fisheries and Oceans Canada - % email: gilbertd@dfo-mpo.gc.ca Web: http://www.qc.dfo-mpo.gc.ca/iml/ - % February 1998; Last revision: 24-Mar-2003 - - % check to see if xticklabel_rotate has already been here (no other reason for this to happen) - if isempty(get(gca,'XTickLabel')), - error('xticklabel_rotate : can not process, either xticklabel_rotate has already been run or XTickLabel field has been erased') ; - end - - % if no XTickLabel AND no XTick are defined use the current XTickLabel - %if nargin < 3 & (~exist('XTick') | isempty(XTick)), - if (nargin < 3 || isempty(varargin{1})) && (~exist('XTick') || isempty(XTick)), - xTickLabels = get(gca,'XTickLabel') ; % use current XTickLabel - if ~iscell(xTickLabels) - % remove trailing spaces if exist (typical with auto generated XTickLabel) - temp1 = num2cell(xTickLabels,2) ; - for loop = 1:length(temp1), - temp1{loop} = deblank(temp1{loop}) ; - end - xTickLabels = temp1 ; - end - varargin = varargin(2:length(varargin)); - end - - % if no XTick is defined use the current XTick - if (~exist('XTick') | isempty(XTick)), - XTick = get(gca,'XTick') ; % use current XTick - end - - %Make XTick a column vector - XTick = XTick(:); - - if ~exist('xTickLabels'), - % Define the xtickLabels - % If XtickLabel is passed as a cell array then use the text - if (length(varargin)>0) & (iscell(varargin{1})), - xTickLabels = varargin{1}; - varargin = varargin(2:length(varargin)); - else - xTickLabels = num2str(XTick); - end - end - - if length(XTick) ~= length(xTickLabels), - error('xticklabel_rotate : must have same number of elements in "XTick" and "XTickLabel"') ; - end - - %Set the Xtick locations and set XTicklabel to an empty string - set(gca,'XTick',XTick,'XTickLabel','') - - if nargin < 2, - rot = 90 ; - end - - % Determine the location of the labels based on the position - % of the xlabel - hxLabel = get(gca,'XLabel'); % Handle to xlabel - xLabelString = get(hxLabel,'String'); - - % if ~isempty(xLabelString) - % warning('You may need to manually reset the XLABEL vertical position') - % end - - set(hxLabel,'Units','data'); - xLabelPosition = get(hxLabel,'Position'); - y = xLabelPosition(2); - - %CODE below was modified following suggestions from Urs Schwarz - y=repmat(y,size(XTick,1),1); - % retrieve current axis' fontsize - fs = get(gca,'fontsize'); - - % Place the new xTickLabels by creating TEXT objects - hText = text(XTick, y, xTickLabels,'fontsize',fs); - - % Rotate the text objects by ROT degrees - set(hText,'Rotation',rot,'HorizontalAlignment','right',varargin{:}) - - % Adjust the size of the axis to accomodate for longest label (like if they are text ones) - % This approach keeps the top of the graph at the same place and tries to keep xlabel at the same place - % This approach keeps the right side of the graph at the same place - - set(get(gca,'xlabel'),'units','data') ; - labxorigpos_data = get(get(gca,'xlabel'),'position') ; - set(get(gca,'ylabel'),'units','data') ; - labyorigpos_data = get(get(gca,'ylabel'),'position') ; - set(get(gca,'title'),'units','data') ; - labtorigpos_data = get(get(gca,'title'),'position') ; - - set(gca,'units','pixel') ; - set(hText,'units','pixel') ; - set(get(gca,'xlabel'),'units','pixel') ; - set(get(gca,'ylabel'),'units','pixel') ; - - origpos = get(gca,'position') ; - - % Modified by Iahn Cajigas - % 3/4/2011 to allow for a single - % xTickLabel to work properly - temphText = get(hText,'extent'); - if(isa(temphText,'cell')) - textsizes = cell2mat(temphText) ; - else - textsizes = temphText; - end - - longest = max(textsizes(:,4)) ; - - laborigext = get(get(gca,'xlabel'),'extent') ; - laborigpos = get(get(gca,'xlabel'),'position') ; - - - labyorigext = get(get(gca,'ylabel'),'extent') ; - labyorigpos = get(get(gca,'ylabel'),'position') ; - leftlabdist = labyorigpos(1) + labyorigext(1) ; - - % assume first entry is the farthest left - leftpos = get(hText(1),'position') ; - leftext = get(hText(1),'extent') ; - leftdist = leftpos(1) + leftext(1) ; - if leftdist > 0, leftdist = 0 ; end % only correct for off screen problems - - botdist = origpos(2) + laborigpos(2) ; - newpos = [origpos(1)-leftdist longest+botdist origpos(3)+leftdist origpos(4)-longest+origpos(2)-botdist] ; - set(gca,'position',newpos) ; - - % readjust position of nex labels after resize of plot - set(hText,'units','data') ; - for loop= 1:length(hText), - set(hText(loop),'position',[XTick(loop), y(loop)]) ; - end - - - % adjust position of xlabel and ylabel - laborigpos = get(get(gca,'xlabel'),'position') ; - set(get(gca,'xlabel'),'position',[laborigpos(1) laborigpos(2)-longest 0]) ; - - % switch to data coord and fix it all - set(get(gca,'ylabel'),'units','data') ; - set(get(gca,'ylabel'),'position',labyorigpos_data) ; - set(get(gca,'title'),'position',labtorigpos_data) ; - - set(get(gca,'xlabel'),'units','data') ; - labxorigpos_data_new = get(get(gca,'xlabel'),'position') ; - set(get(gca,'xlabel'),'position',[labxorigpos_data(1) labxorigpos_data_new(2)]) ; - - - % Reset all units to normalized to allow future resizing - set(get(gca,'xlabel'),'units','normalized') ; - set(get(gca,'ylabel'),'units','normalized') ; - set(get(gca,'title'),'units','normalized') ; - set(hText,'units','normalized') ; - set(gca,'units','normalized') ; - - if nargout < 1, - clear hText - end - -end -function [uniqueLabels, indexIntoOriginal, restoreIndex] = getUniqueLabels(covLabels) -% Given a set of covLabels, returns a subset of labels that are unique - offset = 0; - for i=1:length(covLabels) - currLabels = covLabels{i}; - allLabels((1:length(currLabels))+offset) = currLabels; - offset=length(allLabels); - end - [uniqueLabels, indexIntoOriginal, restoreIndex] = unique(allLabels); -end - - - \ No newline at end of file diff --git a/History.m b/History.m deleted file mode 100644 index 024e7605..00000000 --- a/History.m +++ /dev/null @@ -1,290 +0,0 @@ -classdef History methods -% History Examples -% Reference page in Help browser -% doc History - - -% -% nSTAT v1 Copyright (C) 2012 Masschusetts Institute of Technology -% Cajigas, I, Malik, WQ, Brown, EN -% This program is free software; you can redistribute it and/or -% modify it under the terms of the GNU General Public License as published -% by the Free Software Foundation; either version 2 of the License, or -% (at your option) any later version. -% -% This program is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -% See the GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with this program; if not, write to the Free Software Foundation, -% Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - properties - windowTimes % times specifying the desired history windows - minTime - maxTime - end - - methods - function HistObj = History(windowTimes,minTime,maxTime) - % HistObj = History(windowTimes) - % Window times is a vector of times; We make sure that we have - % them in order and use them to specify windows in which we are - % interested in computing the history; - if(nargin<3) - maxTime=[]; - end - if(nargin<2) - minTime=[]; - end - - HistObj.windowTimes = sort(windowTimes); - HistObj.minTime = minTime; - HistObj.maxTime = maxTime; - end - - function cov = computeHistory(HistObj, nst,historyNum,tn) - % cov = computeHistory(HistObj, nst) - % - % returns a CovColl if more than one neural spike train is - % received as input. - % - % nst can be a nstColl, a cell array of nspikeTrains or a - % single nspikeTrain object. - % - % each output covariate will have the same number of dimensions as - % the number of history windows. The firing history - % corresponding to the window $w_i$ is the ith component of - % the covariate - % If tn is specified only compute the history at time tn - - if(nargin<4) - tn=[]; - end - if(nargin<3) - historyNum=[]; - end - - if(isa(nst,'nstColl')) - temp = cell(1,nst.numSpikeTrains); - for i=1:nst.numSpikeTrains -% if(strcmp(nst.getNST(i).name,'')) -% nst.getNST(i).setName(strcat('n',num2str(i))); -% end - temp{i} =HistObj.computeNSTHistoryWindow(nst.getNST(i),historyNum,tn); - if(strcmp(temp{i}.name,'History')) - %then nspikeTrain didnt have a name number - %history for the covariate collection - temp{i}.setName(['History #' num2str(historyNum) ' for ' nst{i}.name]); - end - end - cov=CovColl(temp); - elseif(isa(nst,'cell') && isa(nst{1},'nspikeTrain')) % a cell collection of neural spike trains - temp = cell(1,length(nst)); - for i=1:length(nst) - temp{i} = HistObj.computeNSTHistoryWindow(nst{i},historyNum,tn); - if(strcmp(temp{i}.name,'History')) - %then nspikeTrain didnt have a name number - %history for the covariate collection - temp{i}.setName(['History #' num2str(historyNum) ' for ' nst{i}.name]); - end - end - cov = CovColl(temp); - cov.setSampleRate(nst{1}.sampleRate); - elseif(isa(nst,'nspikeTrain')) - temp=HistObj.computeNSTHistoryWindow(nst,historyNum,tn); - temp.setName(['History #' num2str(historyNum) ' for ' nst.name]); - cov = CovColl(temp); - else - error('Can only compute History for nstColl, cells, or nspikeTrain'); - end - %size(cov.standardRep.data) - if(~isa(nst,'cell')) - cov.setSampleRate(nst.sampleRate); - end - end - - function setWindow(HistObj,windowTimes) - % setWindow(HistObj,windowTimes) - % replaces HistObj.windowTimes with the windowTimes vector that - % is being specified. - HistObj.windowTimes = windowTimes; - end - - function plot(HistObj) - % plots each of the history windows - tmin=HistObj.windowTimes(1:end-1); - tmax=HistObj.windowTimes(2:end); - sampleRate = 1000; - data=zeros((max(tmax)-min(tmin))*sampleRate,length(tmax)); - for i = 1:length(tmax) - indMin = max(1,(tmin(i)-min(tmin))*sampleRate); - indMax = (tmax(i)-min(tmin))*sampleRate; - data(indMin:indMax,i)=1; - dataLabels{i} = strcat('[',num2str(tmin(i),3),',',num2str(tmax(i),3),']'); - end - name='History'; - time=linspace(min(tmin),max(tmax),length(data)); - xlabelval = 'time'; xunits='s'; yunits=''; - s = SignalObj(time,data,name,xlabelval, xunits, yunits, dataLabels); - s.plot; hold on; - - - end - function filterMat = toFilter(HistObj,delta) -% if(nargin<2) -% delta = .001; -% end - - - tmin=HistObj.windowTimes(1:end-1); - tmax=HistObj.windowTimes(2:end); - timeVec=min(tmin):delta:max(tmax); - - a=ones(length(timeVec),1); - b=zeros(length(tmax),length(timeVec)); - - for i=1:length(tmax) - - - NumSamples = ceil(tmax(i)/delta); -% - StartSample = ceil(tmin(i)/delta) +1; - - - b(i,(StartSample:NumSamples)+1)=1; %delay by 1 - den{i,1} = a(i); - num{i,1} = b(i,:); - - end - filterMat = tf(num,den,delta,'Variable','z^-1'); - - end - function structure = toStructure(HistObj) - fNames = fieldnames(HistObj); - for i=1:length(fNames) - structure.(fNames{i}) = HistObj.(fNames{i}); - end - - end - - end - methods (Static) - function HistObj = fromStructure(structure) - if(~isempty(structure)) - fNames = fieldnames(structure); - windowTimes = structure.windowTimes; - minTime = structure.minTime; - maxTime = structure.maxTime; - HistObj = History(windowTimes,minTime,maxTime); - else - HistObj = []; - end - end - end - methods (Access = private) - function cov = computeNSTHistoryWindow(HistObj,nst,historyNum,tn) - if(nargin<4) - tn=[]; - end - if(nargin<3) - historyNum=[]; - end - - s = nst.getSigRep; - tmin=HistObj.windowTimes(1:end-1); - tmax=HistObj.windowTimes(2:end); - %get signal representionat from nst - %find number of samples to first point in history window - %find number of sample to second.... - data=[]; - dataLabels=cell(1,length(tmax)); - for i=1:length(tmax) - a=1; - -% b=zeros(1,s.findNearestTimeIndex(tmax(i))); - NumSamples = ceil(tmax(i)*nst.sampleRate); - b=zeros(1,NumSamples); - StartSample = ceil(tmin(i)*nst.sampleRate) +1; -% b(s.findNearestTimeIndex(tmin(i)):(s.findNearestTimeIndex(tmax(i))-1))=1; - - b(StartSample:NumSamples)=1; - sTemp = s.filter(b,a); - %Delay by 1 to make lag the actual spike - bdelay=[0 1]; adelay=1; - sOut{i} = sTemp.filter(bdelay,adelay); - data=[data, sOut{i}.dataToMatrix]; - if(isempty(historyNum)) - dataLabels{i} = strcat('[',num2str(tmin(i),3),',',num2str(tmax(i),3),']'); - else - dataLabels{i} = strcat('[',num2str(tmin(i),3),',',num2str(tmax(i),3),']_',num2str(historyNum)); - end - end - %name =['History \; for \;', s.name]; %w\; is a thick space in latex - if(isempty(nst.name)) - name = 'History'; - else - name =['History ' nst.name]; - end - xlabelval = s.xlabelval; - xunits = s.xunits; - yunits = s.yunits; - - - if(~isempty(data)) - if(~isempty(tn)) - - cov = Covariate(s.time, data, name, xlabelval,xunits,yunits,dataLabels); - dataVals = cov.getValueAt(tn); -% figure(2); cov.plot; hold on; plot(tn-1/s.sampleRate, dataVals,'o'); pause(.001); -% cov = Covariate(tn-1/s.sampleRate, dataVals, name, xlabelval,xunits,yunits,dataLabels); -% - - else - cov = Covariate(s.time, data, name, xlabelval,xunits,yunits,dataLabels); - %Window the data if minTime and maxTime have been set. - minTime=HistObj.minTime; - maxTime=HistObj.maxTime; - if(isempty(minTime)) - minTime=cov.minTime; - end - if(isempty(maxTime)) - maxTime=cov.maxTime; - end - cov.resample(nst.sampleRate); - wCov=cov.getSigInTimeWindow(minTime,maxTime); - wCov.setMinTime(nst.minTime); - wCov.setMaxTime(nst.maxTime); - cov=wCov; - end - - - else - cov = Covariate([], data, name, xlabelval,xunits,yunits,dataLabels); - end - - - - - - - %size(data) - end - end - - -end - diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 466532f4..00000000 --- a/LICENSE +++ /dev/null @@ -1,339 +0,0 @@ -GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - Neural Spike Train Analysis Toolbox for Matlab - Copyright (C) 2013 wqmalik - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - {signature of Ty Coon}, 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. diff --git a/PointProcessSimulation.mdl.r2010b b/PointProcessSimulation.mdl.r2010b deleted file mode 100644 index 7355091d..00000000 --- a/PointProcessSimulation.mdl.r2010b +++ /dev/null @@ -1,1283 +0,0 @@ -Model { - Name "PointProcessSimulation" - Version 7.6 - MdlSubVersion 0 - GraphicalInterface { - NumRootInports 2 - Inport { - BusObject "" - SignalName "input" - Name "Stimulus" - } - Inport { - BusObject "" - Name "Ensemble" - } - NumRootOutports 1 - Outport { - BusObject "" - BusOutputAsStruct "off" - SignalName "spike process" - Name "pp" - } - ParameterArgumentNames "" - ComputedModelVersion "1.24" - NumModelReferences 0 - NumTestPointedSignals 0 - } - SavedCharacterEncoding "windows-1252" - SaveDefaultBlockParams on - ScopeRefreshTime 0.035000 - OverrideScopeRefreshTime on - DisableAllScopes off - DataTypeOverride "UseLocalSettings" - DataTypeOverrideAppliesTo "AllNumericTypes" - MinMaxOverflowLogging "UseLocalSettings" - MinMaxOverflowArchiveMode "Overwrite" - MaxMDLFileLineLength 120 - Created "Tue Feb 08 12:34:27 2011" - Creator "Developer" - UpdateHistory "UpdateHistoryNever" - ModifiedByFormat "%" - LastModifiedBy "Developer" - ModifiedDateFormat "%" - LastModifiedDate "Wed Feb 09 16:22:36 2011" - RTWModifiedTimeStamp 219161955 - ModelVersionFormat "1.%" - ConfigurationManager "None" - SampleTimeColors off - SampleTimeAnnotations off - LibraryLinkDisplay "none" - WideLines off - ShowLineDimensions off - ShowPortDataTypes off - ShowLoopsOnError on - IgnoreBidirectionalLines off - ShowStorageClass off - ShowTestPointIcons on - ShowSignalResolutionIcons on - ShowViewerIcons on - SortedOrder off - ExecutionContextIcon off - ShowLinearizationAnnotations on - BlockNameDataTip off - BlockParametersDataTip off - BlockDescriptionStringDataTip off - ToolBar on - StatusBar on - BrowserShowLibraryLinks off - BrowserLookUnderMasks off - SimulationMode "normal" - LinearizationMsg "none" - Profile off - ParamWorkspaceSource "MATLABWorkspace" - AccelSystemTargetFile "accel.tlc" - AccelTemplateMakefile "accel_default_tmf" - AccelMakeCommand "make_rtw" - TryForcingSFcnDF off - RecordCoverage off - CovPath "/" - CovSaveName "covdata" - CovMetricSettings "dw" - CovNameIncrementing off - CovHtmlReporting on - CovForceBlockReductionOff on - covSaveCumulativeToWorkspaceVar on - CovSaveSingleToWorkspaceVar on - CovCumulativeVarName "covCumulativeData" - CovCumulativeReport off - CovReportOnPause on - CovModelRefEnable "Off" - CovExternalEMLEnable off - ExtModeBatchMode off - ExtModeEnableFloating on - ExtModeTrigType "manual" - ExtModeTrigMode "normal" - ExtModeTrigPort "1" - ExtModeTrigElement "any" - ExtModeTrigDuration 1000 - ExtModeTrigDurationFloating "auto" - ExtModeTrigHoldOff 0 - ExtModeTrigDelay 0 - ExtModeTrigDirection "rising" - ExtModeTrigLevel 0 - ExtModeArchiveMode "off" - ExtModeAutoIncOneShot off - ExtModeIncDirWhenArm off - ExtModeAddSuffixToVar off - ExtModeWriteAllDataToWs off - ExtModeArmWhenConnect on - ExtModeSkipDownloadWhenConnect off - ExtModeLogAll on - ExtModeAutoUpdateStatusClock on - BufferReuse on - ShowModelReferenceBlockVersion off - ShowModelReferenceBlockIO off - Array { - Type "Handle" - Dimension 1 - Simulink.ConfigSet { - $ObjectID 1 - Version "1.10.0" - Array { - Type "Handle" - Dimension 8 - Simulink.SolverCC { - $ObjectID 2 - Version "1.10.0" - StartTime "0.0" - StopTime "10" - AbsTol "auto" - FixedStep "Ts" - InitialStep "auto" - MaxNumMinSteps "-1" - MaxOrder 5 - ZcThreshold "auto" - ConsecutiveZCsStepRelTol "10*128*eps" - MaxConsecutiveZCs "1000" - ExtrapolationOrder 4 - NumberNewtonIterations 1 - MaxStep "auto" - MinStep "auto" - MaxConsecutiveMinStep "1" - RelTol "1e-3" - SolverMode "Auto" - ConcurrentTasks off - Solver "FixedStepDiscrete" - SolverName "FixedStepDiscrete" - SolverJacobianMethodControl "auto" - ShapePreserveControl "DisableAll" - ZeroCrossControl "UseLocalSettings" - ZeroCrossAlgorithm "Nonadaptive" - AlgebraicLoopSolver "TrustRegion" - SolverResetMethod "Fast" - PositivePriorityOrder off - AutoInsertRateTranBlk off - SampleTimeConstraint "Unconstrained" - InsertRTBMode "Whenever possible" - } - Simulink.DataIOCC { - $ObjectID 3 - Version "1.10.0" - Decimation "1" - ExternalInput "[t, u]" - FinalStateName "xFinal" - InitialState "xInitial" - LimitDataPoints on - MaxDataPoints "1000" - LoadExternalInput off - LoadInitialState off - SaveFinalState off - SaveCompleteFinalSimState off - SaveFormat "Array" - SaveOutput on - SaveState off - SignalLogging on - DSMLogging on - InspectSignalLogs off - SaveTime on - ReturnWorkspaceOutputs off - StateSaveName "xout" - TimeSaveName "tout" - OutputSaveName "yout" - SignalLoggingName "logsout" - DSMLoggingName "dsmout" - OutputOption "RefineOutputTimes" - OutputTimes "[]" - ReturnWorkspaceOutputsName "out" - Refine "1" - } - Simulink.OptimizationCC { - $ObjectID 4 - Version "1.10.0" - Array { - Type "Cell" - Dimension 8 - Cell "BooleansAsBitfields" - Cell "PassReuseOutputArgsAs" - Cell "PassReuseOutputArgsThreshold" - Cell "ZeroExternalMemoryAtStartup" - Cell "ZeroInternalMemoryAtStartup" - Cell "OptimizeModelRefInitCode" - Cell "NoFixptDivByZeroProtection" - Cell "UseSpecifiedMinMax" - PropName "DisabledProps" - } - BlockReduction on - BooleanDataType on - ConditionallyExecuteInputs on - InlineParams off - UseIntDivNetSlope off - UseSpecifiedMinMax off - InlineInvariantSignals off - OptimizeBlockIOStorage on - BufferReuse on - EnhancedBackFolding off - StrengthReduction off - ExpressionFolding on - BooleansAsBitfields off - BitfieldContainerType "uint_T" - EnableMemcpy on - MemcpyThreshold 64 - PassReuseOutputArgsAs "Structure reference" - ExpressionDepthLimit 2147483647 - FoldNonRolledExpr on - LocalBlockOutputs on - RollThreshold 5 - SystemCodeInlineAuto off - StateBitsets off - DataBitsets off - UseTempVars off - ZeroExternalMemoryAtStartup on - ZeroInternalMemoryAtStartup on - InitFltsAndDblsToZero off - NoFixptDivByZeroProtection off - EfficientFloat2IntCast off - EfficientMapNaN2IntZero on - OptimizeModelRefInitCode off - LifeSpan "inf" - MaxStackSize "Inherit from target" - BufferReusableBoundary on - SimCompilerOptimization "Off" - AccelVerboseBuild off - } - Simulink.DebuggingCC { - $ObjectID 5 - Version "1.10.0" - RTPrefix "error" - ConsistencyChecking "none" - ArrayBoundsChecking "none" - SignalInfNanChecking "none" - SignalRangeChecking "none" - ReadBeforeWriteMsg "UseLocalSettings" - WriteAfterWriteMsg "UseLocalSettings" - WriteAfterReadMsg "UseLocalSettings" - AlgebraicLoopMsg "warning" - ArtificialAlgebraicLoopMsg "warning" - SaveWithDisabledLinksMsg "warning" - SaveWithParameterizedLinksMsg "warning" - CheckSSInitialOutputMsg on - UnderspecifiedInitializationDetection "Classic" - MergeDetectMultiDrivingBlocksExec "none" - CheckExecutionContextPreStartOutputMsg off - CheckExecutionContextRuntimeOutputMsg off - SignalResolutionControl "UseLocalSettings" - BlockPriorityViolationMsg "warning" - MinStepSizeMsg "warning" - TimeAdjustmentMsg "none" - MaxConsecutiveZCsMsg "error" - MaskedZcDiagnostic "warning" - IgnoredZcDiagnostic "warning" - SolverPrmCheckMsg "warning" - InheritedTsInSrcMsg "warning" - DiscreteInheritContinuousMsg "warning" - MultiTaskDSMMsg "error" - MultiTaskCondExecSysMsg "error" - MultiTaskRateTransMsg "error" - SingleTaskRateTransMsg "none" - TasksWithSamePriorityMsg "warning" - SigSpecEnsureSampleTimeMsg "warning" - CheckMatrixSingularityMsg "none" - IntegerOverflowMsg "warning" - Int32ToFloatConvMsg "warning" - ParameterDowncastMsg "error" - ParameterOverflowMsg "error" - ParameterUnderflowMsg "none" - ParameterPrecisionLossMsg "warning" - ParameterTunabilityLossMsg "warning" - FixptConstUnderflowMsg "none" - FixptConstOverflowMsg "none" - FixptConstPrecisionLossMsg "none" - UnderSpecifiedDataTypeMsg "none" - UnnecessaryDatatypeConvMsg "none" - VectorMatrixConversionMsg "none" - InvalidFcnCallConnMsg "error" - FcnCallInpInsideContextMsg "Use local settings" - SignalLabelMismatchMsg "none" - UnconnectedInputMsg "warning" - UnconnectedOutputMsg "warning" - UnconnectedLineMsg "warning" - SFcnCompatibilityMsg "none" - UniqueDataStoreMsg "none" - BusObjectLabelMismatch "warning" - RootOutportRequireBusObject "warning" - AssertControl "UseLocalSettings" - EnableOverflowDetection off - ModelReferenceIOMsg "none" - ModelReferenceMultiInstanceNormalModeStructChecksumCheck "error" - ModelReferenceVersionMismatchMessage "none" - ModelReferenceIOMismatchMessage "none" - ModelReferenceCSMismatchMessage "none" - UnknownTsInhSupMsg "warning" - ModelReferenceDataLoggingMessage "warning" - ModelReferenceSymbolNameMessage "warning" - ModelReferenceExtraNoncontSigs "error" - StateNameClashWarn "warning" - SimStateInterfaceChecksumMismatchMsg "warning" - InitInArrayFormatMsg "warning" - StrictBusMsg "ErrorLevel1" - BusNameAdapt "WarnAndRepair" - NonBusSignalsTreatedAsBus "none" - LoggingUnavailableSignals "error" - BlockIODiagnostic "none" - SFUnusedDataAndEventsDiag "warning" - SFUnexpectedBacktrackingDiag "warning" - SFInvalidInputDataAccessInChartInitDiag "warning" - SFNoUnconditionalDefaultTransitionDiag "warning" - SFTransitionOutsideNaturalParentDiag "warning" - } - Simulink.HardwareCC { - $ObjectID 6 - Version "1.10.0" - ProdBitPerChar 8 - ProdBitPerShort 16 - ProdBitPerInt 32 - ProdBitPerLong 32 - ProdBitPerFloat 32 - ProdBitPerDouble 64 - ProdBitPerPointer 32 - ProdLargestAtomicInteger "Char" - ProdLargestAtomicFloat "None" - ProdIntDivRoundTo "Undefined" - ProdEndianess "Unspecified" - ProdWordSize 32 - ProdShiftRightIntArith on - ProdHWDeviceType "32-bit Generic" - TargetBitPerChar 8 - TargetBitPerShort 16 - TargetBitPerInt 32 - TargetBitPerLong 32 - TargetBitPerFloat 32 - TargetBitPerDouble 64 - TargetBitPerPointer 32 - TargetLargestAtomicInteger "Char" - TargetLargestAtomicFloat "None" - TargetShiftRightIntArith on - TargetIntDivRoundTo "Zero" - TargetEndianess "LittleEndian" - TargetWordSize 32 - TargetTypeEmulationWarnSuppressLevel 0 - TargetPreprocMaxBitsSint 32 - TargetPreprocMaxBitsUint 32 - TargetHWDeviceType "MATLAB Host" - TargetUnknown off - ProdEqTarget off - } - Simulink.ModelReferenceCC { - $ObjectID 7 - Version "1.10.0" - UpdateModelReferenceTargets "IfOutOfDateOrStructuralChange" - CheckModelReferenceTargetMessage "error" - EnableParallelModelReferenceBuilds off - ParallelModelReferenceErrorOnInvalidPool on - ParallelModelReferenceMATLABWorkerInit "None" - ModelReferenceNumInstancesAllowed "Multi" - PropagateVarSize "Infer from blocks in model" - ModelReferencePassRootInputsByReference on - ModelReferenceMinAlgLoopOccurrences off - PropagateSignalLabelsOutOfModel off - SupportModelReferenceSimTargetCustomCode off - } - Simulink.SFSimCC { - $ObjectID 8 - Version "1.10.0" - SFSimEnableDebug on - SFSimOverflowDetection on - SFSimEcho on - SimBlas on - SimCtrlC on - SimExtrinsic on - SimIntegrity on - SimUseLocalCustomCode off - SimParseCustomCode on - SimBuildMode "sf_incremental_build" - } - Simulink.RTWCC { - $BackupClass "Simulink.RTWCC" - $ObjectID 9 - Version "1.10.0" - Array { - Type "Cell" - Dimension 7 - Cell "IncludeHyperlinkInReport" - Cell "GenerateTraceInfo" - Cell "GenerateTraceReport" - Cell "GenerateTraceReportSl" - Cell "GenerateTraceReportSf" - Cell "GenerateTraceReportEml" - Cell "GenerateSLWebview" - PropName "DisabledProps" - } - SystemTargetFile "grt.tlc" - GenCodeOnly off - MakeCommand "make_rtw" - GenerateMakefile on - TemplateMakefile "grt_default_tmf" - Description "Generic Real-Time Target" - GenerateReport off - SaveLog off - RTWVerbose on - RetainRTWFile off - ProfileTLC off - TLCDebug off - TLCCoverage off - TLCAssert off - ProcessScriptMode "Default" - ConfigurationMode "Optimized" - ProcessScript "grt_make_rtw_hook" - ConfigAtBuild off - RTWUseLocalCustomCode off - RTWUseSimCustomCode off - IncludeHyperlinkInReport off - LaunchReport off - TargetLang "C" - IncludeBusHierarchyInRTWFileBlockHierarchyMap off - IncludeERTFirstTime off - GenerateTraceInfo off - GenerateTraceReport off - GenerateTraceReportSl off - GenerateTraceReportSf off - GenerateTraceReportEml off - GenerateCodeInfo off - GenerateSLWebview off - RTWCompilerOptimization "On" - CheckMdlBeforeBuild "Off" - CustomRebuildMode "OnUpdate" - Array { - Type "Handle" - Dimension 2 - Simulink.CodeAppCC { - $ObjectID 10 - Version "1.10.0" - Array { - Type "Cell" - Dimension 21 - Cell "IgnoreCustomStorageClasses" - Cell "IgnoreTestpoints" - Cell "InsertBlockDesc" - Cell "InsertPolySpaceComments" - Cell "SFDataObjDesc" - Cell "MATLABFcnDesc" - Cell "SimulinkDataObjDesc" - Cell "DefineNamingRule" - Cell "SignalNamingRule" - Cell "ParamNamingRule" - Cell "InlinedPrmAccess" - Cell "CustomSymbolStr" - Cell "CustomSymbolStrGlobalVar" - Cell "CustomSymbolStrType" - Cell "CustomSymbolStrField" - Cell "CustomSymbolStrFcn" - Cell "CustomSymbolStrFcnArg" - Cell "CustomSymbolStrBlkIO" - Cell "CustomSymbolStrTmpVar" - Cell "CustomSymbolStrMacro" - Cell "ReqsInCode" - PropName "DisabledProps" - } - ForceParamTrailComments off - GenerateComments on - IgnoreCustomStorageClasses on - IgnoreTestpoints off - IncHierarchyInIds off - MaxIdLength 31 - PreserveName off - PreserveNameWithParent off - ShowEliminatedStatement off - IncAutoGenComments off - SimulinkDataObjDesc off - SFDataObjDesc off - MATLABFcnDesc off - IncDataTypeInIds off - MangleLength 1 - CustomSymbolStrGlobalVar "$R$N$M" - CustomSymbolStrType "$N$R$M" - CustomSymbolStrField "$N$M" - CustomSymbolStrFcn "$R$N$M$F" - CustomSymbolStrFcnArg "rt$I$N$M" - CustomSymbolStrBlkIO "rtb_$N$M" - CustomSymbolStrTmpVar "$N$M" - CustomSymbolStrMacro "$R$N$M" - DefineNamingRule "None" - ParamNamingRule "None" - SignalNamingRule "None" - InsertBlockDesc off - InsertPolySpaceComments off - SimulinkBlockComments on - MATLABSourceComments off - EnableCustomComments off - InlinedPrmAccess "Literals" - ReqsInCode off - UseSimReservedNames off - } - Simulink.GRTTargetCC { - $BackupClass "Simulink.TargetCC" - $ObjectID 11 - Version "1.10.0" - Array { - Type "Cell" - Dimension 16 - Cell "GeneratePreprocessorConditionals" - Cell "IncludeMdlTerminateFcn" - Cell "CombineOutputUpdateFcns" - Cell "SuppressErrorStatus" - Cell "ERTCustomFileBanners" - Cell "GenerateSampleERTMain" - Cell "GenerateTestInterfaces" - Cell "ModelStepFunctionPrototypeControlCompliant" - Cell "CPPClassGenCompliant" - Cell "MultiInstanceERTCode" - Cell "PurelyIntegerCode" - Cell "SupportComplex" - Cell "SupportAbsoluteTime" - Cell "SupportContinuousTime" - Cell "SupportNonInlinedSFcns" - Cell "PortableWordSizes" - PropName "DisabledProps" - } - TargetFcnLib "ansi_tfl_table_tmw.mat" - TargetLibSuffix "" - TargetPreCompLibLocation "" - TargetFunctionLibrary "ANSI_C" - UtilityFuncGeneration "Auto" - ERTMultiwordTypeDef "System defined" - ERTCodeCoverageTool "None" - ERTMultiwordLength 256 - MultiwordLength 2048 - GenerateFullHeader on - GenerateSampleERTMain off - GenerateTestInterfaces off - IsPILTarget off - ModelReferenceCompliant on - ParMdlRefBuildCompliant on - CompOptLevelCompliant on - IncludeMdlTerminateFcn on - GeneratePreprocessorConditionals "Disable all" - CombineOutputUpdateFcns off - CombineSignalStateStructs off - SuppressErrorStatus off - ERTFirstTimeCompliant off - IncludeFileDelimiter "Auto" - ERTCustomFileBanners off - SupportAbsoluteTime on - LogVarNameModifier "rt_" - MatFileLogging on - MultiInstanceERTCode off - SupportNonFinite on - SupportComplex on - PurelyIntegerCode off - SupportContinuousTime on - SupportNonInlinedSFcns on - SupportVariableSizeSignals off - EnableShiftOperators on - ParenthesesLevel "Nominal" - PortableWordSizes off - ModelStepFunctionPrototypeControlCompliant off - CPPClassGenCompliant off - AutosarCompliant off - UseMalloc off - ExtMode off - ExtModeStaticAlloc off - ExtModeTesting off - ExtModeStaticAllocSize 1000000 - ExtModeTransport 0 - ExtModeMexFile "ext_comm" - ExtModeIntrfLevel "Level1" - RTWCAPISignals off - RTWCAPIParams off - RTWCAPIStates off - GenerateASAP2 off - } - PropName "Components" - } - } - PropName "Components" - } - Name "Configuration" - CurrentDlgPage "Optimization" - ConfigPrmDlgPosition " [ 360, 285, 1498, 915 ] " - } - PropName "ConfigurationSets" - } - Simulink.ConfigSet { - $PropName "ActiveConfigurationSet" - $ObjectID 1 - } - BlockDefaults { - ForegroundColor "black" - BackgroundColor "white" - DropShadow off - NamePlacement "normal" - FontName "Helvetica" - FontSize 10 - FontWeight "normal" - FontAngle "normal" - ShowName on - BlockRotation 0 - BlockMirror off - } - AnnotationDefaults { - HorizontalAlignment "center" - VerticalAlignment "middle" - ForegroundColor "black" - BackgroundColor "white" - DropShadow off - FontName "Helvetica" - FontSize 10 - FontWeight "normal" - FontAngle "normal" - UseDisplayTextAsClickCallback off - } - LineDefaults { - FontName "Helvetica" - FontSize 9 - FontWeight "normal" - FontAngle "normal" - } - BlockParameterDefaults { - Block { - BlockType Constant - Value "1" - VectorParams1D on - SamplingMode "Sample based" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Inherit from 'Constant value'" - LockScale off - SampleTime "inf" - FramePeriod "inf" - PreserveConstantTs off - } - Block { - BlockType FrameConversion - InheritSamplingMode off - OutFrame "Frame-based" - } - Block { - BlockType Inport - Port "1" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: auto" - LockScale off - BusOutputAsStruct off - PortDimensions "-1" - VarSizeSig "Inherit" - SampleTime "-1" - SignalType "auto" - SamplingMode "auto" - LatchByDelayingOutsideSignal off - LatchInputForFeedbackSignals off - Interpolate on - } - Block { - BlockType Math - Operator "exp" - OutputSignalType "auto" - SampleTime "-1" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Same as first input" - LockScale off - RndMeth "Floor" - SaturateOnIntegerOverflow on - IntermediateResultsDataTypeStr "Inherit: Inherit via internal rule" - AlgorithmType "Newton-Raphson" - Iterations "3" - } - Block { - BlockType Outport - Port "1" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: auto" - LockScale off - BusOutputAsStruct off - PortDimensions "-1" - VarSizeSig "Inherit" - SampleTime "-1" - SignalType "auto" - SamplingMode "auto" - SourceOfInitialOutputValue "Dialog" - OutputWhenDisabled "held" - InitialOutput "[]" - } - Block { - BlockType Product - Inputs "2" - Multiplication "Element-wise(.*)" - CollapseMode "All dimensions" - CollapseDim "1" - InputSameDT on - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Same as first input" - LockScale off - RndMeth "Zero" - SaturateOnIntegerOverflow on - SampleTime "-1" - } - Block { - BlockType RelationalOperator - Operator ">=" - InputSameDT on - OutDataTypeStr "Inherit: Logical (see Configuration Parameters: Optimization)" - ZeroCross on - SampleTime "-1" - } - Block { - BlockType Reshape - OutputDimensionality "1-D array" - OutputDimensions "[1,1]" - } - Block { - BlockType SignalViewerScope - Floating off - ModelBased off - TickLabels "OneTimeTick" - ZoomMode "on" - Grid "on" - TimeRange "auto" - YMin "-5" - YMax "5" - SaveToWorkspace off - SaveName "ScopeData" - LimitDataPoints on - MaxDataPoints "5000" - Decimation "1" - SampleInput off - SampleTime "0" - Disabled off - ScrollMode on - } - Block { - BlockType Sum - IconShape "rectangular" - Inputs "++" - CollapseMode "All dimensions" - CollapseDim "1" - InputSameDT on - AccumDataTypeStr "Inherit: Inherit via internal rule" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Same as first input" - LockScale off - RndMeth "Floor" - SaturateOnIntegerOverflow on - SampleTime "-1" - } - } - System { - Name "PointProcessSimulation" - Location [2, 93, 1598, 1137] - Open on - ModelBrowserVisibility off - ModelBrowserWidth 200 - ScreenColor "white" - PaperOrientation "landscape" - PaperPositionMode "auto" - PaperType "usletter" - PaperUnits "inches" - TiledPaperMargins [0.500000, 0.500000, 0.500000, 0.500000] - TiledPageScale 1 - ShowPageBoundaries off - ZoomFactor "100" - ReportName "simulink-default.rpt" - SIDHighWatermark "44" - Block { - BlockType Inport - Name "Stimulus" - SID "37" - Position [245, 323, 275, 337] - IconDisplay "Port number" - Port { - PortNumber 1 - Name "input" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Inport - Name "Ensemble" - SID "44" - Position [245, 398, 275, 412] - Port "2" - IconDisplay "Port number" - } - Block { - BlockType Sum - Name "Add" - SID "3" - Ports [4, 1] - Position [575, 250, 605, 290] - Inputs "++++" - InputSameDT off - OutDataTypeStr "Inherit: Inherit via internal rule" - SaturateOnIntegerOverflow off - } - Block { - BlockType Sum - Name "Add1" - SID "32" - Ports [2, 1] - Position [740, 335, 770, 365] - IconShape "round" - Inputs "|++" - InputSameDT off - OutDataTypeStr "Inherit: Inherit via internal rule" - SaturateOnIntegerOverflow off - } - Block { - BlockType Constant - Name "Constant" - SID "1" - Position [515, 175, 545, 205] - BlockRotation 270 - BlockMirror on - BackgroundColor "magenta" - NamePlacement "alternate" - Value "mu" - } - Block { - BlockType Constant - Name "Constant1" - SID "33" - Position [740, 425, 770, 455] - BlockRotation 270 - BackgroundColor "magenta" - } - Block { - BlockType Product - Name "Divide" - SID "31" - Ports [2, 1] - Position [815, 252, 845, 283] - Inputs "*/" - InputSameDT off - OutDataTypeStr "Inherit: Inherit via internal rule" - RndMeth "Floor" - SaturateOnIntegerOverflow off - Port { - PortNumber 1 - Name "s2" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Reference - Name "Ensemble Effect" - SID "43" - Ports [1, 1] - Position [410, 387, 505, 423] - BackgroundColor "darkGreen" - LibraryVersion "1.107" - SourceBlock "cstblocks/LTI System" - SourceType "LTI Block" - ShowPortLabels "FromPortIcon" - SystemSampleTime "-1" - FunctionWithSeparateData off - RTWMemSecFuncInitTerm "Inherit from model" - RTWMemSecFuncExecute "Inherit from model" - RTWMemSecDataConstants "Inherit from model" - RTWMemSecDataInternal "Inherit from model" - RTWMemSecDataParameters "Inherit from model" - GeneratePreprocessorConditionals off - sys "E" - IC "[]" - } - Block { - BlockType FrameConversion - Name "Frame Status Conversion" - SID "11" - Ports [1, 1] - Position [1125, 260, 1180, 300] - OutFrame "Sample-based" - } - Block { - BlockType Reference - Name "Integer Delay" - SID "22" - Ports [1, 1] - Position [410, 123, 445, 157] - BlockMirror on - LibraryVersion "1.225" - UserDataPersistent on - UserData "DataTag0" - SourceBlock "simulink/Discrete/Integer Delay" - SourceType "Integer Delay" - NumDelays "1" - InputProcessing "Elements as channels (sample based)" - vinit "0.0" - samptime "-1" - } - Block { - BlockType Math - Name "Math\nFunction" - SID "8" - Ports [1, 1] - Position [675, 255, 705, 285] - Port { - PortNumber 1 - Name "s1" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Reference - Name "Random Source" - SID "12" - Ports [0, 1] - Position [986, 360, 1024, 395] - BlockRotation 270 - LibraryVersion "1.710" - UserDataPersistent on - UserData "DataTag1" - Diagnostics "AllowInheritedTsInSrc" - SourceBlock "dspsrcs4/Random\nSource" - SourceType "Random Source" - SrcType "Uniform" - NormMethod "Ziggurat" - CltLength "12" - MinVal "0" - MaxVal "1" - MeanVal "0" - VarVal "1" - RepMode "Not repeatable" - rawSeed "seed" - IsInherit on - SampMode "Continuous" - SampTime "Ts" - SampFrame "dsp_sampFrame" - DataType "Double" - OutComplex "Real" - } - Block { - BlockType RelationalOperator - Name "Relational Operator" - SID "13" - Ports [2, 1] - Position [1030, 262, 1060, 293] - ShowName off - Operator ">" - OutDataTypeStr "float('double')" - } - Block { - BlockType Reshape - Name "Reshape" - SID "14" - Ports [1, 1] - Position [1220, 268, 1250, 292] - ShowName off - OutputDimensions "[sampPerFrame,max(length(P),length(seed))]" - Port { - PortNumber 1 - Name "spike process" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Reference - Name "Self-History" - SID "5" - Ports [1, 1] - Position [410, 247, 505, 283] - BackgroundColor "orange" - LibraryVersion "1.107" - SourceBlock "cstblocks/LTI System" - SourceType "LTI Block" - ShowPortLabels "FromPortIcon" - SystemSampleTime "-1" - FunctionWithSeparateData off - RTWMemSecFuncInitTerm "Inherit from model" - RTWMemSecFuncExecute "Inherit from model" - RTWMemSecDataConstants "Inherit from model" - RTWMemSecDataInternal "Inherit from model" - RTWMemSecDataParameters "Inherit from model" - GeneratePreprocessorConditionals off - sys "H" - IC "[]" - } - Block { - BlockType Reference - Name "Stimulus Effect" - SID "6" - Ports [1, 1] - Position [410, 312, 505, 348] - BackgroundColor "darkGreen" - LibraryVersion "1.107" - SourceBlock "cstblocks/LTI System" - SourceType "LTI Block" - ShowPortLabels "FromPortIcon" - SystemSampleTime "-1" - FunctionWithSeparateData off - RTWMemSecFuncInitTerm "Inherit from model" - RTWMemSecFuncExecute "Inherit from model" - RTWMemSecDataConstants "Inherit from model" - RTWMemSecDataInternal "Inherit from model" - RTWMemSecDataParameters "Inherit from model" - GeneratePreprocessorConditionals off - sys "S" - IC "[]" - } - Block { - BlockType Outport - Name "pp" - SID "26" - Position [1310, 273, 1340, 287] - IconDisplay "Port number" - } - Block { - BlockType SignalViewerScope - Name "Scope" - SID "28" - Ports [] - Position [20, 15, 60, 55] - IOType "viewer" - List { - ListType IOSignalStrings - set0ParseKeys "10,18" - set0Sigs "Reshape:o1Stimulus Effect:o1" - } - Location [1, 53, 1601, 1151] - Open off - NumInputPorts "1" - List { - ListType AxesTitles - axes1 "%" - } - ShowDataMarkers off - ShowLegends off - DataFormat "Array" - MaxDataPoints "7500" - RefreshTime 0.035000 - } - Block { - BlockType SignalViewerScope - Name "Scope1" - SID "29" - Ports [] - Position [20, 15, 60, 55] - IOType "viewer" - List { - ListType IOSignalStrings - set0ParseKeys "16,9" - set0Sigs "Math Function:o1Divide:o1" - } - Location [1, 53, 1601, 1151] - Open off - NumInputPorts "1" - List { - ListType AxesTitles - axes1 "%" - } - ShowDataMarkers off - ShowLegends off - SaveName "ScopeData1" - DataFormat "Array" - MaxDataPoints "7500" - RefreshTime 0.035000 - } - Block { - BlockType SignalViewerScope - Name "Scope2" - SID "38" - Ports [] - Position [20, 15, 60, 55] - IOType "viewer" - List { - ListType IOSignalStrings - set0ParseKeys "15" - set0Sigs "Self-History:o1" - } - Location [5, 53, 1605, 1151] - Open off - NumInputPorts "1" - List { - ListType AxesTitles - axes1 "%" - } - ShowDataMarkers off - ShowLegends off - SaveName "ScopeData2" - DataFormat "Array" - MaxDataPoints "7500" - RefreshTime 0.035000 - } - Line { - SrcBlock "Constant" - SrcPort 1 - Points [0, 45] - DstBlock "Add" - DstPort 1 - } - Line { - SrcBlock "Self-History" - SrcPort 1 - DstBlock "Add" - DstPort 2 - } - Line { - SrcBlock "Stimulus Effect" - SrcPort 1 - Points [15, 0; 0, -55] - DstBlock "Add" - DstPort 3 - } - Line { - SrcBlock "Add" - SrcPort 1 - DstBlock "Math\nFunction" - DstPort 1 - } - Line { - SrcBlock "Frame Status Conversion" - SrcPort 1 - DstBlock "Reshape" - DstPort 1 - } - Line { - Name "spike process" - SrcBlock "Reshape" - SrcPort 1 - Points [25, 0] - Branch { - Labels [1, 0] - Points [0, -140] - DstBlock "Integer Delay" - DstPort 1 - } - Branch { - DstBlock "pp" - DstPort 1 - } - } - Line { - SrcBlock "Relational Operator" - SrcPort 1 - DstBlock "Frame Status Conversion" - DstPort 1 - } - Line { - SrcBlock "Random Source" - SrcPort 1 - Points [0, -70] - DstBlock "Relational Operator" - DstPort 2 - } - Line { - Name "input" - Labels [0, 0] - SrcBlock "Stimulus" - SrcPort 1 - DstBlock "Stimulus Effect" - DstPort 1 - } - Line { - SrcBlock "Integer Delay" - SrcPort 1 - Points [-65, 0; 0, 125] - DstBlock "Self-History" - DstPort 1 - } - Line { - SrcBlock "Constant1" - SrcPort 1 - DstBlock "Add1" - DstPort 2 - } - Line { - Name "s1" - Labels [0, 0; 0, 0] - SrcBlock "Math\nFunction" - SrcPort 1 - Points [5, 0] - Branch { - Points [0, 80] - DstBlock "Add1" - DstPort 1 - } - Branch { - Labels [1, 0] - Points [85, 0] - DstBlock "Divide" - DstPort 1 - } - } - Line { - SrcBlock "Add1" - SrcPort 1 - Points [10, 0; 0, -75] - DstBlock "Divide" - DstPort 2 - } - Line { - Name "s2" - Labels [0, 0] - SrcBlock "Divide" - SrcPort 1 - DstBlock "Relational Operator" - DstPort 1 - } - Line { - SrcBlock "Ensemble" - SrcPort 1 - DstBlock "Ensemble Effect" - DstPort 1 - } - Line { - SrcBlock "Ensemble Effect" - SrcPort 1 - Points [25, 0; 0, -120] - DstBlock "Add" - DstPort 4 - } - Annotation { - Name "GLM Model \n\n " - " \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n. " - Position [414, 261] - BackgroundColor "lightBlue" - FontName "Arial Narrow" - FontSize 18 - } - Annotation { - Name "Coin flip with\np= \\lambda \\cdot \\Delta\n\n\n\n\n\n\n\n\n\n\n." - Position [1034, 356] - Interpreter "tex" - FontName "Arial Narrow" - FontSize 18 - } - Annotation { - Name "Inverse of Logistic Link Function\n \n\n\n\n\n\n\n" - "\n\n\n. " - Position [769, 346] - BackgroundColor "yellow" - FontName "Arial Narrow" - FontSize 18 - } - Annotation { - Name "\\lambda \\cdot \\Delta= e^{X \\cdot \\beta}/(1+e^{X\\cdot \\beta})" - Position [759, 496] - Interpreter "tex" - FontName "Arial Narrow" - FontSize 18 - } - } -} -MatData { - NumRecords 2 - DataRecord { - Tag DataTag1 - Data " %)30 . V 8 ( @ % \" $ ! 0 % 0 \"0 $ 2 4V5E9" - " 4V5E9$9L86< #@ #@ & \" 0 !0 @ ! !0 $ $ 4 R,S$Q,P " - "X ! !@ @ $ 4 ( 0 T ! ! - 1&].;W13879E4V5E9 " - } - DataRecord { - Tag DataTag0 - Data " %)30 . B 8 ( @ % \" $ ! 0 % 0 $P $ 3 :&%S26" - "YH97)I=&5D3W!T:6]N #@ # & \" D\" !0 @ ! 0 $ @ ! $ " - } -} diff --git a/PointProcessSimulation.mdl.r2011a b/PointProcessSimulation.mdl.r2011a deleted file mode 100644 index 97bd6160..00000000 --- a/PointProcessSimulation.mdl.r2011a +++ /dev/null @@ -1,1567 +0,0 @@ -Model { - Name "PointProcessSimulation" - Version 7.7 - MdlSubVersion 0 - GraphicalInterface { - NumRootInports 2 - Inport { - BusObject "" - SignalName "input" - Name "Stimulus" - } - Inport { - BusObject "" - Name "Ensemble" - } - NumRootOutports 2 - Outport { - BusObject "" - BusOutputAsStruct "off" - SignalName "spike process" - Name "pp" - } - Outport { - BusObject "" - BusOutputAsStruct "off" - Name "lambdaDelta" - } - ParameterArgumentNames "" - ComputedModelVersion "1.28" - NumModelReferences 0 - NumTestPointedSignals 0 - } - SavedCharacterEncoding "windows-1252" - SaveDefaultBlockParams on - ScopeRefreshTime 0.035000 - OverrideScopeRefreshTime on - DisableAllScopes off - DataTypeOverride "UseLocalSettings" - DataTypeOverrideAppliesTo "AllNumericTypes" - MinMaxOverflowLogging "UseLocalSettings" - MinMaxOverflowArchiveMode "Overwrite" - MaxMDLFileLineLength 120 - Created "Tue Feb 08 12:34:27 2011" - Creator "Developer" - UpdateHistory "UpdateHistoryNever" - ModifiedByFormat "%" - LastModifiedBy "Developer" - ModifiedDateFormat "%" - LastModifiedDate "Thu Oct 20 21:11:06 2011" - RTWModifiedTimeStamp 241044045 - ModelVersionFormat "1.%" - ConfigurationManager "None" - SampleTimeColors off - SampleTimeAnnotations off - LibraryLinkDisplay "none" - WideLines off - ShowLineDimensions off - ShowPortDataTypes off - ShowLoopsOnError on - IgnoreBidirectionalLines off - ShowStorageClass off - ShowTestPointIcons on - ShowSignalResolutionIcons on - ShowViewerIcons on - SortedOrder off - ExecutionContextIcon off - ShowLinearizationAnnotations on - BlockNameDataTip off - BlockParametersDataTip off - BlockDescriptionStringDataTip off - ToolBar on - StatusBar on - BrowserShowLibraryLinks off - BrowserLookUnderMasks off - SimulationMode "normal" - LinearizationMsg "none" - Profile off - ParamWorkspaceSource "MATLABWorkspace" - AccelSystemTargetFile "accel.tlc" - AccelTemplateMakefile "accel_default_tmf" - AccelMakeCommand "make_rtw" - TryForcingSFcnDF off - RecordCoverage off - CovPath "/" - CovSaveName "covdata" - CovMetricSettings "dw" - CovNameIncrementing off - CovHtmlReporting on - CovForceBlockReductionOff on - covSaveCumulativeToWorkspaceVar on - CovSaveSingleToWorkspaceVar on - CovCumulativeVarName "covCumulativeData" - CovCumulativeReport off - CovReportOnPause on - CovModelRefEnable "Off" - CovExternalEMLEnable off - ExtModeBatchMode off - ExtModeEnableFloating on - ExtModeTrigType "manual" - ExtModeTrigMode "normal" - ExtModeTrigPort "1" - ExtModeTrigElement "any" - ExtModeTrigDuration 1000 - ExtModeTrigDurationFloating "auto" - ExtModeTrigHoldOff 0 - ExtModeTrigDelay 0 - ExtModeTrigDirection "rising" - ExtModeTrigLevel 0 - ExtModeArchiveMode "off" - ExtModeAutoIncOneShot off - ExtModeIncDirWhenArm off - ExtModeAddSuffixToVar off - ExtModeWriteAllDataToWs off - ExtModeArmWhenConnect on - ExtModeSkipDownloadWhenConnect off - ExtModeLogAll on - ExtModeAutoUpdateStatusClock on - BufferReuse on - ShowModelReferenceBlockVersion off - ShowModelReferenceBlockIO off - Array { - Type "Handle" - Dimension 1 - Simulink.ConfigSet { - $ObjectID 1 - Version "1.11.0" - Array { - Type "Handle" - Dimension 8 - Simulink.SolverCC { - $ObjectID 2 - Version "1.11.0" - StartTime "0.0" - StopTime "10" - AbsTol "auto" - FixedStep "Ts" - InitialStep "auto" - MaxNumMinSteps "-1" - MaxOrder 5 - ZcThreshold "auto" - ConsecutiveZCsStepRelTol "10*128*eps" - MaxConsecutiveZCs "1000" - ExtrapolationOrder 4 - NumberNewtonIterations 1 - MaxStep "auto" - MinStep "auto" - MaxConsecutiveMinStep "1" - RelTol "1e-3" - SolverMode "Auto" - ConcurrentTasks off - Solver "FixedStepDiscrete" - SolverName "FixedStepDiscrete" - SolverJacobianMethodControl "auto" - ShapePreserveControl "DisableAll" - ZeroCrossControl "UseLocalSettings" - ZeroCrossAlgorithm "Nonadaptive" - AlgebraicLoopSolver "TrustRegion" - SolverResetMethod "Fast" - PositivePriorityOrder off - AutoInsertRateTranBlk off - SampleTimeConstraint "Unconstrained" - InsertRTBMode "Whenever possible" - } - Simulink.DataIOCC { - $ObjectID 3 - Version "1.11.0" - Decimation "1" - ExternalInput "[t, u]" - FinalStateName "xFinal" - InitialState "xInitial" - LimitDataPoints on - MaxDataPoints "1000" - LoadExternalInput off - LoadInitialState off - SaveFinalState off - SaveCompleteFinalSimState off - SaveFormat "Array" - SignalLoggingSaveFormat "ModelDataLogs" - SaveOutput on - SaveState off - SignalLogging on - DSMLogging on - InspectSignalLogs off - SaveTime on - ReturnWorkspaceOutputs off - StateSaveName "xout" - TimeSaveName "tout" - OutputSaveName "yout" - SignalLoggingName "logsout" - DSMLoggingName "dsmout" - OutputOption "RefineOutputTimes" - OutputTimes "[]" - ReturnWorkspaceOutputsName "out" - Refine "1" - } - Simulink.OptimizationCC { - $ObjectID 4 - Version "1.11.0" - Array { - Type "Cell" - Dimension 8 - Cell "BooleansAsBitfields" - Cell "PassReuseOutputArgsAs" - Cell "PassReuseOutputArgsThreshold" - Cell "ZeroExternalMemoryAtStartup" - Cell "ZeroInternalMemoryAtStartup" - Cell "OptimizeModelRefInitCode" - Cell "NoFixptDivByZeroProtection" - Cell "UseSpecifiedMinMax" - PropName "DisabledProps" - } - BlockReduction on - BooleanDataType on - ConditionallyExecuteInputs on - InlineParams off - UseIntDivNetSlope off - UseSpecifiedMinMax off - InlineInvariantSignals off - OptimizeBlockIOStorage on - BufferReuse on - EnhancedBackFolding off - StrengthReduction off - ExpressionFolding on - BooleansAsBitfields off - BitfieldContainerType "uint_T" - EnableMemcpy on - MemcpyThreshold 64 - PassReuseOutputArgsAs "Structure reference" - ExpressionDepthLimit 2147483647 - FoldNonRolledExpr on - LocalBlockOutputs on - RollThreshold 5 - SystemCodeInlineAuto off - StateBitsets off - DataBitsets off - UseTempVars off - ZeroExternalMemoryAtStartup on - ZeroInternalMemoryAtStartup on - InitFltsAndDblsToZero off - NoFixptDivByZeroProtection off - EfficientFloat2IntCast off - EfficientMapNaN2IntZero on - OptimizeModelRefInitCode off - LifeSpan "inf" - MaxStackSize "Inherit from target" - BufferReusableBoundary on - SimCompilerOptimization "Off" - AccelVerboseBuild off - AccelParallelForEachSubsystem on - } - Simulink.DebuggingCC { - $ObjectID 5 - Version "1.11.0" - RTPrefix "error" - ConsistencyChecking "none" - ArrayBoundsChecking "none" - SignalInfNanChecking "none" - SignalRangeChecking "none" - ReadBeforeWriteMsg "UseLocalSettings" - WriteAfterWriteMsg "UseLocalSettings" - WriteAfterReadMsg "UseLocalSettings" - AlgebraicLoopMsg "warning" - ArtificialAlgebraicLoopMsg "warning" - SaveWithDisabledLinksMsg "warning" - SaveWithParameterizedLinksMsg "warning" - CheckSSInitialOutputMsg on - UnderspecifiedInitializationDetection "Classic" - MergeDetectMultiDrivingBlocksExec "none" - CheckExecutionContextPreStartOutputMsg off - CheckExecutionContextRuntimeOutputMsg off - SignalResolutionControl "UseLocalSettings" - BlockPriorityViolationMsg "warning" - MinStepSizeMsg "warning" - TimeAdjustmentMsg "none" - MaxConsecutiveZCsMsg "error" - MaskedZcDiagnostic "warning" - IgnoredZcDiagnostic "warning" - SolverPrmCheckMsg "warning" - InheritedTsInSrcMsg "warning" - DiscreteInheritContinuousMsg "warning" - MultiTaskDSMMsg "error" - MultiTaskCondExecSysMsg "error" - MultiTaskRateTransMsg "error" - SingleTaskRateTransMsg "none" - TasksWithSamePriorityMsg "warning" - SigSpecEnsureSampleTimeMsg "warning" - CheckMatrixSingularityMsg "none" - IntegerOverflowMsg "warning" - Int32ToFloatConvMsg "warning" - ParameterDowncastMsg "error" - ParameterOverflowMsg "error" - ParameterUnderflowMsg "none" - ParameterPrecisionLossMsg "warning" - ParameterTunabilityLossMsg "warning" - FixptConstUnderflowMsg "none" - FixptConstOverflowMsg "none" - FixptConstPrecisionLossMsg "none" - UnderSpecifiedDataTypeMsg "none" - UnnecessaryDatatypeConvMsg "none" - VectorMatrixConversionMsg "none" - InvalidFcnCallConnMsg "error" - FcnCallInpInsideContextMsg "Use local settings" - SignalLabelMismatchMsg "none" - UnconnectedInputMsg "warning" - UnconnectedOutputMsg "warning" - UnconnectedLineMsg "warning" - SFcnCompatibilityMsg "none" - UniqueDataStoreMsg "none" - BusObjectLabelMismatch "warning" - RootOutportRequireBusObject "warning" - AssertControl "UseLocalSettings" - EnableOverflowDetection off - ModelReferenceIOMsg "none" - ModelReferenceMultiInstanceNormalModeStructChecksumCheck "error" - ModelReferenceVersionMismatchMessage "none" - ModelReferenceIOMismatchMessage "none" - ModelReferenceCSMismatchMessage "none" - UnknownTsInhSupMsg "warning" - ModelReferenceDataLoggingMessage "warning" - ModelReferenceSymbolNameMessage "warning" - ModelReferenceExtraNoncontSigs "error" - StateNameClashWarn "warning" - SimStateInterfaceChecksumMismatchMsg "warning" - SimStateOlderReleaseMsg "error" - InitInArrayFormatMsg "warning" - StrictBusMsg "ErrorLevel1" - BusNameAdapt "WarnAndRepair" - NonBusSignalsTreatedAsBus "none" - LoggingUnavailableSignals "error" - BlockIODiagnostic "none" - SFUnusedDataAndEventsDiag "warning" - SFUnexpectedBacktrackingDiag "warning" - SFInvalidInputDataAccessInChartInitDiag "warning" - SFNoUnconditionalDefaultTransitionDiag "warning" - SFTransitionOutsideNaturalParentDiag "warning" - } - Simulink.HardwareCC { - $ObjectID 6 - Version "1.11.0" - ProdBitPerChar 8 - ProdBitPerShort 16 - ProdBitPerInt 32 - ProdBitPerLong 32 - ProdBitPerFloat 32 - ProdBitPerDouble 64 - ProdBitPerPointer 32 - ProdLargestAtomicInteger "Char" - ProdLargestAtomicFloat "None" - ProdIntDivRoundTo "Undefined" - ProdEndianess "Unspecified" - ProdWordSize 32 - ProdShiftRightIntArith on - ProdHWDeviceType "32-bit Generic" - TargetBitPerChar 8 - TargetBitPerShort 16 - TargetBitPerInt 32 - TargetBitPerLong 32 - TargetBitPerFloat 32 - TargetBitPerDouble 64 - TargetBitPerPointer 32 - TargetLargestAtomicInteger "Char" - TargetLargestAtomicFloat "None" - TargetShiftRightIntArith on - TargetIntDivRoundTo "Zero" - TargetEndianess "LittleEndian" - TargetWordSize 32 - TargetTypeEmulationWarnSuppressLevel 0 - TargetPreprocMaxBitsSint 32 - TargetPreprocMaxBitsUint 32 - TargetHWDeviceType "MATLAB Host" - TargetUnknown off - ProdEqTarget off - } - Simulink.ModelReferenceCC { - $ObjectID 7 - Version "1.11.0" - UpdateModelReferenceTargets "IfOutOfDateOrStructuralChange" - CheckModelReferenceTargetMessage "error" - EnableParallelModelReferenceBuilds off - ParallelModelReferenceErrorOnInvalidPool on - ParallelModelReferenceMATLABWorkerInit "None" - ModelReferenceNumInstancesAllowed "Multi" - PropagateVarSize "Infer from blocks in model" - ModelReferencePassRootInputsByReference on - ModelReferenceMinAlgLoopOccurrences off - PropagateSignalLabelsOutOfModel off - SupportModelReferenceSimTargetCustomCode off - } - Simulink.SFSimCC { - $ObjectID 8 - Version "1.11.0" - SFSimEnableDebug on - SFSimOverflowDetection on - SFSimEcho on - SimBlas on - SimCtrlC on - SimExtrinsic on - SimIntegrity on - SimUseLocalCustomCode off - SimParseCustomCode on - SimBuildMode "sf_incremental_build" - } - Simulink.RTWCC { - $BackupClass "Simulink.RTWCC" - $ObjectID 9 - Version "1.11.0" - Array { - Type "Cell" - Dimension 7 - Cell "IncludeHyperlinkInReport" - Cell "GenerateTraceInfo" - Cell "GenerateTraceReport" - Cell "GenerateTraceReportSl" - Cell "GenerateTraceReportSf" - Cell "GenerateTraceReportEml" - Cell "GenerateSLWebview" - PropName "DisabledProps" - } - SystemTargetFile "grt.tlc" - GenCodeOnly off - MakeCommand "make_rtw" - GenerateMakefile on - TemplateMakefile "grt_default_tmf" - Description "Generic Real-Time Target" - GenerateReport off - SaveLog off - RTWVerbose on - RetainRTWFile off - ProfileTLC off - TLCDebug off - TLCCoverage off - TLCAssert off - ProcessScriptMode "Default" - ConfigurationMode "Optimized" - ProcessScript "grt_make_rtw_hook" - ConfigAtBuild off - RTWUseLocalCustomCode off - RTWUseSimCustomCode off - IncludeHyperlinkInReport off - LaunchReport off - TargetLang "C" - IncludeBusHierarchyInRTWFileBlockHierarchyMap off - IncludeERTFirstTime off - GenerateTraceInfo off - GenerateTraceReport off - GenerateTraceReportSl off - GenerateTraceReportSf off - GenerateTraceReportEml off - GenerateCodeInfo off - GenerateSLWebview off - GenerateCodeMetricsReport off - RTWCompilerOptimization "On" - CheckMdlBeforeBuild "Off" - CustomRebuildMode "OnUpdate" - Array { - Type "Handle" - Dimension 2 - Simulink.CodeAppCC { - $ObjectID 10 - Version "1.11.0" - Array { - Type "Cell" - Dimension 21 - Cell "IgnoreCustomStorageClasses" - Cell "IgnoreTestpoints" - Cell "InsertBlockDesc" - Cell "InsertPolySpaceComments" - Cell "SFDataObjDesc" - Cell "MATLABFcnDesc" - Cell "SimulinkDataObjDesc" - Cell "DefineNamingRule" - Cell "SignalNamingRule" - Cell "ParamNamingRule" - Cell "InlinedPrmAccess" - Cell "CustomSymbolStr" - Cell "CustomSymbolStrGlobalVar" - Cell "CustomSymbolStrType" - Cell "CustomSymbolStrField" - Cell "CustomSymbolStrFcn" - Cell "CustomSymbolStrFcnArg" - Cell "CustomSymbolStrBlkIO" - Cell "CustomSymbolStrTmpVar" - Cell "CustomSymbolStrMacro" - Cell "ReqsInCode" - PropName "DisabledProps" - } - ForceParamTrailComments off - GenerateComments on - IgnoreCustomStorageClasses on - IgnoreTestpoints off - IncHierarchyInIds off - MaxIdLength 31 - PreserveName off - PreserveNameWithParent off - ShowEliminatedStatement off - IncAutoGenComments off - SimulinkDataObjDesc off - SFDataObjDesc off - MATLABFcnDesc off - IncDataTypeInIds off - MangleLength 1 - CustomSymbolStrGlobalVar "$R$N$M" - CustomSymbolStrType "$N$R$M" - CustomSymbolStrField "$N$M" - CustomSymbolStrFcn "$R$N$M$F" - CustomSymbolStrFcnArg "rt$I$N$M" - CustomSymbolStrBlkIO "rtb_$N$M" - CustomSymbolStrTmpVar "$N$M" - CustomSymbolStrMacro "$R$N$M" - DefineNamingRule "None" - ParamNamingRule "None" - SignalNamingRule "None" - InsertBlockDesc off - InsertPolySpaceComments off - SimulinkBlockComments on - MATLABSourceComments off - EnableCustomComments off - InlinedPrmAccess "Literals" - ReqsInCode off - UseSimReservedNames off - } - Simulink.GRTTargetCC { - $BackupClass "Simulink.TargetCC" - $ObjectID 11 - Version "1.11.0" - Array { - Type "Cell" - Dimension 16 - Cell "GeneratePreprocessorConditionals" - Cell "IncludeMdlTerminateFcn" - Cell "CombineOutputUpdateFcns" - Cell "SuppressErrorStatus" - Cell "ERTCustomFileBanners" - Cell "GenerateSampleERTMain" - Cell "GenerateTestInterfaces" - Cell "ModelStepFunctionPrototypeControlCompliant" - Cell "CPPClassGenCompliant" - Cell "MultiInstanceERTCode" - Cell "PurelyIntegerCode" - Cell "SupportComplex" - Cell "SupportAbsoluteTime" - Cell "SupportContinuousTime" - Cell "SupportNonInlinedSFcns" - Cell "PortableWordSizes" - PropName "DisabledProps" - } - TargetFcnLib "ansi_tfl_table_tmw.mat" - TargetLibSuffix "" - TargetPreCompLibLocation "" - TargetFunctionLibrary "ANSI_C" - UtilityFuncGeneration "Auto" - ERTMultiwordTypeDef "System defined" - FunctionExecutionProfile off - CodeExecutionProfiling off - ERTCodeCoverageTool "None" - ERTMultiwordLength 256 - MultiwordLength 2048 - GenerateFullHeader on - GenerateSampleERTMain off - GenerateTestInterfaces off - IsPILTarget off - ModelReferenceCompliant on - ParMdlRefBuildCompliant on - CompOptLevelCompliant on - IncludeMdlTerminateFcn on - GeneratePreprocessorConditionals "Disable all" - CombineOutputUpdateFcns off - CombineSignalStateStructs off - SuppressErrorStatus off - ERTFirstTimeCompliant off - IncludeFileDelimiter "Auto" - ERTCustomFileBanners off - SupportAbsoluteTime on - LogVarNameModifier "rt_" - MatFileLogging on - MultiInstanceERTCode off - SupportNonFinite on - SupportComplex on - PurelyIntegerCode off - SupportContinuousTime on - SupportNonInlinedSFcns on - SupportVariableSizeSignals off - EnableShiftOperators on - ParenthesesLevel "Nominal" - PortableWordSizes off - ModelStepFunctionPrototypeControlCompliant off - CPPClassGenCompliant off - AutosarCompliant off - UseMalloc off - ExtMode off - ExtModeStaticAlloc off - ExtModeTesting off - ExtModeStaticAllocSize 1000000 - ExtModeTransport 0 - ExtModeMexFile "ext_comm" - ExtModeIntrfLevel "Level1" - RTWCAPISignals off - RTWCAPIParams off - RTWCAPIStates off - RTWCAPIRootIO off - GenerateASAP2 off - } - PropName "Components" - } - } - PropName "Components" - } - Name "Configuration" - CurrentDlgPage "Solver" - ConfigPrmDlgPosition [ 360, 285, 1498, 915 ] - } - PropName "ConfigurationSets" - } - Simulink.ConfigSet { - $PropName "ActiveConfigurationSet" - $ObjectID 1 - } - BlockDefaults { - ForegroundColor "black" - BackgroundColor "white" - DropShadow off - NamePlacement "normal" - FontName "Helvetica" - FontSize 10 - FontWeight "normal" - FontAngle "normal" - ShowName on - BlockRotation 0 - BlockMirror off - } - AnnotationDefaults { - HorizontalAlignment "center" - VerticalAlignment "middle" - ForegroundColor "black" - BackgroundColor "white" - DropShadow off - FontName "Helvetica" - FontSize 10 - FontWeight "normal" - FontAngle "normal" - UseDisplayTextAsClickCallback off - } - LineDefaults { - FontName "Helvetica" - FontSize 9 - FontWeight "normal" - FontAngle "normal" - } - BlockParameterDefaults { - Block { - BlockType Constant - Value "1" - VectorParams1D on - SamplingMode "Sample based" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Inherit from 'Constant value'" - LockScale off - SampleTime "inf" - FramePeriod "inf" - PreserveConstantTs off - } - Block { - BlockType FrameConversion - InheritSamplingMode off - OutFrame "Frame-based" - } - Block { - BlockType Inport - Port "1" - OutputFunctionCall off - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: auto" - LockScale off - BusOutputAsStruct off - PortDimensions "-1" - VarSizeSig "Inherit" - SampleTime "-1" - SignalType "auto" - SamplingMode "auto" - LatchByDelayingOutsideSignal off - LatchInputForFeedbackSignals off - Interpolate on - } - Block { - BlockType Math - Operator "exp" - OutputSignalType "auto" - SampleTime "-1" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Same as first input" - LockScale off - RndMeth "Floor" - SaturateOnIntegerOverflow on - IntermediateResultsDataTypeStr "Inherit: Inherit via internal rule" - AlgorithmType "Newton-Raphson" - Iterations "3" - } - Block { - BlockType Outport - Port "1" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: auto" - LockScale off - BusOutputAsStruct off - PortDimensions "-1" - VarSizeSig "Inherit" - SampleTime "-1" - SignalType "auto" - SamplingMode "auto" - SourceOfInitialOutputValue "Dialog" - OutputWhenDisabled "held" - InitialOutput "[]" - } - Block { - BlockType Product - Inputs "2" - Multiplication "Element-wise(.*)" - CollapseMode "All dimensions" - CollapseDim "1" - InputSameDT on - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Same as first input" - LockScale off - RndMeth "Zero" - SaturateOnIntegerOverflow on - SampleTime "-1" - } - Block { - BlockType RelationalOperator - Operator ">=" - InputSameDT on - OutDataTypeStr "Inherit: Logical (see Configuration Parameters: Optimization)" - ZeroCross on - SampleTime "-1" - } - Block { - BlockType Reshape - OutputDimensionality "1-D array" - OutputDimensions "[1,1]" - } - Block { - BlockType SignalViewerScope - Floating off - ModelBased off - TickLabels "OneTimeTick" - ZoomMode "on" - Grid "on" - TimeRange "auto" - YMin "-5" - YMax "5" - SaveToWorkspace off - SaveName "ScopeData" - LimitDataPoints on - MaxDataPoints "5000" - Decimation "1" - SampleInput off - SampleTime "0" - Disabled off - ScrollMode on - } - Block { - BlockType SubSystem - ShowPortLabels "FromPortIcon" - Permissions "ReadWrite" - PermitHierarchicalResolution "All" - TreatAsAtomicUnit off - CheckFcnCallInpInsideContextMsg off - SystemSampleTime "-1" - RTWFcnNameOpts "Auto" - RTWFileNameOpts "Auto" - RTWMemSecFuncInitTerm "Inherit from model" - RTWMemSecFuncExecute "Inherit from model" - RTWMemSecDataConstants "Inherit from model" - RTWMemSecDataInternal "Inherit from model" - RTWMemSecDataParameters "Inherit from model" - SimViewingDevice off - DataTypeOverride "UseLocalSettings" - DataTypeOverrideAppliesTo "AllNumericTypes" - MinMaxOverflowLogging "UseLocalSettings" - Variant off - GeneratePreprocessorConditionals off - } - Block { - BlockType Sum - IconShape "rectangular" - Inputs "++" - CollapseMode "All dimensions" - CollapseDim "1" - InputSameDT on - AccumDataTypeStr "Inherit: Inherit via internal rule" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Same as first input" - LockScale off - RndMeth "Floor" - SaturateOnIntegerOverflow on - SampleTime "-1" - } - Block { - BlockType Switch - Criteria "u2 >= Threshold" - Threshold "0" - InputSameDT on - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Inherit via internal rule" - LockScale off - RndMeth "Floor" - SaturateOnIntegerOverflow on - ZeroCross on - SampleTime "-1" - AllowDiffInputSizes off - } - } - System { - Name "PointProcessSimulation" - Location [2, 93, 1598, 1047] - Open on - ModelBrowserVisibility off - ModelBrowserWidth 200 - ScreenColor "white" - PaperOrientation "landscape" - PaperPositionMode "auto" - PaperType "usletter" - PaperUnits "inches" - TiledPaperMargins [0.500000, 0.500000, 0.500000, 0.500000] - TiledPageScale 1 - ShowPageBoundaries off - ZoomFactor "100" - ReportName "simulink-default.rpt" - SIDHighWatermark "60" - Block { - BlockType Inport - Name "Stimulus" - SID "37" - Position [245, 323, 275, 337] - IconDisplay "Port number" - Port { - PortNumber 1 - Name "input" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Inport - Name "Ensemble" - SID "44" - Position [245, 398, 275, 412] - Port "2" - IconDisplay "Port number" - } - Block { - BlockType Sum - Name "Add" - SID "3" - Ports [4, 1] - Position [575, 250, 605, 290] - Inputs "++++" - InputSameDT off - OutDataTypeStr "Inherit: Inherit via internal rule" - SaturateOnIntegerOverflow off - } - Block { - BlockType SubSystem - Name "Binomial" - SID "48" - Ports [1, 1] - Position [725, 335, 765, 395] - MinAlgLoopOccurrences off - PropExecContextOutsideSubsystem off - RTWSystemCode "Auto" - FunctionWithSeparateData off - Opaque off - RequestExecContextInheritance off - MaskHideContents off - System { - Name "Binomial" - Location [597, 320, 927, 614] - Open off - ModelBrowserVisibility off - ModelBrowserWidth 200 - ScreenColor "white" - PaperOrientation "landscape" - PaperPositionMode "auto" - PaperType "usletter" - PaperUnits "inches" - TiledPaperMargins [0.500000, 0.500000, 0.500000, 0.500000] - TiledPageScale 1 - ShowPageBoundaries off - ZoomFactor "100" - Block { - BlockType Inport - Name "In1" - SID "50" - Position [25, 38, 55, 52] - IconDisplay "Port number" - } - Block { - BlockType Sum - Name "Add1" - SID "32" - Ports [2, 1] - Position [145, 110, 175, 140] - IconShape "round" - Inputs "|++" - InputSameDT off - OutDataTypeStr "Inherit: Inherit via internal rule" - SaturateOnIntegerOverflow off - } - Block { - BlockType Constant - Name "Constant1" - SID "33" - Position [145, 200, 175, 230] - BlockRotation 270 - BackgroundColor "magenta" - } - Block { - BlockType Product - Name "Divide" - SID "31" - Ports [2, 1] - Position [220, 27, 250, 58] - Inputs "*/" - InputSameDT off - OutDataTypeStr "Inherit: Inherit via internal rule" - RndMeth "Floor" - SaturateOnIntegerOverflow off - Port { - PortNumber 1 - Name "s2" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Math - Name "Math\nFunction" - SID "8" - Ports [1, 1] - Position [80, 30, 110, 60] - Port { - PortNumber 1 - Name "s1" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Outport - Name "Out1" - SID "49" - Position [275, 38, 305, 52] - IconDisplay "Port number" - } - Line { - SrcBlock "Constant1" - SrcPort 1 - DstBlock "Add1" - DstPort 2 - } - Line { - Name "s1" - Labels [0, 0; 0, 0] - SrcBlock "Math\nFunction" - SrcPort 1 - Points [5, 0] - Branch { - Points [0, 80] - DstBlock "Add1" - DstPort 1 - } - Branch { - Labels [1, 0] - Points [85, 0] - DstBlock "Divide" - DstPort 1 - } - } - Line { - SrcBlock "Add1" - SrcPort 1 - Points [10, 0; 0, -75] - DstBlock "Divide" - DstPort 2 - } - Line { - Name "s2" - Labels [0, 0; 0, 0] - SrcBlock "Divide" - SrcPort 1 - DstBlock "Out1" - DstPort 1 - } - Line { - SrcBlock "In1" - SrcPort 1 - DstBlock "Math\nFunction" - DstPort 1 - } - Annotation { - Name "Inverse of Logistic Link Function\n \n\n\n\n\n\n\n\n\n\n" - ". " - Position [174, 121] - BackgroundColor "yellow" - FontName "Arial Narrow" - FontSize 18 - } - Annotation { - Name "\\lambda \\cdot \\Delta= e^{X \\cdot \\beta}/(1+e^{X\\cdot \\beta})" - Position [164, 271] - Interpreter "tex" - FontName "Arial Narrow" - FontSize 18 - } - } - } - Block { - BlockType Constant - Name "Constant" - SID "1" - Position [515, 175, 545, 205] - BlockRotation 270 - BlockMirror on - BackgroundColor "magenta" - NamePlacement "alternate" - Value "mu" - } - Block { - BlockType Constant - Name "Constant2" - SID "47" - Position [885, 475, 915, 505] - Value "Ts" - } - Block { - BlockType Product - Name "Divide1" - SID "46" - Ports [2, 1] - Position [990, 467, 1020, 498] - Inputs "*/" - InputSameDT off - OutDataTypeStr "Inherit: Inherit via internal rule" - RndMeth "Floor" - SaturateOnIntegerOverflow off - } - Block { - BlockType Reference - Name "Ensemble Effect" - SID "43" - Ports [1, 1] - Position [410, 387, 505, 423] - BackgroundColor "darkGreen" - LibraryVersion "1.107" - SourceBlock "cstblocks/LTI System" - SourceType "LTI Block" - ShowPortLabels "FromPortIcon" - SystemSampleTime "-1" - FunctionWithSeparateData off - RTWMemSecFuncInitTerm "Inherit from model" - RTWMemSecFuncExecute "Inherit from model" - RTWMemSecDataConstants "Inherit from model" - RTWMemSecDataInternal "Inherit from model" - RTWMemSecDataParameters "Inherit from model" - GeneratePreprocessorConditionals off - sys "E" - IC "[]" - } - Block { - BlockType FrameConversion - Name "Frame Status Conversion" - SID "11" - Ports [1, 1] - Position [1125, 260, 1180, 300] - OutFrame "Sample-based" - } - Block { - BlockType Reference - Name "Integer Delay" - SID "22" - Ports [1, 1] - Position [410, 123, 445, 157] - BlockMirror on - LibraryVersion "1.236" - UserDataPersistent on - UserData "DataTag0" - SourceBlock "simulink/Discrete/Integer Delay" - SourceType "Integer Delay" - NumDelays "1" - InputProcessing "Elements as channels (sample based)" - vinit "0.0" - samptime "-1" - } - Block { - BlockType SubSystem - Name "Poisson" - SID "53" - Ports [1, 1] - Position [725, 160, 765, 220] - MinAlgLoopOccurrences off - PropExecContextOutsideSubsystem off - RTWSystemCode "Auto" - FunctionWithSeparateData off - Opaque off - RequestExecContextInheritance off - MaskHideContents off - System { - Name "Poisson" - Location [2, 84, 1678, 978] - Open off - ModelBrowserVisibility off - ModelBrowserWidth 200 - ScreenColor "white" - PaperOrientation "landscape" - PaperPositionMode "auto" - PaperType "usletter" - PaperUnits "inches" - TiledPaperMargins [0.500000, 0.500000, 0.500000, 0.500000] - TiledPageScale 1 - ShowPageBoundaries off - ZoomFactor "100" - Block { - BlockType Inport - Name "In1" - SID "54" - Position [225, 203, 255, 217] - IconDisplay "Port number" - } - Block { - BlockType Math - Name "Math\nFunction" - SID "58" - Ports [1, 1] - Position [360, 195, 390, 225] - Port { - PortNumber 1 - Name "s1" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Outport - Name "Out1" - SID "59" - Position [475, 203, 505, 217] - IconDisplay "Port number" - } - Line { - SrcBlock "In1" - SrcPort 1 - DstBlock "Math\nFunction" - DstPort 1 - } - Line { - Name "s1" - Labels [0, 0; 0, 0; 1, 0] - SrcBlock "Math\nFunction" - SrcPort 1 - DstBlock "Out1" - DstPort 1 - } - Annotation { - Name "\\lambda \\cdot \\Delta= e^{X \\cdot \\beta}" - Position [369, 336] - Interpreter "tex" - FontName "Arial Narrow" - FontSize 18 - } - Annotation { - Name "Inverse of log Link Function\n \n\n\n\n\n\n. " - " " - Position [374, 231] - BackgroundColor "yellow" - FontName "Arial Narrow" - FontSize 18 - } - } - } - Block { - BlockType Reference - Name "Random Source" - SID "12" - Ports [0, 1] - Position [986, 360, 1024, 395] - BlockRotation 270 - LibraryVersion "1.712" - UserDataPersistent on - UserData "DataTag1" - Diagnostics "AllowInheritedTsInSrc" - SourceBlock "dspsrcs4/Random\nSource" - SourceType "Random Source" - SrcType "Uniform" - NormMethod "Ziggurat" - CltLength "12" - MinVal "0" - MaxVal "1" - MeanVal "0" - VarVal "1" - RepMode "Not repeatable" - rawSeed "seed" - IsInherit on - SampMode "Continuous" - SampTime "Ts" - SampFrame "dsp_sampFrame" - DataType "Double" - OutComplex "Real" - } - Block { - BlockType RelationalOperator - Name "Relational Operator" - SID "13" - Ports [2, 1] - Position [1030, 262, 1060, 293] - ShowName off - Operator ">" - OutDataTypeStr "float('double')" - } - Block { - BlockType Reshape - Name "Reshape" - SID "14" - Ports [1, 1] - Position [1220, 268, 1250, 292] - ShowName off - OutputDimensions "[sampPerFrame,max(length(P),length(seed))]" - Port { - PortNumber 1 - Name "spike process" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Reference - Name "Self-History" - SID "5" - Ports [1, 1] - Position [410, 247, 505, 283] - BackgroundColor "orange" - LibraryVersion "1.107" - SourceBlock "cstblocks/LTI System" - SourceType "LTI Block" - ShowPortLabels "FromPortIcon" - SystemSampleTime "-1" - FunctionWithSeparateData off - RTWMemSecFuncInitTerm "Inherit from model" - RTWMemSecFuncExecute "Inherit from model" - RTWMemSecDataConstants "Inherit from model" - RTWMemSecDataInternal "Inherit from model" - RTWMemSecDataParameters "Inherit from model" - GeneratePreprocessorConditionals off - sys "H" - IC "[]" - } - Block { - BlockType Reference - Name "Stimulus Effect" - SID "6" - Ports [1, 1] - Position [410, 312, 505, 348] - BackgroundColor "darkGreen" - LibraryVersion "1.107" - SourceBlock "cstblocks/LTI System" - SourceType "LTI Block" - ShowPortLabels "FromPortIcon" - SystemSampleTime "-1" - FunctionWithSeparateData off - RTWMemSecFuncInitTerm "Inherit from model" - RTWMemSecFuncExecute "Inherit from model" - RTWMemSecDataConstants "Inherit from model" - RTWMemSecDataInternal "Inherit from model" - RTWMemSecDataParameters "Inherit from model" - GeneratePreprocessorConditionals off - sys "S" - IC "[]" - } - Block { - BlockType Switch - Name "Switch" - SID "51" - Position [820, 250, 870, 290] - Criteria "u2 ~= 0" - InputSameDT off - SaturateOnIntegerOverflow off - } - Block { - BlockType Constant - Name "simType\nSelector" - SID "52" - Position [730, 255, 760, 285] - Value "simTypeSelect" - } - Block { - BlockType Outport - Name "pp" - SID "26" - Position [1310, 273, 1340, 287] - IconDisplay "Port number" - } - Block { - BlockType Outport - Name "lambdaDelta" - SID "45" - Position [1065, 478, 1095, 492] - Port "2" - IconDisplay "Port number" - } - Block { - BlockType SignalViewerScope - Name "Scope" - SID "28" - Ports [] - Position [20, 15, 60, 55] - IOType "viewer" - List { - ListType IOSignalStrings - set0ParseKeys "10,18" - set0Sigs "Reshape:o1Stimulus Effect:o1" - } - Location [1, 53, 1601, 1151] - Open off - NumInputPorts "1" - List { - ListType AxesTitles - axes1 "%" - } - ShowDataMarkers off - ShowLegends off - DataFormat "Array" - MaxDataPoints "7500" - RefreshTime 0.035000 - } - Block { - BlockType SignalViewerScope - Name "Scope1" - SID "29" - Ports [] - Position [20, 15, 60, 55] - IOType "viewer" - List { - ListType IOSignalStrings - set0ParseKeys "25,18" - set0Sigs "Binomial/Math Function:o1Binomial/Divide:o1" - } - Location [1, 53, 1601, 1151] - Open off - NumInputPorts "1" - List { - ListType AxesTitles - axes1 "%" - } - ShowDataMarkers off - ShowLegends off - SaveName "ScopeData1" - DataFormat "Array" - MaxDataPoints "7500" - RefreshTime 0.035000 - } - Block { - BlockType SignalViewerScope - Name "Scope2" - SID "38" - Ports [] - Position [20, 15, 60, 55] - IOType "viewer" - List { - ListType IOSignalStrings - set0ParseKeys "15" - set0Sigs "Self-History:o1" - } - Location [5, 53, 1605, 1151] - Open off - NumInputPorts "1" - List { - ListType AxesTitles - axes1 "%" - } - ShowDataMarkers off - ShowLegends off - SaveName "ScopeData2" - DataFormat "Array" - MaxDataPoints "7500" - RefreshTime 0.035000 - } - Line { - SrcBlock "Constant" - SrcPort 1 - Points [0, 45] - DstBlock "Add" - DstPort 1 - } - Line { - SrcBlock "Self-History" - SrcPort 1 - DstBlock "Add" - DstPort 2 - } - Line { - SrcBlock "Stimulus Effect" - SrcPort 1 - Points [15, 0; 0, -55] - DstBlock "Add" - DstPort 3 - } - Line { - SrcBlock "Add" - SrcPort 1 - Points [55, 0] - Branch { - Points [0, 95] - DstBlock "Binomial" - DstPort 1 - } - Branch { - Points [0, -80] - DstBlock "Poisson" - DstPort 1 - } - } - Line { - SrcBlock "Frame Status Conversion" - SrcPort 1 - DstBlock "Reshape" - DstPort 1 - } - Line { - Name "spike process" - SrcBlock "Reshape" - SrcPort 1 - Points [25, 0] - Branch { - Labels [1, 0] - Points [0, -140] - DstBlock "Integer Delay" - DstPort 1 - } - Branch { - DstBlock "pp" - DstPort 1 - } - } - Line { - SrcBlock "Relational Operator" - SrcPort 1 - DstBlock "Frame Status Conversion" - DstPort 1 - } - Line { - SrcBlock "Random Source" - SrcPort 1 - Points [0, -70] - DstBlock "Relational Operator" - DstPort 2 - } - Line { - Name "input" - Labels [0, 0] - SrcBlock "Stimulus" - SrcPort 1 - DstBlock "Stimulus Effect" - DstPort 1 - } - Line { - SrcBlock "Integer Delay" - SrcPort 1 - Points [-65, 0; 0, 125] - DstBlock "Self-History" - DstPort 1 - } - Line { - SrcBlock "Ensemble" - SrcPort 1 - DstBlock "Ensemble Effect" - DstPort 1 - } - Line { - SrcBlock "Ensemble Effect" - SrcPort 1 - Points [25, 0; 0, -120] - DstBlock "Add" - DstPort 4 - } - Line { - SrcBlock "Constant2" - SrcPort 1 - DstBlock "Divide1" - DstPort 2 - } - Line { - SrcBlock "Divide1" - SrcPort 1 - DstBlock "lambdaDelta" - DstPort 1 - } - Line { - SrcBlock "simType\nSelector" - SrcPort 1 - DstBlock "Switch" - DstPort 2 - } - Line { - SrcBlock "Binomial" - SrcPort 1 - Points [15, 0; 0, -80] - DstBlock "Switch" - DstPort 3 - } - Line { - SrcBlock "Switch" - SrcPort 1 - Points [50, 0] - Branch { - DstBlock "Relational Operator" - DstPort 1 - } - Branch { - Points [0, 205] - DstBlock "Divide1" - DstPort 1 - } - } - Line { - SrcBlock "Poisson" - SrcPort 1 - Points [15, 0; 0, 65] - DstBlock "Switch" - DstPort 1 - } - Annotation { - Name "GLM Model \n\n " - " \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n. " - Position [414, 261] - BackgroundColor "lightBlue" - FontName "Arial Narrow" - FontSize 18 - } - Annotation { - Name "Coin flip with\np= \\lambda \\cdot \\Delta\n\n\n\n\n\n\n\n\n\n\n." - Position [1034, 356] - Interpreter "tex" - FontName "Arial Narrow" - FontSize 18 - } - } -} -MatData { - NumRecords 2 - DataRecord { - Tag DataTag1 - Data " %)30 . V 8 ( @ % \" $ ! 0 % 0 \"0 $ 2 4V5E9" - " 4V5E9$9L86< #@ #@ & \" 0 !0 @ ! !0 $ $ 4 R,S$Q,P " - "X ! !@ @ $ 4 ( 0 T ! ! - 1&].;W13879E4V5E9 " - } - DataRecord { - Tag DataTag0 - Data " %)30 . B 8 ( @ % \" $ ! 0 % 0 $P $ 3 :&%S26" - "YH97)I=&5D3W!T:6]N #@ # & \" D\" !0 @ ! 0 $ @ ! $ " - } -} diff --git a/PointProcessSimulation.mdl.r2011b b/PointProcessSimulation.mdl.r2011b deleted file mode 100644 index 85b6a958..00000000 --- a/PointProcessSimulation.mdl.r2011b +++ /dev/null @@ -1,1567 +0,0 @@ -Model { - Name "PointProcessSimulation" - Version 7.8 - MdlSubVersion 0 - GraphicalInterface { - NumRootInports 2 - Inport { - BusObject "" - SignalName "input" - Name "Stimulus" - } - Inport { - BusObject "" - Name "Ensemble" - } - NumRootOutports 2 - Outport { - BusObject "" - BusOutputAsStruct "off" - SignalName "spike process" - Name "pp" - } - Outport { - BusObject "" - BusOutputAsStruct "off" - Name "lambdaDelta" - } - ParameterArgumentNames "" - ComputedModelVersion "1.30" - NumModelReferences 0 - NumTestPointedSignals 0 - } - SavedCharacterEncoding "windows-1252" - SaveDefaultBlockParams on - ScopeRefreshTime 0.035000 - OverrideScopeRefreshTime on - DisableAllScopes off - DataTypeOverride "UseLocalSettings" - DataTypeOverrideAppliesTo "AllNumericTypes" - MinMaxOverflowLogging "UseLocalSettings" - MinMaxOverflowArchiveMode "Overwrite" - FPTRunName "Run 1" - MaxMDLFileLineLength 120 - Created "Tue Feb 08 12:34:27 2011" - Creator "Developer" - UpdateHistory "UpdateHistoryNever" - ModifiedByFormat "%" - LastModifiedBy "Iahn Cajigas" - ModifiedDateFormat "%" - LastModifiedDate "Fri Mar 02 14:56:46 2012" - RTWModifiedTimeStamp 252600540 - ModelVersionFormat "1.%" - ConfigurationManager "None" - SampleTimeColors off - SampleTimeAnnotations off - LibraryLinkDisplay "none" - WideLines off - ShowLineDimensions off - ShowPortDataTypes off - ShowDesignRanges off - ShowLoopsOnError on - IgnoreBidirectionalLines off - ShowStorageClass off - ShowTestPointIcons on - ShowSignalResolutionIcons on - ShowViewerIcons on - SortedOrder off - ExecutionContextIcon off - ShowLinearizationAnnotations on - BlockNameDataTip off - BlockParametersDataTip off - BlockDescriptionStringDataTip off - ToolBar on - StatusBar on - BrowserShowLibraryLinks off - BrowserLookUnderMasks off - SimulationMode "normal" - LinearizationMsg "none" - Profile off - ParamWorkspaceSource "MATLABWorkspace" - AccelSystemTargetFile "accel.tlc" - AccelTemplateMakefile "accel_default_tmf" - AccelMakeCommand "make_rtw" - TryForcingSFcnDF off - RecordCoverage off - CovPath "/" - CovSaveName "covdata" - CovMetricSettings "dw" - CovNameIncrementing off - CovHtmlReporting on - CovForceBlockReductionOff on - covSaveCumulativeToWorkspaceVar on - CovSaveSingleToWorkspaceVar on - CovCumulativeVarName "covCumulativeData" - CovCumulativeReport off - CovReportOnPause on - CovModelRefEnable "Off" - CovExternalEMLEnable off - ExtModeBatchMode off - ExtModeEnableFloating on - ExtModeTrigType "manual" - ExtModeTrigMode "normal" - ExtModeTrigPort "1" - ExtModeTrigElement "any" - ExtModeTrigDuration 1000 - ExtModeTrigDurationFloating "auto" - ExtModeTrigHoldOff 0 - ExtModeTrigDelay 0 - ExtModeTrigDirection "rising" - ExtModeTrigLevel 0 - ExtModeArchiveMode "off" - ExtModeAutoIncOneShot off - ExtModeIncDirWhenArm off - ExtModeAddSuffixToVar off - ExtModeWriteAllDataToWs off - ExtModeArmWhenConnect on - ExtModeSkipDownloadWhenConnect off - ExtModeLogAll on - ExtModeAutoUpdateStatusClock on - BufferReuse on - ShowModelReferenceBlockVersion off - ShowModelReferenceBlockIO off - Array { - Type "Handle" - Dimension 1 - Simulink.ConfigSet { - $ObjectID 1 - Version "1.11.1" - Array { - Type "Handle" - Dimension 8 - Simulink.SolverCC { - $ObjectID 2 - Version "1.11.1" - StartTime "0.0" - StopTime "10" - AbsTol "auto" - FixedStep "Ts" - InitialStep "auto" - MaxNumMinSteps "-1" - MaxOrder 5 - ZcThreshold "auto" - ConsecutiveZCsStepRelTol "10*128*eps" - MaxConsecutiveZCs "1000" - ExtrapolationOrder 4 - NumberNewtonIterations 1 - MaxStep "auto" - MinStep "auto" - MaxConsecutiveMinStep "1" - RelTol "1e-3" - SolverMode "Auto" - ConcurrentTasks off - Solver "FixedStepDiscrete" - SolverName "FixedStepDiscrete" - SolverJacobianMethodControl "auto" - ShapePreserveControl "DisableAll" - ZeroCrossControl "UseLocalSettings" - ZeroCrossAlgorithm "Nonadaptive" - AlgebraicLoopSolver "TrustRegion" - SolverResetMethod "Fast" - PositivePriorityOrder off - AutoInsertRateTranBlk off - SampleTimeConstraint "Unconstrained" - InsertRTBMode "Whenever possible" - } - Simulink.DataIOCC { - $ObjectID 3 - Version "1.11.1" - Decimation "1" - ExternalInput "[t, u]" - FinalStateName "xFinal" - InitialState "xInitial" - LimitDataPoints on - MaxDataPoints "1000" - LoadExternalInput off - LoadInitialState off - SaveFinalState off - SaveCompleteFinalSimState off - SaveFormat "Array" - SignalLoggingSaveFormat "ModelDataLogs" - SaveOutput on - SaveState off - SignalLogging on - DSMLogging on - InspectSignalLogs off - SaveTime on - ReturnWorkspaceOutputs off - StateSaveName "xout" - TimeSaveName "tout" - OutputSaveName "yout" - SignalLoggingName "logsout" - DSMLoggingName "dsmout" - OutputOption "RefineOutputTimes" - OutputTimes "[]" - ReturnWorkspaceOutputsName "out" - Refine "1" - } - Simulink.OptimizationCC { - $ObjectID 4 - Version "1.11.1" - Array { - Type "Cell" - Dimension 8 - Cell "BooleansAsBitfields" - Cell "PassReuseOutputArgsAs" - Cell "PassReuseOutputArgsThreshold" - Cell "ZeroExternalMemoryAtStartup" - Cell "ZeroInternalMemoryAtStartup" - Cell "OptimizeModelRefInitCode" - Cell "NoFixptDivByZeroProtection" - Cell "UseSpecifiedMinMax" - PropName "DisabledProps" - } - BlockReduction on - BooleanDataType on - ConditionallyExecuteInputs on - InlineParams off - UseIntDivNetSlope off - UseFloatMulNetSlope off - UseSpecifiedMinMax off - InlineInvariantSignals off - OptimizeBlockIOStorage on - BufferReuse on - EnhancedBackFolding off - StrengthReduction off - ExpressionFolding on - BooleansAsBitfields off - BitfieldContainerType "uint_T" - EnableMemcpy on - MemcpyThreshold 64 - PassReuseOutputArgsAs "Structure reference" - ExpressionDepthLimit 2147483647 - FoldNonRolledExpr on - LocalBlockOutputs on - RollThreshold 5 - SystemCodeInlineAuto off - StateBitsets off - DataBitsets off - UseTempVars off - ZeroExternalMemoryAtStartup on - ZeroInternalMemoryAtStartup on - InitFltsAndDblsToZero off - NoFixptDivByZeroProtection off - EfficientFloat2IntCast off - EfficientMapNaN2IntZero on - OptimizeModelRefInitCode off - LifeSpan "inf" - MaxStackSize "Inherit from target" - BufferReusableBoundary on - SimCompilerOptimization "Off" - AccelVerboseBuild off - AccelParallelForEachSubsystem on - } - Simulink.DebuggingCC { - $ObjectID 5 - Version "1.11.1" - RTPrefix "error" - ConsistencyChecking "none" - ArrayBoundsChecking "none" - SignalInfNanChecking "none" - SignalRangeChecking "none" - ReadBeforeWriteMsg "UseLocalSettings" - WriteAfterWriteMsg "UseLocalSettings" - WriteAfterReadMsg "UseLocalSettings" - AlgebraicLoopMsg "warning" - ArtificialAlgebraicLoopMsg "warning" - SaveWithDisabledLinksMsg "warning" - SaveWithParameterizedLinksMsg "warning" - CheckSSInitialOutputMsg on - UnderspecifiedInitializationDetection "Classic" - MergeDetectMultiDrivingBlocksExec "none" - CheckExecutionContextPreStartOutputMsg off - CheckExecutionContextRuntimeOutputMsg off - SignalResolutionControl "UseLocalSettings" - BlockPriorityViolationMsg "warning" - MinStepSizeMsg "warning" - TimeAdjustmentMsg "none" - MaxConsecutiveZCsMsg "error" - MaskedZcDiagnostic "warning" - IgnoredZcDiagnostic "warning" - SolverPrmCheckMsg "warning" - InheritedTsInSrcMsg "warning" - DiscreteInheritContinuousMsg "warning" - MultiTaskDSMMsg "error" - MultiTaskCondExecSysMsg "error" - MultiTaskRateTransMsg "error" - SingleTaskRateTransMsg "none" - TasksWithSamePriorityMsg "warning" - SigSpecEnsureSampleTimeMsg "warning" - CheckMatrixSingularityMsg "none" - IntegerOverflowMsg "warning" - Int32ToFloatConvMsg "warning" - ParameterDowncastMsg "error" - ParameterOverflowMsg "error" - ParameterUnderflowMsg "none" - ParameterPrecisionLossMsg "warning" - ParameterTunabilityLossMsg "warning" - FixptConstUnderflowMsg "none" - FixptConstOverflowMsg "none" - FixptConstPrecisionLossMsg "none" - UnderSpecifiedDataTypeMsg "none" - UnnecessaryDatatypeConvMsg "none" - VectorMatrixConversionMsg "none" - InvalidFcnCallConnMsg "error" - FcnCallInpInsideContextMsg "Use local settings" - SignalLabelMismatchMsg "none" - UnconnectedInputMsg "warning" - UnconnectedOutputMsg "warning" - UnconnectedLineMsg "warning" - SFcnCompatibilityMsg "none" - FrameProcessingCompatibilityMsg "warning" - UniqueDataStoreMsg "none" - BusObjectLabelMismatch "warning" - RootOutportRequireBusObject "warning" - AssertControl "UseLocalSettings" - EnableOverflowDetection off - ModelReferenceIOMsg "none" - ModelReferenceMultiInstanceNormalModeStructChecksumCheck "error" - ModelReferenceVersionMismatchMessage "none" - ModelReferenceIOMismatchMessage "none" - ModelReferenceCSMismatchMessage "none" - UnknownTsInhSupMsg "warning" - ModelReferenceDataLoggingMessage "warning" - ModelReferenceSymbolNameMessage "warning" - ModelReferenceExtraNoncontSigs "error" - StateNameClashWarn "warning" - SimStateInterfaceChecksumMismatchMsg "warning" - SimStateOlderReleaseMsg "error" - InitInArrayFormatMsg "warning" - StrictBusMsg "ErrorLevel1" - BusNameAdapt "WarnAndRepair" - NonBusSignalsTreatedAsBus "none" - LoggingUnavailableSignals "error" - BlockIODiagnostic "none" - SFUnusedDataAndEventsDiag "warning" - SFUnexpectedBacktrackingDiag "warning" - SFInvalidInputDataAccessInChartInitDiag "warning" - SFNoUnconditionalDefaultTransitionDiag "warning" - SFTransitionOutsideNaturalParentDiag "warning" - SFUnconditionalTransitionShadowingDiag "warning" - } - Simulink.HardwareCC { - $ObjectID 6 - Version "1.11.1" - ProdBitPerChar 8 - ProdBitPerShort 16 - ProdBitPerInt 32 - ProdBitPerLong 32 - ProdBitPerFloat 32 - ProdBitPerDouble 64 - ProdBitPerPointer 32 - ProdLargestAtomicInteger "Char" - ProdLargestAtomicFloat "None" - ProdIntDivRoundTo "Undefined" - ProdEndianess "Unspecified" - ProdWordSize 32 - ProdShiftRightIntArith on - ProdHWDeviceType "32-bit Generic" - TargetBitPerChar 8 - TargetBitPerShort 16 - TargetBitPerInt 32 - TargetBitPerLong 32 - TargetBitPerFloat 32 - TargetBitPerDouble 64 - TargetBitPerPointer 32 - TargetLargestAtomicInteger "Char" - TargetLargestAtomicFloat "None" - TargetShiftRightIntArith on - TargetIntDivRoundTo "Zero" - TargetEndianess "LittleEndian" - TargetWordSize 32 - TargetTypeEmulationWarnSuppressLevel 0 - TargetPreprocMaxBitsSint 32 - TargetPreprocMaxBitsUint 32 - TargetHWDeviceType "MATLAB Host" - TargetUnknown off - ProdEqTarget off - } - Simulink.ModelReferenceCC { - $ObjectID 7 - Version "1.11.1" - UpdateModelReferenceTargets "IfOutOfDateOrStructuralChange" - CheckModelReferenceTargetMessage "error" - EnableParallelModelReferenceBuilds off - ParallelModelReferenceErrorOnInvalidPool on - ParallelModelReferenceMATLABWorkerInit "None" - ModelReferenceNumInstancesAllowed "Multi" - PropagateVarSize "Infer from blocks in model" - ModelReferencePassRootInputsByReference on - ModelReferenceMinAlgLoopOccurrences off - PropagateSignalLabelsOutOfModel off - SupportModelReferenceSimTargetCustomCode off - } - Simulink.SFSimCC { - $ObjectID 8 - Version "1.11.1" - SFSimEnableDebug on - SFSimOverflowDetection on - SFSimEcho on - SimBlas on - SimCtrlC on - SimExtrinsic on - SimIntegrity on - SimUseLocalCustomCode off - SimParseCustomCode on - SimBuildMode "sf_incremental_build" - } - Simulink.RTWCC { - $BackupClass "Simulink.RTWCC" - $ObjectID 9 - Version "1.11.1" - Array { - Type "Cell" - Dimension 7 - Cell "IncludeHyperlinkInReport" - Cell "GenerateTraceInfo" - Cell "GenerateTraceReport" - Cell "GenerateTraceReportSl" - Cell "GenerateTraceReportSf" - Cell "GenerateTraceReportEml" - Cell "GenerateSLWebview" - PropName "DisabledProps" - } - SystemTargetFile "grt.tlc" - GenCodeOnly off - MakeCommand "make_rtw" - GenerateMakefile on - TemplateMakefile "grt_default_tmf" - Description "Generic Real-Time Target" - GenerateReport off - SaveLog off - RTWVerbose on - RetainRTWFile off - ProfileTLC off - TLCDebug off - TLCCoverage off - TLCAssert off - ProcessScriptMode "Default" - ConfigurationMode "Optimized" - ProcessScript "grt_make_rtw_hook" - ConfigAtBuild off - RTWUseLocalCustomCode off - RTWUseSimCustomCode off - IncludeHyperlinkInReport off - LaunchReport off - TargetLang "C" - IncludeBusHierarchyInRTWFileBlockHierarchyMap off - IncludeERTFirstTime off - GenerateTraceInfo off - GenerateTraceReport off - GenerateTraceReportSl off - GenerateTraceReportSf off - GenerateTraceReportEml off - GenerateCodeInfo off - GenerateSLWebview off - GenerateCodeMetricsReport off - RTWCompilerOptimization "On" - CheckMdlBeforeBuild "Off" - CustomRebuildMode "OnUpdate" - Array { - Type "Handle" - Dimension 2 - Simulink.CodeAppCC { - $ObjectID 10 - Version "1.11.1" - Array { - Type "Cell" - Dimension 21 - Cell "IgnoreCustomStorageClasses" - Cell "IgnoreTestpoints" - Cell "InsertBlockDesc" - Cell "InsertPolySpaceComments" - Cell "SFDataObjDesc" - Cell "MATLABFcnDesc" - Cell "SimulinkDataObjDesc" - Cell "DefineNamingRule" - Cell "SignalNamingRule" - Cell "ParamNamingRule" - Cell "InlinedPrmAccess" - Cell "CustomSymbolStr" - Cell "CustomSymbolStrGlobalVar" - Cell "CustomSymbolStrType" - Cell "CustomSymbolStrField" - Cell "CustomSymbolStrFcn" - Cell "CustomSymbolStrFcnArg" - Cell "CustomSymbolStrBlkIO" - Cell "CustomSymbolStrTmpVar" - Cell "CustomSymbolStrMacro" - Cell "ReqsInCode" - PropName "DisabledProps" - } - ForceParamTrailComments off - GenerateComments on - IgnoreCustomStorageClasses on - IgnoreTestpoints off - IncHierarchyInIds off - MaxIdLength 31 - PreserveName off - PreserveNameWithParent off - ShowEliminatedStatement off - IncAutoGenComments off - SimulinkDataObjDesc off - SFDataObjDesc off - MATLABFcnDesc off - IncDataTypeInIds off - MangleLength 1 - CustomSymbolStrGlobalVar "$R$N$M" - CustomSymbolStrType "$N$R$M" - CustomSymbolStrField "$N$M" - CustomSymbolStrFcn "$R$N$M$F" - CustomSymbolStrFcnArg "rt$I$N$M" - CustomSymbolStrBlkIO "rtb_$N$M" - CustomSymbolStrTmpVar "$N$M" - CustomSymbolStrMacro "$R$N$M" - DefineNamingRule "None" - ParamNamingRule "None" - SignalNamingRule "None" - InsertBlockDesc off - InsertPolySpaceComments off - SimulinkBlockComments on - MATLABSourceComments off - EnableCustomComments off - InlinedPrmAccess "Literals" - ReqsInCode off - UseSimReservedNames off - } - Simulink.GRTTargetCC { - $BackupClass "Simulink.TargetCC" - $ObjectID 11 - Version "1.11.1" - Array { - Type "Cell" - Dimension 16 - Cell "GeneratePreprocessorConditionals" - Cell "IncludeMdlTerminateFcn" - Cell "CombineOutputUpdateFcns" - Cell "SuppressErrorStatus" - Cell "ERTCustomFileBanners" - Cell "GenerateSampleERTMain" - Cell "GenerateTestInterfaces" - Cell "ModelStepFunctionPrototypeControlCompliant" - Cell "CPPClassGenCompliant" - Cell "MultiInstanceERTCode" - Cell "PurelyIntegerCode" - Cell "SupportComplex" - Cell "SupportAbsoluteTime" - Cell "SupportContinuousTime" - Cell "SupportNonInlinedSFcns" - Cell "PortableWordSizes" - PropName "DisabledProps" - } - TargetFcnLib "ansi_tfl_table_tmw.mat" - TargetLibSuffix "" - TargetPreCompLibLocation "" - TargetFunctionLibrary "ANSI_C" - UtilityFuncGeneration "Auto" - ERTMultiwordTypeDef "System defined" - CodeExecutionProfiling off - ERTMultiwordLength 256 - MultiwordLength 2048 - GenerateFullHeader on - GenerateSampleERTMain off - GenerateTestInterfaces off - IsPILTarget off - ModelReferenceCompliant on - ParMdlRefBuildCompliant on - CompOptLevelCompliant on - ConcurrentExecutionCompliant on - IncludeMdlTerminateFcn on - GeneratePreprocessorConditionals "Disable all" - CombineOutputUpdateFcns off - CombineSignalStateStructs off - SuppressErrorStatus off - ERTFirstTimeCompliant off - IncludeFileDelimiter "Auto" - ERTCustomFileBanners off - SupportAbsoluteTime on - LogVarNameModifier "rt_" - MatFileLogging on - MultiInstanceERTCode off - SupportNonFinite on - SupportComplex on - PurelyIntegerCode off - SupportContinuousTime on - SupportNonInlinedSFcns on - SupportVariableSizeSignals off - EnableShiftOperators on - ParenthesesLevel "Nominal" - PortableWordSizes off - ModelStepFunctionPrototypeControlCompliant off - CPPClassGenCompliant off - AutosarCompliant off - UseMalloc off - ExtMode off - ExtModeStaticAlloc off - ExtModeTesting off - ExtModeStaticAllocSize 1000000 - ExtModeTransport 0 - ExtModeMexFile "ext_comm" - ExtModeIntrfLevel "Level1" - RTWCAPISignals off - RTWCAPIParams off - RTWCAPIStates off - RTWCAPIRootIO off - GenerateASAP2 off - } - PropName "Components" - } - } - PropName "Components" - } - Name "Configuration" - CurrentDlgPage "Solver" - ConfigPrmDlgPosition [ 360, 285, 1498, 915 ] - } - PropName "ConfigurationSets" - } - Simulink.ConfigSet { - $PropName "ActiveConfigurationSet" - $ObjectID 1 - } - BlockDefaults { - ForegroundColor "black" - BackgroundColor "white" - DropShadow off - NamePlacement "normal" - FontName "Helvetica" - FontSize 10 - FontWeight "normal" - FontAngle "normal" - ShowName on - BlockRotation 0 - BlockMirror off - } - AnnotationDefaults { - HorizontalAlignment "center" - VerticalAlignment "middle" - ForegroundColor "black" - BackgroundColor "white" - DropShadow off - FontName "Helvetica" - FontSize 10 - FontWeight "normal" - FontAngle "normal" - UseDisplayTextAsClickCallback off - } - LineDefaults { - FontName "Helvetica" - FontSize 9 - FontWeight "normal" - FontAngle "normal" - } - BlockParameterDefaults { - Block { - BlockType Constant - Value "1" - VectorParams1D on - SamplingMode "Sample based" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Inherit from 'Constant value'" - LockScale off - SampleTime "inf" - FramePeriod "inf" - PreserveConstantTs off - } - Block { - BlockType Delay - DelayLengthSource "Dialog" - DelayLength "2" - DelayLengthUpperLimit "100" - InitialConditionSource "Dialog" - InitialCondition "0.0" - ExternalReset "None" - PreventDirectFeedthrough off - DiagnosticForOutOfRangeDelayLength "None" - RemoveProtectionDelayLength off - InputProcessing "Elements as channels (sample based)" - UseCircularBuffer off - SampleTime "-1" - StateMustResolveToSignalObject off - CodeGenStateStorageClass "Auto" - } - Block { - BlockType FrameConversion - InheritSamplingMode off - OutFrame "Frame-based" - } - Block { - BlockType Inport - Port "1" - OutputFunctionCall off - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: auto" - LockScale off - BusOutputAsStruct off - PortDimensions "-1" - VarSizeSig "Inherit" - SampleTime "-1" - SignalType "auto" - SamplingMode "auto" - LatchByDelayingOutsideSignal off - LatchInputForFeedbackSignals off - Interpolate on - } - Block { - BlockType Math - Operator "exp" - OutputSignalType "auto" - SampleTime "-1" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Same as first input" - LockScale off - RndMeth "Floor" - SaturateOnIntegerOverflow on - IntermediateResultsDataTypeStr "Inherit: Inherit via internal rule" - AlgorithmType "Newton-Raphson" - Iterations "3" - } - Block { - BlockType Outport - Port "1" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: auto" - LockScale off - BusOutputAsStruct off - PortDimensions "-1" - VarSizeSig "Inherit" - SampleTime "-1" - SignalType "auto" - SamplingMode "auto" - SourceOfInitialOutputValue "Dialog" - OutputWhenDisabled "held" - InitialOutput "[]" - } - Block { - BlockType Product - Inputs "2" - Multiplication "Element-wise(.*)" - CollapseMode "All dimensions" - CollapseDim "1" - InputSameDT on - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Same as first input" - LockScale off - RndMeth "Zero" - SaturateOnIntegerOverflow on - SampleTime "-1" - } - Block { - BlockType RelationalOperator - Operator ">=" - InputSameDT on - OutDataTypeStr "Inherit: Logical (see Configuration Parameters: Optimization)" - ZeroCross on - SampleTime "-1" - } - Block { - BlockType Reshape - OutputDimensionality "1-D array" - OutputDimensions "[1,1]" - } - Block { - BlockType SignalViewerScope - Floating off - ModelBased off - TickLabels "OneTimeTick" - ZoomMode "on" - Grid "on" - TimeRange "auto" - YMin "-5" - YMax "5" - SaveToWorkspace off - SaveName "ScopeData" - LimitDataPoints on - MaxDataPoints "5000" - Decimation "1" - SampleInput off - SampleTime "0" - Disabled off - ScrollMode on - } - Block { - BlockType SubSystem - ShowPortLabels "FromPortIcon" - Permissions "ReadWrite" - PermitHierarchicalResolution "All" - TreatAsAtomicUnit off - CheckFcnCallInpInsideContextMsg off - SystemSampleTime "-1" - RTWFcnNameOpts "Auto" - RTWFileNameOpts "Auto" - RTWMemSecFuncInitTerm "Inherit from model" - RTWMemSecFuncExecute "Inherit from model" - RTWMemSecDataConstants "Inherit from model" - RTWMemSecDataInternal "Inherit from model" - RTWMemSecDataParameters "Inherit from model" - SimViewingDevice off - DataTypeOverride "UseLocalSettings" - DataTypeOverrideAppliesTo "AllNumericTypes" - MinMaxOverflowLogging "UseLocalSettings" - SFBlockType "NONE" - Variant off - GeneratePreprocessorConditionals off - } - Block { - BlockType Sum - IconShape "rectangular" - Inputs "++" - CollapseMode "All dimensions" - CollapseDim "1" - InputSameDT on - AccumDataTypeStr "Inherit: Inherit via internal rule" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Same as first input" - LockScale off - RndMeth "Floor" - SaturateOnIntegerOverflow on - SampleTime "-1" - } - Block { - BlockType Switch - Criteria "u2 >= Threshold" - Threshold "0" - InputSameDT on - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Inherit via internal rule" - LockScale off - RndMeth "Floor" - SaturateOnIntegerOverflow on - ZeroCross on - SampleTime "-1" - AllowDiffInputSizes off - } - } - System { - Name "PointProcessSimulation" - Location [-1654, 216, -58, 1155] - Open on - ModelBrowserVisibility off - ModelBrowserWidth 200 - ScreenColor "white" - PaperOrientation "landscape" - PaperPositionMode "auto" - PaperType "usletter" - PaperUnits "inches" - TiledPaperMargins [0.500000, 0.500000, 0.500000, 0.500000] - TiledPageScale 1 - ShowPageBoundaries off - ZoomFactor "100" - ReportName "simulink-default.rpt" - SIDHighWatermark "60" - Block { - BlockType Inport - Name "Stimulus" - SID "37" - Position [245, 323, 275, 337] - IconDisplay "Port number" - Port { - PortNumber 1 - Name "input" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Inport - Name "Ensemble" - SID "44" - Position [245, 398, 275, 412] - Port "2" - IconDisplay "Port number" - } - Block { - BlockType Sum - Name "Add" - SID "3" - Ports [4, 1] - Position [575, 250, 605, 290] - Inputs "++++" - InputSameDT off - OutDataTypeStr "Inherit: Inherit via internal rule" - SaturateOnIntegerOverflow off - } - Block { - BlockType SubSystem - Name "Binomial" - SID "48" - Ports [1, 1] - Position [725, 335, 765, 395] - MinAlgLoopOccurrences off - PropExecContextOutsideSubsystem off - RTWSystemCode "Auto" - FunctionWithSeparateData off - Opaque off - RequestExecContextInheritance off - MaskHideContents off - System { - Name "Binomial" - Location [597, 320, 927, 614] - Open off - ModelBrowserVisibility off - ModelBrowserWidth 200 - ScreenColor "white" - PaperOrientation "landscape" - PaperPositionMode "auto" - PaperType "usletter" - PaperUnits "inches" - TiledPaperMargins [0.500000, 0.500000, 0.500000, 0.500000] - TiledPageScale 1 - ShowPageBoundaries off - ZoomFactor "100" - Block { - BlockType Inport - Name "In1" - SID "50" - Position [25, 38, 55, 52] - IconDisplay "Port number" - } - Block { - BlockType Sum - Name "Add1" - SID "32" - Ports [2, 1] - Position [145, 110, 175, 140] - IconShape "round" - Inputs "|++" - InputSameDT off - OutDataTypeStr "Inherit: Inherit via internal rule" - SaturateOnIntegerOverflow off - } - Block { - BlockType Constant - Name "Constant1" - SID "33" - Position [145, 200, 175, 230] - BlockRotation 270 - BackgroundColor "magenta" - } - Block { - BlockType Product - Name "Divide" - SID "31" - Ports [2, 1] - Position [220, 27, 250, 58] - Inputs "*/" - InputSameDT off - OutDataTypeStr "Inherit: Inherit via internal rule" - RndMeth "Floor" - SaturateOnIntegerOverflow off - Port { - PortNumber 1 - Name "s2" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Math - Name "Math\nFunction" - SID "8" - Ports [1, 1] - Position [80, 30, 110, 60] - Port { - PortNumber 1 - Name "s1" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Outport - Name "Out1" - SID "49" - Position [275, 38, 305, 52] - IconDisplay "Port number" - } - Line { - SrcBlock "Constant1" - SrcPort 1 - DstBlock "Add1" - DstPort 2 - } - Line { - Name "s1" - Labels [0, 0] - SrcBlock "Math\nFunction" - SrcPort 1 - Points [5, 0] - Branch { - Points [0, 80] - DstBlock "Add1" - DstPort 1 - } - Branch { - Labels [1, 0] - Points [85, 0] - DstBlock "Divide" - DstPort 1 - } - } - Line { - SrcBlock "Add1" - SrcPort 1 - Points [10, 0; 0, -75] - DstBlock "Divide" - DstPort 2 - } - Line { - Name "s2" - Labels [0, 0] - SrcBlock "Divide" - SrcPort 1 - DstBlock "Out1" - DstPort 1 - } - Line { - SrcBlock "In1" - SrcPort 1 - DstBlock "Math\nFunction" - DstPort 1 - } - Annotation { - Name "Inverse of Logistic Link Function\n \n\n\n\n\n\n\n\n\n\n" - ". " - Position [174, 121] - BackgroundColor "yellow" - FontName "Arial Narrow" - FontSize 18 - } - Annotation { - Name "\\lambda \\cdot \\Delta= e^{X \\cdot \\beta}/(1+e^{X\\cdot \\beta})" - Position [164, 271] - Interpreter "tex" - FontName "Arial Narrow" - FontSize 18 - } - } - } - Block { - BlockType Constant - Name "Constant" - SID "1" - Position [515, 175, 545, 205] - BlockRotation 270 - BlockMirror on - BackgroundColor "magenta" - NamePlacement "alternate" - Value "mu" - } - Block { - BlockType Constant - Name "Constant2" - SID "47" - Position [885, 475, 915, 505] - Value "Ts" - } - Block { - BlockType Product - Name "Divide1" - SID "46" - Ports [2, 1] - Position [990, 467, 1020, 498] - Inputs "*/" - InputSameDT off - OutDataTypeStr "Inherit: Inherit via internal rule" - RndMeth "Floor" - SaturateOnIntegerOverflow off - } - Block { - BlockType Reference - Name "Ensemble Effect" - SID "43" - Ports [1, 1] - Position [410, 387, 505, 423] - BackgroundColor "darkGreen" - LibraryVersion "1.108" - SourceBlock "cstblocks/LTI System" - SourceType "LTI Block" - sys "E" - IC "[]" - } - Block { - BlockType FrameConversion - Name "Frame Status Conversion" - SID "11" - Ports [1, 1] - Position [1125, 260, 1180, 300] - OutFrame "Sample-based" - } - Block { - BlockType Delay - Name "Integer Delay" - SID "22" - Ports [1, 1] - Position [410, 123, 445, 157] - BlockMirror on - UserDataPersistent on - UserData "DataTag0" - InputPortMap "u0" - DelayLength "1" - ExternalReset "None" - } - Block { - BlockType SubSystem - Name "Poisson" - SID "53" - Ports [1, 1] - Position [725, 160, 765, 220] - MinAlgLoopOccurrences off - PropExecContextOutsideSubsystem off - RTWSystemCode "Auto" - FunctionWithSeparateData off - Opaque off - RequestExecContextInheritance off - MaskHideContents off - System { - Name "Poisson" - Location [2, 84, 1678, 978] - Open off - ModelBrowserVisibility off - ModelBrowserWidth 200 - ScreenColor "white" - PaperOrientation "landscape" - PaperPositionMode "auto" - PaperType "usletter" - PaperUnits "inches" - TiledPaperMargins [0.500000, 0.500000, 0.500000, 0.500000] - TiledPageScale 1 - ShowPageBoundaries off - ZoomFactor "100" - Block { - BlockType Inport - Name "In1" - SID "54" - Position [225, 203, 255, 217] - IconDisplay "Port number" - } - Block { - BlockType Math - Name "Math\nFunction" - SID "58" - Ports [1, 1] - Position [360, 195, 390, 225] - Port { - PortNumber 1 - Name "s1" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Outport - Name "Out1" - SID "59" - Position [475, 203, 505, 217] - IconDisplay "Port number" - } - Line { - SrcBlock "In1" - SrcPort 1 - DstBlock "Math\nFunction" - DstPort 1 - } - Line { - Name "s1" - Labels [0, 0; 1, 0] - SrcBlock "Math\nFunction" - SrcPort 1 - DstBlock "Out1" - DstPort 1 - } - Annotation { - Name "\\lambda \\cdot \\Delta= e^{X \\cdot \\beta}" - Position [369, 336] - Interpreter "tex" - FontName "Arial Narrow" - FontSize 18 - } - Annotation { - Name "Inverse of log Link Function\n \n\n\n\n\n\n. " - " " - Position [374, 231] - BackgroundColor "yellow" - FontName "Arial Narrow" - FontSize 18 - } - } - } - Block { - BlockType Reference - Name "Random Source" - SID "12" - Ports [0, 1] - Position [986, 360, 1024, 395] - BlockRotation 270 - LibraryVersion "1.714" - UserDataPersistent on - UserData "DataTag1" - Diagnostics "AllowInheritedTsInSrc" - SourceBlock "dspsrcs4/Random\nSource" - SourceType "Random Source" - SrcType "Uniform" - NormMethod "Ziggurat" - CltLength "12" - MinVal "0" - MaxVal "1" - MeanVal "0" - VarVal "1" - RepMode "Not repeatable" - rawSeed "seed" - IsInherit on - SampMode "Continuous" - SampTime "Ts" - SampFrame "dsp_sampFrame" - DataType "Double" - OutComplex "Real" - } - Block { - BlockType RelationalOperator - Name "Relational Operator" - SID "13" - Ports [2, 1] - Position [1030, 262, 1060, 293] - ShowName off - Operator ">" - OutDataTypeStr "float('double')" - } - Block { - BlockType Reshape - Name "Reshape" - SID "14" - Ports [1, 1] - Position [1220, 268, 1250, 292] - ShowName off - OutputDimensions "[sampPerFrame,max(length(P),length(seed))]" - Port { - PortNumber 1 - Name "spike process" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Reference - Name "Self-History" - SID "5" - Ports [1, 1] - Position [410, 247, 505, 283] - BackgroundColor "orange" - LibraryVersion "1.108" - SourceBlock "cstblocks/LTI System" - SourceType "LTI Block" - sys "H" - IC "[]" - } - Block { - BlockType Reference - Name "Stimulus Effect" - SID "6" - Ports [1, 1] - Position [410, 312, 505, 348] - BackgroundColor "darkGreen" - LibraryVersion "1.108" - SourceBlock "cstblocks/LTI System" - SourceType "LTI Block" - sys "S" - IC "[]" - } - Block { - BlockType Switch - Name "Switch" - SID "51" - Position [820, 250, 870, 290] - Criteria "u2 ~= 0" - InputSameDT off - SaturateOnIntegerOverflow off - } - Block { - BlockType Constant - Name "simType\nSelector" - SID "52" - Position [730, 255, 760, 285] - Value "simTypeSelect" - } - Block { - BlockType Outport - Name "pp" - SID "26" - Position [1310, 273, 1340, 287] - IconDisplay "Port number" - } - Block { - BlockType Outport - Name "lambdaDelta" - SID "45" - Position [1065, 478, 1095, 492] - Port "2" - IconDisplay "Port number" - } - Block { - BlockType SignalViewerScope - Name "Scope" - SID "28" - Ports [] - Position [20, 15, 60, 55] - IOType "viewer" - List { - ListType IOSignalStrings - set0ParseKeys "10,18" - set0Sigs "Reshape:o1Stimulus Effect:o1" - } - Location [1, 53, 1601, 1151] - Open off - NumInputPorts "1" - List { - ListType AxesTitles - axes1 "%" - } - ShowDataMarkers off - ShowLegends off - DataFormat "Array" - MaxDataPoints "7500" - RefreshTime 0.035000 - } - Block { - BlockType SignalViewerScope - Name "Scope1" - SID "29" - Ports [] - Position [20, 15, 60, 55] - IOType "viewer" - List { - ListType IOSignalStrings - set0ParseKeys "25,18" - set0Sigs "Binomial/Math Function:o1Binomial/Divide:o1" - } - Location [1, 53, 1601, 1151] - Open off - NumInputPorts "1" - List { - ListType AxesTitles - axes1 "%" - } - ShowDataMarkers off - ShowLegends off - SaveName "ScopeData1" - DataFormat "Array" - MaxDataPoints "7500" - RefreshTime 0.035000 - } - Block { - BlockType SignalViewerScope - Name "Scope2" - SID "38" - Ports [] - Position [20, 15, 60, 55] - IOType "viewer" - List { - ListType IOSignalStrings - set0ParseKeys "15" - set0Sigs "Self-History:o1" - } - Location [5, 53, 1605, 1151] - Open off - NumInputPorts "1" - List { - ListType AxesTitles - axes1 "%" - } - ShowDataMarkers off - ShowLegends off - SaveName "ScopeData2" - DataFormat "Array" - MaxDataPoints "7500" - RefreshTime 0.035000 - } - Line { - SrcBlock "Constant" - SrcPort 1 - Points [0, 45] - DstBlock "Add" - DstPort 1 - } - Line { - SrcBlock "Self-History" - SrcPort 1 - DstBlock "Add" - DstPort 2 - } - Line { - SrcBlock "Stimulus Effect" - SrcPort 1 - Points [15, 0; 0, -55] - DstBlock "Add" - DstPort 3 - } - Line { - SrcBlock "Add" - SrcPort 1 - Points [55, 0] - Branch { - Points [0, 95] - DstBlock "Binomial" - DstPort 1 - } - Branch { - Points [0, -80] - DstBlock "Poisson" - DstPort 1 - } - } - Line { - SrcBlock "Frame Status Conversion" - SrcPort 1 - DstBlock "Reshape" - DstPort 1 - } - Line { - Name "spike process" - SrcBlock "Reshape" - SrcPort 1 - Points [25, 0] - Branch { - Labels [1, 0] - Points [0, -140] - DstBlock "Integer Delay" - DstPort 1 - } - Branch { - DstBlock "pp" - DstPort 1 - } - } - Line { - SrcBlock "Relational Operator" - SrcPort 1 - DstBlock "Frame Status Conversion" - DstPort 1 - } - Line { - SrcBlock "Random Source" - SrcPort 1 - Points [0, -70] - DstBlock "Relational Operator" - DstPort 2 - } - Line { - Name "input" - Labels [0, 0] - SrcBlock "Stimulus" - SrcPort 1 - DstBlock "Stimulus Effect" - DstPort 1 - } - Line { - SrcBlock "Integer Delay" - SrcPort 1 - Points [-65, 0; 0, 125] - DstBlock "Self-History" - DstPort 1 - } - Line { - SrcBlock "Ensemble" - SrcPort 1 - DstBlock "Ensemble Effect" - DstPort 1 - } - Line { - SrcBlock "Ensemble Effect" - SrcPort 1 - Points [25, 0; 0, -120] - DstBlock "Add" - DstPort 4 - } - Line { - SrcBlock "Constant2" - SrcPort 1 - DstBlock "Divide1" - DstPort 2 - } - Line { - SrcBlock "Divide1" - SrcPort 1 - DstBlock "lambdaDelta" - DstPort 1 - } - Line { - SrcBlock "simType\nSelector" - SrcPort 1 - DstBlock "Switch" - DstPort 2 - } - Line { - SrcBlock "Binomial" - SrcPort 1 - Points [15, 0; 0, -80] - DstBlock "Switch" - DstPort 3 - } - Line { - SrcBlock "Switch" - SrcPort 1 - Points [50, 0] - Branch { - DstBlock "Relational Operator" - DstPort 1 - } - Branch { - Points [0, 205] - DstBlock "Divide1" - DstPort 1 - } - } - Line { - SrcBlock "Poisson" - SrcPort 1 - Points [15, 0; 0, 65] - DstBlock "Switch" - DstPort 1 - } - Annotation { - Name "GLM Model \n\n " - " \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n. " - Position [414, 261] - BackgroundColor "lightBlue" - FontName "Arial Narrow" - FontSize 18 - } - Annotation { - Name "Coin flip with\np= \\lambda \\cdot \\Delta\n\n\n\n\n\n\n\n\n\n\n." - Position [1034, 356] - Interpreter "tex" - FontName "Arial Narrow" - FontSize 18 - } - Annotation { - Name "Poisson:\n\\lambda \\cdot \\Delta = e^{X \\cdot \\beta}\nBinomial: \n\\lambda \\cdot \\Delta = e^{X" - " \\cdot \\beta}/({1+e^{X \\cdot \\beta}})" - Position [869, 78] - BackgroundColor "yellow" - Interpreter "tex" - FontName "Arial Narrow" - FontSize 22 - } - } -} -MatData { - NumRecords 2 - DataRecord { - Tag DataTag1 - Data " %)30 . V 8 ( @ % \" $ ! 0 % 0 \"0 $ 2 4V5E9" - " 4V5E9$9L86< #@ #@ & \" 0 !0 @ ! !0 $ $ 4 R,S$Q,P " - "X ! !@ @ $ 4 ( 0 T ! ! - 1&].;W13879E4V5E9 " - } - DataRecord { - Tag DataTag0 - Data " %)30 . B 8 ( @ % \" $ ! 0 % 0 $P $ 3 :&%S26" - "YH97)I=&5D3W!T:6]N #@ # & \" D\" !0 @ ! 0 $ @ ! $ " - } -} diff --git a/PointProcessSimulation.mdl.r2013a b/PointProcessSimulation.mdl.r2013a deleted file mode 100644 index 81c744a8..00000000 --- a/PointProcessSimulation.mdl.r2013a +++ /dev/null @@ -1,1718 +0,0 @@ -Model { - Name "PointProcessSimulation" - Version 8.1 - MdlSubVersion 0 - GraphicalInterface { - NumRootInports 2 - Inport { - BusObject "" - SignalName "input" - Name "Stimulus" - } - Inport { - BusObject "" - Name "Ensemble" - } - NumRootOutports 2 - Outport { - BusObject "" - BusOutputAsStruct "off" - SignalName "spike process" - Name "pp" - } - Outport { - BusObject "" - BusOutputAsStruct "off" - Name "lambdaDelta" - } - ParameterArgumentNames "" - ComputedModelVersion "1.32" - NumModelReferences 0 - NumTestPointedSignals 0 - } - SavedCharacterEncoding "ISO-8859-1" - SaveDefaultBlockParams on - ScopeRefreshTime 0.035000 - OverrideScopeRefreshTime on - DisableAllScopes off - DataTypeOverride "UseLocalSettings" - DataTypeOverrideAppliesTo "AllNumericTypes" - MinMaxOverflowLogging "UseLocalSettings" - MinMaxOverflowArchiveMode "Overwrite" - FPTRunName "Run 1" - MaxMDLFileLineLength 120 - Object { - $PropName "BdWindowsInfo" - $ObjectID 1 - $ClassName "Simulink.BDWindowsInfo" - Object { - $PropName "WindowsInfo" - $ObjectID 2 - $ClassName "Simulink.WindowInfo" - IsActive [1] - Location [8.0, 240.0, 1636.0, 973.0] - Object { - $PropName "ModelBrowserInfo" - $ObjectID 3 - $ClassName "Simulink.ModelBrowserInfo" - Visible [0] - DockPosition "Left" - Width [50] - Height [50] - Filter [8] - } - Object { - $PropName "ExplorerBarInfo" - $ObjectID 4 - $ClassName "Simulink.ExplorerBarInfo" - Visible [1] - } - Object { - $PropName "EditorsInfo" - $ObjectID 5 - $ClassName "Simulink.EditorInfo" - IsActive [1] - ViewObjType "SimulinkTopLevel" - LoadSaveID "0" - Extents [1602.0, 800.0] - ZoomFactor [1.0] - Offset [0.0, 0.0] - } - } - } - Created "Tue Feb 08 12:34:27 2011" - Creator "Developer" - UpdateHistory "UpdateHistoryNever" - ModifiedByFormat "%" - LastModifiedBy "wqm" - ModifiedDateFormat "%" - LastModifiedDate "Thu May 23 16:51:18 2013" - RTWModifiedTimeStamp 291228671 - ModelVersionFormat "1.%" - ConfigurationManager "None" - SampleTimeColors off - SampleTimeAnnotations off - LibraryLinkDisplay "none" - WideLines off - ShowLineDimensions off - ShowPortDataTypes off - ShowDesignRanges off - ShowLoopsOnError on - IgnoreBidirectionalLines off - ShowStorageClass off - ShowTestPointIcons on - ShowSignalResolutionIcons on - ShowViewerIcons on - SortedOrder off - ExecutionContextIcon off - ShowLinearizationAnnotations on - BlockNameDataTip off - BlockParametersDataTip off - BlockDescriptionStringDataTip off - ToolBar on - StatusBar on - BrowserShowLibraryLinks off - BrowserLookUnderMasks off - SimulationMode "normal" - LinearizationMsg "none" - Profile off - ParamWorkspaceSource "MATLABWorkspace" - AccelSystemTargetFile "accel.tlc" - AccelTemplateMakefile "accel_default_tmf" - AccelMakeCommand "make_rtw" - TryForcingSFcnDF off - Object { - $PropName "DataLoggingOverride" - $ObjectID 6 - $ClassName "Simulink.SimulationData.ModelLoggingInfo" - model_ "PointProcessSimulation" - Array { - Type "Cell" - Dimension 1 - Cell "PointProcessSimulation" - PropName "logAsSpecifiedByModels_" - } - Array { - Type "Cell" - Dimension 1 - Cell "" - PropName "logAsSpecifiedByModelsSSIDs_" - } - } - RecordCoverage off - CovPath "/" - CovSaveName "covdata" - CovMetricSettings "dw" - CovNameIncrementing off - CovHtmlReporting on - CovForceBlockReductionOff on - covSaveCumulativeToWorkspaceVar on - CovSaveSingleToWorkspaceVar on - CovCumulativeVarName "covCumulativeData" - CovCumulativeReport off - CovReportOnPause on - CovModelRefEnable "Off" - CovExternalEMLEnable off - ExtModeBatchMode off - ExtModeEnableFloating on - ExtModeTrigType "manual" - ExtModeTrigMode "normal" - ExtModeTrigPort "1" - ExtModeTrigElement "any" - ExtModeTrigDuration 1000 - ExtModeTrigDurationFloating "auto" - ExtModeTrigHoldOff 0 - ExtModeTrigDelay 0 - ExtModeTrigDirection "rising" - ExtModeTrigLevel 0 - ExtModeArchiveMode "off" - ExtModeAutoIncOneShot off - ExtModeIncDirWhenArm off - ExtModeAddSuffixToVar off - ExtModeWriteAllDataToWs off - ExtModeArmWhenConnect on - ExtModeSkipDownloadWhenConnect off - ExtModeLogAll on - ExtModeAutoUpdateStatusClock on - BufferReuse on - ShowModelReferenceBlockVersion off - ShowModelReferenceBlockIO off - Array { - Type "Handle" - Dimension 1 - Simulink.ConfigSet { - $ObjectID 7 - Version "1.13.0" - Array { - Type "Handle" - Dimension 8 - Simulink.SolverCC { - $ObjectID 8 - Version "1.13.0" - StartTime "0.0" - StopTime "10" - AbsTol "auto" - FixedStep "Ts" - InitialStep "auto" - MaxNumMinSteps "-1" - MaxOrder 5 - ZcThreshold "auto" - ConsecutiveZCsStepRelTol "10*128*eps" - MaxConsecutiveZCs "1000" - ExtrapolationOrder 4 - NumberNewtonIterations 1 - MaxStep "auto" - MinStep "auto" - MaxConsecutiveMinStep "1" - RelTol "1e-3" - SolverMode "Auto" - EnableConcurrentExecution off - ConcurrentTasks off - Solver "FixedStepDiscrete" - SolverName "FixedStepDiscrete" - SolverJacobianMethodControl "auto" - ShapePreserveControl "DisableAll" - ZeroCrossControl "UseLocalSettings" - ZeroCrossAlgorithm "Nonadaptive" - AlgebraicLoopSolver "TrustRegion" - SolverResetMethod "Fast" - PositivePriorityOrder off - AutoInsertRateTranBlk off - SampleTimeConstraint "Unconstrained" - InsertRTBMode "Whenever possible" - } - Simulink.DataIOCC { - $ObjectID 9 - Version "1.13.0" - Decimation "1" - ExternalInput "[t, u]" - FinalStateName "xFinal" - InitialState "xInitial" - LimitDataPoints on - MaxDataPoints "1000" - LoadExternalInput off - LoadInitialState off - SaveFinalState off - SaveCompleteFinalSimState off - SaveFormat "Array" - SignalLoggingSaveFormat "Dataset" - SaveOutput on - SaveState off - SignalLogging on - DSMLogging on - InspectSignalLogs off - SaveTime on - ReturnWorkspaceOutputs off - StateSaveName "xout" - TimeSaveName "tout" - OutputSaveName "yout" - SignalLoggingName "logsout" - DSMLoggingName "dsmout" - OutputOption "RefineOutputTimes" - OutputTimes "[]" - ReturnWorkspaceOutputsName "out" - Refine "1" - } - Simulink.OptimizationCC { - $ObjectID 10 - Version "1.13.0" - Array { - Type "Cell" - Dimension 8 - Cell "BooleansAsBitfields" - Cell "PassReuseOutputArgsAs" - Cell "PassReuseOutputArgsThreshold" - Cell "ZeroExternalMemoryAtStartup" - Cell "ZeroInternalMemoryAtStartup" - Cell "OptimizeModelRefInitCode" - Cell "NoFixptDivByZeroProtection" - Cell "UseSpecifiedMinMax" - PropName "DisabledProps" - } - BlockReduction on - BooleanDataType on - ConditionallyExecuteInputs on - InlineParams off - UseIntDivNetSlope off - UseFloatMulNetSlope off - UseSpecifiedMinMax off - InlineInvariantSignals off - OptimizeBlockIOStorage on - BufferReuse on - EnhancedBackFolding off - StrengthReduction off - ExpressionFolding on - BooleansAsBitfields off - BitfieldContainerType "uint_T" - EnableMemcpy on - MemcpyThreshold 64 - PassReuseOutputArgsAs "Structure reference" - ExpressionDepthLimit 2147483647 - FoldNonRolledExpr on - LocalBlockOutputs on - RollThreshold 5 - SystemCodeInlineAuto off - StateBitsets off - DataBitsets off - UseTempVars off - ZeroExternalMemoryAtStartup on - ZeroInternalMemoryAtStartup on - InitFltsAndDblsToZero off - NoFixptDivByZeroProtection off - EfficientFloat2IntCast off - EfficientMapNaN2IntZero on - OptimizeModelRefInitCode off - LifeSpan "inf" - MaxStackSize "Inherit from target" - BufferReusableBoundary on - SimCompilerOptimization "Off" - AccelVerboseBuild off - ParallelExecutionInRapidAccelerator on - } - Simulink.DebuggingCC { - $ObjectID 11 - Version "1.13.0" - RTPrefix "error" - ConsistencyChecking "none" - ArrayBoundsChecking "none" - SignalInfNanChecking "none" - SignalRangeChecking "none" - ReadBeforeWriteMsg "UseLocalSettings" - WriteAfterWriteMsg "UseLocalSettings" - WriteAfterReadMsg "UseLocalSettings" - AlgebraicLoopMsg "warning" - ArtificialAlgebraicLoopMsg "warning" - SaveWithDisabledLinksMsg "warning" - SaveWithParameterizedLinksMsg "warning" - CheckSSInitialOutputMsg on - UnderspecifiedInitializationDetection "Classic" - MergeDetectMultiDrivingBlocksExec "none" - CheckExecutionContextPreStartOutputMsg off - CheckExecutionContextRuntimeOutputMsg off - SignalResolutionControl "UseLocalSettings" - BlockPriorityViolationMsg "warning" - MinStepSizeMsg "warning" - TimeAdjustmentMsg "none" - MaxConsecutiveZCsMsg "error" - MaskedZcDiagnostic "warning" - IgnoredZcDiagnostic "warning" - SolverPrmCheckMsg "warning" - InheritedTsInSrcMsg "warning" - DiscreteInheritContinuousMsg "warning" - MultiTaskDSMMsg "error" - MultiTaskCondExecSysMsg "error" - MultiTaskRateTransMsg "error" - SingleTaskRateTransMsg "none" - TasksWithSamePriorityMsg "warning" - SigSpecEnsureSampleTimeMsg "warning" - CheckMatrixSingularityMsg "none" - IntegerOverflowMsg "warning" - Int32ToFloatConvMsg "warning" - ParameterDowncastMsg "error" - ParameterOverflowMsg "error" - ParameterUnderflowMsg "none" - ParameterPrecisionLossMsg "warning" - ParameterTunabilityLossMsg "warning" - FixptConstUnderflowMsg "none" - FixptConstOverflowMsg "none" - FixptConstPrecisionLossMsg "none" - UnderSpecifiedDataTypeMsg "none" - UnnecessaryDatatypeConvMsg "none" - VectorMatrixConversionMsg "none" - InvalidFcnCallConnMsg "error" - FcnCallInpInsideContextMsg "EnableAllAsError" - SignalLabelMismatchMsg "none" - UnconnectedInputMsg "warning" - UnconnectedOutputMsg "warning" - UnconnectedLineMsg "warning" - SFcnCompatibilityMsg "none" - FrameProcessingCompatibilityMsg "warning" - UniqueDataStoreMsg "none" - BusObjectLabelMismatch "warning" - RootOutportRequireBusObject "warning" - AssertControl "UseLocalSettings" - EnableOverflowDetection off - ModelReferenceIOMsg "none" - ModelReferenceMultiInstanceNormalModeStructChecksumCheck "error" - ModelReferenceVersionMismatchMessage "none" - ModelReferenceIOMismatchMessage "none" - ModelReferenceCSMismatchMessage "none" - UnknownTsInhSupMsg "warning" - ModelReferenceDataLoggingMessage "warning" - ModelReferenceSymbolNameMessage "warning" - ModelReferenceExtraNoncontSigs "error" - StateNameClashWarn "warning" - SimStateInterfaceChecksumMismatchMsg "warning" - SimStateOlderReleaseMsg "error" - InitInArrayFormatMsg "warning" - StrictBusMsg "ErrorLevel1" - BusNameAdapt "WarnAndRepair" - NonBusSignalsTreatedAsBus "none" - LoggingUnavailableSignals "error" - BlockIODiagnostic "none" - SFUnusedDataAndEventsDiag "warning" - SFUnexpectedBacktrackingDiag "warning" - SFInvalidInputDataAccessInChartInitDiag "warning" - SFNoUnconditionalDefaultTransitionDiag "warning" - SFTransitionOutsideNaturalParentDiag "warning" - SFUnconditionalTransitionShadowingDiag "warning" - SFUndirectedBroadcastEventsDiag "warning" - SFTransitionActionBeforeConditionDiag "warning" - } - Simulink.HardwareCC { - $ObjectID 12 - Version "1.13.0" - ProdBitPerChar 8 - ProdBitPerShort 16 - ProdBitPerInt 32 - ProdBitPerLong 32 - ProdBitPerLongLong 64 - ProdBitPerFloat 32 - ProdBitPerDouble 64 - ProdBitPerPointer 32 - ProdLargestAtomicInteger "Char" - ProdLargestAtomicFloat "None" - ProdIntDivRoundTo "Undefined" - ProdEndianess "Unspecified" - ProdWordSize 32 - ProdShiftRightIntArith on - ProdLongLongMode off - ProdHWDeviceType "32-bit Generic" - TargetBitPerChar 8 - TargetBitPerShort 16 - TargetBitPerInt 32 - TargetBitPerLong 64 - TargetBitPerLongLong 64 - TargetBitPerFloat 32 - TargetBitPerDouble 64 - TargetBitPerPointer 64 - TargetLargestAtomicInteger "Char" - TargetLargestAtomicFloat "None" - TargetShiftRightIntArith on - TargetLongLongMode off - TargetIntDivRoundTo "Zero" - TargetEndianess "LittleEndian" - TargetWordSize 64 - TargetTypeEmulationWarnSuppressLevel 0 - TargetPreprocMaxBitsSint 32 - TargetPreprocMaxBitsUint 32 - TargetHWDeviceType "MATLAB Host" - TargetUnknown off - ProdEqTarget off - } - Simulink.ModelReferenceCC { - $ObjectID 13 - Version "1.13.0" - UpdateModelReferenceTargets "IfOutOfDateOrStructuralChange" - CheckModelReferenceTargetMessage "error" - EnableParallelModelReferenceBuilds off - ParallelModelReferenceErrorOnInvalidPool on - ParallelModelReferenceMATLABWorkerInit "None" - ModelReferenceNumInstancesAllowed "Multi" - PropagateVarSize "Infer from blocks in model" - ModelReferencePassRootInputsByReference on - ModelReferenceMinAlgLoopOccurrences off - PropagateSignalLabelsOutOfModel off - SupportModelReferenceSimTargetCustomCode off - } - Simulink.SFSimCC { - $ObjectID 14 - Version "1.13.0" - SFSimEnableDebug on - SFSimOverflowDetection on - SFSimEcho on - SimBlas on - SimCtrlC on - SimExtrinsic on - SimIntegrity on - SimUseLocalCustomCode off - SimParseCustomCode on - SimBuildMode "sf_incremental_build" - } - Simulink.RTWCC { - $BackupClass "Simulink.RTWCC" - $ObjectID 15 - Version "1.13.0" - Array { - Type "Cell" - Dimension 7 - Cell "IncludeHyperlinkInReport" - Cell "GenerateTraceInfo" - Cell "GenerateTraceReport" - Cell "GenerateTraceReportSl" - Cell "GenerateTraceReportSf" - Cell "GenerateTraceReportEml" - Cell "GenerateSLWebview" - PropName "DisabledProps" - } - SystemTargetFile "grt.tlc" - GenCodeOnly off - MakeCommand "make_rtw" - GenerateMakefile on - PackageGeneratedCodeAndArtifacts off - TemplateMakefile "grt_default_tmf" - Description "Generic Real-Time Target" - GenerateReport off - SaveLog off - RTWVerbose on - RetainRTWFile off - ProfileTLC off - TLCDebug off - TLCCoverage off - TLCAssert off - ProcessScriptMode "Default" - ConfigurationMode "Optimized" - ProcessScript "grt_make_rtw_hook" - ConfigAtBuild off - RTWUseLocalCustomCode off - RTWUseSimCustomCode off - IncludeHyperlinkInReport off - LaunchReport off - PortableWordSizes off - GenerateErtSFunction off - CreateSILPILBlock "None" - CodeExecutionProfiling off - CodeExecutionProfileVariable "executionProfile" - CodeProfilingSaveOptions "SummaryOnly" - CodeProfilingInstrumentation off - SILDebugging off - TargetLang "C" - IncludeBusHierarchyInRTWFileBlockHierarchyMap off - IncludeERTFirstTime off - GenerateTraceInfo off - GenerateTraceReport off - GenerateTraceReportSl off - GenerateTraceReportSf off - GenerateTraceReportEml off - GenerateCodeInfo off - GenerateWebview off - GenerateCodeMetricsReport off - GenerateCodeReplacementReport off - RTWCompilerOptimization "On" - CheckMdlBeforeBuild "Off" - CustomRebuildMode "OnUpdate" - Array { - Type "Handle" - Dimension 2 - Simulink.CodeAppCC { - $ObjectID 16 - Version "1.13.0" - Array { - Type "Cell" - Dimension 21 - Cell "IgnoreCustomStorageClasses" - Cell "IgnoreTestpoints" - Cell "InsertBlockDesc" - Cell "InsertPolySpaceComments" - Cell "SFDataObjDesc" - Cell "MATLABFcnDesc" - Cell "SimulinkDataObjDesc" - Cell "DefineNamingRule" - Cell "SignalNamingRule" - Cell "ParamNamingRule" - Cell "InlinedPrmAccess" - Cell "CustomSymbolStr" - Cell "CustomSymbolStrGlobalVar" - Cell "CustomSymbolStrType" - Cell "CustomSymbolStrField" - Cell "CustomSymbolStrFcn" - Cell "CustomSymbolStrFcnArg" - Cell "CustomSymbolStrBlkIO" - Cell "CustomSymbolStrTmpVar" - Cell "CustomSymbolStrMacro" - Cell "ReqsInCode" - PropName "DisabledProps" - } - ForceParamTrailComments off - GenerateComments on - IgnoreCustomStorageClasses on - IgnoreTestpoints off - IncHierarchyInIds off - MaxIdLength 31 - PreserveName off - PreserveNameWithParent off - ShowEliminatedStatement off - OperatorAnnotations off - IncAutoGenComments off - SimulinkDataObjDesc off - SFDataObjDesc off - MATLABFcnDesc off - IncDataTypeInIds off - MangleLength 1 - CustomSymbolStrGlobalVar "$R$N$M" - CustomSymbolStrType "$N$R$M_T" - CustomSymbolStrField "$N$M" - CustomSymbolStrFcn "$R$N$M$F" - CustomSymbolStrFcnArg "rt$I$N$M" - CustomSymbolStrBlkIO "rtb_$N$M" - CustomSymbolStrTmpVar "$N$M" - CustomSymbolStrMacro "$R$N$M" - DefineNamingRule "None" - ParamNamingRule "None" - SignalNamingRule "None" - InsertBlockDesc off - InsertPolySpaceComments off - SimulinkBlockComments on - MATLABSourceComments off - EnableCustomComments off - InternalIdentifier "Shortened" - InlinedPrmAccess "Literals" - ReqsInCode off - UseSimReservedNames off - } - Simulink.GRTTargetCC { - $BackupClass "Simulink.TargetCC" - $ObjectID 17 - Version "1.13.0" - Array { - Type "Cell" - Dimension 16 - Cell "GeneratePreprocessorConditionals" - Cell "IncludeMdlTerminateFcn" - Cell "CombineOutputUpdateFcns" - Cell "SuppressErrorStatus" - Cell "ERTCustomFileBanners" - Cell "GenerateSampleERTMain" - Cell "GenerateTestInterfaces" - Cell "ModelStepFunctionPrototypeControlCompliant" - Cell "CPPClassGenCompliant" - Cell "PortableWordSizes" - Cell "PurelyIntegerCode" - Cell "SupportComplex" - Cell "SupportAbsoluteTime" - Cell "SupportContinuousTime" - Cell "SupportNonInlinedSFcns" - Cell "GenerateAllocFcn" - PropName "DisabledProps" - } - TargetFcnLib "ansi_tfl_table_tmw.mat" - TargetLibSuffix "" - TargetPreCompLibLocation "" - CodeReplacementLibrary "ANSI_C" - UtilityFuncGeneration "Auto" - ERTMultiwordTypeDef "System defined" - ERTMultiwordLength 256 - MultiwordLength 2048 - GenerateFullHeader on - GenerateSampleERTMain off - GenerateTestInterfaces off - IsPILTarget off - ModelReferenceCompliant on - ParMdlRefBuildCompliant on - CompOptLevelCompliant on - ConcurrentExecutionCompliant on - IncludeMdlTerminateFcn on - GeneratePreprocessorConditionals "Disable all" - CombineOutputUpdateFcns off - CombineSignalStateStructs off - SuppressErrorStatus off - ERTFirstTimeCompliant off - IncludeFileDelimiter "Auto" - ERTCustomFileBanners off - SupportAbsoluteTime on - LogVarNameModifier "rt_" - MatFileLogging on - MultiInstanceERTCode off - SupportNonFinite on - SupportComplex on - PurelyIntegerCode off - SupportContinuousTime on - SupportNonInlinedSFcns on - SupportVariableSizeSignals off - EnableShiftOperators on - ParenthesesLevel "Nominal" - MATLABClassNameForMDSCustomization "Simulink.SoftwareTarget.GRTCustomization" - ModelStepFunctionPrototypeControlCompliant off - CPPClassGenCompliant off - AutosarCompliant off - GRTInterface on - GenerateAllocFcn off - UseMalloc off - ExtMode off - ExtModeStaticAlloc off - ExtModeTesting off - ExtModeStaticAllocSize 1000000 - ExtModeTransport 0 - ExtModeMexFile "ext_comm" - ExtModeIntrfLevel "Level1" - RTWCAPISignals off - RTWCAPIParams off - RTWCAPIStates off - RTWCAPIRootIO off - GenerateASAP2 off - } - PropName "Components" - } - } - PropName "Components" - } - Name "Configuration" - CurrentDlgPage "Diagnostics/Connectivity" - ConfigPrmDlgPosition [ 485, 268, 1623, 942 ] - } - PropName "ConfigurationSets" - } - Simulink.ConfigSet { - $PropName "ActiveConfigurationSet" - $ObjectID 7 - } - Object { - $PropName "DataTransfer" - $ObjectID 18 - $ClassName "Simulink.GlobalDataTransfer" - DefaultTransitionBetweenSyncTasks "Ensure deterministic transfer (maximum delay)" - DefaultTransitionBetweenAsyncTasks "Ensure data integrity only" - DefaultTransitionBetweenContTasks "Ensure deterministic transfer (minimum delay)" - DefaultExtrapolationMethodBetweenContTasks "None" - AutoInsertRateTranBlk [0] - } - ExplicitPartitioning off - BlockDefaults { - ForegroundColor "black" - BackgroundColor "white" - DropShadow off - NamePlacement "normal" - FontName "Helvetica" - FontSize 10 - FontWeight "normal" - FontAngle "normal" - ShowName on - BlockRotation 0 - BlockMirror off - } - AnnotationDefaults { - HorizontalAlignment "center" - VerticalAlignment "middle" - ForegroundColor "black" - BackgroundColor "white" - DropShadow off - FontName "Helvetica" - FontSize 10 - FontWeight "normal" - FontAngle "normal" - UseDisplayTextAsClickCallback off - } - LineDefaults { - FontName "Helvetica" - FontSize 9 - FontWeight "normal" - FontAngle "normal" - } - MaskDefaults { - SelfModifiable "off" - IconFrame "on" - IconOpaque "on" - RunInitForIconRedraw "off" - IconRotate "none" - PortRotate "default" - IconUnits "autoscale" - } - MaskParameterDefaults { - Evaluate "on" - Tunable "on" - NeverSave "off" - Internal "off" - ReadOnly "off" - Enabled "on" - Visible "on" - ToolTip "on" - } - BlockParameterDefaults { - Block { - BlockType Constant - Value "1" - VectorParams1D on - SamplingMode "Sample based" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Inherit from 'Constant value'" - LockScale off - SampleTime "inf" - FramePeriod "inf" - PreserveConstantTs off - } - Block { - BlockType Delay - DelayLengthSource "Dialog" - DelayLength "2" - DelayLengthUpperLimit "100" - InitialConditionSource "Dialog" - InitialCondition "0.0" - ExternalReset "None" - PreventDirectFeedthrough off - DiagnosticForOutOfRangeDelayLength "None" - RemoveProtectionDelayLength off - InputProcessing "Elements as channels (sample based)" - UseCircularBuffer off - SampleTime "-1" - StateMustResolveToSignalObject off - CodeGenStateStorageClass "Auto" - } - Block { - BlockType FrameConversion - InheritSamplingMode off - OutFrame "Frame-based" - } - Block { - BlockType Inport - Port "1" - OutputFunctionCall off - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: auto" - LockScale off - BusOutputAsStruct off - PortDimensions "-1" - VarSizeSig "Inherit" - SampleTime "-1" - SignalType "auto" - SamplingMode "auto" - LatchByDelayingOutsideSignal off - LatchInputForFeedbackSignals off - Interpolate on - } - Block { - BlockType Math - Operator "exp" - OutputSignalType "auto" - SampleTime "-1" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Same as first input" - LockScale off - RndMeth "Floor" - SaturateOnIntegerOverflow on - IntermediateResultsDataTypeStr "Inherit: Inherit via internal rule" - AlgorithmType "Newton-Raphson" - Iterations "3" - } - Block { - BlockType Outport - Port "1" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: auto" - LockScale off - BusOutputAsStruct off - PortDimensions "-1" - VarSizeSig "Inherit" - SampleTime "-1" - SignalType "auto" - SamplingMode "auto" - SourceOfInitialOutputValue "Dialog" - OutputWhenDisabled "held" - InitialOutput "[]" - } - Block { - BlockType Product - Inputs "2" - Multiplication "Element-wise(.*)" - CollapseMode "All dimensions" - CollapseDim "1" - InputSameDT on - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Same as first input" - LockScale off - RndMeth "Zero" - SaturateOnIntegerOverflow on - SampleTime "-1" - } - Block { - BlockType RelationalOperator - Operator ">=" - InputSameDT on - OutDataTypeStr "Inherit: Logical (see Configuration Parameters: Optimization)" - ZeroCross on - SampleTime "-1" - } - Block { - BlockType Reshape - OutputDimensionality "1-D array" - OutputDimensions "[1,1]" - } - Block { - BlockType SignalViewerScope - Floating off - ModelBased off - TickLabels "OneTimeTick" - ZoomMode "on" - Grid "on" - TimeRange "auto" - YMin "-5" - YMax "5" - SaveToWorkspace off - SaveName "ScopeData" - DataFormat "Array" - LimitDataPoints on - MaxDataPoints "5000" - Decimation "1" - SampleInput off - SampleTime "0" - Disabled off - ScrollMode on - } - Block { - BlockType SubSystem - ShowPortLabels "FromPortIcon" - Permissions "ReadWrite" - PermitHierarchicalResolution "All" - TreatAsAtomicUnit off - CheckFcnCallInpInsideContextMsg off - SystemSampleTime "-1" - RTWFcnNameOpts "Auto" - RTWFileNameOpts "Auto" - FunctionInterfaceSpec "void_void" - RTWMemSecFuncInitTerm "Inherit from model" - RTWMemSecFuncExecute "Inherit from model" - RTWMemSecDataConstants "Inherit from model" - RTWMemSecDataInternal "Inherit from model" - RTWMemSecDataParameters "Inherit from model" - SimViewingDevice off - DataTypeOverride "UseLocalSettings" - DataTypeOverrideAppliesTo "AllNumericTypes" - MinMaxOverflowLogging "UseLocalSettings" - SFBlockType "NONE" - Variant off - GeneratePreprocessorConditionals off - } - Block { - BlockType Sum - IconShape "rectangular" - Inputs "++" - CollapseMode "All dimensions" - CollapseDim "1" - InputSameDT on - AccumDataTypeStr "Inherit: Inherit via internal rule" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Same as first input" - LockScale off - RndMeth "Floor" - SaturateOnIntegerOverflow on - SampleTime "-1" - } - Block { - BlockType Switch - Criteria "u2 >= Threshold" - Threshold "0" - InputSameDT on - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Inherit via internal rule" - LockScale off - RndMeth "Floor" - SaturateOnIntegerOverflow on - ZeroCross on - SampleTime "-1" - AllowDiffInputSizes off - } - } - System { - Name "PointProcessSimulation" - Location [8, 240, 1644, 1213] - Open on - ModelBrowserVisibility off - ModelBrowserWidth 200 - ScreenColor "white" - PaperOrientation "landscape" - PaperPositionMode "auto" - PaperType "usletter" - PaperUnits "inches" - TiledPaperMargins [0.500000, 0.500000, 0.500000, 0.500000] - TiledPageScale 1 - ShowPageBoundaries off - ZoomFactor "100" - ReportName "simulink-default.rpt" - SIDHighWatermark "67" - Block { - BlockType Inport - Name "Stimulus" - SID "37" - Position [245, 323, 275, 337] - ZOrder -1 - IconDisplay "Port number" - Port { - PortNumber 1 - Name "input" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Inport - Name "Ensemble" - SID "44" - Position [245, 398, 275, 412] - ZOrder -2 - Port "2" - IconDisplay "Port number" - } - Block { - BlockType Sum - Name "Add" - SID "3" - Ports [4, 1] - Position [575, 250, 605, 290] - ZOrder -3 - Inputs "++++" - InputSameDT off - OutDataTypeStr "Inherit: Inherit via internal rule" - SaturateOnIntegerOverflow off - } - Block { - BlockType SubSystem - Name "Binomial" - SID "48" - Ports [1, 1] - Position [725, 335, 765, 395] - ZOrder -4 - MinAlgLoopOccurrences off - PropExecContextOutsideSubsystem off - RTWSystemCode "Auto" - FunctionWithSeparateData off - Opaque off - RequestExecContextInheritance off - MaskHideContents off - System { - Name "Binomial" - Location [559, 200, 929, 672] - Open off - ModelBrowserVisibility off - ModelBrowserWidth 200 - ScreenColor "white" - PaperOrientation "landscape" - PaperPositionMode "auto" - PaperType "usletter" - PaperUnits "inches" - TiledPaperMargins [0.500000, 0.500000, 0.500000, 0.500000] - TiledPageScale 1 - ShowPageBoundaries off - ZoomFactor "100" - Block { - BlockType Inport - Name "In1" - SID "50" - Position [25, 38, 55, 52] - ZOrder -1 - IconDisplay "Port number" - } - Block { - BlockType Sum - Name "Add1" - SID "32" - Ports [2, 1] - Position [145, 110, 175, 140] - ZOrder -2 - IconShape "round" - Inputs "|++" - InputSameDT off - OutDataTypeStr "Inherit: Inherit via internal rule" - SaturateOnIntegerOverflow off - } - Block { - BlockType Constant - Name "Constant1" - SID "33" - Position [145, 200, 175, 230] - ZOrder -3 - BlockRotation 270 - BackgroundColor "magenta" - } - Block { - BlockType Product - Name "Divide" - SID "31" - Ports [2, 1] - Position [220, 27, 250, 58] - ZOrder -4 - Inputs "*/" - InputSameDT off - OutDataTypeStr "Inherit: Inherit via internal rule" - RndMeth "Floor" - SaturateOnIntegerOverflow off - Port { - PortNumber 1 - Name "s2" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Math - Name "Math\nFunction" - SID "8" - Ports [1, 1] - Position [80, 30, 110, 60] - ZOrder -5 - Port { - PortNumber 1 - Name "s1" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Outport - Name "Out1" - SID "49" - Position [275, 38, 305, 52] - ZOrder -6 - IconDisplay "Port number" - } - Line { - SrcBlock "Constant1" - SrcPort 1 - DstBlock "Add1" - DstPort 2 - } - Line { - Name "s1" - Labels [0, 0] - SrcBlock "Math\nFunction" - SrcPort 1 - Points [5, 0] - Branch { - Points [0, 80] - DstBlock "Add1" - DstPort 1 - } - Branch { - Labels [1, 0] - Points [85, 0] - DstBlock "Divide" - DstPort 1 - } - } - Line { - SrcBlock "Add1" - SrcPort 1 - Points [10, 0; 0, -75] - DstBlock "Divide" - DstPort 2 - } - Line { - Name "s2" - Labels [0, 0] - SrcBlock "Divide" - SrcPort 1 - DstBlock "Out1" - DstPort 1 - } - Line { - SrcBlock "In1" - SrcPort 1 - DstBlock "Math\nFunction" - DstPort 1 - } - Annotation { - SID "61" - Name "Inverse of Logistic Link Function\n \n\n\n\n\n\n\n\n\n\n" - ". " - Position [174, 121] - BackgroundColor "yellow" - ZOrder -1 - FontName "Arial Narrow" - FontSize 18 - } - Annotation { - SID "62" - Name "\\lambda \\cdot \\Delta= e^{X \\cdot \\beta}/(1+e^{X\\cdot \\beta})" - Position [164, 271] - Interpreter "tex" - ZOrder -2 - FontName "Arial Narrow" - FontSize 18 - } - } - } - Block { - BlockType Constant - Name "Constant" - SID "1" - Position [515, 175, 545, 205] - ZOrder -5 - BlockRotation 270 - BlockMirror on - BackgroundColor "magenta" - NamePlacement "alternate" - Value "mu" - } - Block { - BlockType Constant - Name "Constant2" - SID "47" - Position [885, 475, 915, 505] - ZOrder -6 - Value "Ts" - } - Block { - BlockType Product - Name "Divide1" - SID "46" - Ports [2, 1] - Position [990, 467, 1020, 498] - ZOrder -7 - Inputs "*/" - InputSameDT off - OutDataTypeStr "Inherit: Inherit via internal rule" - RndMeth "Floor" - SaturateOnIntegerOverflow off - } - Block { - BlockType Reference - Name "Ensemble Effect" - SID "43" - Ports [1, 1] - Position [410, 387, 505, 423] - ZOrder -8 - BackgroundColor "darkGreen" - LibraryVersion "1.108" - SourceBlock "cstblocks/LTI System" - SourceType "LTI Block" - sys "E" - IC "[]" - } - Block { - BlockType FrameConversion - Name "Frame Status Conversion" - SID "11" - Ports [1, 1] - Position [1125, 260, 1180, 300] - ZOrder -9 - OutFrame "Sample-based" - } - Block { - BlockType Delay - Name "Integer Delay" - SID "22" - Ports [1, 1] - Position [410, 123, 445, 157] - ZOrder -10 - BlockMirror on - UserDataPersistent on - UserData "DataTag0" - InputPortMap "u0" - DelayLength "1" - } - Block { - BlockType SubSystem - Name "Poisson" - SID "53" - Ports [1, 1] - Position [725, 160, 765, 220] - ZOrder -11 - MinAlgLoopOccurrences off - PropExecContextOutsideSubsystem off - RTWSystemCode "Auto" - FunctionWithSeparateData off - Opaque off - RequestExecContextInheritance off - MaskHideContents off - System { - Name "Poisson" - Location [8, 44, 1724, 1116] - Open off - ModelBrowserVisibility off - ModelBrowserWidth 200 - ScreenColor "white" - PaperOrientation "landscape" - PaperPositionMode "auto" - PaperType "usletter" - PaperUnits "inches" - TiledPaperMargins [0.500000, 0.500000, 0.500000, 0.500000] - TiledPageScale 1 - ShowPageBoundaries off - ZoomFactor "100" - Block { - BlockType Inport - Name "In1" - SID "54" - Position [225, 203, 255, 217] - ZOrder -1 - IconDisplay "Port number" - } - Block { - BlockType Math - Name "Math\nFunction" - SID "58" - Ports [1, 1] - Position [360, 195, 390, 225] - ZOrder -2 - Port { - PortNumber 1 - Name "s1" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Outport - Name "Out1" - SID "59" - Position [475, 203, 505, 217] - ZOrder -3 - IconDisplay "Port number" - } - Line { - SrcBlock "In1" - SrcPort 1 - DstBlock "Math\nFunction" - DstPort 1 - } - Line { - Name "s1" - Labels [0, 0; 1, 0] - SrcBlock "Math\nFunction" - SrcPort 1 - DstBlock "Out1" - DstPort 1 - } - Annotation { - SID "63" - Name "\\lambda \\cdot \\Delta= e^{X \\cdot \\beta}" - Position [369, 336] - Interpreter "tex" - ZOrder -1 - FontName "Arial Narrow" - FontSize 18 - } - Annotation { - SID "64" - Name "Inverse of log Link Function\n \n\n\n\n\n\n. " - " " - Position [374, 231] - BackgroundColor "yellow" - ZOrder -2 - FontName "Arial Narrow" - FontSize 18 - } - } - } - Block { - BlockType Reference - Name "Random Source" - SID "12" - Ports [0, 1] - Position [986, 360, 1024, 395] - ZOrder -12 - BlockRotation 270 - LibraryVersion "1.727" - UserDataPersistent on - UserData "DataTag1" - Diagnostics "AllowInheritedTsInSrc" - SourceBlock "dspsrcs4/Random\nSource" - SourceType "Random Source" - SrcType "Uniform" - NormMethod "Ziggurat" - CltLength "12" - MinVal "0" - MaxVal "1" - MeanVal "0" - VarVal "1" - RepMode "Not repeatable" - rawSeed "seed" - IsInherit on - SampMode "Continuous" - SampTime "Ts" - SampFrame "dsp_sampFrame" - DataType "Double" - OutComplex "Real" - } - Block { - BlockType RelationalOperator - Name "Relational Operator" - SID "13" - Ports [2, 1] - Position [1030, 262, 1060, 293] - ZOrder -13 - ShowName off - Operator ">" - OutDataTypeStr "float('double')" - } - Block { - BlockType Reshape - Name "Reshape" - SID "14" - Ports [1, 1] - Position [1220, 268, 1250, 292] - ZOrder -14 - ShowName off - OutputDimensions "[sampPerFrame,max(length(P),length(seed))]" - Port { - PortNumber 1 - Name "spike process" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Reference - Name "Self-History" - SID "5" - Ports [1, 1] - Position [410, 247, 505, 283] - ZOrder -15 - BackgroundColor "orange" - LibraryVersion "1.108" - SourceBlock "cstblocks/LTI System" - SourceType "LTI Block" - sys "H" - IC "[]" - } - Block { - BlockType Reference - Name "Stimulus Effect" - SID "6" - Ports [1, 1] - Position [410, 312, 505, 348] - ZOrder -16 - BackgroundColor "darkGreen" - LibraryVersion "1.108" - SourceBlock "cstblocks/LTI System" - SourceType "LTI Block" - sys "S" - IC "[]" - } - Block { - BlockType Switch - Name "Switch" - SID "51" - Position [820, 250, 870, 290] - ZOrder -17 - Criteria "u2 ~= 0" - InputSameDT off - SaturateOnIntegerOverflow off - } - Block { - BlockType Constant - Name "simType\nSelector" - SID "52" - Position [730, 255, 760, 285] - ZOrder -18 - Value "simTypeSelect" - } - Block { - BlockType Outport - Name "pp" - SID "26" - Position [1310, 273, 1340, 287] - ZOrder -19 - IconDisplay "Port number" - } - Block { - BlockType Outport - Name "lambdaDelta" - SID "45" - Position [1065, 478, 1095, 492] - ZOrder -20 - Port "2" - IconDisplay "Port number" - } - Block { - BlockType SignalViewerScope - Name "Scope" - SID "28" - Ports [] - Position [20, 15, 60, 55] - ZOrder -21 - IOType "viewer" - List { - ListType IOSignalStrings - set0ParseKeys "10,18" - set0Sigs "Reshape:o1Stimulus Effect:o1" - } - Location [1, 53, 1601, 1151] - Open off - NumInputPorts "1" - List { - ListType AxesTitles - axes1 "%" - } - ShowDataMarkers off - ShowLegends off - MaxDataPoints "7500" - RefreshTime 0.035000 - } - Block { - BlockType SignalViewerScope - Name "Scope1" - SID "29" - Ports [] - Position [20, 15, 60, 55] - ZOrder -22 - IOType "viewer" - List { - ListType IOSignalStrings - set0ParseKeys "25,18" - set0Sigs "Binomial/Math Function:o1Binomial/Divide:o1" - } - Location [1, 53, 1601, 1151] - Open off - NumInputPorts "1" - List { - ListType AxesTitles - axes1 "%" - } - ShowDataMarkers off - ShowLegends off - SaveName "ScopeData1" - MaxDataPoints "7500" - RefreshTime 0.035000 - } - Block { - BlockType SignalViewerScope - Name "Scope2" - SID "38" - Ports [] - Position [20, 15, 60, 55] - ZOrder -23 - IOType "viewer" - List { - ListType IOSignalStrings - set0ParseKeys "15" - set0Sigs "Self-History:o1" - } - Location [5, 53, 1605, 1151] - Open off - NumInputPorts "1" - List { - ListType AxesTitles - axes1 "%" - } - ShowDataMarkers off - ShowLegends off - SaveName "ScopeData2" - MaxDataPoints "7500" - RefreshTime 0.035000 - } - Line { - SrcBlock "Constant" - SrcPort 1 - Points [0, 45] - DstBlock "Add" - DstPort 1 - } - Line { - SrcBlock "Self-History" - SrcPort 1 - DstBlock "Add" - DstPort 2 - } - Line { - SrcBlock "Stimulus Effect" - SrcPort 1 - Points [15, 0; 0, -55] - DstBlock "Add" - DstPort 3 - } - Line { - SrcBlock "Add" - SrcPort 1 - Points [55, 0] - Branch { - Points [0, 95] - DstBlock "Binomial" - DstPort 1 - } - Branch { - Points [0, -80] - DstBlock "Poisson" - DstPort 1 - } - } - Line { - SrcBlock "Frame Status Conversion" - SrcPort 1 - DstBlock "Reshape" - DstPort 1 - } - Line { - Name "spike process" - SrcBlock "Reshape" - SrcPort 1 - Points [25, 0] - Branch { - Labels [1, 0] - Points [0, -140] - DstBlock "Integer Delay" - DstPort 1 - } - Branch { - DstBlock "pp" - DstPort 1 - } - } - Line { - SrcBlock "Relational Operator" - SrcPort 1 - DstBlock "Frame Status Conversion" - DstPort 1 - } - Line { - SrcBlock "Random Source" - SrcPort 1 - Points [0, -70] - DstBlock "Relational Operator" - DstPort 2 - } - Line { - Name "input" - Labels [0, 0] - SrcBlock "Stimulus" - SrcPort 1 - DstBlock "Stimulus Effect" - DstPort 1 - } - Line { - SrcBlock "Integer Delay" - SrcPort 1 - Points [-65, 0; 0, 125] - DstBlock "Self-History" - DstPort 1 - } - Line { - SrcBlock "Ensemble" - SrcPort 1 - DstBlock "Ensemble Effect" - DstPort 1 - } - Line { - SrcBlock "Ensemble Effect" - SrcPort 1 - Points [25, 0; 0, -120] - DstBlock "Add" - DstPort 4 - } - Line { - SrcBlock "Constant2" - SrcPort 1 - DstBlock "Divide1" - DstPort 2 - } - Line { - SrcBlock "Divide1" - SrcPort 1 - DstBlock "lambdaDelta" - DstPort 1 - } - Line { - SrcBlock "simType\nSelector" - SrcPort 1 - DstBlock "Switch" - DstPort 2 - } - Line { - SrcBlock "Binomial" - SrcPort 1 - Points [15, 0; 0, -80] - DstBlock "Switch" - DstPort 3 - } - Line { - SrcBlock "Switch" - SrcPort 1 - Points [50, 0] - Branch { - DstBlock "Relational Operator" - DstPort 1 - } - Branch { - Points [0, 205] - DstBlock "Divide1" - DstPort 1 - } - } - Line { - SrcBlock "Poisson" - SrcPort 1 - Points [15, 0; 0, 65] - DstBlock "Switch" - DstPort 1 - } - Annotation { - SID "65" - Name "GLM Model \n\n " - " \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n. " - Position [414, 261] - BackgroundColor "lightBlue" - ZOrder -1 - FontName "Arial Narrow" - FontSize 18 - } - Annotation { - SID "66" - Name "Coin flip with\np= \\lambda \\cdot \\Delta\n\n\n\n\n\n\n\n\n\n\n." - Position [1034, 356] - Interpreter "tex" - ZOrder -2 - FontName "Arial Narrow" - FontSize 18 - } - Annotation { - SID "67" - Name "Poisson:\n\\lambda \\cdot \\Delta = e^{X \\cdot \\beta}\nBinomial: \n\\lambda \\cdot \\Delta = e^{X" - " \\cdot \\beta}/({1+e^{X \\cdot \\beta}})" - Position [869, 78] - BackgroundColor "yellow" - Interpreter "tex" - ZOrder -3 - FontName "Arial Narrow" - FontSize 22 - } - } -} -MatData { - NumRecords 2 - DataRecord { - Tag DataTag0 - Data " %)30 . B 8 ( @ % \" $ ! 0 % 0 $P $ 3 :&%S26" - "YH97)I=&5D3W!T:6]N #@ # & \" D\" !0 @ ! 0 $ @ ! $ " - } - DataRecord { - Tag DataTag1 - Data " %)30 . V 8 ( @ % \" $ ! 0 % 0 \"0 $ 2 4V5E9" - " 4V5E9$9L86< #@ #@ & \" 0 !0 @ ! !0 $ $ 4 R,S$Q,P " - "X ! !@ @ $ 4 ( 0 T ! ! - 1&].;W13879E4V5E9 " - } -} diff --git a/PointProcessSimulation.slx b/PointProcessSimulation.slx deleted file mode 100644 index 770da87d..00000000 Binary files a/PointProcessSimulation.slx and /dev/null differ diff --git a/PointProcessSimulation.slx.r2013a b/PointProcessSimulation.slx.r2013a deleted file mode 100644 index e8746942..00000000 Binary files a/PointProcessSimulation.slx.r2013a and /dev/null differ diff --git a/PointProcessSimulationCont.slx b/PointProcessSimulationCont.slx deleted file mode 100644 index d836f898..00000000 Binary files a/PointProcessSimulationCont.slx and /dev/null differ diff --git a/PointProcessSimulationThinning.mdl.r2011a b/PointProcessSimulationThinning.mdl.r2011a deleted file mode 100644 index 663825d5..00000000 --- a/PointProcessSimulationThinning.mdl.r2011a +++ /dev/null @@ -1,2076 +0,0 @@ -Model { - Name "PointProcessSimulationThinning" - Version 7.7 - MdlSubVersion 0 - GraphicalInterface { - NumRootInports 2 - Inport { - BusObject "" - Name "Stimulus" - } - Inport { - BusObject "" - Name "Ensemble" - } - NumRootOutports 3 - Outport { - BusObject "" - BusOutputAsStruct "off" - Name "pointProcess" - } - Outport { - BusObject "" - BusOutputAsStruct "off" - Name "lambdaDelta" - } - Outport { - BusObject "" - BusOutputAsStruct "off" - Name "SpikeTimes" - } - ParameterArgumentNames "" - ComputedModelVersion "1.65" - NumModelReferences 0 - NumTestPointedSignals 0 - } - SavedCharacterEncoding "windows-1252" - slprops.hdlmdlprops { - $PropName "HDLParams" - $ObjectID 1 - Array { - Type "Cell" - Dimension 2 - Cell "HDLSubsystem" - Cell "PointProcessSimulationThinning" - PropName "mdlProps" - } - } - SaveDefaultBlockParams on - ScopeRefreshTime 0.035000 - OverrideScopeRefreshTime on - DisableAllScopes off - DataTypeOverride "UseLocalSettings" - DataTypeOverrideAppliesTo "AllNumericTypes" - MinMaxOverflowLogging "UseLocalSettings" - MinMaxOverflowArchiveMode "Overwrite" - MaxMDLFileLineLength 120 - Created "Thu Oct 20 20:22:33 2011" - Creator "Developer" - UpdateHistory "UpdateHistoryNever" - ModifiedByFormat "%" - LastModifiedBy "Developer" - ModifiedDateFormat "%" - LastModifiedDate "Mon Oct 24 11:15:57 2011" - RTWModifiedTimeStamp 241355740 - ModelVersionFormat "1.%" - ConfigurationManager "None" - SampleTimeColors off - SampleTimeAnnotations off - LibraryLinkDisplay "none" - WideLines off - ShowLineDimensions off - ShowPortDataTypes off - ShowLoopsOnError on - IgnoreBidirectionalLines off - ShowStorageClass off - ShowTestPointIcons on - ShowSignalResolutionIcons on - ShowViewerIcons on - SortedOrder off - ExecutionContextIcon off - ShowLinearizationAnnotations on - BlockNameDataTip off - BlockParametersDataTip off - BlockDescriptionStringDataTip off - ToolBar on - StatusBar on - BrowserShowLibraryLinks off - BrowserLookUnderMasks off - SimulationMode "accelerator" - LinearizationMsg "none" - Profile off - ParamWorkspaceSource "MATLABWorkspace" - AccelSystemTargetFile "accel.tlc" - AccelTemplateMakefile "accel_default_tmf" - AccelMakeCommand "make_rtw" - TryForcingSFcnDF off - Object { - $PropName "DataLoggingOverride" - $ObjectID 2 - $ClassName "Simulink.SimulationData.ModelLoggingInfo" - model_ "PointProcessSimulationThinning" - overrideMode_ [0.0] - Array { - Type "Cell" - Dimension 1 - Cell "PointProcessSimulationThinning" - PropName "logAsSpecifiedByModels_" - } - Array { - Type "Cell" - Dimension 1 - Cell [] - PropName "logAsSpecifiedByModelsSSIDs_" - } - } - RecordCoverage off - CovPath "/" - CovSaveName "covdata" - CovMetricSettings "dw" - CovNameIncrementing off - CovHtmlReporting on - CovForceBlockReductionOff on - covSaveCumulativeToWorkspaceVar on - CovSaveSingleToWorkspaceVar on - CovCumulativeVarName "covCumulativeData" - CovCumulativeReport off - CovReportOnPause on - CovModelRefEnable "Off" - CovExternalEMLEnable off - ExtModeBatchMode off - ExtModeEnableFloating on - ExtModeTrigType "manual" - ExtModeTrigMode "normal" - ExtModeTrigPort "1" - ExtModeTrigElement "any" - ExtModeTrigDuration 1000 - ExtModeTrigDurationFloating "auto" - ExtModeTrigHoldOff 0 - ExtModeTrigDelay 0 - ExtModeTrigDirection "rising" - ExtModeTrigLevel 0 - ExtModeArchiveMode "off" - ExtModeAutoIncOneShot off - ExtModeIncDirWhenArm off - ExtModeAddSuffixToVar off - ExtModeWriteAllDataToWs off - ExtModeArmWhenConnect on - ExtModeSkipDownloadWhenConnect off - ExtModeLogAll on - ExtModeAutoUpdateStatusClock on - BufferReuse on - ShowModelReferenceBlockVersion off - ShowModelReferenceBlockIO off - Array { - Type "Handle" - Dimension 1 - Simulink.ConfigSet { - $ObjectID 3 - Version "1.11.0" - Array { - Type "Handle" - Dimension 9 - Simulink.SolverCC { - $ObjectID 4 - Version "1.11.0" - StartTime "0.0" - StopTime "10" - AbsTol "auto" - FixedStep "Ts" - InitialStep "auto" - MaxNumMinSteps "-1" - MaxOrder 5 - ZcThreshold "auto" - ConsecutiveZCsStepRelTol "10*128*eps" - MaxConsecutiveZCs "1000" - ExtrapolationOrder 4 - NumberNewtonIterations 1 - MaxStep "auto" - MinStep "auto" - MaxConsecutiveMinStep "1" - RelTol "1e-3" - SolverMode "SingleTasking" - ConcurrentTasks off - Solver "FixedStepDiscrete" - SolverName "FixedStepDiscrete" - SolverJacobianMethodControl "auto" - ShapePreserveControl "DisableAll" - ZeroCrossControl "UseLocalSettings" - ZeroCrossAlgorithm "Nonadaptive" - AlgebraicLoopSolver "TrustRegion" - SolverResetMethod "Fast" - PositivePriorityOrder off - AutoInsertRateTranBlk off - SampleTimeConstraint "Unconstrained" - InsertRTBMode "Whenever possible" - } - Simulink.DataIOCC { - $ObjectID 5 - Version "1.11.0" - Decimation "1" - ExternalInput "[t, u]" - FinalStateName "xFinal" - InitialState "xInitial" - LimitDataPoints off - MaxDataPoints "1000" - LoadExternalInput on - LoadInitialState off - SaveFinalState off - SaveCompleteFinalSimState off - SaveFormat "StructureWithTime" - SignalLoggingSaveFormat "ModelDataLogs" - SaveOutput off - SaveState off - SignalLogging on - DSMLogging on - InspectSignalLogs off - SaveTime off - ReturnWorkspaceOutputs off - StateSaveName "xout" - TimeSaveName "tout" - OutputSaveName "yout" - SignalLoggingName "logsout" - DSMLoggingName "dsmout" - OutputOption "RefineOutputTimes" - OutputTimes "[]" - ReturnWorkspaceOutputsName "out" - Refine "1" - } - Simulink.OptimizationCC { - $ObjectID 6 - Version "1.11.0" - Array { - Type "Cell" - Dimension 8 - Cell "BooleansAsBitfields" - Cell "PassReuseOutputArgsAs" - Cell "PassReuseOutputArgsThreshold" - Cell "ZeroExternalMemoryAtStartup" - Cell "ZeroInternalMemoryAtStartup" - Cell "OptimizeModelRefInitCode" - Cell "NoFixptDivByZeroProtection" - Cell "UseSpecifiedMinMax" - PropName "DisabledProps" - } - BlockReduction on - BooleanDataType on - ConditionallyExecuteInputs on - InlineParams off - UseIntDivNetSlope off - UseSpecifiedMinMax off - InlineInvariantSignals off - OptimizeBlockIOStorage on - BufferReuse on - EnhancedBackFolding off - StrengthReduction off - ExpressionFolding on - BooleansAsBitfields off - BitfieldContainerType "uint_T" - EnableMemcpy on - MemcpyThreshold 64 - PassReuseOutputArgsAs "Structure reference" - ExpressionDepthLimit 2147483647 - FoldNonRolledExpr on - LocalBlockOutputs on - RollThreshold 5 - SystemCodeInlineAuto off - StateBitsets off - DataBitsets off - UseTempVars off - ZeroExternalMemoryAtStartup on - ZeroInternalMemoryAtStartup on - InitFltsAndDblsToZero off - NoFixptDivByZeroProtection off - EfficientFloat2IntCast off - EfficientMapNaN2IntZero on - OptimizeModelRefInitCode off - LifeSpan "inf" - MaxStackSize "Inherit from target" - BufferReusableBoundary on - SimCompilerOptimization "Off" - AccelVerboseBuild off - AccelParallelForEachSubsystem on - } - Simulink.DebuggingCC { - $ObjectID 7 - Version "1.11.0" - RTPrefix "error" - ConsistencyChecking "none" - ArrayBoundsChecking "none" - SignalInfNanChecking "none" - SignalRangeChecking "none" - ReadBeforeWriteMsg "UseLocalSettings" - WriteAfterWriteMsg "UseLocalSettings" - WriteAfterReadMsg "UseLocalSettings" - AlgebraicLoopMsg "warning" - ArtificialAlgebraicLoopMsg "warning" - SaveWithDisabledLinksMsg "warning" - SaveWithParameterizedLinksMsg "warning" - CheckSSInitialOutputMsg on - UnderspecifiedInitializationDetection "Classic" - MergeDetectMultiDrivingBlocksExec "none" - CheckExecutionContextPreStartOutputMsg off - CheckExecutionContextRuntimeOutputMsg off - SignalResolutionControl "UseLocalSettings" - BlockPriorityViolationMsg "warning" - MinStepSizeMsg "warning" - TimeAdjustmentMsg "none" - MaxConsecutiveZCsMsg "error" - MaskedZcDiagnostic "warning" - IgnoredZcDiagnostic "warning" - SolverPrmCheckMsg "warning" - InheritedTsInSrcMsg "warning" - DiscreteInheritContinuousMsg "warning" - MultiTaskDSMMsg "error" - MultiTaskCondExecSysMsg "error" - MultiTaskRateTransMsg "error" - SingleTaskRateTransMsg "none" - TasksWithSamePriorityMsg "warning" - SigSpecEnsureSampleTimeMsg "warning" - CheckMatrixSingularityMsg "none" - IntegerOverflowMsg "warning" - Int32ToFloatConvMsg "warning" - ParameterDowncastMsg "error" - ParameterOverflowMsg "error" - ParameterUnderflowMsg "none" - ParameterPrecisionLossMsg "warning" - ParameterTunabilityLossMsg "warning" - FixptConstUnderflowMsg "none" - FixptConstOverflowMsg "none" - FixptConstPrecisionLossMsg "none" - UnderSpecifiedDataTypeMsg "none" - UnnecessaryDatatypeConvMsg "none" - VectorMatrixConversionMsg "none" - InvalidFcnCallConnMsg "error" - FcnCallInpInsideContextMsg "Use local settings" - SignalLabelMismatchMsg "none" - UnconnectedInputMsg "warning" - UnconnectedOutputMsg "warning" - UnconnectedLineMsg "warning" - SFcnCompatibilityMsg "none" - UniqueDataStoreMsg "none" - BusObjectLabelMismatch "warning" - RootOutportRequireBusObject "warning" - AssertControl "UseLocalSettings" - EnableOverflowDetection off - ModelReferenceIOMsg "none" - ModelReferenceMultiInstanceNormalModeStructChecksumCheck "error" - ModelReferenceVersionMismatchMessage "none" - ModelReferenceIOMismatchMessage "none" - ModelReferenceCSMismatchMessage "none" - UnknownTsInhSupMsg "warning" - ModelReferenceDataLoggingMessage "warning" - ModelReferenceSymbolNameMessage "warning" - ModelReferenceExtraNoncontSigs "error" - StateNameClashWarn "warning" - SimStateInterfaceChecksumMismatchMsg "warning" - SimStateOlderReleaseMsg "error" - InitInArrayFormatMsg "warning" - StrictBusMsg "ErrorLevel1" - BusNameAdapt "WarnAndRepair" - NonBusSignalsTreatedAsBus "none" - LoggingUnavailableSignals "error" - BlockIODiagnostic "none" - SFUnusedDataAndEventsDiag "warning" - SFUnexpectedBacktrackingDiag "warning" - SFInvalidInputDataAccessInChartInitDiag "warning" - SFNoUnconditionalDefaultTransitionDiag "warning" - SFTransitionOutsideNaturalParentDiag "warning" - } - Simulink.HardwareCC { - $ObjectID 8 - Version "1.11.0" - ProdBitPerChar 8 - ProdBitPerShort 16 - ProdBitPerInt 32 - ProdBitPerLong 32 - ProdBitPerFloat 32 - ProdBitPerDouble 64 - ProdBitPerPointer 32 - ProdLargestAtomicInteger "Char" - ProdLargestAtomicFloat "None" - ProdIntDivRoundTo "Undefined" - ProdEndianess "Unspecified" - ProdWordSize 32 - ProdShiftRightIntArith on - ProdHWDeviceType "32-bit Generic" - TargetBitPerChar 8 - TargetBitPerShort 16 - TargetBitPerInt 32 - TargetBitPerLong 32 - TargetBitPerFloat 32 - TargetBitPerDouble 64 - TargetBitPerPointer 32 - TargetLargestAtomicInteger "Char" - TargetLargestAtomicFloat "None" - TargetShiftRightIntArith on - TargetIntDivRoundTo "Undefined" - TargetEndianess "Unspecified" - TargetWordSize 32 - TargetTypeEmulationWarnSuppressLevel 0 - TargetPreprocMaxBitsSint 32 - TargetPreprocMaxBitsUint 32 - TargetHWDeviceType "Specified" - TargetUnknown off - ProdEqTarget on - } - Simulink.ModelReferenceCC { - $ObjectID 9 - Version "1.11.0" - UpdateModelReferenceTargets "IfOutOfDateOrStructuralChange" - CheckModelReferenceTargetMessage "error" - EnableParallelModelReferenceBuilds off - ParallelModelReferenceErrorOnInvalidPool on - ParallelModelReferenceMATLABWorkerInit "None" - ModelReferenceNumInstancesAllowed "Multi" - PropagateVarSize "Infer from blocks in model" - ModelReferencePassRootInputsByReference on - ModelReferenceMinAlgLoopOccurrences off - PropagateSignalLabelsOutOfModel off - SupportModelReferenceSimTargetCustomCode off - } - Simulink.SFSimCC { - $ObjectID 10 - Version "1.11.0" - SFSimEnableDebug on - SFSimOverflowDetection on - SFSimEcho on - SimBlas on - SimCtrlC on - SimExtrinsic on - SimIntegrity on - SimUseLocalCustomCode off - SimParseCustomCode on - SimBuildMode "sf_incremental_build" - } - Simulink.RTWCC { - $BackupClass "Simulink.RTWCC" - $ObjectID 11 - Version "1.11.0" - Array { - Type "Cell" - Dimension 8 - Cell "IncludeHyperlinkInReport" - Cell "GenerateTraceInfo" - Cell "GenerateTraceReport" - Cell "GenerateTraceReportSl" - Cell "GenerateTraceReportSf" - Cell "GenerateTraceReportEml" - Cell "GenerateSLWebview" - Cell "GenerateCodeMetricsReport" - PropName "DisabledProps" - } - SystemTargetFile "grt.tlc" - GenCodeOnly off - MakeCommand "make_rtw" - GenerateMakefile on - TemplateMakefile "grt_default_tmf" - GenerateReport off - SaveLog off - RTWVerbose on - RetainRTWFile off - ProfileTLC off - TLCDebug off - TLCCoverage off - TLCAssert off - ProcessScriptMode "Default" - ConfigurationMode "Optimized" - ConfigAtBuild off - RTWUseLocalCustomCode off - RTWUseSimCustomCode off - IncludeHyperlinkInReport off - LaunchReport off - TargetLang "C" - IncludeBusHierarchyInRTWFileBlockHierarchyMap off - IncludeERTFirstTime off - GenerateTraceInfo off - GenerateTraceReport off - GenerateTraceReportSl off - GenerateTraceReportSf off - GenerateTraceReportEml off - GenerateCodeInfo off - GenerateSLWebview off - GenerateCodeMetricsReport off - RTWCompilerOptimization "Off" - CheckMdlBeforeBuild "Off" - CustomRebuildMode "OnUpdate" - Array { - Type "Handle" - Dimension 2 - Simulink.CodeAppCC { - $ObjectID 12 - Version "1.11.0" - Array { - Type "Cell" - Dimension 21 - Cell "IgnoreCustomStorageClasses" - Cell "IgnoreTestpoints" - Cell "InsertBlockDesc" - Cell "InsertPolySpaceComments" - Cell "SFDataObjDesc" - Cell "MATLABFcnDesc" - Cell "SimulinkDataObjDesc" - Cell "DefineNamingRule" - Cell "SignalNamingRule" - Cell "ParamNamingRule" - Cell "InlinedPrmAccess" - Cell "CustomSymbolStr" - Cell "CustomSymbolStrGlobalVar" - Cell "CustomSymbolStrType" - Cell "CustomSymbolStrField" - Cell "CustomSymbolStrFcn" - Cell "CustomSymbolStrFcnArg" - Cell "CustomSymbolStrBlkIO" - Cell "CustomSymbolStrTmpVar" - Cell "CustomSymbolStrMacro" - Cell "ReqsInCode" - PropName "DisabledProps" - } - ForceParamTrailComments off - GenerateComments on - IgnoreCustomStorageClasses on - IgnoreTestpoints off - IncHierarchyInIds off - MaxIdLength 31 - PreserveName off - PreserveNameWithParent off - ShowEliminatedStatement off - IncAutoGenComments off - SimulinkDataObjDesc off - SFDataObjDesc off - MATLABFcnDesc off - IncDataTypeInIds off - MangleLength 1 - CustomSymbolStrGlobalVar "$R$N$M" - CustomSymbolStrType "$N$R$M" - CustomSymbolStrField "$N$M" - CustomSymbolStrFcn "$R$N$M$F" - CustomSymbolStrFcnArg "rt$I$N$M" - CustomSymbolStrBlkIO "rtb_$N$M" - CustomSymbolStrTmpVar "$N$M" - CustomSymbolStrMacro "$R$N$M" - DefineNamingRule "None" - ParamNamingRule "None" - SignalNamingRule "None" - InsertBlockDesc off - InsertPolySpaceComments off - SimulinkBlockComments on - MATLABSourceComments off - EnableCustomComments off - InlinedPrmAccess "Literals" - ReqsInCode off - UseSimReservedNames off - } - Simulink.GRTTargetCC { - $BackupClass "Simulink.TargetCC" - $ObjectID 13 - Version "1.11.0" - Array { - Type "Cell" - Dimension 16 - Cell "GeneratePreprocessorConditionals" - Cell "IncludeMdlTerminateFcn" - Cell "CombineOutputUpdateFcns" - Cell "SuppressErrorStatus" - Cell "ERTCustomFileBanners" - Cell "GenerateSampleERTMain" - Cell "GenerateTestInterfaces" - Cell "ModelStepFunctionPrototypeControlCompliant" - Cell "CPPClassGenCompliant" - Cell "MultiInstanceERTCode" - Cell "PurelyIntegerCode" - Cell "SupportComplex" - Cell "SupportAbsoluteTime" - Cell "SupportContinuousTime" - Cell "SupportNonInlinedSFcns" - Cell "PortableWordSizes" - PropName "DisabledProps" - } - TargetFcnLib "ansi_tfl_table_tmw.mat" - TargetLibSuffix "" - TargetPreCompLibLocation "" - TargetFunctionLibrary "ANSI_C" - UtilityFuncGeneration "Auto" - ERTMultiwordTypeDef "System defined" - FunctionExecutionProfile off - CodeExecutionProfiling off - ERTCodeCoverageTool "None" - ERTMultiwordLength 256 - MultiwordLength 2048 - GenerateFullHeader on - GenerateSampleERTMain off - GenerateTestInterfaces off - IsPILTarget off - ModelReferenceCompliant on - ParMdlRefBuildCompliant on - CompOptLevelCompliant on - IncludeMdlTerminateFcn on - GeneratePreprocessorConditionals "Disable all" - CombineOutputUpdateFcns off - CombineSignalStateStructs off - SuppressErrorStatus off - ERTFirstTimeCompliant off - IncludeFileDelimiter "Auto" - ERTCustomFileBanners off - SupportAbsoluteTime on - LogVarNameModifier "rt_" - MatFileLogging on - MultiInstanceERTCode off - SupportNonFinite on - SupportComplex on - PurelyIntegerCode off - SupportContinuousTime on - SupportNonInlinedSFcns on - SupportVariableSizeSignals off - EnableShiftOperators on - ParenthesesLevel "Nominal" - PortableWordSizes off - ModelStepFunctionPrototypeControlCompliant off - CPPClassGenCompliant off - AutosarCompliant off - UseMalloc off - ExtMode off - ExtModeStaticAlloc off - ExtModeTesting off - ExtModeStaticAllocSize 1000000 - ExtModeTransport 0 - ExtModeMexFile "ext_comm" - ExtModeIntrfLevel "Level1" - RTWCAPISignals off - RTWCAPIParams off - RTWCAPIStates off - RTWCAPIRootIO off - GenerateASAP2 off - } - PropName "Components" - } - } - hdlcoderui.hdlcc { - $ObjectID 14 - Version "1.11.0" - Description "HDL Coder custom configuration component" - Name "HDL Coder" - Array { - Type "Cell" - Dimension 1 - Cell "" - PropName "HDLConfigFile" - } - HDLCActiveTab "0" - } - PropName "Components" - } - Name "Configuration" - CurrentDlgPage "Data Import//Export" - ConfigPrmDlgPosition [ 400, 210, 1614, 840 ] - } - PropName "ConfigurationSets" - } - Simulink.ConfigSet { - $PropName "ActiveConfigurationSet" - $ObjectID 3 - } - BlockDefaults { - ForegroundColor "black" - BackgroundColor "white" - DropShadow off - NamePlacement "normal" - FontName "Helvetica" - FontSize 10 - FontWeight "normal" - FontAngle "normal" - ShowName on - BlockRotation 0 - BlockMirror off - } - AnnotationDefaults { - HorizontalAlignment "center" - VerticalAlignment "middle" - ForegroundColor "black" - BackgroundColor "white" - DropShadow off - FontName "Helvetica" - FontSize 10 - FontWeight "normal" - FontAngle "normal" - UseDisplayTextAsClickCallback off - } - LineDefaults { - FontName "Helvetica" - FontSize 9 - FontWeight "normal" - FontAngle "normal" - } - BlockParameterDefaults { - Block { - BlockType Clock - DisplayTime off - } - Block { - BlockType Constant - Value "1" - VectorParams1D on - SamplingMode "Sample based" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Inherit from 'Constant value'" - LockScale off - SampleTime "inf" - FramePeriod "inf" - PreserveConstantTs off - } - Block { - BlockType DataTypeConversion - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Inherit via back propagation" - LockScale off - ConvertRealWorld "Real World Value (RWV)" - RndMeth "Zero" - SaturateOnIntegerOverflow on - SampleTime "-1" - } - Block { - BlockType DiscreteIntegrator - IntegratorMethod "Integration: Forward Euler" - gainval "1.0" - ExternalReset "none" - InitialConditionSource "internal" - InitialCondition "0" - InitialConditionMode "State and output" - SampleTime "1" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Inherit via internal rule" - LockScale off - RndMeth "Floor" - SaturateOnIntegerOverflow off - LimitOutput off - UpperSaturationLimit "inf" - LowerSaturationLimit "-inf" - ShowSaturationPort off - ShowStatePort off - IgnoreLimit off - StateMustResolveToSignalObject off - RTWStateStorageClass "Auto" - } - Block { - BlockType Fcn - Expr "sin(u[1])" - SampleTime "-1" - } - Block { - BlockType From - IconDisplay "Tag" - TagVisibility "local" - } - Block { - BlockType Goto - IconDisplay "Tag" - } - Block { - BlockType Inport - Port "1" - OutputFunctionCall off - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: auto" - LockScale off - BusOutputAsStruct off - PortDimensions "-1" - VarSizeSig "Inherit" - SampleTime "-1" - SignalType "auto" - SamplingMode "auto" - LatchByDelayingOutsideSignal off - LatchInputForFeedbackSignals off - Interpolate on - } - Block { - BlockType Math - Operator "exp" - OutputSignalType "auto" - SampleTime "-1" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Same as first input" - LockScale off - RndMeth "Floor" - SaturateOnIntegerOverflow on - IntermediateResultsDataTypeStr "Inherit: Inherit via internal rule" - AlgorithmType "Newton-Raphson" - Iterations "3" - } - Block { - BlockType Outport - Port "1" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: auto" - LockScale off - BusOutputAsStruct off - PortDimensions "-1" - VarSizeSig "Inherit" - SampleTime "-1" - SignalType "auto" - SamplingMode "auto" - SourceOfInitialOutputValue "Dialog" - OutputWhenDisabled "held" - InitialOutput "[]" - } - Block { - BlockType Product - Inputs "2" - Multiplication "Element-wise(.*)" - CollapseMode "All dimensions" - CollapseDim "1" - InputSameDT on - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Same as first input" - LockScale off - RndMeth "Zero" - SaturateOnIntegerOverflow on - SampleTime "-1" - } - Block { - BlockType RateTransition - Integrity on - Deterministic on - X0 "0" - OutPortSampleTimeOpt "Specify" - OutPortSampleTimeMultiple "1" - OutPortSampleTime "-1" - } - Block { - BlockType RelationalOperator - Operator ">=" - InputSameDT on - OutDataTypeStr "Inherit: Logical (see Configuration Parameters: Optimization)" - ZeroCross on - SampleTime "-1" - } - Block { - BlockType Scope - ModelBased off - TickLabels "OneTimeTick" - ZoomMode "on" - Grid "on" - TimeRange "auto" - YMin "-5" - YMax "5" - SaveToWorkspace off - SaveName "ScopeData" - LimitDataPoints on - MaxDataPoints "5000" - Decimation "1" - SampleInput off - SampleTime "-1" - } - Block { - BlockType SignalViewerScope - Floating off - ModelBased off - TickLabels "OneTimeTick" - ZoomMode "on" - Grid "on" - TimeRange "auto" - YMin "-5" - YMax "5" - SaveToWorkspace off - SaveName "ScopeData" - LimitDataPoints on - MaxDataPoints "5000" - Decimation "1" - SampleInput off - SampleTime "0" - Disabled off - ScrollMode on - } - Block { - BlockType SubSystem - ShowPortLabels "FromPortIcon" - Permissions "ReadWrite" - PermitHierarchicalResolution "All" - TreatAsAtomicUnit off - CheckFcnCallInpInsideContextMsg off - SystemSampleTime "-1" - RTWFcnNameOpts "Auto" - RTWFileNameOpts "Auto" - RTWMemSecFuncInitTerm "Inherit from model" - RTWMemSecFuncExecute "Inherit from model" - RTWMemSecDataConstants "Inherit from model" - RTWMemSecDataInternal "Inherit from model" - RTWMemSecDataParameters "Inherit from model" - SimViewingDevice off - DataTypeOverride "UseLocalSettings" - DataTypeOverrideAppliesTo "AllNumericTypes" - MinMaxOverflowLogging "UseLocalSettings" - Variant off - GeneratePreprocessorConditionals off - } - Block { - BlockType Sum - IconShape "rectangular" - Inputs "++" - CollapseMode "All dimensions" - CollapseDim "1" - InputSameDT on - AccumDataTypeStr "Inherit: Inherit via internal rule" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Same as first input" - LockScale off - RndMeth "Floor" - SaturateOnIntegerOverflow on - SampleTime "-1" - } - Block { - BlockType Switch - Criteria "u2 >= Threshold" - Threshold "0" - InputSameDT on - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Inherit via internal rule" - LockScale off - RndMeth "Floor" - SaturateOnIntegerOverflow on - ZeroCross on - SampleTime "-1" - AllowDiffInputSizes off - } - Block { - BlockType UniformRandomNumber - Minimum "-1" - Maximum "1" - Seed "0" - SampleTime "-1" - VectorParams1D on - } - Block { - BlockType UnitDelay - X0 "0" - InputProcessing "Inherited" - SampleTime "1" - StateMustResolveToSignalObject off - RTWStateStorageClass "Auto" - } - } - System { - Name "PointProcessSimulationThinning" - Location [9, 94, 1671, 1023] - Open on - ModelBrowserVisibility off - ModelBrowserWidth 200 - ScreenColor "white" - PaperOrientation "landscape" - PaperPositionMode "auto" - PaperType "usletter" - PaperUnits "inches" - TiledPaperMargins [0.500000, 0.500000, 0.500000, 0.500000] - TiledPageScale 1 - ShowPageBoundaries off - ZoomFactor "80" - ReportName "simulink-default.rpt" - SIDHighWatermark "204" - Block { - BlockType Inport - Name "Stimulus" - SID "108" - Position [20, 178, 50, 192] - IconDisplay "Port number" - } - Block { - BlockType Inport - Name "Ensemble" - SID "180" - Position [20, 253, 50, 267] - Port "2" - IconDisplay "Port number" - } - Block { - BlockType Sum - Name "Add" - SID "111" - Ports [4, 1] - Position [255, 105, 285, 145] - Inputs "++++" - InputSameDT off - OutDataTypeStr "Inherit: Inherit via internal rule" - SaturateOnIntegerOverflow off - } - Block { - BlockType SubSystem - Name "Binomial" - SID "112" - Ports [1, 1] - Position [335, 190, 375, 250] - MinAlgLoopOccurrences off - PropExecContextOutsideSubsystem off - RTWSystemCode "Auto" - FunctionWithSeparateData off - Opaque off - RequestExecContextInheritance off - MaskHideContents off - System { - Name "Binomial" - Location [597, 320, 927, 614] - Open off - ModelBrowserVisibility off - ModelBrowserWidth 200 - ScreenColor "white" - PaperOrientation "landscape" - PaperPositionMode "auto" - PaperType "usletter" - PaperUnits "inches" - TiledPaperMargins [0.500000, 0.500000, 0.500000, 0.500000] - TiledPageScale 1 - ShowPageBoundaries off - ZoomFactor "100" - Block { - BlockType Inport - Name "In1" - SID "113" - Position [25, 38, 55, 52] - IconDisplay "Port number" - } - Block { - BlockType Sum - Name "Add1" - SID "114" - Ports [2, 1] - Position [145, 110, 175, 140] - IconShape "round" - Inputs "|++" - InputSameDT off - OutDataTypeStr "Inherit: Inherit via internal rule" - SaturateOnIntegerOverflow off - } - Block { - BlockType Constant - Name "Constant1" - SID "115" - Position [145, 200, 175, 230] - BlockRotation 270 - BackgroundColor "magenta" - } - Block { - BlockType Product - Name "Divide" - SID "116" - Ports [2, 1] - Position [220, 27, 250, 58] - Inputs "*/" - InputSameDT off - OutDataTypeStr "Inherit: Inherit via internal rule" - RndMeth "Floor" - SaturateOnIntegerOverflow off - Port { - PortNumber 1 - Name "s2" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Math - Name "Math\nFunction" - SID "117" - Ports [1, 1] - Position [80, 30, 110, 60] - Port { - PortNumber 1 - Name "s1" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Outport - Name "Out1" - SID "118" - Position [275, 38, 305, 52] - IconDisplay "Port number" - } - Line { - SrcBlock "Constant1" - SrcPort 1 - DstBlock "Add1" - DstPort 2 - } - Line { - Name "s1" - Labels [0, 0; 0, 0] - SrcBlock "Math\nFunction" - SrcPort 1 - Points [5, 0] - Branch { - Points [0, 80] - DstBlock "Add1" - DstPort 1 - } - Branch { - Labels [1, 0] - Points [85, 0] - DstBlock "Divide" - DstPort 1 - } - } - Line { - SrcBlock "Add1" - SrcPort 1 - Points [10, 0; 0, -75] - DstBlock "Divide" - DstPort 2 - } - Line { - Name "s2" - Labels [0, 0; 0, 0] - SrcBlock "Divide" - SrcPort 1 - DstBlock "Out1" - DstPort 1 - } - Line { - SrcBlock "In1" - SrcPort 1 - DstBlock "Math\nFunction" - DstPort 1 - } - Annotation { - Name "Inverse of Logistic Link Function\n \n\n\n\n\n\n\n\n\n\n" - ". " - Position [174, 121] - BackgroundColor "yellow" - FontName "Arial Narrow" - FontSize 18 - } - Annotation { - Name "\\lambda \\cdot \\Delta= e^{X \\cdot \\beta}/(1+e^{X\\cdot \\beta})" - Position [164, 271] - Interpreter "tex" - FontName "Arial Narrow" - FontSize 18 - } - } - } - Block { - BlockType Clock - Name "Clock" - SID "189" - Position [100, 775, 120, 795] - Decimation "10" - } - Block { - BlockType Constant - Name "Constant1" - SID "48" - Position [595, 215, 625, 245] - Value "0" - } - Block { - BlockType Constant - Name "Constant3" - SID "195" - Position [450, 845, 480, 875] - NamePlacement "alternate" - Value "Ts" - SampleTime "Ts" - } - Block { - BlockType Constant - Name "Constant4" - SID "119" - Position [210, 25, 240, 55] - BlockRotation 270 - BlockMirror on - BackgroundColor "magenta" - NamePlacement "alternate" - Value "mu" - } - Block { - BlockType DataTypeConversion - Name "Data Type Conversion" - SID "91" - Position [1025, 195, 1065, 235] - RndMeth "Floor" - SaturateOnIntegerOverflow off - } - Block { - BlockType DataTypeConversion - Name "Data Type Conversion1" - SID "196" - Position [635, 785, 675, 825] - RndMeth "Floor" - SaturateOnIntegerOverflow off - } - Block { - BlockType Constant - Name "Delta" - SID "120" - Position [500, 205, 530, 235] - BlockRotation 270 - Value "TsInt" - } - Block { - BlockType Reference - Name "Detect\nChange" - SID "90" - Ports [1, 1] - Position [945, 200, 1005, 230] - LibraryVersion "1.236" - SourceBlock "simulink/Logic and Bit\nOperations/Detect\nChange" - SourceType "Detect Change" - ShowPortLabels "FromPortIcon" - SystemSampleTime "-1" - FunctionWithSeparateData off - RTWMemSecFuncInitTerm "Inherit from model" - RTWMemSecFuncExecute "Inherit from model" - RTWMemSecDataConstants "Inherit from model" - RTWMemSecDataInternal "Inherit from model" - RTWMemSecDataParameters "Inherit from model" - GeneratePreprocessorConditionals off - vinit "0" - } - Block { - BlockType Reference - Name "Difference" - SID "193" - Ports [1, 1] - Position [410, 767, 470, 803] - LibraryVersion "1.236" - SourceBlock "simulink/Discrete/Difference" - SourceType "Difference" - ShowPortLabels "FromPortIcon" - SystemSampleTime "-1" - FunctionWithSeparateData off - RTWMemSecFuncInitTerm "Inherit from model" - RTWMemSecFuncExecute "Inherit from model" - RTWMemSecDataConstants "Inherit from model" - RTWMemSecDataInternal "Inherit from model" - RTWMemSecDataParameters "Inherit from model" - GeneratePreprocessorConditionals off - ICPrevInput "0.0" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Inherit via internal rule" - OutputDataTypeScalingMode "Inherit via internal rule" - OutDataType "fixdt(1, 16)" - OutScaling "2^-10" - LockScale off - RndMeth "Floor" - DoSatur off - } - Block { - BlockType DiscreteIntegrator - Name "Discrete-Time\nIntegrator" - SID "203" - Ports [3, 1] - Position [720, 141, 780, 249] - IntegratorMethod "Integration: Forward Euler" - ExternalReset "either" - InitialConditionSource "external" - SampleTime "Ts" - ICPrevOutput "DiscIntNeverNeededParam" - ICPrevScaledInput "DiscIntNeverNeededParam" - } - Block { - BlockType Product - Name "Divide1" - SID "121" - Ports [2, 1] - Position [530, 142, 560, 173] - Inputs "*/" - InputSameDT off - OutDataTypeStr "Inherit: Inherit via internal rule" - RndMeth "Floor" - SaturateOnIntegerOverflow off - SampleTime "TsInt" - } - Block { - BlockType Reference - Name "Ensemble Effect" - SID "122" - Ports [1, 1] - Position [90, 242, 185, 278] - BackgroundColor "darkGreen" - LibraryVersion "1.107" - SourceBlock "cstblocks/LTI System" - SourceType "LTI Block" - ShowPortLabels "FromPortIcon" - SystemSampleTime "-1" - FunctionWithSeparateData off - RTWMemSecFuncInitTerm "Inherit from model" - RTWMemSecFuncExecute "Inherit from model" - RTWMemSecDataConstants "Inherit from model" - RTWMemSecDataInternal "Inherit from model" - RTWMemSecDataParameters "Inherit from model" - GeneratePreprocessorConditionals off - sys "E" - IC "[]" - } - Block { - BlockType Fcn - Name "Fcn" - SID "5" - Position [365, 360, 425, 390] - Expr "-log(u(1))" - } - Block { - BlockType From - Name "From" - SID "183" - Position [20, 106, 60, 134] - GotoTag "HistInput" - } - Block { - BlockType From - Name "From1" - SID "186" - Position [256, 265, 284, 305] - BlockRotation 270 - BlockMirror on - NamePlacement "alternate" - GotoTag "NewSample" - } - Block { - BlockType From - Name "From2" - SID "188" - Position [630, 181, 670, 209] - GotoTag "NewSample" - } - Block { - BlockType From - Name "From3" - SID "192" - Position [181, 670, 209, 710] - BlockRotation 270 - BlockMirror on - NamePlacement "alternate" - GotoTag "NewSample" - } - Block { - BlockType Goto - Name "Goto1" - SID "200" - Position [955, 855, 995, 885] - GotoTag "HistInput" - TagVisibility "local" - } - Block { - BlockType Goto - Name "Goto2" - SID "187" - Position [1180, 200, 1220, 230] - GotoTag "NewSample" - TagVisibility "local" - } - Block { - BlockType SubSystem - Name "Poisson" - SID "123" - Ports [1, 1] - Position [335, 15, 375, 75] - MinAlgLoopOccurrences off - PropExecContextOutsideSubsystem off - RTWSystemCode "Auto" - FunctionWithSeparateData off - Opaque off - RequestExecContextInheritance off - MaskHideContents off - System { - Name "Poisson" - Location [2, 84, 1678, 978] - Open off - ModelBrowserVisibility off - ModelBrowserWidth 200 - ScreenColor "white" - PaperOrientation "landscape" - PaperPositionMode "auto" - PaperType "usletter" - PaperUnits "inches" - TiledPaperMargins [0.500000, 0.500000, 0.500000, 0.500000] - TiledPageScale 1 - ShowPageBoundaries off - ZoomFactor "100" - Block { - BlockType Inport - Name "In1" - SID "124" - Position [225, 203, 255, 217] - IconDisplay "Port number" - } - Block { - BlockType Math - Name "Math\nFunction" - SID "125" - Ports [1, 1] - Position [360, 195, 390, 225] - Port { - PortNumber 1 - Name "s1" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Outport - Name "Out1" - SID "126" - Position [475, 203, 505, 217] - IconDisplay "Port number" - } - Line { - SrcBlock "In1" - SrcPort 1 - DstBlock "Math\nFunction" - DstPort 1 - } - Line { - Name "s1" - Labels [0, 0; 0, 0; 1, 0] - SrcBlock "Math\nFunction" - SrcPort 1 - DstBlock "Out1" - DstPort 1 - } - Annotation { - Name "\\lambda \\cdot \\Delta= e^{X \\cdot \\beta}" - Position [369, 336] - Interpreter "tex" - FontName "Arial Narrow" - FontSize 18 - } - Annotation { - Name "Inverse of log Link Function\n \n\n\n\n\n\n. " - " " - Position [374, 231] - BackgroundColor "yellow" - FontName "Arial Narrow" - FontSize 18 - } - } - } - Block { - BlockType RateTransition - Name "Rate Transition1" - SID "197" - Position [745, 849, 785, 891] - NamePlacement "alternate" - OutPortSampleTime "TsInt" - } - Block { - BlockType RateTransition - Name "Rate Transition2" - SID "175" - Position [650, 139, 680, 181] - NamePlacement "alternate" - ShowName off - OutPortSampleTime "Ts" - } - Block { - BlockType RelationalOperator - Name "Relational\nOperator" - SID "49" - Ports [2, 1] - Position [845, 176, 905, 249] - InputSameDT off - SampleTime "Ts" - } - Block { - BlockType RelationalOperator - Name "Relational\nOperator1" - SID "194" - Ports [2, 1] - Position [540, 766, 600, 839] - Operator ">" - InputSameDT off - } - Block { - BlockType Reference - Name "Sample\nand Hold" - SID "4" - Ports [1, 1, 0, 1] - Position [230, 344, 310, 406] - LibraryVersion "1.716" - SourceBlock "dspsigops/Sample\nand Hold" - SourceType "Sample and Hold" - ShowPortLabels "FromPortIcon" - SystemSampleTime "-1" - FunctionWithSeparateData off - RTWMemSecFuncInitTerm "Inherit from model" - RTWMemSecFuncExecute "Inherit from model" - RTWMemSecDataConstants "Inherit from model" - RTWMemSecDataInternal "Inherit from model" - RTWMemSecDataParameters "Inherit from model" - GeneratePreprocessorConditionals off - trig "Rising edge" - initCond "rand(1,1)" - latchinput on - } - Block { - BlockType Reference - Name "Sample\nand Hold1" - SID "190" - Ports [1, 1, 0, 1] - Position [155, 754, 235, 816] - LibraryVersion "1.716" - SourceBlock "dspsigops/Sample\nand Hold" - SourceType "Sample and Hold" - ShowPortLabels "FromPortIcon" - SystemSampleTime "-1" - FunctionWithSeparateData off - RTWMemSecFuncInitTerm "Inherit from model" - RTWMemSecFuncExecute "Inherit from model" - RTWMemSecDataConstants "Inherit from model" - RTWMemSecDataInternal "Inherit from model" - RTWMemSecDataParameters "Inherit from model" - GeneratePreprocessorConditionals off - trig "Rising edge" - initCond "0" - latchinput on - } - Block { - BlockType Scope - Name "Scope2" - SID "191" - Ports [1] - Position [360, 719, 390, 751] - Floating off - Location [188, 390, 512, 629] - Open off - NumInputPorts "1" - List { - ListType AxesTitles - axes1 "%" - } - YMin "1.05" - YMax "1.25" - DataFormat "StructureWithTime" - SampleTime "0" - } - Block { - BlockType Reference - Name "Self-History" - SID "127" - Ports [1, 1] - Position [90, 102, 185, 138] - BackgroundColor "orange" - LibraryVersion "1.107" - SourceBlock "cstblocks/LTI System" - SourceType "LTI Block" - ShowPortLabels "FromPortIcon" - SystemSampleTime "-1" - FunctionWithSeparateData off - RTWMemSecFuncInitTerm "Inherit from model" - RTWMemSecFuncExecute "Inherit from model" - RTWMemSecDataConstants "Inherit from model" - RTWMemSecDataInternal "Inherit from model" - RTWMemSecDataParameters "Inherit from model" - GeneratePreprocessorConditionals off - sys "H" - IC "[]" - } - Block { - BlockType Reference - Name "Stimulus Effect" - SID "128" - Ports [1, 1] - Position [90, 167, 185, 203] - BackgroundColor "darkGreen" - LibraryVersion "1.107" - SourceBlock "cstblocks/LTI System" - SourceType "LTI Block" - ShowPortLabels "FromPortIcon" - SystemSampleTime "-1" - FunctionWithSeparateData off - RTWMemSecFuncInitTerm "Inherit from model" - RTWMemSecFuncExecute "Inherit from model" - RTWMemSecDataConstants "Inherit from model" - RTWMemSecDataInternal "Inherit from model" - RTWMemSecDataParameters "Inherit from model" - GeneratePreprocessorConditionals off - sys "S" - IC "[]" - } - Block { - BlockType Switch - Name "Switch" - SID "129" - Position [430, 130, 480, 170] - Criteria "u2 ~= 0" - InputSameDT off - SaturateOnIntegerOverflow off - } - Block { - BlockType UniformRandomNumber - Name "Uniform Random\nNumber" - SID "3" - Position [150, 359, 180, 391] - Minimum "0" - SampleTime "Ts" - } - Block { - BlockType UnitDelay - Name "Unit Delay" - SID "158" - Position [1095, 198, 1120, 232] - InputProcessing "Elements as channels (sample based)" - SampleTime "Ts" - } - Block { - BlockType UnitDelay - Name "Unit Delay2" - SID "199" - Position [865, 853, 900, 887] - InputProcessing "Elements as channels (sample based)" - SampleTime "-1" - } - Block { - BlockType Constant - Name "simType\nSelector" - SID "201" - Position [340, 110, 370, 140] - Value "simTypeSelect" - } - Block { - BlockType Outport - Name "pointProcess" - SID "141" - Position [795, 798, 825, 812] - IconDisplay "Port number" - } - Block { - BlockType Outport - Name "lambdaDelta" - SID "202" - Position [565, 38, 595, 52] - Port "2" - IconDisplay "Port number" - } - Block { - BlockType Outport - Name "SpikeTimes" - SID "136" - Position [300, 853, 330, 867] - Port "3" - IconDisplay "Port number" - } - Block { - BlockType Scope - Name "Floating\nScope" - SID "85" - Ports [] - Position [185, 14, 215, 46] - IOType "viewer" - Floating on - Location [376, 294, 700, 533] - Open off - NumInputPorts "1" - List { - ListType AxesTitles - axes1 "%" - } - YMin "25" - YMax "275" - SaveName "ScopeData2" - DataFormat "StructureWithTime" - SampleTime "0" - } - Block { - BlockType Scope - Name "Floating\nScope1" - SID "86" - Ports [] - Position [185, 14, 215, 46] - IOType "viewer" - Floating on - Location [376, 294, 700, 533] - Open off - NumInputPorts "1" - List { - ListType AxesTitles - axes1 "%" - } - SaveName "ScopeData3" - DataFormat "StructureWithTime" - SampleTime "0" - } - Block { - BlockType Scope - Name "Floating\nScope2" - SID "87" - Ports [] - Position [185, 14, 215, 46] - IOType "viewer" - Floating on - Location [376, 294, 700, 533] - Open off - NumInputPorts "1" - List { - ListType AxesTitles - axes1 "%" - } - YMin "1" - YMax "1" - SaveName "ScopeData4" - DataFormat "StructureWithTime" - SampleTime "0" - } - Block { - BlockType Scope - Name "Floating\nScope3" - SID "93" - Ports [] - Position [185, 14, 215, 46] - IOType "viewer" - Floating on - Location [376, 294, 700, 533] - Open off - NumInputPorts "1" - List { - ListType AxesTitles - axes1 "%" - } - SaveName "ScopeData5" - DataFormat "StructureWithTime" - SampleTime "0" - } - Block { - BlockType SignalViewerScope - Name "Scope" - SID "84" - Ports [] - Position [20, 15, 60, 55] - IOType "viewer" - Location [188, 365, 512, 604] - Open off - NumInputPorts "1" - List { - ListType AxesTitles - axes1 "%" - } - ShowDataMarkers off - ShowLegends off - YMin "-1" - YMax "1" - DataFormat "Array" - MaxDataPoints "7500" - RefreshTime 0.035000 - } - Line { - SrcBlock "Uniform Random\nNumber" - SrcPort 1 - DstBlock "Sample\nand Hold" - DstPort 1 - } - Line { - SrcBlock "Sample\nand Hold" - SrcPort 1 - DstBlock "Fcn" - DstPort 1 - } - Line { - SrcBlock "Relational\nOperator" - SrcPort 1 - DstBlock "Detect\nChange" - DstPort 1 - } - Line { - SrcBlock "Fcn" - SrcPort 1 - Points [375, 0; 0, -145] - DstBlock "Relational\nOperator" - DstPort 2 - } - Line { - SrcBlock "Detect\nChange" - SrcPort 1 - DstBlock "Data Type Conversion" - DstPort 1 - } - Line { - SrcBlock "Data Type Conversion" - SrcPort 1 - DstBlock "Unit Delay" - DstPort 1 - } - Line { - SrcBlock "Constant4" - SrcPort 1 - Points [0, 50] - DstBlock "Add" - DstPort 1 - } - Line { - SrcBlock "Self-History" - SrcPort 1 - DstBlock "Add" - DstPort 2 - } - Line { - SrcBlock "Stimulus Effect" - SrcPort 1 - Points [15, 0; 0, -55] - DstBlock "Add" - DstPort 3 - } - Line { - SrcBlock "Add" - SrcPort 1 - Points [20, 0] - Branch { - Points [0, 95] - DstBlock "Binomial" - DstPort 1 - } - Branch { - Points [0, -80] - DstBlock "Poisson" - DstPort 1 - } - } - Line { - SrcBlock "Ensemble Effect" - SrcPort 1 - Points [25, 0; 0, -120] - DstBlock "Add" - DstPort 4 - } - Line { - SrcBlock "Delta" - SrcPort 1 - DstBlock "Divide1" - DstPort 2 - } - Line { - SrcBlock "Divide1" - SrcPort 1 - DstBlock "Rate Transition2" - DstPort 1 - } - Line { - SrcBlock "Binomial" - SrcPort 1 - Points [25, 0; 0, -55] - DstBlock "Switch" - DstPort 3 - } - Line { - SrcBlock "Switch" - SrcPort 1 - Points [15, 0] - Branch { - DstBlock "Divide1" - DstPort 1 - } - Branch { - Points [0, -105] - DstBlock "lambdaDelta" - DstPort 1 - } - } - Line { - SrcBlock "Poisson" - SrcPort 1 - Points [25, 0; 0, 90] - DstBlock "Switch" - DstPort 1 - } - Line { - SrcBlock "simType\nSelector" - SrcPort 1 - Points [40, 0] - DstBlock "Switch" - DstPort 2 - } - Line { - SrcBlock "Stimulus" - SrcPort 1 - DstBlock "Stimulus Effect" - DstPort 1 - } - Line { - SrcBlock "Unit Delay" - SrcPort 1 - DstBlock "Goto2" - DstPort 1 - } - Line { - SrcBlock "Discrete-Time\nIntegrator" - SrcPort 1 - DstBlock "Relational\nOperator" - DstPort 1 - } - Line { - SrcBlock "Constant1" - SrcPort 1 - DstBlock "Discrete-Time\nIntegrator" - DstPort 3 - } - Line { - SrcBlock "Rate Transition2" - SrcPort 1 - DstBlock "Discrete-Time\nIntegrator" - DstPort 1 - } - Line { - SrcBlock "Ensemble" - SrcPort 1 - DstBlock "Ensemble Effect" - DstPort 1 - } - Line { - SrcBlock "From" - SrcPort 1 - DstBlock "Self-History" - DstPort 1 - } - Line { - SrcBlock "From1" - SrcPort 1 - DstBlock "Sample\nand Hold" - DstPort trigger - } - Line { - SrcBlock "From2" - SrcPort 1 - DstBlock "Discrete-Time\nIntegrator" - DstPort 2 - } - Line { - SrcBlock "Clock" - SrcPort 1 - DstBlock "Sample\nand Hold1" - DstPort 1 - } - Line { - SrcBlock "Sample\nand Hold1" - SrcPort 1 - Points [35, 0] - Branch { - Points [70, 0] - Branch { - DstBlock "Scope2" - DstPort 1 - } - Branch { - DstBlock "Difference" - DstPort 1 - } - } - Branch { - Points [0, 75] - DstBlock "SpikeTimes" - DstPort 1 - } - } - Line { - SrcBlock "From3" - SrcPort 1 - DstBlock "Sample\nand Hold1" - DstPort trigger - } - Line { - SrcBlock "Difference" - SrcPort 1 - DstBlock "Relational\nOperator1" - DstPort 1 - } - Line { - SrcBlock "Constant3" - SrcPort 1 - Points [20, 0; 0, -40] - DstBlock "Relational\nOperator1" - DstPort 2 - } - Line { - SrcBlock "Relational\nOperator1" - SrcPort 1 - DstBlock "Data Type Conversion1" - DstPort 1 - } - Line { - SrcBlock "Data Type Conversion1" - SrcPort 1 - Points [35, 0] - Branch { - DstBlock "pointProcess" - DstPort 1 - } - Branch { - Points [0, 65] - DstBlock "Rate Transition1" - DstPort 1 - } - } - Line { - SrcBlock "Rate Transition1" - SrcPort 1 - DstBlock "Unit Delay2" - DstPort 1 - } - Line { - SrcBlock "Unit Delay2" - SrcPort 1 - DstBlock "Goto1" - DstPort 1 - } - Annotation { - Position [2110, 606] - } - Annotation { - Position [25, 187] - } - Annotation { - Name "u_j ~ U(0,1)\nGenerate a new random number\neach time that the integral of \\lambda\nbecome equal t" - "o previous z_j" - Position [268, 490] - Interpreter "tex" - FontName "Arial Narrow" - FontSize 20 - } - Annotation { - Name "z_j \nExponential rate on random number" - Position [629, 339] - Interpreter "tex" - FontName "Arial Narrow" - FontSize 20 - } - Annotation { - Name "z_j= \\int_{0}^{tj} \\lambda(t|H_t) dt" - Position [768, 117] - Interpreter "tex" - FontName "Arial Narrow" - FontSize 20 - } - Annotation { - Name "dN(t)" - Position [728, 787] - Interpreter "tex" - FontName "Arial Narrow" - FontSize 20 - } - Annotation { - Name "\\lambda(t|H_t)" - Position [608, 137] - Interpreter "tex" - FontName "Arial Narrow" - FontSize 20 - } - Annotation { - Name "\\lambda(t|H_t)\\Delta" - Position [483, 112] - Interpreter "tex" - FontName "Arial Narrow" - FontSize 20 - } - Annotation { - Name "t_j" - Position [273, 762] - Interpreter "tex" - FontName "Arial Narrow" - FontSize 20 - } - Annotation { - Name "Sample the simulation clock each time that the\nintegral of \\lambda reaches the current value of z" - "_j" - Position [248, 625] - Interpreter "tex" - FontName "Arial Narrow" - FontSize 20 - } - } -} diff --git a/README.md b/README.md index f064e3e7..3687b397 100644 --- a/README.md +++ b/README.md @@ -1,36 +1,147 @@ -nSTAT -===== +# Python nSTAT -Neural Spike Train Analysis Toolbox for Matlab +This repository contains the standalone Python implementation of nSTAT. +## Canonical API modules -nSTAT is an open-source, object-oriented Matlab toolbox that implements a range of models and algorithms for neural spike train data analysis. Such data are frequently obtained from neuroscience experiments and our intention in writing nSTAT is to facilitate quick, easy and consistent neural data analysis. +- `nstat.signal`: `Signal`, `Covariate` +- `nstat.spikes`: `SpikeTrain`, `SpikeTrainCollection` +- `nstat.events`: `Events` +- `nstat.history`: `HistoryBasis` +- `nstat.trial`: `CovariateCollection`, `TrialConfig`, `ConfigCollection`, `Trial` +- `nstat.cif`: `CIFModel` +- `nstat.analysis`: `Analysis` +- `nstat.fit`: `FitResult`, `FitSummary` +- `nstat.decoding`: `DecoderSuite` +- `nstat.datasets`: dataset registry and checksum verification -One of nSTAT's key strengths is point process generalized linear models for spike train signals that provide a formal statistical framework for processing signals recorded from ensembles of single neurons. It also has extensive support for model fitting, model order analysis, and adaptive decoding. In addition to point process algorithms, nSTAT also provides tools for Gaussian signals, ranging from correlation analysis to the Kalman filter, which can be applied to continuous normally-distributed neural signals such as local field potentials, EEG, ECoG, etc. +MATLAB-style entry points remain importable as compatibility adapters with `DeprecationWarning` messages. -Although created with neural signal processing in mind, nSTAT can be used as a generic tool for analyzing any types of discrete and continuous signals, and thus has wide applicability. +## Install -Like all open-source projects, nSTAT will benefit from your involvement, suggestions and contributions. This platform is intended as a repository for extensions to the toolbox based on your code contributions as well as for flagging and tracking open issues. +```bash +python3 -m pip install -e . +``` -The current release version of nSTAT can be downloaded from http://www.neurostat.mit.edu/nstat . +## Run paper examples equivalent -For mathematical and programmatic details of the toolbox, see: +```bash +python3 examples/nstat_paper_examples.py --repo-root . +``` -Cajigas I, Malik WQ, Brown EN. nSTAT: Open-source neural spike train analysis toolbox for Matlab. Journal of Neuroscience Methods 211: 245–264, Nov. 2012 -http://doi.org/10.1016/j.jneumeth.2012.08.009 +## Generate docs and notebooks -If you use nSTAT in your work, please remember to cite the above paper in any publications. -nSTAT is protected by the GPL v2 Open Source License. +```bash +python3 tools/generate_help_topic_docs.py +python3 tools/generate_example_notebooks.py +``` -The code repository for nSTAT is hosted on GitHub at https://github.com/cajigaslab/nSTAT. -You can download the example data file from the paper at: https://doi.org/10.6084/m9.figshare.4834640 +## Validation -Python nSTAT -============ +```bash +python3 tools/freeze_port_baseline.py +python3 tools/generate_method_parity_matrix.py +python3 tools/generate_implemented_method_coverage.py +python3 tools/verify_examples_notebooks.py +NSTAT_MATLAB_EXTRA_ARGS='-maca64 -nodisplay -noFigureWindows -softwareopengl' \ + python3 tools/verify_python_vs_matlab_similarity.py --enforce-gate +python3 tools/freeze_similarity_baseline.py +python3 tools/verify_offline_standalone.py +python3 -m pytest +``` -The Python port is in active development. +If Git LFS assets are unavailable (for example, CI quota exhaustion), set +`NSTAT_ALLOW_SYNTHETIC_DATA=1` to use deterministic synthetic fallbacks for +data-heavy paper example loaders. -Use this page for Python scope, status, and development guidance: +### Local parity block debugging -- docs/python-nstat.md -- python/examples/README.md +```bash +python3 tools/debug_parity_blocks.py \ + --set-actions-runner-svc \ + --matlab-extra-args "-maca64 -nodisplay -noFigureWindows -softwareopengl" +``` + +Single wrapper command (fail-fast ladder): + +```bash +tools/run_parity_ladder.sh +``` + +Single preflight command (Stage A ladder + selected Stage B topics): + +```bash +tools/run_parity_preflight.sh +``` + +Notes: + +- Runs blocks in order: `core_smoke -> timeout_front -> graphics_mid -> heavy_tail -> full_suite`. +- Exits immediately if a block regresses (`python_ok`, `matlab_ok`, scalar overlap, parity contract, or regression gate). +- Includes runtime regression guard using machine baseline block times with multiplier `NSTAT_PARITY_RUNTIME_MULTIPLIER` (default `2.5`). +- Set `NSTAT_PARITY_RUNTIME_MULTIPLIER=0` to disable runtime regression checks. +- Pass specific block names as args to run subset ladders, e.g.: + `tools/run_parity_ladder.sh core_smoke timeout_front`. +- Ladder writes retry telemetry to `reports/parity_retry_summary.json` (block, attempt count, retry reason, timeout-topic list). +- Retry behavior is controlled by `NSTAT_PARITY_RETRY_TIMEOUT_BLOCKS` and `NSTAT_PARITY_TIMEOUT_RETRY_BLOCKS`. +- Set `NSTAT_MATLAB_TOPIC_MAX_ATTEMPTS=2` to retry per-topic MATLAB timeouts/crashes once before failing. +- Set `NSTAT_PARITY_RETRY_RECOVERABLE_BLOCKS=1` and `NSTAT_PARITY_RECOVERABLE_RETRY_BLOCKS` to retry block failures caused by recoverable MATLAB failures (timeouts/crash signatures). +- Preflight topic selection can be overridden with `NSTAT_PARITY_PREFLIGHT_STAGEB_TOPICS`. + +See `docs/parity_runbook.rst` for the exact locally validated parity command set. + +Use targeted blocks to debug delays locally before running remote CI: + +```bash +# 1) Fast API/parity smoke +python3 tools/debug_parity_blocks.py --blocks core_smoke \ + --set-actions-runner-svc --matlab-extra-args "-maca64 -nodisplay -noFigureWindows -softwareopengl" + +# 2) Former timeout-prone front topics +python3 tools/debug_parity_blocks.py --blocks timeout_front \ + --set-actions-runner-svc --matlab-extra-args "-maca64 -nodisplay -noFigureWindows -softwareopengl" + +# 3) Graphics-sensitive middle topics +python3 tools/debug_parity_blocks.py --blocks graphics_mid \ + --set-actions-runner-svc --matlab-extra-args "-maca64 -nodisplay -noFigureWindows -softwareopengl" + +# 4) Heavy tail topics +python3 tools/debug_parity_blocks.py --blocks heavy_tail \ + --set-actions-runner-svc --matlab-extra-args "-maca64 -nodisplay -noFigureWindows -softwareopengl" + +# 5) Full gate-equivalent suite +python3 tools/debug_parity_blocks.py --blocks full_suite \ + --set-actions-runner-svc --matlab-extra-args "-maca64 -nodisplay -noFigureWindows -softwareopengl" +``` + +Summarize a parity report quickly: + +```bash +python3 tools/summarize_parity_report.py reports/parity_block_full_suite.json +``` + +Recent local baseline on this machine (MATLAB R2025b, no figure windows, software OpenGL): + +- `core_smoke`: ~47s +- `timeout_front`: ~122s +- `graphics_mid`: ~291s +- `heavy_tail`: ~385s +- `full_suite` (25 topics): ~826s + +## CI + +- `.github/workflows/python-ci.yml` runs docs, notebook verification, offline standalone checks, and `pytest`. +- `.github/workflows/matlab-parity-gate.yml` runs MATLAB/Python parity gate on self-hosted macOS runners with MATLAB installed. + +## Repo split inventory + +Snapshot MATLAB/Python help and example coverage before splitting `nSTAT` and `nSTAT-python`: + +```bash +python3 tools/generate_repo_split_inventory.py +``` + +Outputs: +- `reports/repo_split_inventory/summary.json` +- `reports/repo_split_inventory/topic_coverage_matrix.json` +- `reports/repo_split_inventory/split_readiness_gates.json` diff --git a/README.txt b/README.txt deleted file mode 100644 index 40c52dee..00000000 --- a/README.txt +++ /dev/null @@ -1,76 +0,0 @@ -%% Installation Notes %% -Authors: -Iahn Cajigas and Wasim Malik -Massachusetts Institute of Technology - - -To install the nSTAT toolbox: -1) Copy the files to the directory of your choice, e.g. c:\nSTAT\ -2) Within Matlab, go the directory where you have copied the files - e.g. >> cd('c:\nSTAT\'); -3) type nSTAT_Install from the matlab command prompt - e.g. >> nSTAT_Install - This step adds nSTAT to the matlab search path and makes the helpfiles - searchable along with all other matlab functions -4) Should you wish to install nSTAT in a directory named something other - than nSTAT, you will need to add that directory to Matlab's search - path manually - -nSTAT should now appear along with all other installed toolboxes in the -matlab help browser. - - -% UPDATES % -The most up-to-date version of nSTAT source code can be obtained from the -subversion repository at https://code.google.com/p/nstat-for-matlab/ - - -% CITATION % -If you use nSTAT in your work, please remember to cite the following paper -in any publications: - - Cajigas I, Malik WQ, Brown EN. nSTAT: Open-source neural spike train - analysis toolbox for Matlab. Journal of Neuroscience Methods - 211(2): 245?264, Nov. 2012 - - -% LICENSE INFORMATION % -nSTAT v1 Copyright (C) 2012 Masschusetts Institute of Technology -Cajigas, I, Malik, WQ, Brown, EN -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License as published -by the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -See the GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software Foundation, -Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -%% Additional files -Library files: zernike.zip, fixPSlinestyle.m, xticklabel_rotate.m were -obtained from http://www.mathworks.com/matlabcentral and are subject to -the terms and conditions of the BSD 2-Clause license located at -http://opensource.org/licenses/bsd-license.php. The respective authors -reserve copyrights on their original software. - -%% Additional files -Library files: zernike.zip, fixPSlinestyle.m, xticklabel_rotate.m were -obtained from http://www.mathworks.com/matlabcentral and are subject to -the terms and conditions of the BSD 2-Clause license located at -http://opensource.org/licenses/bsd-license.php. The respective authors -reserve copyrights on their original software. - -Links: -zernike polynomials - http://www.mathworks.com/matlabcentral/fileexchange/7687-zernike-polynomials -fixPSlinstyle - http://www.mathworks.com/matlabcentral/fileexchange/17928-fixpslinestyle -xticklabel_rotate: - http://www.mathworks.com/matlabcentral/fileexchange/3486-xticklabelrotate - - diff --git a/RELEASE_CHECKLIST.md b/RELEASE_CHECKLIST.md new file mode 100644 index 00000000..748a4244 --- /dev/null +++ b/RELEASE_CHECKLIST.md @@ -0,0 +1,41 @@ +# nSTAT Python Release Checklist + +- [ ] Install from source in a clean environment: + - `python3 -m pip install -e .` +- [ ] Refresh parity and coverage artifacts: + - `python3 tools/freeze_port_baseline.py` + - `python3 tools/generate_method_parity_matrix.py` + - `python3 tools/generate_implemented_method_coverage.py` +- [ ] Generate docs and notebooks: + - `python3 tools/generate_help_topic_docs.py` + - `python3 tools/generate_example_notebooks.py` +- [ ] Confirm docs build artifacts are not tracked: + - `docs/_build/` must remain gitignored and excluded from commits. +- [ ] Build docs and execute examples: + - `python3 tools/verify_examples_notebooks.py` + - `sphinx-build -b html docs docs/_build/html` +- [ ] Run similarity gate (requires MATLAB): + - `NSTAT_MATLAB_EXTRA_ARGS='-maca64 -nodisplay -noFigureWindows' python3 tools/verify_python_vs_matlab_similarity.py --enforce-gate` +- [ ] Freeze similarity baseline: + - `python3 tools/freeze_similarity_baseline.py` +- [ ] Verify standalone offline workflow: + - `python3 tools/verify_offline_standalone.py` + - Strict install gate (release hardening): `python3 tools/verify_offline_standalone.py --require-target-install` +- [ ] Run full test suite: + - `python3 -m pytest -q` +- [ ] Confirm release criteria: + - Class parity: `9/9` + - Help/notebook parity: `25/25` Python and `25/25` MATLAB + - Scalar parity contract: `25/25` help topics pass required keys + - Regression gate: pass with no allowlist-required failures +- [ ] Confirm compatibility adapters still import and emit `DeprecationWarning`. +- [ ] Update `RELEASE_NOTES.md` with API changes and known differences. +- [ ] Verify both release-gate workflows complete on the release candidate commit: + - `.github/workflows/python-ci.yml` + - `.github/workflows/matlab-parity-gate.yml` +- [ ] Run MATLAB preflight before parity verification: + - Trigger `.github/workflows/matlab-smoke.yml` on the target branch and confirm success. +- [ ] Verify required branch checks are enforced on `master`: + - `Python CI / test-and-build` + - `MATLAB Parity Gate / parity-gate` +- [ ] Create and tag GitHub release. diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md new file mode 100644 index 00000000..7081f94d --- /dev/null +++ b/RELEASE_NOTES.md @@ -0,0 +1,77 @@ +# nSTAT Python Release Notes + +## Highlights + +- Introduced canonical Pythonic APIs under `nstat`: + - `nstat.signal.Signal`, `nstat.signal.Covariate` + - `nstat.spikes.SpikeTrain`, `nstat.spikes.SpikeTrainCollection` + - `nstat.trial.CovariateCollection`, `nstat.trial.TrialConfig`, `nstat.trial.ConfigCollection`, `nstat.trial.Trial` + - `nstat.analysis.Analysis` + - `nstat.fit.FitResult`, `nstat.fit.FitSummary` + - `nstat.cif.CIFModel` + - `nstat.decoding.DecoderSuite` + - `nstat.datasets` dataset registry/checksum API +- Added standalone simulation replacements in `nstat.simulators`. +- Added source-driven notebook generation for all MATLAB help `Examples` topics. +- Added Sphinx docs generation from `helpfiles/helptoc.xml`. +- Added parity/baseline reporting tools: + - `tools/freeze_port_baseline.py` + - `tools/generate_method_parity_matrix.py` + - `tools/verify_python_vs_matlab_similarity.py --enforce-gate` + - `tools/freeze_similarity_baseline.py` + - `tools/generate_implemented_method_coverage.py` + - `tools/verify_offline_standalone.py` +- Added CI workflows: + - `.github/workflows/python-ci.yml` + - `.github/workflows/matlab-parity-gate.yml` +- Standardized docs artifact policy: + - Generated Sphinx output under `docs/_build/` is now treated as a build artifact and excluded from source control. +- Expanded parity contract coverage: + - The MATLAB/Python scalar parity contract now requires one numeric parity key for all 25 help topics. + +## Release criteria (v1.0 gate) + +- Class similarity gate: `9/9` pass. +- Help-topic execution gate: Python `25/25`, MATLAB `25/25`. +- Parity contract gate: required keys pass for all `25/25` help topics. +- Regression gate must pass with no unexpected failures. +- Standalone/offline source checkout workflow must pass `verify_offline_standalone.py`. + +## MATLAB-to-Python API mapping (selected) + +| MATLAB | Python canonical | +|---|---| +| `SignalObj` | `nstat.signal.Signal` | +| `Covariate` | `nstat.signal.Covariate` | +| `nspikeTrain` | `nstat.spikes.SpikeTrain` | +| `nstColl` | `nstat.spikes.SpikeTrainCollection` | +| `CovColl` | `nstat.trial.CovariateCollection` | +| `TrialConfig` | `nstat.trial.TrialConfig` | +| `ConfigColl` | `nstat.trial.ConfigCollection` | +| `Analysis.RunAnalysisForAllNeurons` | `nstat.analysis.Analysis.run_analysis_for_all_neurons` | +| `FitResSummary` | `nstat.fit.FitSummary` | +| `CIF` | `nstat.cif.CIFModel` | +| `DecodingAlgorithms` | `nstat.decoding.DecoderSuite` | + +## Final migration status + +| Area | Status | Notes | +|---|---|---| +| Core classes | Complete | Canonical APIs implemented under `nstat.*`. | +| MATLAB-style import adapters | Transitional | Compatibility modules emit `DeprecationWarning` and forward to canonical APIs. | +| Help topic docs | Complete | All topics listed in `helpfiles/helptoc.xml` are represented in Sphinx docs. | +| Example notebooks | Complete | 25/25 help examples are generated as executable notebooks. | +| Parity contract | Complete | Scalar parity keys required for all 25 help topics. | +| Standalone runtime | Complete | No MATLAB runtime required for Python package execution. MATLAB is only required for parity validation workflows. | + +## Compatibility adapters + +MATLAB-style adapters remain importable under `nstat/*.py` compatibility modules and emit `DeprecationWarning` with migration targets. + +## Known differences / omissions + +| Topic | Current behavior | +|---|---| +| Legacy plotting helpers | Not all MATLAB plotting helpers are direct API ports; plotting is primarily notebook/doc-driven. | +| Parity tolerance | MATLAB/Python scalar comparisons are tolerance-based; stochastic workflows rely on seeded aggregate metrics. | +| Method surface differences | Some low-value legacy MATLAB methods are intentionally omitted and documented in `reports/method_parity_matrix.json`. | diff --git a/SignalObj.m b/SignalObj.m deleted file mode 100644 index 2f763518..00000000 --- a/SignalObj.m +++ /dev/null @@ -1,2382 +0,0 @@ -classdef SignalObj < handle -%SIGNALOBJ Class representing a signal abstraction -% SignalObj consist of data that is indexed by time (as a default). The -% indexing variable can be any other type of data and the x-axis labels -% modified to represent this change. -% -% A SignalObj can be multivariate in that the data can have more than one component. The -% sample rate of the SignalObj is determined by the time increment used -% in the time sequence used when the SingalObj is created -% -% Usage: -% >> s=SignalObj(time, data, name, xlabelval, xunits, yunits, dataLabels, plotProps) -% -% Only time and data need to be specified. Other arguments are optional. -% -% -% time: indexing variable for the data. n x 1 or 1 x n array. The sample -% rate is determined by the time increment between samples of this vector. Units of -% [sec] are assumed, but need not be used. If the time vector is -% in units of [sec], the sampleRate is in units of [Hz]. If the -% time vector is in units of [msec] then the sampleRate is in -% units of [1/msec] or 10^3 [Hz]. -% -% data: n x m or m x n array reprenting the signal at each index of the time vector. -% The dimension that is compatible with the time vector will be automatically detected. -% Thus a SignalObj can be created by either passing the data matrix or its transpose. The remaining -% dimension will determine the dimensionality of the SignalObj. -% -% name: string that determines the name of the signal. This is used to -% label the y-axis of the SignalObj. -% -% xlabelval: A string specifying the name of the indexing variable. If -% this value is not specified, 'time' is used. -% -% xunits: A string specifying the name of the units of the indexing -% variable. In not specified, 'sec' is used. -% -% yunits: A string specifying the units of the SignalObj. Used when plotting the SignalObj. -% -% dataLabels: If data is multivariate, the names of the components of the SignalObj can be specified. -% These can be used to reference specific data within the -% signal (e.g. the x-component of a 3-d vector) and are -% also used for plotting. SignalObj's will be created for -% each component of the orignal SignalObj under the -% vars field. Can be specified all at once or by a cell of -% strings. -% -% plotProps: Can be specified for each component of the SignalObj -% individually or by a cell of string of same dimension as the -% number of components in the data. -% -% -% methods -% SignalObj Examples -% -% Reference page in Help browser -% doc SignalObj - - -% -% nSTAT v1 Copyright (C) 2012 Masschusetts Institute of Technology -% Cajigas, I, Malik, WQ, Brown, EN -% This program is free software; you can redistribute it and/or -% modify it under the terms of the GNU General Public License as published -% by the Free Software Foundation; either version 2 of the License, or -% (at your option) any later version. -% -% This program is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -% See the GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with this program; if not, write to the Free Software Foundation, -% Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - properties (SetAccess = private) - name % name of the SignalObj - time % time vector. Time increment determines sampleRate - data % actual SignalObj data - dimension % number of different components of the SignalObj - minTime % minimum Time value of the SignalObj - maxTime % maximum Time value of the SignalObj - xlabelval % label to use for the x-axis - xunits % units for x-axis - yunits % units for y-axis data - dataLabels % labels for each dimension of the data; - dataMask % vector same length as SignalObj dimension. a 1 indicates this SignalObj should be output a 0 otherwie - sampleRate % Hz if time is in seconds - plotProps % Plotting properties - end - properties (Hidden) - origSampleRate - originalTime %original timeVector - originalData %original Data - end -% properties (Dependent = true) -% vars %Contains subfields of the same names as the dataLabels that contain Signals with only the data corresponding to that label. -% end - methods - %Constructor - function s=SignalObj(time, data, name, xlabelval, xunits, yunits, dataLabels, plotProps) - - if(nargin<6) - yunits=''; - end - if(nargin<5) - xunits='s'; - end - if(nargin<4) - xlabelval='time'; - end - if(nargin<3) - name=''; - end - [l,w]=size(time); - if(l>=w) - if(w>1) - error('Time vector can only have one dimension'); - else - s.time=time; - - end - elseif(l<=w) - if(l>1) - error('Time vector can only have one dimension'); - else - s.time=time'; - end - end - s.originalTime=s.time; - [l,w]=size(data); - if(l==length(s.time)); - s.data=data; - s.dimension =w; - elseif(w==length(s.time)) - s.data=data'; - s.dimension=l; - else - error('Data dimensions do not match the time vector specified'); - end - s.originalData = s.data; - if(nargin <7) - if(s.dimension==0) - dataLabels =''; - else - for i=1:s.dimension - dataLabels{i} = ''; - end - end - end - s.dataMask = ones(1,s.dimension); - if(nargin<8) - plotProps = cell(s.dimension,1); - end - deltaT=mean(diff(s.time)); - if(isnan(deltaT))%diff not well defined - deltaT=0.001; - end - precision =2*ceil(log10(1/deltaT)); - deltaT = roundn(deltaT,-precision); -% deltaT = roundn(mean(diff(s.time)),-3); %To avoid round-off error, when computing samplerate - s.sampleRate = 1/deltaT; - s.origSampleRate = s.sampleRate; - s.name=name; - s.xlabelval=xlabelval; - s.xunits=xunits; - s.yunits=yunits; - s.minTime=min(s.time); - s.maxTime=max(s.time); - s.setPlotProps(plotProps); - s.setDataLabels(dataLabels); - end - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %Set functions - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - function setName(sObj,name) - % setName(sObj,name) - % set the name after construction - if(isa(name,'char')) - sObj.name = name; - else - error('Name must be a string!'); - end - end - function setXlabel(sObj,name) - %setXlabel(sObj,name) - %set the x-axis label to string name - sObj.xlabelval = name; - end - function setYLabel(sObj,name) - %setYLabel(sObj,name) - %set the ylabel to string name; - %Same as calling setName(sObj,name); - sObj.setName(name); - end - function setUnits(sObj, xUnits, yUnits) - %setUnits(sObj, xUnits, yUnits) - %Set the axis units. - %Same as calling sObj.setXUnits(xUnits) and - %sObj.setYUnits(yUnits) separately. - %yUnits is optional argument. If it is not specified, the this - %function behaves like setXUnits. - if(nargin==3) - if(isa(yUnits,'char')) - sObj.setYunits(yUnits); - end - end - if(nargin>=2) - if(isa(xUnits,'char')) - sObj.setXunits(xUnits); - end - end - end - function setXUnits(sObj, units) - %setXUnits(sObj, units) - %Sets the units of the x-axis - if(isa(units, 'char')) - sObj.xunits = units; - end - end - function setYUnits(sObj, units) - %setYUnits(sObj, units) - %Sets the units of the y-axis - if(isa(units,'char')) - sObj.yunits = units; - end - end - function setSampleRate(sObj, sampleRate) - % setSampleRate(sObj, sampleRate) - % sets the current sampleRate of the object to rate specified - if(sObj.sampleRate~=sampleRate) - if(~(floor(sampleRate*1000)/1000==floor(sObj.sampleRate*1000)/1000)) %Compare to 3 decimal places (finite precision has caused errors 500.000001 ~= 500.00000x - if(sampleRate>sObj.sampleRate) - %fprintf(strcat('SignalObj,',sObj.name',', upsampled to:',num2str(sampleRate))); - else - %fprintf(strcat('SignalObj,',sObj.name',', downsampled to:',num2str(sampleRate))); - end - sObj.resampleMe(sampleRate); - end - end - end - function setDataLabels(sObj,dataLabels) - %setDataLabels(sObj,dataLabels) - %sets the labels for each of the components of the SignalObj. - %if sObj has only a single component, then dataLabels can be a - %string. Otherwise, dataLabels must be a cell with the same - %dimensions as sObj. dataLabels{i} specifies the string for the - %ith component of sObj. - if(~isempty(dataLabels)) - if(isa(dataLabels,'char')) - if(sObj.dimension==1) - sObj.dataLabels{1}=dataLabels; - else - display('Adding single dataLabel to a SignalObj with more that 1 dimension. All dimensions have same label now!'); - for i=1:sObj.dimension - sObj.dataLabels{i} = dataLabels; - end - end - - elseif(isa(dataLabels,'cell')) - if(length(dataLabels)==sObj.dimension) - %ind=sObj.findIndFromDataMask; - %for i=ind - % sObj.dataLabels{i} = dataLabels{i}; - %end - sObj.dataLabels = dataLabels; - else - error('Need the number of labels to match the number of dimensions of the SignalObj'); - end - end - else - if(sObj.dimension==1) - sObj.dataLabels=''; - else - for i=1:sObj.dimension - sObj.dataLabels{i}=''; - end - end - end - end - function setMinTime(sObj,minTime,holdVals) - %setMinTime(sObj,minTime,holdVals) - %sets the minimun value of the time vector to minTime. If - %minTime>min(sObj.time) then the data before minTime will be - %ignored. If minTime < min(sObj.time) then the time vector is - %extended at the current sampleRate to minTime. - %holdVals: 1 or 0. If not specifed, defaults to 0. If - %holdVals=1, then the value at min(sObj.time) is extended to - %the new minTime. Otherwise, the added time is padded with - %zeros. - if(nargin<3) - holdVals=0; - end - - if(nargin<2) - minTime=sObj.time(1); - end - timeVec=sObj.getTime; - if(minTime max(sObj.time) then the time vector is - %extended at the current sampleRate to maxTime. - %holdVals: 1 or 0. If not specifed, defaults to 0. If - %holdVals=1, then the value at min(sObj.time) is extended to - %the new minTime. Otherwise, the added time is padded with - %zeros. - if(nargin<3) - holdVals=0; - end - - if(nargin<2) - maxTime=sObj.time(end); - end - timeVec=sObj.getTime; - if(max(timeVec)0 && index<=sObj.dimension) - sObj.plotProps{index} = plotProps{:}; - else - error('Index out of bounds during setPlotProps'); - end - elseif(isa(plotProps,'char')) - if(index>0 && index<=sObj.dimension) - sObj.plotProps{index} = plotProps; - else - error('Index out of bounds during setPlotProps'); - end - - end - end - end - function setMask(sObj, mask) - %setMask(sObj, mask) - % if called with no arguments, all the components of the signal - % are masked. No data will be visible. - % mask: either a set of indices or a cell array of characters - % indicating which signal components are to remain visible. - if(nargin<2) - mask=zeros(1,sObj.dimension); - sObj.setDataMask(mask); - return; - end - %mask is either a set of indices or names; - if(isa(mask,'cell')) - if(isa(mask{1},'char')) - sObj.setMaskByLabels(mask); - else - error('Mask cells must contains strings!'); - end - elseif(isa(mask,'double')) - sObj.setMaskByInd(mask); - else - error('Can only set datamask with strings or indices') - end - end - - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - function tVec = getTime(sObj) - % tVec = getTime(sObj) - % returns the time vector of the Signal Obj - tVec=sObj.time; - end - function data = getData(sObj) - % data = getData(sObj) - % Returns the signal data as a matrix. If masks are set, then - % only the components that are visible will be returned. Each - % column corresponds to each component of the SignalObj that is - % visible. The columns are in the same order as the dataLabels. - data=sObj.dataToMatrix; - end - function [t,d] = getOriginalData(sObj) - % [t,d] = getOriginalData(sObj) - % SignalObjs have memory. The original data and time vectors - % are stored even when the signal is resamples, windowed, etc. - % This commands returns the original data used to create the - % SignalObj - t=sObj.originalTime; - d=sObj.originalData; - end - function s = getOrigDataSig(sObj) - % s = getOrigDataSig(sObj) - % same as getOriginalData, except that a SignalObj containing the original data is returned. - - [time,data]=sObj.getOriginalData; - name=sObj.name; - xlabelval=sObj.xlabelval; - xunits=sObj.xunits; - yunits=sObj.yunits; - dataLabels=sObj.dataLabels; - plotProps=sObj.plotProps; - ctorHandle = str2func(class(sObj)); - s = ctorHandle(time, data,name, xlabelval, xunits, yunits,dataLabels,plotProps); - %s = SignalObj(time, data,name, xlabelval, xunits, yunits,dataLabels,plotProps); - end - function val = getValueAt(sObj,x) - %val = getValueAt(sObj,x) - %returns a row vector of length sObj.dimension corresponding to - %the values of the signal evaluated at time=x - - %ind=sObj.findNearestTimeIndices(x); - %val=sObj.data(ind,:); - - [l,w]=size(x); - if(w>l) - x=x'; - end - -% val = interp1(sObj.time,sObj.data,x,'spline',0); %extrapolate to zero - val = interp1(sObj.time,sObj.data,x,'nearest',0); %extrapolate to zero -% if(any(isnan(sObj.data))) -% pause -% end -% if(sObj.dimension==1) -% val=val'; -% end - - end - function PropsStr = getPlotProps(sObj,index) - %PropsStr = getPlotProps(sObj,index) - %Returns the string correspond to the plotting properties of - %the SignalObj component corresponding to index - if(index>0 && index<=sObj.dimension) - PropsStr = cell2str(sObj.plotProps{index}); - else - error('index is out of bounds!'); - end - end - function indices = getIndicesFromLabels(sObj,label) - %indices = getIndicesFromLabels(sObj,label) - %Returns a cell array if the label appears for various point - %in the SignalObj. indices{i} contains all the the indices - %corresponding to label{i} if label is a cell-array or label if - %it is a string. - %Returns an array if the SignalObj label appears only once in the - %SignalObj - if(isa(label,'cell')) - indices =cell(1,length(label)); - numInd =zeros(1,length(label)); - for i=1:length(label) - tempInd = sObj.getIndexFromLabel(label{i}); - if(~isempty(tempInd)) - numInd(i) = length(tempInd); - indices{i}=tempInd; - else - error('Label does not exist!'); - end - - end - elseif(isa(label,'char')) - indices = sObj.getIndexFromLabel(label); - numInd(1) = length(indices); - end - - - if(max(numInd)==1) %For backwards compatibility if assuming only on index per label - if(isa(indices,'cell')) - for i=1:length(numInd) - - tempInd(i) = indices{i}; - end - indices = tempInd; - end - end - end - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - % Operand Definitions and other mathematical operations - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - function s3 = plus(s1,s2) - % s3 = plus(s1,s2) - % Adds two signals - if(isa(s1,'SignalObj') && isa(s2,'SignalObj')) - % What if s2 is a constant or double? - if(s1.dimension == s2.dimension) - [s1c,s2c] = makeCompatible(s1,s2); - s3=s1c.copySignal; - s3.data = s1c.data+s2c.data; - - for i=1:length(s3.dataLabels) - if(~s2c.areDataLabelsEmpty && ~isempty(s2c.dataLabels{i})) - if(strcmp(s2c.dataLabels{i}(1),'-')) - s3.dataLabels{i} = [s1c.dataLabels{i} '-' s2c.dataLabels{i}(2:end)]; - else - s3.dataLabels{i} = [s1c.dataLabels{i} '+' s2c.dataLabels{i}]; - end - end - end - else - error('Can only add signals if they have the same dimension'); - end - elseif(isa(s1,'double') || isa(s2,'double')) - if(isa(s1,'double')) - s3=s2.copySignal; - [l,w] = size(s1); - if(w==s3.dimension && l==1) - s3.data = s3.data+ones(length(s3.data),1)*s1; - for i=1:length(s3.dataLabels) - if(sign(s1(i))==-1) - s3.dataLabels{i} = [s2.dataLabels{i} '-' num2str(abs(s1(i)))]; - else - s3.dataLabels{i} = [s2.dataLabels{i} '+' num2str(abs(s1(i)))]; - end - end - else - s3.data = s3.data+s1; - %dont modify dataLabels since s1 is a matrix; - - %for i=1:length(s3.dataLabels) - % s3.dataLabels{i} = [s2.dataLabels{i} '+' num2str(s1(i))]; - %end - end - else - s3=s1.copySignal; - [l,w] = size(s2); - %size(s3.data) - if(w==s3.dimension && l==1) - s3.data = s3.data+ones(length(s3.data),1)*s2; - for i=1:length(s3.dataLabels) - if(sign(s2(i))==-1) - s3.dataLabels{i} = [s1.dataLabels{i} '-' num2str(abs(s2(i)))]; - else - s3.dataLabels{i} = [s1.dataLabels{i} '+' num2str(abs(s2(i)))]; - end - end - else - - s3.data = s3.data+s2; - %dont modify dataLabels since s2 is a matrix; - %for i=1:length(s3.dataLabels) - % s3.dataLabels{i} = [s1.dataLabels{i} '+' num2str(s2)]; - %end - end - end - else - error('only Signals or doubles are currently supported'); - end - end - function s3 = minus(s1,s2) - % s3 = minus(s1,s2) - % Subtracts two signals - s3=plus(s1,-s2); - end - function s3 = uplus(s1) %+s1 - % s3 = uplus(s1) - % Multiplies signal by +1 - s3=s1.copySignal; - end - function s3 = uminus(s1) %-s1 - % s3 = uminus(s1) %-s1 - % Multiplies the signal by -1. - % dataLabels are updated to reflect this. - s3=s1.copySignal; - s3.data=-s3.data; - for i=1:length(s3.dataLabels) - s3.dataLabels{i} = strcat('-',s1.dataLabels{i}); - end - end - function s3 = power(s1,exponent) - if(isa(exponent,'double')) - s3=s1.copySignal; - s3.data=s3.data.^exponent; - else - error('Exponent should be a double'); - end - end - - function s3 = sqrt(s1) - s3=s1.copySignal; - s3.data=sqrt(s3.data); - - end - function s3 = times(s1,s2) %s1.*s2 - %s3 = times(s1,s2) - %Multiplies each sample in s1 with each sample of s2. - %s1 or s2 can be doubles - if(isa(s1,'SignalObj') && isa(s2,'SignalObj')) - if(s1.dimension == s2.dimension) - [s1c,s2c] = makeCompatible(s1,s2); - s3 = s1c; - s3.data = s1c.data.*s2c.data; - %can multiply units - else - error('can only multiply signals with same dimension'); - end - elseif(isa(s1,'double') || isa(s2,'double')) - if(isa(s1,'double')) - s3=s2.copySignal; - [l,w] = size(s1); - if(w==s3.dimension && l==1) - s3.data = s3.data.*(ones(length(s3.data),1)*s1); - else - s3.data = s3.data.*s1; - end - else - s3=s1.copySignal; - [l,w] = size(s2); - if(w==s3.dimension && l==1) - s3.data = s3.data.*(ones(length(s3.data),1)*s2); - else - s3.data = s3.data.*s2; - end - end - end - end - function s3 = mtimes(s1,s2) %s1*s2 - %Matrix multiplication of two signals - %Needs work - %If s1 and s2 are signals, same as times(s1,s2) - if(isa(s1,'SignalObj') && isa(s2,'SignalObj')) - %[s1c,s2c] = makeCompatible(s1,s2); - s3 = s1.copySignal; - s3.data = s1.data.*s2.data; - %can multiply units - elseif(isa(s1,'double') || isa(s2,'double')) - if(isa(s1,'double')) - s3=s2.copySignal; - s3.data = (s1*s3.data')'; - else - s3=s1.copySignal; - s3.data = (s3.data'*s2)'; - end - end - end - function s3 = rdivide(s1,s2) - if(isa(s1,'SignalObj') && isa(s2,'SignalObj')) - if(s1.dimension == s2.dimension) - [s1c,s2c] = makeCompatible(s1,s2); - s3 = s1c; - s3.data = s1c.data./s2c.data; - %can multiply units - else - error('can only multiply signals with same dimension'); - end - elseif(isa(s1,'double') || isa(s2,'double')) - if(isa(s1,'double')) - s3=s2.copySignal; - s3.data = s1./s3.data; - else - s3=s1.copySignal; - s3.data = s3.data./s2; - end - end - end - function s3 = ldivide(s1,s2) - if(isa(s1,'SignalObj') && isa(s2,'SignalObj')) - if(s1.dimension == s2.dimension) - [s1c,s2c] = makeCompatible(s1,s2); - s3 = s1c; - s3.data = s1c.data.\s2c.data; - %can multiply units - else - error('can only multiply signals with same dimension'); - end - elseif(isa(s1,'double') || isa(s2,'double')) - if(isa(s1,'double')) - s3=s2.copySignal; - s3.data = s1.\s3.data; - else - s3=s1.copySignal; - s3.data = s3.data.\s2; - end - end - end - function s3 = ctranspose(s1) - s3=s1.copySignal; - s3.data=s3.data.'; - [l,w]=size(s3.data); - s3.dimension=w; - end - function s3 = transpose(s1) - s3=s1.copySignal; - s3.data=s3.data.'; - [l,w]=size(s3.data); - s3.dimension=w; - end - function s3 = derivative(sObj) - %Computes derivative of each component of the SignalObj with - %respect to the x-axis variable. -% B=[1 -1]*sObj.sampleRate; -% A=1; -% s3=sObj.filter(B,A); - s3=sObj.copySignal; - tData=diff(s3.data)*s3.sampleRate; - tData=[zeros(1,s3.dimension); tData]; - s3.data=tData; - - s3.setYUnits(strcat('\frac{',s3.yunits,'}{',s3.xunits,'}')); - denomstr = strcat('d', s3.xlabelval(1)); - - s3.setName(strcat('\frac{d}{',denomstr,'}',s3.name)); - for i=1:s3.dimension - if(s3.dimension ==1) - if(~strcmp(sObj.dataLabels,'')) - s3.dataLabels{i}= strcat('\frac{d}{',denomstr,'}',s3.dataLabels); - end - else - if(~strcmp(sObj.dataLabels{i},'')) - s3.dataLabels{i}= strcat('\frac{d}{',denomstr,'}',s3.dataLabels{i}); - end - end - end - end - function val = derivativeAt(sObj,x0) - % val = derivativeAt(sObj,x0) - %computes the derivative of the Signal at x0. Returns a row - %vector of length equal to sObj.dimension. - sTemp = sObj.derivative; - val = sTemp.getValueAt(x0); - end - function s3 = integral(sObj,t0,tf) - %s3 = integral(sObj,t0,tf) - %computes the integral of the signal in the window from t0 to tf. - %if tf is not specified, sObj.maxTime is used. - %if t0 is not specified, sObj.minTime is used. - % Both t0 and tf are optional but t0 must be specified if tf is - % to be specified (e.g. cant specified tf only) - % Data labels are updated with latex notation for integral. - % the value of the returned signal at time t is the value of - % the integral from minTime to t. - if(nargin<3) - tf=sObj.maxTime; - end - if(nargin<2) - t0=sObj.minTime; - end - - %y[n] = y[n-1] + x[n]*deltaT - B=1*1/sObj.sampleRate; - A=[1 -1]; - s3=sObj.getSigInTimeWindow(t0,tf); - s3=s3.filter(B,A); - s3.setYUnits(strcat(s3.yunits,'*',s3.xunits)); - dtstr = strcat(' d','\tau'); - s3.setName(['\int_',num2str(s3.minTime),'^',s3.xlabelval(1),'\!\!{',[s3.name dtstr],'}']); - if(~sObj.areDataLabelsEmpty) - for i=1:s3.dimension - if(~strcmp(sObj.dataLabels{i},'')) - s3.dataLabels{i}= ['\int_',num2str(s3.minTime),'^',s3.xlabelval(1),'\!\!{',[s3.dataLabels{i} dtstr],'}']; - else - s3.dataLabels{i} = ''; - end - end - end - end - function s3 = filter(sObj, B,A) - %s3 = filter(sObj, B,A) - %applies the discrete filter specified by B and A to the sObj - %data. Same as running filter(B,A,sObj.dataToMatrix). dataMasks - %are ignores so that the signal dimensionality does not change. - s3=sObj.copySignal; - s3.data = filter(B,A,s3.data); - end - function s3 = filtfilt(sObj,B,A) - %s3 = filtfilt(sObj,B,A) - %applies the discrete filter specified by B and A to the sObj - %data using filtfilt. Same as running filtfilt(B,A,sObj.dataToMatrix). dataMasks - %are ignores so that the signal dimensionality does not change. - s3=sObj.copySignal; - s3.data = filtfilt(B,A,s3.data); - end - function [s1c,s2c] = makeCompatible(s1,s2,holdVals) - %[s1c,s2c] = makeCompatible(s1,s2,holdVals) - %returns two signals that copies of the original signals but - %that have been resampled or extended in time so that the time - %axis of both signals in the same. This is done before most - %mathmatical operations to make sure that the signals have the - %same support. - % holdVals = 1 makes the signals keep their endpoint values if - % they are extended in time. holdVals is an optional argument. - if(nargin<3) - holdVals=0; - end - if(s1.minTime~=s2.minTime || s1.maxTime~=s2.maxTime || s1.sampleRate ~=s2.sampleRate) - s1c = s1.copySignal; s2c = s2.copySignal; - minTime=min(s1c.minTime,s2c.minTime); - maxTime=max(s1c.maxTime,s2c.maxTime); - sampleRate=max(s1c.sampleRate,s2c.sampleRate); - s1c.setSampleRate(sampleRate); s2c.setSampleRate(sampleRate); - s1c.setMinTime(minTime,holdVals); s2c.setMinTime(minTime,holdVals); - s1c.setMaxTime(maxTime,holdVals); s2c.setMaxTime(maxTime,holdVals); - - %pause - % for i=1:s2c.dimension - %if(max(s2c.time-s1c.time)>0) - data = interp1(s2c.time,s2c.data,s1c.time,'nearest',0); - %else - % data = s2c.data; - %end - % end - s2c.time = s1c.time; - [nrows,ncolumns] = size(data); - if(nrows>ncolumns) - s2c.data = data; - else - s2c.data = data'; - end - else - s1c = s1; - s2c = s2; - end - - end - function s = abs(sObj) - absData=abs(sObj.data); - [nrows,ncolumns]=size(absData); - name = ['|', sObj.name '|']; - plotProps = sObj.plotProps; - if(~sObj.areDataLabelsEmpty) - dataLabels = cell(size(sObj.dataLabels)); -% plotProps = sObj.plotProps; - for i=1:sObj.dimension - dataLabels{i} = strcat('|',sObj.dataLabels{i},'|'); - end - evalstring = strcat('s=',class(sObj),'(sObj.time, absData,name,sObj.xlabelval, sObj.xunits,sObj.yunits,dataLabels,plotProps);'); - else - - evalstring = strcat('s=',class(sObj),'(sObj.time, absData,name,sObj.xlabelval, sObj.xunits,sObj.yunits,[],plotProps);'); - end - eval(evalstring); - end - - function s = log(sObj) - logData=log(sObj.data); - [nrows,ncolumns]=size(logData); - name = ['ln(' sObj.name ')']; - yunits = ['ln(' sObj.yunits ')']; - plotProps = sObj.plotProps; - if(~sObj.areDataLabelsEmpty) - dataLabels = cell(size(sObj.dataLabels)); -% plotProps = sObj.plotProps; - for i=1:sObj.dimension - dataLabels{i} = strcat('ln(',sObj.dataLabels{i},')'); - end - evalstring = strcat('s=',class(sObj),'(sObj.time, logData,name,sObj.xlabelval, sObj.xunits,yunits,dataLabels,plotProps);'); - else - - evalstring = strcat('s=',class(sObj),'(sObj.time, logData,name,sObj.xlabelval, sObj.xunits,yunits,[],plotProps);'); - end - eval(evalstring); - end - - function m=median(sObj,varargin) - %m=median(sObj,varargin) - %Computes the column-wise median of SignalObj data. Returns a - %signal with the corresponding median values - %same as calling median(sObj.dataToMatrix,varargin) - %Additional parameters are passed to the matlab median function. - %Default computes median of each signal component across time. - %mean(sObj,2) computes median value of the SignalObj at each - %point in time. - mdata=median(sObj.data,varargin{:}); - [nrows,ncolumns]=size(mdata); - if( (nrows==length(sObj.time)) && (ncolumns==1) ) %mean across dimensions - name = ['median(', sObj.name ')']; - evalstring = strcat('m=',class(sObj),'(sObj.time, mdata,name,sObj.xlabelval, sObj.xunits,sObj.yunits);'); - eval(evalstring); - elseif( (nrows==1) && (ncolumns == sObj.dimension) ) %mean of each dimension - if(~sObj.areDataLabelsEmpty) - dataLabels = cell(size(sObj.dataLabels)); - for i=1:sObj.dimension - dataLabels{i} = strcat('median(',sObj.dataLabels{i},')'); - end - name = ['median(', sObj.name ')']; - evalstring = strcat('m=',class(sObj),'([sObj.time(1); sObj.time(end)], [mdata;mdata],name,sObj.xlabelval, sObj.xunits,sObj.yunits,dataLabels);'); - eval(evalstring); - %m=SignalObj([sObj.time(1); sObj.time(end)], [mdata;mdata], ['Mean of ' sObj.name],sObj.xlabelval, sObj.xunits,sObj.yunits,dataLabels); - else - name = ['median(', sObj.name ')']; - evalstring = strcat('m=',class(sObj),'([sObj.time(1); sObj.time(end)], [mdata;mdata],name,sObj.xlabelval, sObj.xunits,sObj.yunits);'); - eval(evalstring); - %m=SignalObj([sObj.time(1); sObj.time(end)], [mdata;mdata], ['Mean of ' sObj.name],sObj.xlabelval, sObj.xunits,sObj.yunits); - end - - - end - - - - end - function m=mode(sObj,varargin) - %m=mode(sObj,varargin) - %Computes the column-wise mode of SignalObj data. Returns a - %signal with the corresponding mode values - %same as calling mode(sObj.dataToMatrix,varargin) - %Additional parameters are passed to the matlab mode function. - %Default computes mode of each signal component across time. - %mean(sObj,2) computes mode value of the SignalObj at each - %point in time. - mdata=mode(sObj.data,varargin{:}); - [nrows,ncolumns]=size(mdata); - if( (nrows==length(sObj.time)) && (ncolumns==1) ) %mean across dimensions - name = ['mode(', sObj.name ')']; - evalstring = strcat('m=',class(sObj),'(sObj.time, mdata,name,sObj.xlabelval, sObj.xunits,sObj.yunits);'); - eval(evalstring); - elseif( (nrows==1) && (ncolumns == sObj.dimension) ) %mean of each dimension - if(~sObj.areDataLabelsEmpty) - dataLabels = cell(size(sObj.dataLabels)); - for i=1:sObj.dimension - dataLabels{i} = strcat('mode(',sObj.dataLabels{i},')'); - end - name = ['mode(', sObj.name ')']; - evalstring = strcat('m=',class(sObj),'([sObj.time(1); sObj.time(end)], [mdata;mdata],name,sObj.xlabelval, sObj.xunits,sObj.yunits,dataLabels);'); - eval(evalstring); - %m=SignalObj([sObj.time(1); sObj.time(end)], [mdata;mdata], ['Mean of ' sObj.name],sObj.xlabelval, sObj.xunits,sObj.yunits,dataLabels); - else - name = ['mode(', sObj.name ')']; - evalstring = strcat('m=',class(sObj),'([sObj.time(1); sObj.time(end)], [mdata;mdata],name,sObj.xlabelval, sObj.xunits,sObj.yunits);'); - eval(evalstring); - %m=SignalObj([sObj.time(1); sObj.time(end)], [mdata;mdata], ['Mean of ' sObj.name],sObj.xlabelval, sObj.xunits,sObj.yunits); - end - end - end - - - function m=mean(sObj,varargin) - %m=mean(sObj,varargin) - %Computes the column-wise mean of SignalObj data. Returns a - %signal with the corresponding mean values - %same as calling mean(sObj.dataToMatrix,varargin) - %Additional parameters are passed to the matlab mean function. - %Default computes mean of each signal component across time. - %mean(sObj,2) computes mean value of the SignalObj at each - %point in time. - mdata=mean(sObj.data,varargin{:}); - [nrows,ncolumns]=size(mdata); - if( (nrows==length(sObj.time)) && (ncolumns==1) ) %mean across dimensions - name = ['\mu(', sObj.name ')']; - evalstring = strcat('m=',class(sObj),'(sObj.time, mdata,name,sObj.xlabelval, sObj.xunits,sObj.yunits);'); - eval(evalstring); - elseif( (nrows==1) && (ncolumns == sObj.dimension) ) %mean of each dimension - if(~sObj.areDataLabelsEmpty) - dataLabels = cell(size(sObj.dataLabels)); - for i=1:sObj.dimension - dataLabels{i} = strcat('\mu(',sObj.dataLabels{i},')'); - end - name = ['\mu(', sObj.name ')']; - evalstring = strcat('m=',class(sObj),'([sObj.time(1); sObj.time(end)], [mdata;mdata],name,sObj.xlabelval, sObj.xunits,sObj.yunits,dataLabels);'); - eval(evalstring); - %m=SignalObj([sObj.time(1); sObj.time(end)], [mdata;mdata], ['Mean of ' sObj.name],sObj.xlabelval, sObj.xunits,sObj.yunits,dataLabels); - else - name = ['\mu(', sObj.name ')']; - evalstring = strcat('m=',class(sObj),'([sObj.time(1); sObj.time(end)], [mdata;mdata],name,sObj.xlabelval, sObj.xunits,sObj.yunits);'); - eval(evalstring); - %m=SignalObj([sObj.time(1); sObj.time(end)], [mdata;mdata], ['Mean of ' sObj.name],sObj.xlabelval, sObj.xunits,sObj.yunits); - end - end - end - function m=std(sObj,varargin) - %m=std(sObj,varargin) - %Computes the column-wise std of SignalObj data. Returns a - %signal with the corresponding mean values - %same as calling std(sObj.dataToMatrix,varargin) - %Additional parameters are passed to the matlab std function. - %Default computes std of each signal component across time. - %std(sObj,[],2) computes std value of the SignalObj at each - %point in time. - stdData=std(sObj.data,varargin{:}); - [nrows,ncolumns]=size(stdData); - if( (nrows==length(sObj.time)) && (ncolumns==1) ) %mean across dimensions - name=['\sigma(' sObj.name ')']; - evalstring = strcat('m=',class(sObj),'(sObj.time, stdData,name,sObj.xlabelval, sObj.xunits,sObj.yunits);'); - eval(evalstring); - %m=SignalObj(sObj.time, stdData, name,sObj.xlabelval, sObj.xunits,sObj.yunits); - elseif( (nrows==1) && (ncolumns == sObj.dimension) ) %mean of each dimension - if(~sObj.areDataLabelsEmpty) - dataLabels = cell(size(sObj.dataLabels)); - for i=1:sObj.dimension - dataLabels{i} = strcat('\sigma(',sObj.dataLabels{i},')'); - end - name=['\sigma(' sObj.name ')']; - evalstring = strcat('m=',class(sObj),'([sObj.time(1); sObj.time(end)], [stdData;stdData],name,sObj.xlabelval, sObj.xunits,sObj.yunits,dataLabels);'); - eval(evalstring); - %m=SignalObj([sObj.time(1); sObj.time(end)], [stdData;stdData], ['Std. Dev. of ' sObj.name],sObj.xlabelval, sObj.xunits,sObj.yunits,dataLabels); - else - name=['\sigma(' sObj.name ')']; - evalstring = strcat('m=',class(sObj),'([sObj.time(1); sObj.time(end)], [stdData;stdData],name,sObj.xlabelval, sObj.xunits,sObj.yunits);'); - eval(evalstring); - %m=SignalObj([sObj.time(1); sObj.time(end)], [stdData;stdData], ['Std. Dev. of ' sObj.name],sObj.xlabelval, sObj.xunits,sObj.yunits); - end - end - - end - function [m, index,time]=max(sObj,varargin) - %[m,time]=max(sObj,varargin) - %calls matlab max function with the SignalObj's data. - %Additional parameters are passed to the matlab function - [m,index]=max(sObj.data,varargin{:}); - time = sObj.time(index); - - end - function [m,index,time]=min(sObj,varargin) - %m=min(sObj,varargin) - %calls matlab min function with the SignalObj's data. - %Additional parameters are passed to the matlab function - [m,index]=min(sObj.data,varargin{:}); - time = sObj.time(index); - end - - function s = autocorrelation(sObj) - if(sObj.dimension==1) - [ACF,lags,bounds] = crosscorr(sObj.data,sObj.data,length(sObj.data)-1); - s=SignalObj(lags/sObj.sampleRate, ACF,['ACF(' sObj.name, ')'], 'Lag', sObj.xunits, [sObj.yunits '^2']); - else - %if more than one dimension then computes the - %autocorrelation of each dimension with itself - for i=1:sObj.dimension - - [ACF(:,i),lags,bounds] = crosscor(sObj.data(:,i),sObj.data(:,i),length(sObj.data(:,i))-1); - - end - s=SignalObj(lags/sObj.sampleRate, ACF,['ACF(' sObj.name, ')'], 'Lag', sObj.xunits, [sObj.yunits '^2']); - end - - end - - function s = crosscorrelation(sObj, s2) - if(and(sObj.dimension ==1, s2.dimension==1)) - - [xcf,lags,bounds] = crosscorr(sObj.data, s2.data,length(sObj.data)-1); - s=SignalObj(lags/sObj.sampleRate, xcf,['XCORF(' sObj.name, ')'], 'Lag', sObj.xunits, [sObj.yunits '^2']); - else - error('Does not support multidimensional signals'); - end - end - - function periodogram = periodogram(sObj) - %periodogram = periodogram(sObj) - % computes the periodogram of each component of the SignalObj. - % Calls matlab periodogram with each component. - % fs = sObj.sampleRate; - % NFFT = 1024 - fs = sObj.sampleRate; % Sampling frequency - periodogram = cell(1,sObj.dimension); - for i=1:sObj.dimension - xn = sObj.data(:,i); - Hs = spectrum.periodogram('rectangular'); - switch sObj.dimension - case 2 - subplot(1,2,i) - case 3 - subplot(1,3,i) - case 4 - subplot(2,2,i) - case 5 - subplot(3,2,i) - case 6 - subplot(3,2,i) - otherwise - h=gcf;figure(h); - end - periodogram{i}=psd(Hs,xn,'Fs',fs,'NFFT',1024); - - if(~isempty(sObj.dataLabels)) - h=periodogram{i}.plot;legend(h, sObj.dataLabels{i}); - else - h=periodogram{i}.plot; - end - end - end - function mtmSpec = MTMspectrum(sObj,NW,NFFT,Pval) - %mtmSpec = MTMspectrum(sObj,NW,NFFT,Pval) - %computes Multi-taper spectral estimate of each component of - %the SignalObj with defaults: - %NW=4, NFFT=[], Pval=.95 - % Defaults can be changed by passing in additional arguments - if(nargin<4) - Pval=.95; - end - if(nargin<3) - NFFT=[]; - end - if(nargin<2) - NW=4; - end - - Fs=sObj.sampleRate; - mtmSpec = cell(1,sObj.dimension); - for i=1:sObj.dimension - xn=sObj.data(:,i); - [Pxx,Pxxc,f] = pmtm(xn,NW,NFFT,Fs,Pval); - hpsd = dspdata.psd([Pxx Pxxc],'Fs',Fs); - mtmSpec{i} = hpsd; - switch sObj.dimension - case 2 - subplot(1,2,i) - case 3 - subplot(1,3,i) - case 4 - subplot(2,2,i) - case 5 - subplot(3,2,i) - case 6 - subplot(3,2,i) - otherwise - h=gcf;figure(h); - end - str1=strcat(num2str(Pval*100), '% Conf. Int.'); - h=plot(hpsd); legend(h, sObj.dataLabels{i},strcat('-',str1),strcat('+',str1)); - end - end - function [spectrogramData,h] = spectrogram(sObj,freqVec,h) - if(nargin<3 ||isempty(h)) - h=figure; - end - if(nargin<2 || isempty(freqVec)) - freqVec=0:.1:50; - end - t=sObj.time; % 2 secs @ 1kHz sample rate - x=sObj.data; % Start @ DC, cross 150Hz at t=1sec - F = freqVec; - window=kaiser(round(length(t)/20)); - nooverlap = round(round(length(t)/40)); - clear y f t p; - for i=1:sObj.dimension -% figure; - [y{i},f{i},t{i},p{i}] = spectrogram(x(:,i),window,nooverlap,F,sObj.sampleRate); - t{i} = t{i}+min(sObj.time); - surf(t{i},f{i},10*log10(abs(p{i})),'EdgeColor','none'); - axis xy; axis tight; colormap(jet); view(0,90); - xlabel('time [s]'); - ylabel('frequency [Hz]'); - - end - if(sObj.dimension>1) - for i=1:sObj.dimension - spectrogramData{i}.t = t{i}; - spectrogramData{i}.f = f{i}; - spectrogramData{i}.p = p{i}; - spectrogramData{i}.y = y{i}; - end - else - spectrogramData.t = t{i}; - spectrogramData.f = f{i}; - spectrogramData.p = p{i}; - spectrogramData.y = y{i}; - - end - end - - - function sxCorr= xcorr(s1,s2,varargin) - if(nargin<2) - s2=s1; - end - - [s1c,s2c] = makeCompatible(s1,s2); - if(~isempty(varargin)) - [tempC tempLags] =xcorr([s1c.data, s2c.data],varargin{1}); - else - [tempC tempLags] =xcorr([s1c.data, s2c.data]); - end - index=[]; - for i=1:s1c.dimension - offset(i)=(i-1)*(s1c.dimension+s2c.dimension); - index = [index, (offset(i)+s1c.dimension+1):(offset(i)+s1c.dimension+s2c.dimension)]; - end - sum=0; - dataLabels = cell(1,length(index)); - for i=1:s1c.dimension - for j=1:s2c.dimension - sum = sum+1; - dataLabels{sum} = strcat('corr(',s1c.dataLabels{i},',',s2c.dataLabels{j}, ']'); - end - end - - M=length(s1c.data); - if(nargin<2) - data=tempC(M-1:end,index); - lags=tempLags(M-1:end)./s1c.sampleRate; - else - data=tempC(1:end,index); - lags=tempLags(1:end)./s1c.sampleRate; - end - name = [ 'corr(' s1.name ',' s2.name ')']; - evalstring=strcat('sxCorr=',class(s1),'(lags,data,name,''\Delta \tau'',''s'',dataLabels);'); - eval(evalstring); - end - function sxCov = xcov(s1,s2,varargin) - if(nargin<2) - s2=s1; - end - [s1c,s2c] = makeCompatible(s1,s2); - if(~isempty(varargin)) - [tempC tempLags] =xcov([s1c.data, s2c.data],varargin{1}); - else - [tempC tempLags] =xcov([s1c.data, s2c.data]); - end - index=[]; - for i=1:s1c.dimension - offset(i)=(i-1)*(s1c.dimension+s2c.dimension); - index = [index, (offset(i)+s1c.dimension+1):(offset(i)+s1c.dimension+s2c.dimension)]; - end - sum=0; - dataLabels = cell(1,length(index)); - for i=1:s1c.dimension - for j=1:s2c.dimension - sum = sum+1; - dataLabels{sum} = strcat('cov(',s1c.dataLabels{i},',',s2c.dataLabels{j}, ']'); - end - end - - M=length(s1c.data); - if(nargin<2) - data=tempC(M-1:end,index); - lags=tempLags(M-1:end)./s1c.sampleRate; - else - data=tempC(1:end,index); - lags=tempLags(1:end)./s1c.sampleRate; - end - name = [ 'cov(' s1.name ',' s2.name ')']; - evalstring=strcat('sxCov=',class(s1),'(lags,data,name,''\Delta \tau'',''s'',dataLabels);'); - eval(evalstring); - %sxCov=SignalObj(lags,data,name,'lags','n',dataLabels); - - - end - - - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %Utility Functions - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - function mergedSig = merge(sObj,varargin) - %mergedSig = merge(sObj,varargin) - %merges the data in any signals passed in with the data in sObj. - %if one of the input arguments is a double then it is assumed - %to be the value of holdVals to be used when making the signals - %compatible. See makeCompatible(s1,s2) - numToMerge=0; - holdVals=0; - for i=1:length(varargin) - if(isa(varargin{i},'SignalObj')) - numToMerge = numToMerge+1; - end - if(isa(varargin{i},'double')&&i==length(varargin)) %expect only one double at the end - holdVals = varargin{i}; - end - end - - if(numToMerge == 1) - - [s1c, s2c] = sObj.makeCompatible(varargin{1},holdVals); - data=[s1c.dataToMatrix, s2c.dataToMatrix]; - dataLabels = cell(s1c.dimension+s2c.dimension,1); - for i=1:s1c.dimension - dataLabels{i} = s1c.dataLabels{i}; - end - for i=1:s2c.dimension - dataLabels{s1c.dimension+i}=s2c.dataLabels{i}; - end - name = s1c.name;%, ',', s2c.name]; %name of the original is kept - - evalstring = strcat('mergedSig = ',class(sObj),'(s1c.time, data, name, s1c.xlabelval,s1c.xunits, s1c.yunits, dataLabels);'); - eval(evalstring); - else - mergedSig = sObj.merge(varargin{1},holdVals); - for i=2:numToMerge - mergedSig = mergedSig.merge(varargin{i},holdVals); - end - end - end - function sigOut=copySignal(sigIn) - %sigOut=copySignal(sigIn) - %sigOut is a copy of the original signal sigIn. - %This function is necessary because SignalObj's are handles and - %as such, setting s2=s1, and then changing s1, causes changes - %in s2 as well. To avoid this, make a copy of s1 and set it as - %s2. (eg. s2=s1.copySignal; ) - time=sigIn.time; - data=sigIn.data; - name=sigIn.name; - xlabelval=sigIn.xlabelval; - xunits=sigIn.xunits; - yunits=sigIn.yunits; - dataLabels=sigIn.dataLabels; - plotProps=sigIn.plotProps; - evalstring = strcat('sigOut=',class(sigIn),'(time, data,name, xlabelval, xunits, yunits,dataLabels,plotProps);'); - eval(evalstring); - %sigOut = SignalObj(time, data,name, xlabelval, xunits, yunits,dataLabels,plotProps); - sigOut.dataMask = sigIn.dataMask; - end - function sObjOut=resample(sObj, newSampleRate) - %sObjOut=resample(sObj, newSampleRate) - %sObjOut is a copy of sObj with the newSampleRate specified; - if(sObj.sampleRate ~=newSampleRate) - sObjOut = sObj.copySignal; - if(or(~isnan(sObjOut.sampleRate),size(sObjOut.data,1)>1)) - sObjOut.resampleMe(newSampleRate); - end - else - sObjOut = sObj.copySignal; - end - end - function resampleMe(sObj, newSampleRate) - %resampleMe(sObj, newSampleRate) - %Actually changes the sampleRate of the sObj signal. There is - %no output variable. Recall that SignalObj's are handles. - - if(sObj.sampleRate~=newSampleRate) - sObj.restoreToOriginal; %use default data for changing samplerate - %Change the sampling rate of this object - minTime=sObj.minTime; - maxTime=sObj.maxTime; - newTime=minTime:1/newSampleRate:maxTime; - newData=zeros(length(newTime),sObj.dimension); - if(size(sObj.data,1)>1) - for i=1:sObj.dimension - % newData(:,i)= interp1(sObj.time,sObj.data(:,i),newTime,'spline','extrap'); - newData(:,i)= interp1(sObj.time,sObj.data(:,i),newTime,'spline',0); - end - else - newData = sObj.data; - end - sObj.time=newTime'; - sObj.data=newData; - sObj.sampleRate=newSampleRate; - end - end - function restoreToOriginal(sObj,rMask) - %restoreToOriginal(sObj) - %return the signal to its original state when created. The - %dataMasks are the only thing preserved. - % - %restoreToOriginal(sObj,rMask) - %if rMask=1, then the dataMask is reset. - - if(nargin<2) - rMask = 0; %keep mask even when data reset - end - [time,data]=sObj.getOriginalData; - sObj.time=time; - sObj.data=data; - sObj.minTime=min(time); - sObj.maxTime=max(time); - sObj.sampleRate = 1/mean(diff(time)); - if(rMask==1) - sObj.resetMask; - end - end - function resetMask(sObj) - %resetMask(sObj) - %Resets the dataMask for the SignalObj so that all components - %of the object are visible. - sObj.dataMask = ones(1,sObj.dimension); - end - function ind = findIndFromDataMask(sObj) - %ind = findIndFromDataMask(sObj) - %returns the indices of the visible components of the data - ind = find(sObj.dataMask ==1); -% if(isempty(ind)) -% error('All data masked out of SignalObj'); -% end - end - function ind = findNearestTimeIndices(sObj,times) - ind = zeros(size(times)); - for i=1:length(ind) - ind(i) = sObj.findNearestTimeIndex(times(i)); - end - end - - function ind=findNearestTimeIndex(sObj, time) - %ind=findNearestTimeIndex(sObj, time) - %returns the nearest index to t=time; - if(timesObj.maxTime) - ind=length(sObj.time); - else - ind1=find(sObj.time>=time,1,'first'); - ind2=find(sObj.time<=time,1,'last'); - if(abs(sObj.time(ind1)-time)<=abs(sObj.time(ind2)-time)) - ind=ind1; - else - ind=ind2; - end -% if(time-sObj.minTime < sObj.maxTime-time) %Time is close to beginning -% ind=min([ind1, ind2]); -% else -% ind=max([ind1, ind2]); -% end - end - end - function sOut = shift(sObj, deltaT,updateLabels) - %sOut = shift(sObj, deltaT - %returns a SignalObj sOut shifted by deltaT. If deltaT is positive - %the SignalObj is moved deltaT time steps forward - %if deltaT is negative, the SignalObj is moved deltaT units - %backwards. - if(nargin<3) - updateLabels =0; - end - - %compute number of samples delayed - sOut=sObj.copySignal; - if(deltaT~=0) - newMinTime = sOut.minTime+deltaT; - newMaxTime = sOut.maxTime+deltaT; - newTime = sOut.time + deltaT; -% newTime=newMinTime:1/sOut.sampleRate:newMaxTime; - sOut.time = newTime; - sOut.minTime = newMinTime; - sOut.maxTime = newMaxTime; - if(updateLabels) - dataLabels = strcat(sObj.dataLabels,'(t-',num2str(deltaT),')'); - sOut.setName(strcat(sObj.name,'(t-',num2str(deltaT),')')); - sOut.setDataLabels(dataLabels); - end - - end - end - function shiftMe(sObj,deltaT,updateLabels) - %shiftMe(sObj,deltaT) - % same as shift(sObj,deltaT) except that no signal is return. - % The shift is done to sObj. - if(nargin<3) - updateLabels=0; - end - sTemp = sObj.shift(deltaT,updateLabels); - sObj.data=sTemp.data; - sObj.time=sTemp.time; - end - function alignTime(sObj, timeMarker,newTime) - if(sObj.minTime<=timeMarker && sObj.maxTime>=timeMarker) - deltaT=newTime-timeMarker; - sObj.shiftMe(deltaT); - end - end - function answer = plotPropsSet(sObj) - %answer = plotPropsSet(sObj) - %returns 1 if any of the plotting properties has been set. Else - %0. - answer =0; - for i=1:sObj.dimension - if(~strcmp(sObj.getPlotProps(i),'')) - answer=1; - break; - end - end - end - function answer = areDataLabelsEmpty(sObj) - %answer = areDataLabelsEmpty(sObj) - %returns 0 is dataLabels are empty and 1 otherwise - answer = 1; - for i=1:length(sObj.dataLabels); - if(~strcmp(sObj.dataLabels{i},'')) - answer = 0; - break; - end - end - end - function answer = isLabelPresent(sObj, label) - %answer = isLabelPresent(sObj, label) - %returns 1 if label is present in sObj, and 0 otherwise - if(isa(label,'char')) - if(strcmp(label,'all')||~isempty(sObj.getIndexFromLabel(label))) - answer=1; - else - answer=0; - end - else - error('Labels must be a char'); - end - end - function answer = isMaskSet(sObj) - %answer = isMaskSet(sObj) - %returns 0 is mask is not set, 1 if it is. - answer=any(sObj.dataMask==0); - end - function sArray = convertNamesToIndices(sObj, selectorArray) - %sArray = convertNamesToIndices(sObj, selectorArray) - %converts the names in selectorArray to a vector of indices. - - if(sObj.areDataLabelsEmpty) - sArray = 1:sObj.dimension; % Return all the data; - fprintf('tried to find data by labels but data doesnot have labels assigned'); - else - if(isa(selectorArray, 'char')) - if(strcmp(selectorArray,'all')) - sArray=1:sObj.dimension; - elseif(sObj.isLabelPresent(selectorArray)) - sArray=sObj.getIndexFromLabel(selectorArray); - else - error('Specified label does not match data label'); - end - - elseif(isa(selectorArray, 'double')) - sArray=selectorArray; - elseif(isa(selectorArray, 'cell')) - sArray = zeros(1, length(selectorArray)); - for i=1:length(sArray) - if(sObj.isLabelPresent(selectorArray{i})) - sArray(i) = sObj.getIndexFromLabel(selectorArray{i}); - end - end - else - error('selectorArray cells must contain text'); - end - end - end - function [sAligned,meanTime] = alignToMax(sObj) - - [indices,values] = sObj.findGlobalPeak('maxima'); - meanTime = mean(indices); - deltaT = -(indices-meanTime); % if index is greater than mean index then deltaT is negative so that we can align it witht the mean - - for i=1:sObj.dimension - if(i==1) - sAligned = sObj.getSubSignal(i).shift(deltaT(i)); - else - sAligned = sAligned.merge(sObj.getSubSignal(i).shift(deltaT(i))); - end - end - end - function [ind, val] = findGlobalPeak(sObj,type) - if(nargin<2) - type='maxima'; - end - if(strcmp(type,'maxima')) - [val,index] = max(sObj.data); - ind = sObj.time(index); - elseif(strcmp(type,'minima')) - [val,index] = min(sOBj.data); - ind = sObj.time(index); - end - end - function [indices, values] = findPeaks(sObj,type,minDistance) - %[indices, values] = findPeaks(sObj,type) - %type:'minima' or 'maxima' - %indices: indices at which the minima or maxima occur - %values: values at the minima or maxima - if(nargin<3) - minDistance = round(sObj.sampleRate*(sObj.maxTime-sObj.minTime)/10); - end - if(nargin<2) - type='maxima'; - end - values=cell(1,sObj.dimension); - indices=cell(1,sObj.dimension); - if(strcmp(type,'maxima')) - for i=1:sObj.dimension - [values{i},indices{i}] = findpeaks(sObj.data(:,i),'MINPEAKDISTANCE',minDistance); - end - elseif(strcmp(type,'minima')) - for i=1:sObj.dimension - [values{i},indices{i}] = findpeaks(sObj.data(:,i),'MINPEAKDISTANCE',minDistance); - end - end - end - - function [indices, values] = findMaxima(sObj) - %Same as findPeaks(sObj,'maxima'); - [indices,values]=sObj.findPeaks('maxima'); - end - function [indices, values] = findMinima(sObj) - %Same as findPeaks(sObj,'minima'); - [indices,values]= sObj.findPeaks('minima'); - end - function clearPlotProps(sObj,index) - %clearPlotProps(sObj,index) - %clear the plotProps{index} if index is specified. - %Otherwise all plotProps are cleared. - if(nargin<2) - index=1:sObj.dimension; - end - tempCell = cell(length(index),1); - for i=index - sObj.plotProps{i} = cell2str(tempCell{i}); - end - - end -% function v=get.vars(sObj) -% %returns a structure with fieldnames for each dataLabel -% %eg: if s has components x and y. v will have two fields: v.x -% %and v.y . -% %Accessing v.x returns a SignalObj containing just the data -% %corresponding to the label x. -% v=[]; -% if(~sObj.areDataLabelsEmpty) -% UniqueSigLabels = unique(sObj.dataLabels); -% -% for i=1:length(UniqueSigLabels) -% if(~isempty(UniqueSigLabels{i})) -% K=strfind(UniqueSigLabels{i},'\'); -% actString = UniqueSigLabels{i}(K+1:end); -% eval(strcat('v.(''',actString,''')=sObj.getSubSignal(''',UniqueSigLabels{i},''');')) -% end -% -% end -% %sObj.vars=v; -% else -% for i=1:sObj.dimension -% if(~isempty(sObj.dataLabels{i})) -% eval(strcat('v.(''',sObj.dataLabels{i},''')=sObj.getSubSignal(i);')) -% end -% end -% end -% end - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %Change of Representation Functions - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - function structure=dataToStructure(sObj,selectorArray) - %structure=dataToStructure(sObj) - %return unmasked data in sObj as a standard matlab structure - %with fields: - %structure.time - %structure.signals.values - % - %structure=dataToStructure(sObj,selectorArray) - %returns a structure containing only the components specified - %by the selectorArray - - if(nargin<2) - if(sObj.isMaskSet) - selectorArray=sObj.findIndFromDataMask; - else - selectorArray=1:sObj.dimension; - end - end - %Convert to a standard matlab structure - structure.time=sObj.time; - structure.signals.values=sObj.dataToMatrix(selectorArray); - structure.name = sObj.name; - structure.dimension = min(sObj.dimension,length(selectorArray)); - structure.signals.dimensions = min(sObj.dimension,length(selectorArray)); - structure.minTime = sObj.minTime; - structure.maxTime = sObj.maxTime; - structure.xlabelval = sObj.xlabelval; - structure.xunits = sObj.xunits; - structure.yunits = sObj.yunits; - if(isa(sObj.dataLabels,'char')) - structure.dataLabels = sObj.dataLabels; - elseif(isa(sObj.dataLabels,'cell')) - structure.dataLabels = sObj.dataLabels(selectorArray); - else - structure.dataLabels = []; - end - structure.dataMask = sObj.dataMask(selectorArray); - structure.sampleRate = sObj.sampleRate; - structure.plotProps = sObj.plotProps(selectorArray); - end - function dataMat=dataToMatrix(sObj,selectorArray) - %dataMat=dataToMatrix(sObj) - %returns the data for the visible components (i.e. those not - %masked out, in a nxm matrix where n is the determined by the - %sampleRate and the length of the current time vector, and m is - %the number of unmasked dimensions. - % - %dataMat=dataToMatrix(sObj,selectorArray) - %returns a matrix containing only the components specified - %by the selectorArray - if(nargin<2) - if(sObj.isMaskSet) - selectorArray=sObj.findIndFromDataMask; - else - selectorArray=1:sObj.dimension; - end - end - % Convert data to a standard matrix. - % The matrix is length(times)x dimension - dataMat=sObj.data(:,selectorArray); - end - function sOut = getSubSignal(sObj,identifier) - %sOut = getSubSignal(sObj,identifier) - %Returns a new signal that consists of only the data - %correspnding to the identifier. The identifier can be a string specifying the name - %of the component, a cell array of strings specifying various - %components, a vector specifying the indices of the components - %of interest. - if(isa(identifier,'cell')) - if(isa(identifier{1},'char')) - sOut = sObj.getSubSignalFromNames(identifier); - elseif(isa(identifier{1},'double')) - sOut = sObj.getSubSignalFromInd(identifier); - else - error('Cells must contain strings!'); - end - elseif(isa(identifier,'char')) - sOut = sObj.getSubSignalFromNames(identifier); - elseif(isa(identifier,'double')) - sOut = sObj.getSubSignalFromInd(identifier); - end - end - function sOut = normWindowedSignal(sObj,windowTimes,numPoints,lbound,ubound) - %Use the lower and upper bounds to specify the smallest and - %largest window sizes that are allowed. Windows smaller or - %larger than these will be ignored. - if(nargin<5) - if(nargin>4) - ubound = lbound; - else - ubound = []; - end - - end - if(nargin<4 || isempty(lbound)); - lbound=[]; - end - if(nargin<3 || isempty(numPoints)) - numPoints =100; - end - - if(sObj.dimension == 1) - data=[]; - for i=1:length(windowTimes)-1 - - minTime = windowTimes(i); - maxTime = windowTimes(i+1); - if(and(~isempty(lbound),~isempty(ubound))) - if(and(abs(maxTime-minTime)<=(ubound),abs(maxTime-minTime)>=(lbound))) - dim=size(data,2); - time = linspace(minTime,maxTime,numPoints); - actSig= sObj.getSigInTimeWindow(minTime, maxTime); -% data(:,dim+1) = interp1(actSig.time,actSig.data,time,'spline')'; - - data(:,dim+1) = interp1(actSig.time,actSig.data,time,'nearest',0)'; - end - else - time = linspace(minTime,maxTime,numPoints); - actSig= sObj.getSigInTimeWindow(minTime, maxTime); -% data(:,i) = interp1(actSig.time,actSig.data,time,'spline')'; - data(:,i) = interp1(actSig.time,actSig.data,time,'nearest',0)'; - end - end - actTime = (0:1:numPoints-1)./numPoints; %time -time(1); - name = sObj.name; - xlabelval = sObj.xlabelval; - xunits = '%'; - yunits = sObj.yunits; - dataLabels(1:size(data,2)) =sObj.dataLabels; - %plotProps = sObj.plotProps; -% if(i==1) - evalstring = strcat('sOut=',class(sObj),'(actTime, data,name, xlabelval, xunits, yunits,dataLabels);'); - eval(evalstring); -% sOut.setMinTime(0); -% else -% evalstring = strcat('sOut = sOut.merge(',class(sObj),'(actTime, data,name, xlabelval, xunits, yunits,dataLabels,plotProps));'); -% eval(evalstring); -% end - - end - end - - function sOut = windowedSignal(sObj,windowTimes) - if(sObj.dimension == 1) - for i=1:length(windowTimes)-1 - if(i==1) - sOut = sObj.getSigInTimeWindow(windowTimes(1), windowTimes(2)); - else - temp =sObj.getSigInTimeWindow(windowTimes(i), windowTimes(i+1)); - temp = temp.shift(-windowTimes(i)); - sOut=sOut.merge(temp); - end - end - - end - end - function wSignals = getSigInTimeWindow(sObj,wMin,wMax,holdVals) - %wSignal = getSigInTimeWindow(sObj) - %returns a copy of sObj from t0=sObj.minTime to tf=sObj.maxTime; - %wSignal = getSigInTimeWindow(sObj,wMin) - %returns a new signal starting at t0=wMin to tf=sObj.maxTime - % - %wSignal = getSigInTimeWindow(sObj,wMin,wMax) - %returns a new signal starting at t0=wMin to tf=wMax; - % - %wSignal = getSigInTimeWindow(sObj,wMin,wMax,holdVals) - %if holdVals =1 and wMin or wMax are outside the bounds of the - %current SignalObj time vector, then the endpoint values are - %held. Otherwise, this region is padded with zeros; - if(nargin<4) - holdVals =0; - end - if(nargin<3) - wMax=sObj.maxTime; - end - if(nargin<2) - wMin=sObj.minTime; - end - - if(length(wMin)~=length(wMax)) - error('Window minTimes must contain the same number of elements as window maxTimes'); - end - if(length(wMin)==1 && sObj.minTime==wMin && sObj.maxTime==wMax) - wSignals = sObj.copySignal; - else - for i=1:length(wMin) - wSignal = sObj.copySignal; - if(wMin(i)wSignal.maxTime) - %if wMax is too big, pad with zeros at end and set as new - %end - wSignal.setMaxTime(wMax(i),holdVals); - end - - startIndex= wSignal.findNearestTimeIndex(wMin(i)); - endIndex = wSignal.findNearestTimeIndex(wMax(i)); - wSignal.time=wSignal.time(startIndex:endIndex); - wSignal.data=wSignal.data(startIndex:endIndex,:); - if(length(wMin)>1) - for j=1:wSignal.dimension - dataLabels{j} = strcat(wSignal.dataLabels{j},'_{',num2str(i),'}'); - end - else - if(wSignal.dimension==1) - dataLabels = wSignal.dataLabels; - else - for j=1:wSignal.dimension - dataLabels{j} = wSignal.dataLabels{j}; - end - end - end - wSignal.setDataLabels(dataLabels); - wSignal.setMinTime; - wSignal.setMaxTime; - if(i==1) - wSignals = wSignal; - else - wSignals = wSignals.merge(wSignal); - end - end - end - end - - function [s sigIndex]=getSubSignalsWithinNStd(sObj,nStd) - mSig=mean(sObj.data,2); - stdSig = std(sObj.data,0,2); - minVal = mSig-nStd*stdSig; - maxVal = mSig+nStd*stdSig; - indMin= find(sum(sObj.data-minVal*ones(1,sObj.dimension)<0)==0); - indMax=find(sum(sObj.data-maxVal*ones(1,sObj.dimension)>0)==0); - sigIndex = intersect(indMin,indMax); - s=sObj.getSubSignal(sigIndex); - - end - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %Plotting Functions - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - - function h=plot(sObj,selectorArray,plotPropsIn,handle) - - % h=plot(sObj,selectorArray,plotProps,handle) - % plotProps: is a cell array with strings in each a entry. - % The strings must evaluate to parameters that can be - % passed to the standard matlab plot function. - % example: To plot a three dimensional signals with each line - % with specific properties (not the use of double quotes on the - % color entries so that the actual arguments have a quotes around - % them. - % - % >> plotProps = {{' ''-.g'', ''LineWidth'' ,2'},... - % {' ''k'', ''LineWidth'' ,2'},... - % {' ''-.b'' '}}; - % - % selectorArrray: is either an numeric array indexing the - % elements within the SignalObj data or a cell array - % of characters that refers to the data elements - % by their labels. - % handle: is figure handle to tell the signal where to plot - % itself. - % % 8-25-09 : Legend wont plot is SignalObj dimension >10; - - - - if(nargin<4) - handle=gca; - end - if((nargin<3) || isempty(plotPropsIn)) - %plotPropsIn=[]; - plotPropsIn=sObj.plotProps; - end - if((nargin<2) || isempty(selectorArray)) - if(sObj.isMaskSet) - selectorArray=sObj.findIndFromDataMask; - if(isempty(selectorArray)) - h=[]; - return; - end - else - selectorArray=1:sObj.dimension; - end - end - - - - if(isa(selectorArray,'cell')) - sArray = sObj.convertNamesToIndices(selectorArray); - elseif(isa(selectorArray,'char')) - sArray = sObj.convertNamesToIndices(selectorArray); - elseif(isa(selectorArray,'double')) - sArray = selectorArray; - else - error('selectorArray must contain either dataLabels or their indices'); - end - - - % if plot params are passed in then assign them to the SignalObj - if(length(plotPropsIn)==length(sArray)) - for i=1:length(sArray) - sObj.setPlotProps(plotPropsIn{i},sArray(i)); - end - elseif(length(plotPropsIn)<=length(sArray) && length(plotPropsIn)==1) - for i=1:length(sArray) - sObj.setPlotProps(plotPropsIn,sArray(i)); - end - end - - - - - %If the dimensions of the data are larger than one can specify - %the plot style for each dimension by placing their values in - %an cell array. -% h=gcf;figure(h); - if((nargin>=3) && ~isempty(plotPropsIn)) %is we got called with parameter use those - %sObj.setPlotProps(plotProps); %Only accepts entire cell of plotting properties as input - %if(length(plotCell)>=length(sArray)) %if we specified plot parameters for each dimension - for i=sArray - %plotStr=cell2str(plotCell{:,find(sArray==i)}); - plotStr=cell2str(sObj.getPlotProps(i)); - if(~strcmp(plotStr,'') && ~isempty(plotStr)) - evalstring = strcat('h(',num2str(find(sArray==i)),')=plot(handle,sObj.time,sObj.data(:,',num2str(i),'),', plotStr,');'); - eval(evalstring); hold on; - else -% set(gca,handle); - axes(handle); - evalstring = strcat('h(',num2str(find(sArray==i)),')=plot(sObj.time,sObj.data(:,',num2str(i),'));'); -% evalstring = strcat('h(',num2str(find(sArray==i)),')=plot(handle,sObj.time,sObj.data(:,',num2str(i),'));'); - eval(evalstring); hold on; - end - %evalstring - %eval(evalstring); hold on; - end - elseif(sObj.plotPropsSet) %% We use the values that have been set previously - %plotCell = cell2str(sObj.getPlotProps(i)); - %fprintf('varargin is not empty') - for i=sArray - plotStr =cell2str(sObj.getPlotProps(i)); - %plotStr=cell2str(plotCell{:,1}); - if(~strcmp(plotStr,'') && ~isempty(plotStr)) - evalstring = strcat('h(',num2str(i),')=plot(handle,sObj.time,sObj.data(:,',num2str(i),'),', plotStr,');'); - else - evalstring = strcat('h(',num2str(i),')=plot(handle,sObj.time,sObj.data(:,',num2str(i),'));'); - end - %evalstring - if(~isempty(sObj.data(:,i))) - eval(evalstring); hold on; - end - end - else %We didnt get any plotting properties. Use matlab default - %plotCell{1} = ''''; - %fprintf('varargin is empty') - set(gcf,'CurrentAxes',handle); - h=plot(handle,sObj.time,sObj.data(:,sArray)); - end - - sObj.setupPlots(handle,sArray); - end - function setupPlots(sObj,handle,sArray) - %setupPlots(sObj,sArray) - %Sets the labels for the x-axis, y-axis, and legend. - %sArray is an array on indexes corresponding to which labels - %will appear in the legend. -% set(gcf,'CurrentAxes',handle); - warning off; - if(~strcmp(sObj.xunits,'')) - xunitsStr=strcat('\; [',sObj.xunits,']'); %\; is a large space in latex - else - xunitsStr=''; - end - - if(~strcmp(sObj.yunits,'')) - yunitsStr=strcat('\; [',sObj.yunits,']'); - else - yunitsStr=''; - end - - if(strcmp(sObj.xlabelval,'')) - xlabel(strcat('$$',xunitsStr,'$$'),'Interpreter','latex'); - - else -% strcat(['$$' sObj.xlabelval xunitsStr '$$']) - xlabel(strcat('$$',[sObj.xlabelval xunitsStr],'$$'),'Interpreter','latex'); - - end - if(~strcmp(sObj.name,'')) - if(~strcmp(yunitsStr,'')) - %strcat('$$',sObj.name,yunitsStr,'$$') - ylabel(strcat('$$',[sObj.name yunitsStr],'$$'),'Interpreter','latex'); - - else - - ylabel(strcat('$$',sObj.name,'$$'),'Interpreter','latex'); - %ylabel(sObj.name,'Interpreter','none'); - - end - end - - if(~sObj.areDataLabelsEmpty) %%&& sObj.dimension<10) -% labelArray= cell(1,length(sArray)); - labelArray =sObj.dataLabels(sArray); -% for i=1:length(sArray) -% labelArray{i} = strcat('$$',sObj.dataLabels{sArray(i)},'$$'); -% end - legend(handle,labelArray);%,'Interpreter','latex'); - end - axis tight; - warning on; - end - - function h=plotVariability(sObj,selectorArray) - %h=plotVariability(sObj) - %Calls plotAllVariability(sObj) for each set of unique labels - %in the SignalObj. For example, if a SignalObj s has for - %components (2 with label 'x', and 2 with label 'y'), two - %figures will be generated, one for the variability of the x - %component and one for the variability of the y component. If - %all components have the same label, then only one plot will be - %generated. Plot handles are returned in h. - % - %h=plotVariability(sObj,selectorArray) - %if selectorArray is specified, then plotAllVariability is - %called once on a SignalObj that only has the components - %specified by the selectorArray. - if(nargin<2) - if(~sObj.areDataLabelsEmpty) - uLabels =unique(sObj.dataLabels); - for i=1:length(uLabels) - selectorArray{i} = sObj.getIndicesFromLabels(uLabels{i}); - end - else - selectorArray = 1:sObj.dimension; - end - end - if(isa(selectorArray,'cell')) %More than component has the same - [numSubSignals]=length(selectorArray); - for i=1:numSubSignals - %figure; - h(i)=sObj.getSubSignal(selectorArray{i}).plotAllVariability(getAvailableColor(i)); - end - elseif(isa(selectorArray,'double')) - h=sObj.getSubSignal(selectorArray).plotAllVariability; - end - end - - function h=plotAllVariability(sObj,faceColor,linewidth,ciUpper,ciLower) - %h=plotAllVariability(sObj) - % Computes the mean across all components in the signal and - % plots +/- 1 standard deviation from the mean. All other - % parameters are optional. - % - % faceColor: defaults to red if not specified. - % linewidth: defaults to 3 if not specified. - % - % ciUpper: if a single number then specifies the multiple of - % standard deviations to be used. i.e. ciUpper=1 - % results in default. If ciUpper is an double array of - % the same length as the signal, then the upper bound - % of the confidence interval at time t will be - % ciUpper+mean(sObj). If ciUpper is a SignalObj, then - % the behavior is the same as if a double array were - % specified. If only ciUpper is specified, ciLower is - % assigned the same maginitude - % ciLower: if a single number then specifies the multiple of - % standard deviations to be used. i.e. ciLower=1 - % results in default. If ciLower is an double array of - % the same length as the signal, then the lower bound - % of the confidence interval at time t will be - % mean(sObj)-ciLower. If ciLower is a SignalObj, then - % the behavior is the same as if a double array were - % specified. - if(nargin<4 || isempty(ciUpper)) - ciUpper =1.96; - end - if(nargin<=4) - ciLower=ciUpper; - end - if(nargin<2 || isempty(faceColor)) - faceColor=getAvailableColor(1); - end - if(nargin<3 || isempty(linewidth)) - linewidth=3; - end -% sObj=s; - meanSig = mean(sObj,2); - stdSig = std(sObj,[],2); - - if(length(ciUpper)==1) - ciTop=meanSig+ciUpper.*stdSig; - elseif(length(ciUpper)==length(sObj.time)) - ciTop=meanSig+ciUpper; - else - error('Upper confidence interval must be either length 1 or same length as the time vector'); - end - - if(length(ciLower)==1) - ciBottom=meanSig-ciLower.*stdSig; - elseif(length(ciUpper)==length(sObj.time)) - ciBottom=meanSig-ciLower; - else - error('Lower confidence interval must be either length 1 or same length as the time vector'); - end - - ci2=ciTop.dataToMatrix; - ci1=ciBottom.dataToMatrix; - - - - p=patch([reshape(sObj.time,[1 length(sObj.time)]) reshape(fliplr(sObj.time'),[1 length(sObj.time)])],... - [reshape(ci1',[1 length(sObj.time)]) reshape(fliplr(ci2'),[1,length(sObj.time)])],strcat('',faceColor,'')); - set(p,'facecolor',faceColor,'edgecolor','none'); - alpha(.5);hold on; - h=plot(sObj.time,meanSig.dataToMatrix,'k-','linewidth',linewidth); - - sArray=1; %only want the first label to plot; - meanSig.setupPlots(sArray); -% legend([h,p],'mean','variance'); - - end - - - - - end % public methods - methods (Access = private) - function index = getIndexFromLabel(sObj,label) - %index = getIndexFromLabel(sObj,label) - %Given a label, returns the index to the SignalObj component - %with the specified label - index=[]; - for i=1:length(sObj.dataLabels) - if(strcmp(label, sObj.dataLabels{i})) - index = [index i]; - end - end - end - - - function setDataMask(sObj, dataMask) - % setDataMask(sObj, dataMask) - % dataMask is a vector of ones and zeros of length sObj.dimension - % components marked by ones will be visible.i - %DataMasks affect how the SignalObj is visualized and converted to - %other representations. It doesnt change the dimensions of the - %object, nor does it delete data. - if(length(dataMask)==sObj.dimension) - sObj.dataMask = dataMask; - end - - end - function setMaskByInd(sObj,index) - % setMaskByInd(sObj,index) - % if length(index)== sObj.dimension then the mask is set using - % the values in index. - % if length(index)< sObj.dimension only the component specified - % by the index will be visible. All others will be hidden. - if(length(index)==sObj.dimension) - sObj.setDataMask(index); - else - mask=zeros(1,sObj.dimension); - mask(index)=1; - sObj.setDataMask(mask); - end - end - function setMaskByLabels(sObj,labels) - %setMaskByLabels(sObj,labels) - %labels is a cell array with the labels of the components that - %are to remain visible. The indices for these labels are found - %and the mask set using setDataMask - ind=sObj.getIndicesFromLabels(labels); - mask=zeros(1,sObj.dimension); - mask(ind)=1; - sObj.setDataMask(mask); - end - - function sOut = getSubSignalFromInd(sObj, selectorArray) - if(nargin<2) - if(sObj.isDataMaskSet) - selectorArray=sObj.findIndFromDataMask; - else - selectorArray=1:sObj.dimension; - end - end - s3 = sObj.copySignal; - time = s3.time; - if(isa(selectorArray,'cell')) - data=[]; - for i=1:length(selectorArray) - offset=0; - data = [data s3.data(:,selectorArray{i})]; - for j=1:length(selectorArray{i}) - dataLabels{offset + j} = s3.dataLabels{selectorArray{i}(j)}; - if(~isempty(s3.plotProps)) - plotProps{offset+ j} = s3.plotProps{selectorArray{i}(j)}; - end - end - offset = offset + length(selectorArray{i}); - end - else - data = s3.data(:,selectorArray); - dataLabels = cell(1,length(selectorArray)); - plotProps = []; - for i=1:length(selectorArray) - dataLabels{i}= s3.dataLabels{selectorArray(i)}; - if(~isempty(s3.plotProps)) - plotProps{i} = s3.plotProps{selectorArray(i)}; - end - end - end - - - - - name = s3.name; - xlabelval = s3.xlabelval; xunits=s3.xunits; yunits = s3.yunits; - - %sOut=SignalObj(time, data, name, xlabelval, xunits, yunits, dataLabels, plotProps); - evalstring = strcat('sOut=',class(sObj),'(time, data,name, xlabelval, xunits, yunits,dataLabels,plotProps);'); - eval(evalstring); - end - function sOut = getSubSignalFromNames(sObj,labels) - ind = sObj.getIndicesFromLabels(labels); - if(isa(ind,'cell')) - if(length(ind)>1) - for i=1:length(ind) - s{i} = getSubSignalFromInd(ind{i}); - end - sOut = s{1}.merge(s{2:end}); - else - sOut = sObj.getSubSignalFromInd(ind{1}); - end - elseif(isa(ind,'double')) - sOut = sObj.getSubSignalFromInd(ind); - end - end - end %private methods - methods (Static) - function sObj =signalFromStruct(structure) - fNames = {'time','signals','name','xlabelval','xunits','yunits','dataLabels','plotProps'}; - structField = fields(structure); - for i=1:length(fNames) - if(~any(strcmp(structField,fNames{i}))) - error(['Field ' fNames{i} 'not present is structure! Needed to make a signal from a structure']); - end - end - sObj=SignalObj(structure.time, structure.signals.values, structure.name, structure.xlabelval, structure.xunits, structure.yunits, structure.dataLabels, structure.plotProps); - sObj.setMask(structure.dataMask); - end - function simpleStructure = convertSigStructureToStructure(sigStructure) - if(isa(sigStructure,'struct')) - fNames = fields(sigStructure); - for i=1:length(fNames) - if(isa(sigStructure.(fNames{i}),'SignalObj')) - simpleStructure.(fNames{i}) = sigStructure.(fNames{i}).dataToStructure; - end - end - end - end - function sigStructure = convertSimpleStructureToSigStructure(simpleStructure) - if(isa(simpleStructure,'struct')) - fNames = fields(simpleStructure); - for i=1:length(fNames) - if(isa(simpleStructure.(fNames{i}),'struct')) - sigStructure.(fNames{i}) = SignalObj.signalFromStruct(simpleStructure.(fNames{i})); - end - end - end - end - - - - end -end%classdef - -% Helper function -function stringout=cell2str(input) - if(isempty(input)) - stringout = ''; - else - if(isa(input,'char')) - stringout=input; - elseif(isa(input,'cell')) - stringout=cell2str(input{1}); - end - end -end -function color=getAvailableColor(index) - availableColors = {'g','b','r','y','c','m','k'}; - color=availableColors{mod(index,length(availableColors))+1}; -end - - diff --git a/Trial.m b/Trial.m deleted file mode 100644 index 2dca6874..00000000 --- a/Trial.m +++ /dev/null @@ -1,1061 +0,0 @@ -classdef Trial methods -% Trial Examples -% -% see also CovColl, -% Covariate, -% SignalObj, -% nspikeTrain -% -% Reference page in Help browser -% doc Trial - -% -% nSTAT v1 Copyright (C) 2012 Masschusetts Institute of Technology -% Cajigas, I, Malik, WQ, Brown, EN -% This program is free software; you can redistribute it and/or -% modify it under the terms of the GNU General Public License as published -% by the Free Software Foundation; either version 2 of the License, or -% (at your option) any later version. -% -% This program is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -% See the GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with this program; if not, write to the Free Software Foundation, -% Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - properties - % A trial consists of - nspikeColl; % a collection of neural spikes - covarColl; % a collection covariates - ensCovHist; % the history structure used to create the ensCovColl - ev; % events - history ; % current history settings for this trial - sampleRate; % sampleRate for all the covariates and nstColl - minTime; % minTime of all data or minTime of interest - maxTime; % maxTime of all data or maxTime of interest - covMask; % mask indicating visible covariates - ensCovMask; % mask indicating which neurons to consider for neighbor effcts; - neuronMask; % mask indicating visible neurons - trainingWindow % start and endtimes for training data - validationWindow % start and endtime for validation data - - end - properties (Hidden) - ensCovColl; % a covariate collection of neighboring neuron spiking activity - end - - - methods - function tObj=Trial(nspikeColl, covarColl, event, hist,ensCovHist,ensCovMask) - % tObj=Trial(nspikeColl, covarColl, event, hist,ensCovHist) - % nspikeColl: is an nstColl object - % containing all of the relevant spike trains for this experimental trial. - % covarColl: is a CovColl - % object containing all of the covariates associated with the trial - % event: Events object. - % hist: History - % object for any given spike train - % ensCovHist:History - % object that specifies how much history to include for the ensemble effect. - if(nargin<6) - nSpikes = nspikeColl.numSpikeTrains; - ensCovMask = ones(nSpikes,nSpikes)-eye(nSpikes,nSpikes); - end - if(nargin<5) - ensCovHist = []; - end - if(nargin<4) - hist = []; - end - if(nargin<3) - event=[]; - end - - if(isa(nspikeColl,'nstColl')) - tObj.nspikeColl = nspikeColl; - else - error('nstColl is a required argument'); - end - - if(isa(covarColl,'CovColl')) - tObj.covarColl = covarColl; - else - error('CovColl is a required argument'); - end - - tObj.setTrialEvents(event); - - - - if(isa(hist,'History') || isa(hist,'double')) - tObj.setHistory(hist); - else - tObj.history = []; - end - - if(isa(ensCovHist,'History')|| isa(ensCovHist,'double')) - tObj.setEnsCovHist(ensCovHist); - else - tObj.ensCovHist=[]; - end - - tObj.covMask = covarColl.covMask; - tObj.neuronMask = nspikeColl.neuronMask; - tObj.ensCovMask = ensCovMask; - if(~tObj.isSampleRateConsistent) - tObj.makeConsistentSampleRate; - else - tObj.sampleRate = tObj.covarColl.sampleRate; - end - - tObj.makeConsistentTime; - tObj.setTrialPartition([]); %default to all training data - tObj.setTrialTimesFor('training'); -% tObj.setBatchMode('off'); % Turn batchMode off by default - end - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %Set functions - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - function setTrialEvents(tObj,event) - if(isa(event,'Events')) - tObj.ev = event; - else - tObj.ev = []; - end - end -% -% function setBatchMode(tObj,mode) -% if(isa(mode,'char')) -% if(strcmp(mode,'on')) -% tObj.batchMode = 'on'; -% elseif(strcmp(mode,'off')); -% tObj.batchMode ='off'; -% end -% elseif(isa(mode,'double')) -% if(mode==1) -% tObj.batchMode='on'; -% elseif(mode==0) -% tObj.batchMode='off'; -% end -% end -% -% end -% - function setTrialPartition(tObj,partitionTimes) - %partitionTimes is an array containing three or four elements - % 4 elements :[startTraining stopTraining startValidation endValidation] - % 3 elements [startTraining stopTraining/startValidation endValidation] - % the middle value is used for end of training period and start - % of validation period - if(nargin<2 || isempty(partitionTimes)) - partitionTimes = tObj.getTrialPartition; - end - - if(~isempty(partitionTimes)) - %partitionTimes = round(partitionTimes*tObj.sampleRate/10)./tObj.sampleRate*10; %make sure that the partition time are achievable at the current sampleRate; - % if sampleRate is 100 then we multiply partionTimes by 10 - % and so we keep only the first decimal place. - if(length(partitionTimes)==4) - trainingWindow = [partitionTimes(1) partitionTimes(2)]; - validationWindow = [partitionTimes(3) partitionTimes(4)]; - elseif(length(partitionTimes)==3) - trainingWindow = [partitionTimes(1) partitionTimes(2)]; - validationWindow = [partitionTimes(2) partitionTimes(3)]; - else - error('partitionTimes must be length 3 or 4'); - end - - tObj.trainingWindow = trainingWindow; - tObj.validationWindow = validationWindow; - tObj.setMinTime(trainingWindow(1)); - tObj.setMaxTime(trainingWindow(2)); %default to ready for training - end - end - function p=getTrialPartition(tObj) - p1=tObj.trainingWindow; - p2=tObj.validationWindow; - p=[p1 p2]; - if(isempty(p)) - p1 = [tObj.minTime, tObj.maxTime]; - p2 = [tObj.maxTime, tObj.maxTime]; - p = [p1, p2]; - end - end - - - function setTrialTimesFor(tObj,partitionName) - if(nargin<2) - partitionName = 'training'; - end - - p = tObj.getTrialPartition; - - if(strcmp(partitionName,'training')) - timeWindow = p(1:2); - elseif(strcmp(partitionName,'validation')) - timeWindow = p(3:4); - else - error('partitionName must be either training or validation'); - end - - if(~isempty(timeWindow)) - %currSamplingRate = tObj.sampleRate; - %tObj.restoreToOriginal; - %tObj.resample(currSamplingRate); - tObj.setMinTime(timeWindow(1)); - tObj.setMaxTime(timeWindow(2)); - % tObj.makeConsistentTime; - % tObj.restoreToOriginal; - % tObj.resample(currSamplingRate); - end - - end - function setMinTime(tObj,minTime) - % setMinTime(tObj,minTime) - % sets the minTime of interest of the trial to minTime - - if(nargin<2) - minTime = tObj.findMinTime; - end; - tObj.nspikeColl.setMinTime(minTime); - tObj.covarColl.setMinTime(minTime); - if(~isempty(tObj.ensCovColl)) - tObj.ensCovColl.setMinTime(minTime); - end - %tObj.covarColl.covArray{1}.standardRep - tObj.minTime = minTime; - end - function setMaxTime(tObj,maxTime) - % setMaxTime(tObj,maxTime) - % sets the maxTime of interest of the trial to maxTime - if(nargin<2) - maxTime=tObj.findMaxTime; - end - tObj.nspikeColl.setMaxTime(maxTime); - tObj.covarColl.setMaxTime(maxTime); - if(~isempty(tObj.ensCovColl)) - tObj.ensCovColl.setMaxTime(maxTime); - end - tObj.maxTime = maxTime; - end - - function updateTimePartitions(tObj) - if((~isempty(tObj.minTime))&& (~isempty(tObj.maxTime))) %avoid calling before maxTime and minTime are set - p = tObj.getTrialPartition; - if(~isempty(p)) - training = p(1:2); - validation=p(3:end); - newTrainMin = max(tObj.minTime,training(1)); - newTrainMax = min(tObj.maxTime,training(2)); - newValMin = max(tObj.minTime,validation(1)); - newValMax = min(tObj.maxTime,validation(2)); - - tObj.setTrialPartition([newTrainMin newTrainMax newValMin newValMax]); - end - end - - end - - function setSampleRate(tObj,sampleRate) - % setSampleRate(tObj,sampleRate) - % sets the sampleRate of the trial and all of its components to - % sampleRate - tObj.sampleRate=sampleRate; - tObj.nspikeColl.resample(sampleRate); - tObj.covarColl.resample(sampleRate); - tObj.resampleEnsColl; - end - function setEnsCovMask(tObj,mask) - % setEnsCovMask(tObj, mask) - % sets the mask of neighboring neurons to be considered when - % ensCovHist is set - if(nargin<2 || isempty(mask)) - nSpikes = tObj.nspikeColl.numSpikeTrains; - mask = ones(nSpikes,nSpikes)-eye(nSpikes,nSpikes); - end - tObj.ensCovMask=mask; % needs to be a nSpikeTrain x nSpikeTrain matrix with zeroes along diagonal if all neurons are possible neighbors - end - function setCovMask(tObj,mask) - % setCovMask(tObj,mask) - % sets the covariate mask of the trial and of the covColl to - % mask - if(isa(mask,'char')) - if(strcmp(mask,'all')); - tObj.covarColl.resetMask; - end - else - tObj.covarColl.setMask(mask); - end - tObj.covMask = tObj.covarColl.covMask; - - end - function setNeuronMask(tObj,mask) - % setNeuronMask(tObj,mask) - % sets the neuron mask of the trial and of the nstColl to mask - tObj.nspikeColl.setMask(mask); - tObj.neuronMask = tObj.nspikeColl.neuronMask; - end - function setNeighbors(tObj,varargin) - tObj.nspikeColl.setNeighbors(varargin{:}); - end - function setHistory(tObj,hist) - % setHistory(tObj,hist) - % sets the history object of the trial to hist. - % hist can be of class History or a vector of doubles - % specifying the windowTimes for the History object - if(isempty(hist)) - tObj.history = []; - else - if(isa(hist,'History')) - tObj.history = hist; - elseif(isa(hist,'cell')) - if(isa(hist{1},'History')) - tObj.history = hist; - end - elseif(isa(hist,'double')) %then we got windowTimes - [l,w]=size(hist); - if(min(l,w)>1) - error('Only one of the dimension of the windowTimes can be greater than 1.'); - else - if(length(hist)>1) - tObj.history = History(hist); - else - error('At least two times points must be specified to determine a window'); - end - - end - else - error('Can only set trial history to be an instantiation of the History object class or by using windowTimes'); - end - end - end - function setEnsCovHist(tObj, hist) - % ensCovHist(tObj,hist) - % sets the ensCovHist of the trial to hist. - % hist can be of class History or a vector of doubles - % specifying the windowTimes for the History object - if(nargin<2) - hist =[]; - end - - if(isempty(hist)) - tObj.ensCovHist = []; - tObj.ensCovColl = []; - else - if(isa(hist,'History')) - tObj.ensCovHist = hist; - - elseif(isa(hist,'double')) %then we got windowTimes - [l,w]=size(hist); - if(min(l,w)>1) - error('Only one of the dimension of the windowTimes can be greater than 1.'); - else - if(length(hist)>1) - tObj.ensCovHist = History(hist); - - else - error('At least two times points must be specified to determine a window'); - end - - end - else - error('Can only set trial ensCovHist to be an instantiation of the History object class or by using windowTimes'); - end - % getEnsembleNeuronCovariates(nstCollObj,neuronNum,neighbor - % Index,windowTimes) - tObj.ensCovColl=tObj.getEnsembleNeuronCovariates(1,[],tObj.ensCovHist); - - % initialize ensCovColl to first neuron and its default - % neighbors - end - end - function answer=isNeuronMaskSet(tObj) - % answer=isNeuronMaskSet(tObj) - % 1 if neuronMask of nstColl is set; - % 0 otherwise - answer=tObj.nspikeColl.isNeuronMaskSet; - end - function answer=isCovMaskSet(tObj) - % answer=isCovMaskSet(tObj) - % 1 if the covMask of the covColl is set - % 0 otherwise - answer = tObj.covarColl.isCovMaskSet; - end - function answer=isMaskSet(tObj) - % answer=isMaskSet(tObj) - % 1 if either neuronMask or covMask is set for the trial - % 0 if neither is set - answer=tObj.isNeuronMaskSet||tObj.isCovMaskSet; - end - function answer=isHistSet(tObj) - % answer=isHistSet(tObj) - % 1 if the history object of the trial is non-empty - % 0 if it is empty - if(~isempty(tObj.history)) - if(isa(tObj.history,'History')) - answer =1; - elseif(isa(tObj.history,'cell')) - if(isa(tObj.history{1},'History')) - answer=1; - else - answer=0; - end - end - else - answer =0; - end - - - end - function answer=isEnsCovHistSet(tObj) - % answer=isHistSet(tObj) - % 1 if the history object of the trial is non-empty - % 0 if it is empty - answer=(~isempty(tObj.ensCovHist))&& (isa(tObj.ensCovHist,'History')); - end - - function addCov(tObj,cov) - tObj.covarColl.addToColl(cov); - tObj.covMask = tObj.covarColl.covMask; - if(~tObj.isSampleRateConsistent) - tObj.makeConsistentSampleRate; - end - tObj.makeConsistentTime; - end - function removeCov(tObj,identifier) - tObj.covarColl.removeCovariate(identifier); - tObj.covMask = tObj.covarColl.covMask; - if(~tObj.isSampleRateConsistent) - tObj.makeConsistentSampleRate; - end - tObj.makeConsistentTime; - end - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %Get functions - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - function y=getSpikeVector(tObj,varargin) - % y=getSpikeVector(tObj,varargin) - % returns a matrix of spikes by calling the dataToMatrix method - % of nstColl with any arguments passed in - % see also nstColl.dataToMatrix, - y=tObj.nspikeColl.dataToMatrix(varargin{:}); - end - function X=getDesignMatrix(tObj,neuronNum,varargin) - % X=getDesignMatrix(tObj,varargin) - % returns a matrix X by calling covColl.getDataMatrix with repType='zero-mean' - % along with any parameters passed in. - % - % dataSelector must be in the following format - % dataSelector{1} = {'Position','x','y'}; - % dataSelector{2} = {'Force','fx','fy','fz'}; - % see also covColl.dataToMatrix - - if(nargin<2) - error('Must specify neuronNumber to getDesignMatrix!'); - end - - %repType='zero-mean'; - repType='standard'; - X=tObj.covarColl.dataToMatrix(repType,varargin{:}); - - if(tObj.isHistSet) - H=tObj.getHistMatrices(neuronNum); - if(isempty(X)) - X=H; - else - X=[X,H]; - end - end - if(tObj.isEnsCovHistSet) - includedNeurons = find(tObj.ensCovMask(:,neuronNum)==1); - E = tObj.getEnsCovMatrix(neuronNum,includedNeurons); - if(isempty(X)) - X=E; - else - X=[X,E]; - end - end - end - function ensCovMatOut = getEnsCovMatrix(tObj,neuronNum,includedNeurons,varargin) - if(nargin<3) - includedNeurons = find(tObj.ensCovMask(:,neuronNum)==1); - end - if(nargin<2) - error('Must specify neuronNumber to get the right neighbors!'); - end - if(tObj.isEnsCovHistSet && ~isempty(neuronNum)) - if(neuronNum>0 && neuronNum<=tObj.nspikeColl.numSpikeTrains) - ensCovCollTemp = tObj.ensCovColl; - neighbors = tObj.getNeuronNeighbors(neuronNum); - neighbors = intersect(neighbors, includedNeurons); - ensCovCollTemp.maskAwayAllExcept(neighbors); - repType='standard'; - ensCovMatOut=ensCovCollTemp.dataToMatrix(repType,varargin{:}); - end - else - ensCovMatOut=[]; %dont return matrix if neuron number not specified. - % display('isEnsCovEnabled=0 - empty matrix returnecd'); - end - end - function histCovColl = getHistForNeurons(tObj,neuronIndex) - % histCovColl = getHistForNeurons(tObj,neuronIndex) - % returns a CovColl with number of Covariates equal to the - % length of neuronIndex. - % CovColl.getCov(i) corresponds to the History for the - % nspikeTrain corresponding to neuronIndex(i) - % - if(tObj.isHistSet) - nst=tObj.nspikeColl.getNST(neuronIndex); - if(length(neuronIndex)>=1) - if(isa(tObj.history,'History')) - histCovColl = tObj.history.computeHistory(nst); - elseif(isa(tObj.history,'cell')) - for i=1:length(tObj.history) - if(i==1) - histCovColl = tObj.history{1}.computeHistory(nst,i); -% histCovColl.getCov - else - tempHistCovColl = tObj.history{i}.computeHistory(nst,i); - histCovColl.addToColl(tempHistCovColl); - end - end - end - - end - else - histCovColl = []; %returns an empty array to indicate no History - display('History has not been specified. Empty array returned'); - display('Set Trial history and retry'); - end - if(~isempty(histCovColl)) - if(isa(nst,'cell')) - histCovColl.setSampleRate(nst{1}.sampleRate); - else - histCovColl.setSampleRate(nst.sampleRate); - end - end - - end - function matrices = getHistMatrices(tObj,neuronIndex) - % matrices = getHistMatrices(tObj,neuronIndex) - % return a matrix representation of the History Covariates - % corresponding the History object specified for the trial and - % the data corresponding to neuronIndex - if(tObj.isHistSet) - histCovColl = tObj.getHistForNeurons(neuronIndex); - matrices = cell(1,length(neuronIndex)); - if(length(histCovColl)==1) - matrices = histCovColl.dataToMatrix; - else - for i=1:length(histCovColl) - matrices{i} = histCovColl{i}.dataToMatrix; - end - end - else - matrices = cell(1, length(neuronIndex)); - for i=1:length(neuronIndex) - matrices{i} = zeros(length(tObj.nspikeColl.getNST(neuronIndex(i)).sigRep.time),0); - end - end - end - function ensembleCovariates = getEnsembleNeuronCovariates(tObj,varargin) - % getEnsembleNeuronCovariates(nstCollObj,neuronNum,neighborIndex,windowTimes) - ensembleCovariates = tObj.nspikeColl.getEnsembleNeuronCovariates(varargin{:}); - end - function index = getNeuronIndFromMask(tObj) - % index = getNeuronIndFromMask(tObj) - % see also nstColl.getIndFromMask - index=tObj.nspikeColl.getIndFromMask; - end - function num = getNumUniqueNeurons(tObj) - num = length(tObj.nspikeColl.uniqueNeuronNames); - end - function names = getNeuronNames(tObj) - names = tObj.nspikeColl.getNSTnames; - end - function unames = getUniqueNeuronNames(tObj) - unames = tObj.nspikeColl.getUniqueNSTnames; - end - function index = getNeuronIndFromName(tObj,neuronName) - tempInd = tObj.nspikeColl.getNSTIndicesFromName(neuronName); - currMask = find(tObj.neuronMask==1); - if(isa(tempInd,'cell')) - for i=1:length(tempInd) - index{i} = intersect(currMask,tempInd{i}); - end - elseif(isa(tempInd,'double')) - index = intersect(currMask,tempInd); - end - - - end - - - function n = getNeuronNeighbors(tObj, neuronNum) - if(nargin<2) - neuronNum = tObj.getNeuronIndFromMask; - end - n=tObj.nspikeColl.getNeighbors(neuronNum); - end - - function selector = getCovSelectorFromMask(tObj) - % selector = getCovSelectorFromMask(tObj) - % see also CovColl.getSelectorFromMasks - selector = tObj.covarColl.getSelectorFromMasks; - end - function cov = getCov(tObj,identifier) - % cov = getCov(tObj,identifier) - % see also CovColl.getCov - cov=tObj.covarColl.getCov(identifier); - end - function NST = getNeuron(tObj,identifier) - % NST = getNeuron(tObj,identifier) - % see also nstColl.getNST - NST = tObj.nspikeColl.getNST(identifier); - end - function e = getEvents(tObj) - % e = getEvents(tObj) - % Returns the Events object associated with the Trial - % e is either [] or an Events object - e=tObj.ev; - end - - function l = getAllLabels(tObj) - l=tObj.getAllCovLabels; - offset=length(l); - if(tObj.isHistSet) - l2=tObj.getHistLabels; - for i=1:length(l2) - l{offset+i} = l2{i}; - end - end - offset=length(l); - if(tObj.isEnsCovHistSet) - l3=tObj.getEnsCovLabels; - for i=1:length(l3) - l{offset+i} = l3{i}; - end - end - end - function n = getNumHist(tObj) - % n = getNumHist(tObj) - % Return the number of history windows (length windowTimes - 1) - if(tObj.isHistSet) - if(isa(tObj.history,'History')) - n=length(tObj.history.windowTimes)-1; - elseif(and(isa(tObj.history,'cell'),isa(tObj.history{1},'History'))) - for i=1:length(tObj.history) - n(i) = length(tObj.history{i}.windowTimes)-1; - end - end - else - n=0; - end - - end - function l = getAllCovLabels(tObj) - l =tObj.covarColl.getAllCovLabels; - end - function l = getCovLabelsFromMask(tObj) - l = tObj.covarColl.getCovLabelsFromMask; - end - - function l = getHistLabels(tObj) - if(tObj.isHistSet) - histCovColl = tObj.getHistForNeurons(1); - if(isa(histCovColl,'Covariate')) - l= histCovColl.dataLabels; - elseif(isa(histCovColl,'CovColl')) - l = histCovColl.getAllCovLabels; - else - error('histCovColl must be either a Covariate or a CovColl'); - end - else - l={}; - end - - end - function l = getEnsCovLabels(tObj) - if(tObj.isEnsCovHistSet) - ensCovCollTemp = tObj.ensCovColl; - if(isa(ensCovCollTemp,'CovColl')) -% if(nargin<2) -% %l = ensCovCollTemp.getCovLabelsFromMask; %return labels from current mask -% getAllCovLabels -% else %set mask and return those labels -% ensCovCollTemp.maskAwayAllExcept(tObj.getNeuronNeighbors(neuronNum)); -% l = ensCovCollTemp.getCovLabelsFromMask; -% end - l=ensCovCollTemp.getAllCovLabels; - else - error('ensCovColl must be either a CovColl'); - end - else - l={}; - end - - end - function l = getEnsCovLabelsFromMask(tObj,neuronNum) - if(nargin<2) - error('Must specify neuron number!'); - end - - if(isa(neuronNum,'char')) - tempIndices = tObj.getNeuronIndFromName(neuronNum); - if(length(tempIndices)>1) - neuronNum=tempIndices(1); - else - neuronNum=tempIndices; - end - end - if(tObj.isEnsCovHistSet) - ensCovCollTemp = tObj.ensCovColl; - if(isa(ensCovCollTemp,'CovColl')) -% if(nargin<2) -% %l = ensCovCollTemp.getCovLabelsFromMask; %return labels from current mask -% getAllCovLabels -% else %set mask and return those labels -% ensCovCollTemp.maskAwayAllExcept(tObj.getNeuronNeighbors(neuronNum)); -% l = ensCovCollTemp.getCovLabelsFromMask; -% end - if(neuronNum>0 && neuronNum<=tObj.nspikeColl.numSpikeTrains) - ensCovCollTemp.maskAwayAllExcept(tObj.getNeuronNeighbors(neuronNum)); - l=ensCovCollTemp.getCovLabelsFromMask; - else - error('NeuronNum is out of bounds!'); - end - else - error('ensCovColl must be either a CovColl'); - end - else - l={}; - end - - end - function l = getLabelsFromMask(tObj,neuronNum) - if(nargin<2) - error('To get right labels need to specify neuronNum'); %because of ensemble - end - l = tObj.getCovLabelsFromMask; - offset=length(l); - if(tObj.isHistSet) - l2=tObj.getHistLabels; - l((1:length(l2))+offset) = l2; - end - offset=length(l); - if(tObj.isEnsCovHistSet) - l3=tObj.getEnsCovLabelsFromMask(neuronNum); - l((1:length(l3))+offset) = l3; - end - end - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %Utility functions - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% function shiftTrial(tObj,deltaT) -% tObj.covarColl.shiftCovariates(deltaT); -% tObj.nspikeColl.shift(deltaT); -% tObj.makeConsistentTime; -% tObj.setTrialPartition([]); %default to all training data -% %tObj.setTrialTimesFor('training'); -% end -% - function flatMask=flattenCovMask(tObj) - flatMask = tObj.covarColl.flattenCovMask; -% if(tObj.isHistSet) -% histCovColl = tObj.getHistForNeurons(1); -% if(isa(histCovColl,'Covariate')) -% flatMask = [flatMask histCovColl.dataMask]; -% elseif(isa(histCovColl,'CovColl')) -% flatMask = [flatMask histCovColl.flattenCovMask]; -% else -% error('histCovColl must be either a Covariate or a CovColl'); -% end -% end - - end - function flatMask=flattenMask(tObj) - flatMask = tObj.flattenCovMask; - if(tObj.isHistSet) - histCovColl = tObj.getHistForNeurons(1); - if(isa(histCovColl,'Covariate')) - flatMask = [flatMask histCovColl.dataMask]; - elseif(isa(histCovColl,'CovColl')) - flatMask = [flatMask histCovColl.flattenCovMask]; - else - error('histCovColl must be either a Covariate or a CovColl'); - end - end - if(tObj.isEnsCovHistSet) - ensCovCollTemp = tObj.ensCovColl; - if(isa(ensCovCollTemp,'CovColl')) - flatMask = [flatMask ensCovCollTemp.flattenCovMask]; - else - error('ensCovCollTemp must be either a CovColl'); - end - end - end - function shiftCovariates(tObj, varargin) - tObj.covarColl.setCovShift(varargin{:}); - tObj.makeConsistentTime; - end - - function resetEnsCovMask(tObj) - nSpikes = tObj.nspikeColl.numSpikeTrains; - tObj.ensCovMask = ones(nSpikes,nSpikes)-eye(nSpikes,nSpikes); - end - function resetCovMask(tObj) - % resetCovMask(tObj) - % see also CovColl.resetMask - tObj.covarColl.resetMask; - end - function resetNeuronMask(tObj) - % resetNeuronMask(tObj) - % see also nstColl.resetMask - tObj.nspikeColl.resetMask; - end - function resetHistory(tObj) - % resetHistory(tObj) - % Sets the History object associated with this Trial equal to - % the empty array []. - tObj.history = []; - end -% function shiftCovs(tObj, covLag) -% % shiftCovs(tObj, covLag) -% % if covLag is not specified or isempty ([]) all covariates are -% % href="matlab:help('CovColl.restoreToOriginal')">CovColl.restoreToOriginal -% % If specified, all covariates are shifted by covLag -% % href="matlab:help('Covariate.shift')">Covariate.shift -% % -% % The trial minTime and maxTime properties are updated to -% % reflect any changes. -% -% if(nargin<2) -% covLag = []; -% end -% if(isempty(covLag)) -% for i =1:tObj.covarColl.numCov -% tCov = tObj.covarColl.getCov(i); -% tCov.restoreToOriginal; -% end -% else -% for i =1:tObj.covarColl.numCov -% tCov = tObj.covarColl.getCov(i); -% tCov.shift(covLag); -% end -% end -% tObj.makeConsistentTime; -% end - function resample(tObj,sampleRate) - % resample(tObj,sampleRate) - % calls Trial.setSampleRate - tObj.setSampleRate(sampleRate); - end - function resampleEnsColl(tObj) - if(~isempty(tObj.ensCovColl) && ~isempty(tObj.ensCovHist)) - tObj.ensCovColl=tObj.getEnsembleNeuronCovariates(1,[],tObj.ensCovHist); - else - tObj.setEnsCovHist; %set to empty; - end - end - function restoreToOriginal(tObj) - % restoreToOriginal(tObj) - % calls nstColl.resto - % reToOriginal, CovColl.restoreToOriginal - % resets minTime and maxTime of the Trial according to the - % changes that happened when restoring the nstColl and CovColl - % to their original states. - tObj.nspikeColl.restoreToOriginal; - tObj.covarColl.restoreToOriginal; - if(~tObj.isSampleRateConsistent) - tObj.makeConsistentSampleRate; - end - tObj.resampleEnsColl; % compute at the new sampling rate - tObj.makeConsistentTime; - end - function makeConsistentSampleRate(tObj) - tObj.resample(tObj.findMaxSampleRate); - end - function makeConsistentTime(tObj) - tObj.setMinTime; - tObj.setMaxTime; - %tObj.setTrialPartition; - %tObj.updateTimePartitions; - end - - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %Plot functions - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - function plotRaster(tObj,handle) - if(nargin<2) - handle =gcf; - end - end - function plotCovariates(tObj,handle) - if(nargin<2) - handle =gcf; - end - numCovars = tObj.covarColl.nActCovar; %accounts for masks - figure(handle); - if(numCovars==1) - tObj.covarColl.plot; hold on; - if(~isempty(tObj.ev)) - tObj.ev.plot; - end - elseif(numCovars==2) - a1=subplot(1,2,1); - a2=subplot(1,2,2); - tObj.covarColl.plot([a1,a2]); hold on; - if(~isempty(tObj.ev)) - tObj.ev.plot([a1,a2]); - end - elseif(numCovars==3) - a1=subplot(3,2,[1 3 5]); - tObj.nspikeColl.plot;hold on; - a2=subplot(3,2,2); a3=subplot(3,2,4); a4=subplot(3,2,6); - tObj.covarColl.plot([a2,a3 a4]); hold on; - if(~isempty(tObj.ev)) - tObj.ev.plot([a1,a2,a3,a4]); - end - else - figure(handle); - tObj.nspikeColl.plot; hold on; - if(~isempty(tObj.ev)) - tObj.ev.plot; - end - figure; - tObj.covarColl.plot; hold on; - if(~isempty(tObj.ev)) - tObj.ev.plot; - end - end - end - - function plot(tObj,handle) - % plot(tObj,handle) - % plots the Trial on the figure handle specified. - % if handle is not specified, then handle = gcf; - if(nargin<2) - handle =gcf; - end - numCovars = tObj.covarColl.nActCovar; %accounts for masks - figure(handle); - if(numCovars==1) - a1=subplot(2,2,[1 3]); - tObj.nspikeColl.plot;hold on; - a2=subplot(2,2,[2 4]); - tObj.covarColl.plot(a2); hold on; - if(~isempty(tObj.ev)) - tObj.ev.plot([a1,a2]); - end - elseif(numCovars==2) - a1=subplot(2,2,[1 3]); - tObj.nspikeColl.plot;hold on; - a2=subplot(2,2,2); a3=subplot(2,2,4); - tObj.covarColl.plot([a2,a3]); hold on; - if(~isempty(tObj.ev)) - tObj.ev.plot([a1,a2,a3]); - end - elseif(numCovars==3) - a1=subplot(3,2,[1 3 5]); - tObj.nspikeColl.plot;hold on; - a2=subplot(3,2,2); a3=subplot(3,2,4); a4=subplot(3,2,6); - tObj.covarColl.plot([a2,a3 a4]); hold on; - if(~isempty(tObj.ev)) - tObj.ev.plot([a1,a2,a3,a4]); - end - else - figure(handle); - tObj.nspikeColl.plot; hold on; - if(~isempty(tObj.ev)) - tObj.ev.plot; - end - figure; - tObj.covarColl.plot; hold on; - if(~isempty(tObj.ev)) - tObj.ev.plot; - end - end - %make sure events plot on every covariate plot - %add events and covariate labels to the legend or mark events - %with text on the screen. - end - function structure = toStructure(tObj) - fNames =fieldnames(tObj); - for i=1:length(fNames) - currObj = tObj.(fNames{i}); - if(isa(currObj,'double')||isa(currObj,'cell')) - structure.(fNames{i}) = currObj; - elseif(isa(currObj,'nstColl')||isa(currObj,'CovColl')||isa(currObj,'Events')||isa(currObj,'History')) - if(~isempty(currObj)) - structure.(fNames{i}) = currObj.toStructure; - else - structure.(fNames{i}) = currObj; - end - end - end - end - - end - methods (Static) - function tObj = fromStructure(structure) - nspikeColl = nstColl.fromStructure(structure.nspikeColl); - covarColl = CovColl.fromStructure(structure.covarColl); - ev = Events.fromStructure(structure.ev); - h = History.fromStructure(structure.history); - ensHist = History.fromStructure(structure.ensCovHist); - tObj = Trial(nspikeColl,covarColl,ev, h, ensHist); - - minTime = structure.minTime; - maxTime = structure.maxTime; - - tObj.setMinTime(minTime); - tObj.setMaxTime(maxTime); - trainingW = structure.trainingWindow; - validationW= structure.validationWindow; - - tObj.setTrialPartition([trainingW validationW]); - end - end - methods (Access = private) - - function answer = isSampleRateConsistent(tObj) - answer = (tObj.findMinSampleRate == tObj.findMaxSampleRate); - end - function minTime = findMinTime(tObj) - minTime=min([tObj.nspikeColl.minTime,tObj.covarColl.minTime]); - end - function maxTime = findMaxTime(tObj) - maxTime =max([tObj.nspikeColl.maxTime, tObj.covarColl.maxTime]); - end - function minSampleRate = findMinSampleRate(tObj) - minSampleRate = min([tObj.sampleRate, tObj.nspikeColl.sampleRate, tObj.covarColl.sampleRate]); - end - function maxSampleRate = findMaxSampleRate(tObj) - maxSampleRate = max([tObj.sampleRate, tObj.nspikeColl.sampleRate, tObj.covarColl.sampleRate]); - end - - end - -end - - - diff --git a/TrialConfig.m b/TrialConfig.m deleted file mode 100644 index 91300d4f..00000000 --- a/TrialConfig.m +++ /dev/null @@ -1,170 +0,0 @@ -classdef TrialConfig >tcObj=TrialConfig(covMask,sampleRate, history,ensCovHist,covLag,name) -% -% All parameters are optional -% methods -% TrialConfig Examples -% -% see also Trial, -% CovColl, -% nstColl -% -% Reference page in Help browser -% doc TrialConfig - -% -% nSTAT v1 Copyright (C) 2012 Masschusetts Institute of Technology -% Cajigas, I, Malik, WQ, Brown, EN -% This program is free software; you can redistribute it and/or -% modify it under the terms of the GNU General Public License as published -% by the Free Software Foundation; either version 2 of the License, or -% (at your option) any later version. -% -% This program is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -% See the GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with this program; if not, write to the Free Software Foundation, -% Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - - properties - covMask % which covariates are going to be used for analysis - covLag % deltaT for the covariate. Negative to shift back in time - sampleRate % sampleRate to be used for the fitting of this trial - history % History object this trial - ensCovHist % History term for neiboring neurons - aka Ensemble History - ensCovMask % Mask Matrix for neighboring neurons; - name % Name of the configuration - - end - - - methods - function tcObj=TrialConfig(covMask,sampleRate, history,ensCovHist,ensCovMask,covLag,name) - % tcObj=TrialConfig(covMask,sampleRate, history,covHist,covLag,name) - % covMask: List of covariate names and labels that are to be used: - % ex: {{'Position','x'},{'Velocity','v_x'}} - % would use the component x of the Position covariate and - % the component v_x of the Velocity covariate for the fits - % - if empty then no covariates are used - % - % sampleRate: if empty uses the current sampleRate. Otherwise - % resamples all of the data to the specified sample - % rate. - % - % history: history object, cell of history objects, or a vector of windowTimes - % ensCovHist: same as history. Used to determine ensemble covariate history - % covLag : delay to be used with covariates - % name: name o f the configuration - if(nargin<7 || isempty(name)) - name =''; - end - if(nargin<6 || isempty(covLag)) - covLag=[]; - end - if(nargin<5 || isempty(ensCovMask)) - ensCovMask=[]; - end - if(nargin<4 || isempty(ensCovHist)) - ensCovHist = []; - end - if(nargin<3 || isempty(history)) - history = []; - end - if(nargin<2 || isempty(sampleRate)) - sampleRate =[]; - end - if(nargin<1 || isempty(covMask)) - covMask=[]; - end - - tcObj.covMask = covMask; - tcObj.sampleRate = sampleRate; - tcObj.history = history; - tcObj.ensCovHist = ensCovHist; - tcObj.ensCovMask = ensCovMask; - tcObj.covLag = covLag; - tcObj.name = name; - end - function setConfig(tcObj, trial) - % setConfig(tcObj, trial) - % applies this configuration to trial. - if(~isempty(tcObj.history)) - trial.setHistory(tcObj.history); - else - trial.resetHistory; - end - - - if(~isempty(tcObj.sampleRate)) - if(trial.sampleRate~=tcObj.sampleRate) - trial.resample(tcObj.sampleRate); - end - else - %trial.restoreToOriginal; - %keep sampleRate - end - - %if(~isempty(tcObj.covMask)) - trial.setCovMask(tcObj.covMask); - %all mask to be empty - %else - % trial.resetCovMask; - %end - - if(~isempty(tcObj.covLag)) - trial.shiftCovariates(tcObj.covLag); - end - - - if(~isempty(tcObj.ensCovHist)) - trial.setEnsCovHist(tcObj.ensCovHist); - trial.setEnsCovMask(tcObj.ensCovMask); - else - trial.setEnsCovHist; %sets it to be empty - trial.setEnsCovMask; %sets it to the default; - end -% trial.setTrialTimesFor('training'); - end - function n=getName(tcObj) - % n=getName(tcObj) - % returns a string with the name of this configuration - n = tcObj.name; - end - function setName(tcObj,n) - % setName(tcObj,n) - % sets the name of the current configuration to n - tcObj.name = n; - end - function structure = toStructure(tcObj) - % structure = toStructure(tcObj) - % structure is a standard matlab structure that can be saved as - % a .mat file. - % A TrialConfig object can be obtained by calling - % tcObj = TrialConfig.fromStructure(structure); - fNames = fieldnames(tcObj); - for i=1:length(fNames) - structure.(fNames{i}) = tcObj.(fNames{i}); - end - - end - - end - methods (Static) - function tcObj = fromStructure(structure) - % tcObj is a TrialConfig object that is reconstructed from the - % structure - tcObj=TrialConfig(structure.covMask,structure.sampleRate, ... - structure.history,structure.ensCovHist, ... - structure.covLag,structure.name); - end - end - - - -end diff --git a/__init__.py b/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/data/Explicit Stimulus/Dir3/Neuron1/Stim2/trngdataBis.mat b/data/Explicit Stimulus/Dir3/Neuron1/Stim2/trngdataBis.mat new file mode 100644 index 00000000..b8a024c7 Binary files /dev/null and b/data/Explicit Stimulus/Dir3/Neuron1/Stim2/trngdataBis.mat differ diff --git a/data/Place Cells/PlaceCellDataAnimal1.mat b/data/Place Cells/PlaceCellDataAnimal1.mat new file mode 100644 index 00000000..3bb0d52f Binary files /dev/null and b/data/Place Cells/PlaceCellDataAnimal1.mat differ diff --git a/helpfiles/SSGLMExampleData.mat b/data/SSGLMExampleData.mat similarity index 60% rename from helpfiles/SSGLMExampleData.mat rename to data/SSGLMExampleData.mat index e51ead9d..7e77367a 100644 Binary files a/helpfiles/SSGLMExampleData.mat and b/data/SSGLMExampleData.mat differ diff --git a/data/mEPSCs/epsc2.txt b/data/mEPSCs/epsc2.txt new file mode 100644 index 00000000..5630c67c --- /dev/null +++ b/data/mEPSCs/epsc2.txt @@ -0,0 +1,574 @@ + Time (ms) Amplitude Rise (ms) Decay (ms) Area Baseline Noise Group Channel 10-90Rise HalfWidth Rise50 Peak Dir Burst# BurstE# 10-90Slope Rel Time +1.00 10.50 27.46 0.80 2.90 64.09 8.41 2.16 0.00 0.00 0.50 2.63 0.50 -1.00 0.00 0.00 -43.97 10.50 +2.00 374.30 11.21 0.80 2.30 21.33 9.82 0.45 0.00 0.00 0.61 1.76 0.60 -1.00 0.00 0.00 -14.79 67.10 +3.00 411.00 10.04 1.80 1.70 20.59 9.47 -1.20 0.00 0.00 1.20 2.31 1.10 -1.00 0.00 0.00 -6.68 103.80 +4.00 587.00 20.69 1.30 12.20 153.82 10.45 0.92 0.00 0.00 0.41 1.80 0.50 -1.00 0.00 0.00 -39.99 23.80 +5.00 590.90 22.18 5.20 8.40 167.16 11.37 -0.52 255.00 0.00 4.31 3.01 0.70 -1.00 0.00 0.00 -4.12 78.90 +6.00 672.80 11.91 0.80 4.80 44.82 8.16 2.19 0.00 0.00 0.69 3.99 0.60 -1.00 0.00 0.00 -13.87 32.80 +7.00 693.90 6.56 6.00 1.70 27.38 8.31 1.31 0.00 0.00 5.33 2.79 1.30 -1.00 0.00 0.00 -0.98 53.90 +8.00 824.80 6.75 3.20 0.70 11.72 8.79 0.38 0.00 0.00 2.16 0.86 0.70 -1.00 0.00 0.00 -2.50 56.80 +9.00 920.00 11.07 0.90 3.00 30.07 8.61 0.89 0.00 0.00 0.72 3.17 0.60 -1.00 0.00 0.00 -12.21 24.00 +10.00 926.90 7.32 0.50 2.60 15.14 3.38 1.42 0.00 0.00 0.32 2.10 0.30 -1.00 0.00 0.00 -18.38 107.70 +11.00 1273.30 18.01 0.80 3.60 51.89 11.01 0.12 0.00 0.00 0.34 2.46 0.50 -1.00 0.00 0.00 -42.54 121.30 +12.00 1620.00 11.37 0.70 1.60 15.03 11.50 0.88 0.00 0.00 0.49 1.43 0.40 -1.00 0.00 0.00 -18.73 32.80 +13.00 1624.10 13.64 0.60 3.80 36.45 10.68 0.03 255.00 0.00 0.43 1.80 0.40 -1.00 0.00 0.00 -25.35 88.10 +14.00 1667.50 10.39 1.50 2.20 22.28 11.06 0.28 0.00 0.00 1.26 1.90 0.80 -1.00 0.00 0.00 -6.60 3.50 +15.00 1743.80 7.32 3.10 1.20 11.95 11.53 -0.82 0.00 0.00 1.87 0.38 0.20 -1.00 0.00 0.00 -3.13 79.80 +16.00 1815.00 20.14 1.30 3.00 51.33 11.07 0.64 0.00 0.00 0.89 2.27 0.50 -1.00 0.00 0.00 -18.04 23.00 +17.00 2323.20 36.70 1.10 3.20 96.54 10.92 -0.26 0.00 0.00 0.51 2.77 0.90 -1.00 0.00 0.00 -57.12 19.20 +18.00 2361.10 6.20 1.70 1.80 11.59 10.43 0.35 0.00 0.00 1.48 0.64 0.30 -1.00 0.00 0.00 -3.35 57.10 +19.00 2366.50 8.11 0.70 1.40 11.09 8.32 -0.19 0.00 0.00 0.55 1.29 0.60 -1.00 0.00 0.00 -11.73 11.30 +20.00 2469.20 9.17 0.80 1.40 12.41 10.11 -0.34 0.00 0.00 0.72 1.71 0.60 -1.00 0.00 0.00 -10.24 37.20 +21.00 2599.80 17.00 1.20 2.60 37.50 10.75 -0.41 0.00 0.00 0.47 2.46 0.40 -1.00 0.00 0.00 -28.87 39.80 +22.00 2843.40 6.17 1.50 1.00 10.03 11.95 -0.35 0.00 0.00 1.21 2.00 1.30 -1.00 0.00 0.00 -4.06 27.40 +23.00 3327.00 14.68 0.60 1.90 24.23 7.73 1.02 0.00 0.00 0.38 1.64 0.40 -1.00 0.00 0.00 -30.75 127.00 +24.00 3434.80 11.37 0.90 1.90 18.33 11.01 -0.22 0.00 0.00 0.63 1.48 0.40 -1.00 0.00 0.00 -14.55 106.80 +25.00 3621.50 13.92 0.50 2.00 20.23 10.04 -0.71 0.00 0.00 0.33 1.51 0.30 -1.00 0.00 0.00 -33.66 37.50 +26.00 3904.90 15.11 1.80 3.00 36.92 10.01 -0.24 0.00 0.00 0.35 2.24 0.40 -1.00 0.00 0.00 -34.45 64.90 +27.00 3910.70 19.88 7.60 4.20 103.33 10.10 1.40 255.00 0.00 6.18 2.22 0.50 -1.00 0.00 0.00 -2.57 70.70 +28.00 4105.00 10.45 0.70 4.00 33.53 10.97 0.41 0.00 0.00 0.50 4.07 0.60 -1.00 0.00 0.00 -16.77 85.80 +29.00 4319.70 6.09 0.90 5.30 25.68 12.07 -1.92 0.00 0.00 0.71 2.79 0.60 -1.00 0.00 0.00 -6.87 95.70 +30.00 4558.60 23.37 1.00 2.50 46.11 10.42 -1.13 0.00 0.00 0.55 1.94 0.60 -1.00 0.00 0.00 -34.14 78.60 +31.00 4637.60 8.43 0.50 2.40 16.59 6.57 4.30 0.00 0.00 0.35 2.20 0.40 -1.00 0.00 0.00 -19.46 29.60 +32.00 4678.00 8.32 3.00 0.80 15.33 9.09 1.29 0.00 0.00 1.89 1.89 1.20 -1.00 0.00 0.00 -3.52 70.00 +33.00 4776.80 20.53 1.40 3.80 54.01 9.45 0.43 0.00 0.00 0.47 2.16 0.50 -1.00 0.00 0.00 -35.25 40.80 +34.00 4799.30 11.05 1.00 2.50 23.39 6.70 0.66 0.00 0.00 0.79 1.27 0.60 -1.00 0.00 0.00 -11.13 63.30 +35.00 4812.60 6.31 0.90 0.90 4.60 5.47 -1.26 0.00 0.00 0.35 0.46 0.30 -1.00 0.00 0.00 -14.51 76.60 +36.00 4848.80 6.20 1.70 1.60 9.77 7.84 1.35 0.00 0.00 1.32 1.11 0.20 -1.00 0.00 0.00 -3.75 112.80 +37.00 4889.20 6.36 1.10 0.40 4.40 7.51 0.52 0.00 0.00 0.58 0.66 0.50 -1.00 0.00 0.00 -8.70 25.20 +38.00 4997.00 6.27 0.90 1.60 8.36 9.91 -0.39 0.00 0.00 0.73 0.82 0.50 -1.00 0.00 0.00 -6.88 5.00 +39.00 5041.40 6.39 0.70 0.90 5.42 9.84 1.32 0.00 0.00 0.63 0.42 0.20 -1.00 0.00 0.00 -8.14 49.40 +40.00 5056.60 12.42 0.80 2.80 25.86 9.99 -0.84 0.00 0.00 0.49 1.24 0.50 -1.00 0.00 0.00 -20.09 64.60 +41.00 5073.60 9.24 0.80 4.60 30.92 9.66 -0.18 0.00 0.00 0.50 2.76 0.60 -1.00 0.00 0.00 -14.79 81.60 +42.00 5127.80 6.39 1.20 2.00 10.24 9.45 2.01 0.00 0.00 0.72 1.22 0.20 -1.00 0.00 0.00 -7.06 84.60 +43.00 5314.30 7.44 1.10 0.90 10.51 9.94 -0.10 0.00 0.00 0.81 1.48 1.00 -1.00 0.00 0.00 -7.39 66.30 +44.00 5399.70 16.65 0.60 3.80 47.71 9.93 -0.19 0.00 0.00 0.34 2.91 0.50 -1.00 0.00 0.00 -38.71 23.70 +45.00 5500.10 6.89 1.40 0.80 6.79 10.49 -0.39 0.00 0.00 0.92 0.78 0.50 -1.00 0.00 0.00 -6.01 124.10 +46.00 6013.20 12.27 4.00 2.00 33.41 11.51 -0.57 0.00 0.00 3.24 2.20 0.80 -1.00 0.00 0.00 -3.03 125.20 +47.00 6213.80 7.02 0.70 0.80 4.80 11.17 1.98 0.00 0.00 0.54 0.44 0.40 -1.00 0.00 0.00 -10.35 69.80 +48.00 6436.90 10.41 1.10 1.80 19.49 9.81 1.64 0.00 0.00 0.96 2.35 0.90 -1.00 0.00 0.00 -8.64 36.90 +49.00 6459.90 7.28 1.70 1.00 8.87 9.23 -1.11 0.00 0.00 1.55 0.43 0.30 -1.00 0.00 0.00 -3.75 59.90 +50.00 6526.10 9.21 1.40 1.20 13.22 9.80 1.15 0.00 0.00 1.16 1.58 1.10 -1.00 0.00 0.00 -6.34 126.10 +51.00 6582.80 6.81 2.70 1.10 12.80 10.16 2.23 0.00 0.00 1.97 1.17 0.50 -1.00 0.00 0.00 -2.77 54.80 +52.00 6666.20 15.35 0.90 2.50 31.46 9.49 0.44 0.00 0.00 0.49 1.89 0.70 -1.00 0.00 0.00 -25.16 10.20 +53.00 6752.70 12.03 1.00 2.00 23.88 9.84 -0.21 0.00 0.00 0.86 1.96 0.60 -1.00 0.00 0.00 -11.20 96.70 +54.00 7634.60 13.35 0.90 2.00 25.02 7.77 0.58 0.00 0.00 0.69 1.67 0.80 -1.00 0.00 0.00 -15.56 82.60 +55.00 7708.30 6.13 1.70 2.00 11.83 11.13 -0.15 0.00 0.00 1.48 0.93 0.50 -1.00 0.00 0.00 -3.31 28.30 +56.00 7806.30 7.58 1.10 0.80 8.73 11.29 -1.94 0.00 0.00 0.85 1.29 0.70 -1.00 0.00 0.00 -7.17 126.30 +57.00 8213.70 9.16 0.80 2.40 18.03 10.95 0.57 0.00 0.00 0.64 1.44 0.30 -1.00 0.00 0.00 -11.46 21.70 +58.00 8254.60 13.28 0.80 2.00 25.32 10.22 -0.43 0.00 0.00 0.45 2.27 0.60 -1.00 0.00 0.00 -23.88 62.60 +59.00 8466.60 9.36 0.90 2.50 22.05 10.50 1.20 0.00 0.00 0.68 2.61 0.40 -1.00 0.00 0.00 -11.05 18.60 +60.00 8723.20 11.43 2.60 2.30 25.13 10.93 -0.56 0.00 0.00 0.62 1.72 0.50 -1.00 0.00 0.00 -14.81 19.20 +61.00 8813.70 11.52 0.70 2.00 18.71 10.88 0.45 0.00 0.00 0.43 1.26 0.50 -1.00 0.00 0.00 -21.24 109.70 +62.00 8832.30 13.50 2.20 1.90 23.85 10.68 -0.01 0.00 0.00 0.40 1.58 0.40 -1.00 0.00 0.00 -26.98 51.50 +63.00 8872.90 7.69 1.00 1.00 9.27 10.26 0.74 0.00 0.00 0.86 1.30 0.50 -1.00 0.00 0.00 -7.18 40.90 +64.00 8881.70 6.42 1.50 0.70 6.86 10.53 -1.25 0.00 0.00 1.10 1.12 0.50 -1.00 0.00 0.00 -4.68 49.70 +65.00 9007.60 6.32 0.60 4.60 22.96 10.03 -0.19 0.00 0.00 0.40 2.75 0.30 -1.00 0.00 0.00 -12.65 47.60 +66.00 9104.70 12.60 1.30 1.60 20.88 10.27 1.42 0.00 0.00 1.06 1.58 0.90 -1.00 0.00 0.00 -9.55 16.70 +67.00 9117.70 10.40 0.60 1.30 14.08 7.49 -0.34 0.00 0.00 0.47 1.56 0.50 -1.00 0.00 0.00 -17.74 29.70 +68.00 9373.30 17.79 2.70 3.30 54.81 10.52 1.33 0.00 0.00 0.77 3.13 0.70 -1.00 0.00 0.00 -18.52 29.30 +69.00 9412.70 11.90 0.70 4.30 34.43 10.61 0.69 0.00 0.00 0.49 2.28 0.50 -1.00 0.00 0.00 -19.61 68.70 +70.00 9585.00 14.71 0.80 3.60 42.41 11.66 2.13 0.00 0.00 0.36 2.63 0.60 -1.00 0.00 0.00 -32.30 113.00 +71.00 9597.80 23.32 0.90 3.40 64.35 9.20 0.13 0.00 0.00 0.42 2.54 0.70 -1.00 0.00 0.00 -44.53 125.80 +72.00 9660.40 13.30 0.80 1.80 19.35 9.69 0.40 0.00 0.00 0.54 1.58 0.50 -1.00 0.00 0.00 -19.81 9.20 +73.00 9676.90 26.85 1.20 3.90 84.18 8.60 -2.12 0.00 0.00 0.74 3.17 0.90 -1.00 0.00 0.00 -28.89 76.90 +74.00 9766.40 6.53 1.80 1.50 8.94 10.33 -0.59 0.00 0.00 1.67 0.60 0.40 -1.00 0.00 0.00 -3.12 38.40 +75.00 9781.50 6.12 0.60 2.00 9.67 8.13 0.64 0.00 0.00 0.42 1.74 0.20 -1.00 0.00 0.00 -11.64 53.50 +76.00 9802.90 12.81 0.60 3.10 30.83 11.46 0.26 0.00 0.00 0.46 2.29 0.40 -1.00 0.00 0.00 -22.49 74.90 +77.00 9884.40 6.75 3.30 1.70 15.17 9.62 -1.06 0.00 0.00 2.10 1.40 0.40 -1.00 0.00 0.00 -2.57 28.40 +78.00 9902.10 8.77 0.60 2.80 17.70 10.36 1.32 0.00 0.00 0.38 1.40 0.30 -1.00 0.00 0.00 -18.28 46.10 +79.00 9918.90 9.93 0.80 1.30 11.86 9.32 0.02 0.00 0.00 0.57 1.25 0.50 -1.00 0.00 0.00 -13.85 62.90 +80.00 9980.50 6.94 0.40 0.50 4.01 10.14 0.99 0.00 0.00 0.30 0.56 0.30 -1.00 0.00 0.00 -18.77 124.50 +81.00 10086.80 19.18 0.80 2.10 34.67 11.64 0.46 0.00 0.00 0.52 1.89 0.60 -1.00 0.00 0.00 -29.41 102.80 +82.00 10130.40 6.28 0.80 1.20 6.87 10.33 0.06 0.00 0.00 0.61 0.88 0.30 -1.00 0.00 0.00 -8.18 18.40 +83.00 10174.10 13.81 1.10 1.90 29.44 10.28 1.27 0.00 0.00 0.78 2.27 0.90 -1.00 0.00 0.00 -14.20 36.50 +84.00 10233.50 13.28 1.10 2.80 27.92 9.81 0.64 0.00 0.00 0.82 1.40 0.80 -1.00 0.00 0.00 -12.98 95.90 +85.00 10475.40 14.08 0.60 1.90 23.34 9.50 -0.46 0.00 0.00 0.43 1.78 0.30 -1.00 0.00 0.00 -26.10 107.40 +86.00 10604.20 12.29 0.90 3.20 33.45 9.97 0.26 0.00 0.00 0.54 3.04 0.60 -1.00 0.00 0.00 -18.21 108.20 +87.00 10613.70 9.04 10.40 0.80 66.76 10.78 -0.55 255.00 0.00 3.14 0.97 0.70 -1.00 0.00 0.00 -2.30 117.70 +88.00 10702.10 7.62 2.10 1.00 12.08 12.96 -1.12 0.00 0.00 1.34 1.12 0.70 -1.00 0.00 0.00 -4.55 78.10 +89.00 11182.20 22.16 2.00 2.70 53.83 10.90 1.45 0.00 0.00 1.21 2.09 0.70 -1.00 0.00 0.00 -14.63 46.20 +90.00 11215.90 6.91 1.10 1.10 8.53 8.07 -1.22 0.00 0.00 0.96 1.16 0.90 -1.00 0.00 0.00 -5.74 79.90 +91.00 11218.40 13.33 3.80 4.70 65.28 11.07 1.53 255.00 0.00 3.46 4.08 1.00 -1.00 0.00 0.00 -3.09 82.40 +92.00 11405.90 7.43 2.70 0.40 11.75 10.90 0.79 0.00 0.00 1.53 0.51 0.30 -1.00 0.00 0.00 -3.88 13.90 +93.00 11474.60 7.22 0.70 1.20 8.45 8.89 1.11 0.00 0.00 0.54 1.19 0.30 -1.00 0.00 0.00 -10.63 82.60 +94.00 11521.90 15.35 1.00 2.40 35.33 10.21 1.27 0.00 0.00 0.73 2.89 0.90 -1.00 0.00 0.00 -16.83 1.90 +95.00 11530.40 7.67 1.70 1.10 9.01 7.90 -1.29 0.00 0.00 0.84 0.86 0.60 -1.00 0.00 0.00 -7.27 10.40 +96.00 11578.60 6.45 2.50 0.80 11.04 10.05 1.21 0.00 0.00 2.37 0.95 0.60 -1.00 0.00 0.00 -2.18 58.60 +97.00 11598.70 11.78 0.90 2.20 20.57 11.26 0.29 0.00 0.00 0.56 1.71 0.50 -1.00 0.00 0.00 -16.84 78.70 +98.00 11680.60 6.15 1.20 1.20 7.43 11.62 1.00 0.00 0.00 1.03 0.55 0.30 -1.00 0.00 0.00 -4.79 7.00 +99.00 11687.40 7.54 3.00 1.70 20.12 12.19 -2.31 0.00 0.00 2.67 2.84 1.40 -1.00 0.00 0.00 -2.26 39.40 +100.00 11698.40 7.25 2.70 5.00 30.11 11.31 -1.94 0.00 0.00 2.40 1.70 0.90 -1.00 0.00 0.00 -2.41 50.40 +101.00 11744.50 22.50 0.70 2.90 50.40 11.35 0.54 0.00 0.00 0.43 2.11 0.50 -1.00 0.00 0.00 -41.53 96.50 +102.00 11792.10 8.01 0.80 1.00 9.70 9.34 -0.60 0.00 0.00 0.53 1.27 0.60 -1.00 0.00 0.00 -12.11 16.10 +103.00 11814.60 6.37 1.50 0.80 5.99 9.92 -1.25 0.00 0.00 0.33 0.44 0.20 -1.00 0.00 0.00 -15.62 38.60 +104.00 12033.30 17.96 1.20 2.30 34.32 10.04 0.42 0.00 0.00 0.97 1.86 0.70 -1.00 0.00 0.00 -14.88 1.30 +105.00 12052.00 6.58 1.20 1.60 9.75 11.07 0.10 0.00 0.00 1.05 0.73 0.30 -1.00 0.00 0.00 -5.02 20.00 +106.00 12117.60 10.32 1.10 2.10 20.01 11.00 -1.86 0.00 0.00 0.58 1.65 0.60 -1.00 0.00 0.00 -14.30 85.60 +107.00 12267.20 14.37 0.60 1.90 24.05 11.14 2.05 0.00 0.00 0.47 2.16 0.40 -1.00 0.00 0.00 -24.57 107.20 +108.00 12458.30 20.94 1.00 3.00 49.74 10.27 1.19 0.00 0.00 0.52 1.99 0.50 -1.00 0.00 0.00 -32.50 42.30 +109.00 12491.00 6.72 0.60 1.30 8.24 7.26 -2.38 0.00 0.00 0.33 1.07 0.40 -1.00 0.00 0.00 -16.12 75.00 +110.00 12566.70 6.47 2.60 1.80 16.24 9.95 -0.06 0.00 0.00 2.45 1.94 1.20 -1.00 0.00 0.00 -2.11 22.70 +111.00 12639.50 8.20 4.60 0.90 16.05 10.70 -0.97 0.00 0.00 2.13 0.77 0.30 -1.00 0.00 0.00 -3.08 95.50 +112.00 12643.30 11.46 0.50 1.50 15.81 8.26 1.73 0.00 0.00 0.32 1.28 0.40 -1.00 0.00 0.00 -28.80 99.30 +113.00 12653.10 7.39 2.40 2.60 20.13 10.75 -0.26 0.00 0.00 1.64 2.83 1.50 -1.00 0.00 0.00 -3.60 109.10 +114.00 12687.20 12.35 1.10 1.40 17.60 11.12 0.43 0.00 0.00 0.86 1.45 0.60 -1.00 0.00 0.00 -11.44 15.20 +115.00 12838.60 11.29 1.40 6.10 55.18 12.33 1.25 0.00 0.00 0.89 2.38 0.90 -1.00 0.00 0.00 -10.10 38.60 +116.00 12841.50 10.83 4.00 1.40 40.00 11.05 0.78 255.00 0.00 3.53 1.74 1.20 -1.00 0.00 0.00 -2.45 41.50 +117.00 12899.50 7.10 3.70 1.80 21.45 10.92 -0.17 0.00 0.00 2.87 3.18 1.60 -1.00 0.00 0.00 -1.98 99.50 +118.00 12942.00 10.37 0.70 1.50 14.31 11.52 -1.69 0.00 0.00 0.43 1.32 0.40 -1.00 0.00 0.00 -19.31 14.00 +119.00 12942.80 8.00 1.50 2.70 22.88 11.63 0.10 0.00 0.00 0.34 1.81 1.30 -1.00 0.00 0.00 -18.71 14.80 +120.00 13013.70 9.29 0.90 1.50 13.42 12.10 1.53 0.00 0.00 0.72 1.80 0.70 -1.00 0.00 0.00 -10.26 85.70 +121.00 13028.10 16.16 1.10 2.80 38.13 10.43 -0.48 0.00 0.00 0.84 2.03 0.90 -1.00 0.00 0.00 -15.31 100.10 +122.00 13172.60 10.46 1.30 1.80 22.98 10.89 -0.36 0.00 0.00 1.15 2.23 1.10 -1.00 0.00 0.00 -7.27 116.60 +123.00 13176.00 7.25 4.70 2.50 36.85 10.07 0.02 255.00 0.00 1.41 1.24 0.90 -1.00 0.00 0.00 -4.12 120.00 +124.00 13444.90 12.69 2.00 4.40 39.54 11.78 0.47 0.00 0.00 0.80 1.40 0.70 -1.00 0.00 0.00 -12.65 4.90 +125.00 13521.30 7.09 6.30 0.30 23.61 11.37 0.89 0.00 0.00 5.76 2.24 2.10 -1.00 0.00 0.00 -0.99 81.30 +126.00 13547.20 7.64 1.70 1.80 14.61 10.70 -0.59 0.00 0.00 1.48 1.03 0.90 -1.00 0.00 0.00 -4.12 107.20 +127.00 13575.10 16.76 0.70 3.20 40.67 9.85 -1.43 0.00 0.00 0.27 2.14 0.50 -1.00 0.00 0.00 -49.02 7.10 +128.00 13592.80 6.07 6.00 0.60 17.16 10.26 -0.21 0.00 0.00 3.45 0.61 0.40 -1.00 0.00 0.00 -1.41 24.80 +129.00 13620.40 7.39 1.00 1.10 8.95 10.74 0.60 0.00 0.00 0.83 1.03 0.80 -1.00 0.00 0.00 -7.09 52.40 +130.00 13802.40 7.33 1.50 1.60 12.70 11.20 -0.71 0.00 0.00 1.05 1.83 0.50 -1.00 0.00 0.00 -5.57 106.40 +131.00 13845.00 8.51 0.70 3.50 23.48 11.08 -0.25 0.00 0.00 0.52 1.69 0.50 -1.00 0.00 0.00 -13.19 21.00 +132.00 13847.80 8.22 3.50 0.70 22.45 10.83 0.60 255.00 0.00 3.27 0.68 0.40 -1.00 0.00 0.00 -2.01 23.80 +133.00 14038.90 20.31 1.90 2.70 52.46 11.37 -0.21 0.00 0.00 1.39 2.36 0.90 -1.00 0.00 0.00 -11.67 86.90 +134.00 14223.80 18.10 0.70 4.40 53.56 11.33 0.56 0.00 0.00 0.43 2.56 0.40 -1.00 0.00 0.00 -33.85 15.80 +135.00 14345.70 40.99 0.90 3.70 105.35 10.79 0.81 0.00 0.00 0.51 2.26 0.50 -1.00 0.00 0.00 -64.53 9.70 +136.00 14362.60 18.63 17.80 3.70 251.87 10.93 0.10 255.00 0.00 17.34 2.49 0.80 -1.00 0.00 0.00 -0.86 26.60 +137.00 15138.50 11.05 0.40 1.90 17.33 8.84 1.64 0.00 0.00 0.28 1.65 0.30 -1.00 0.00 0.00 -32.14 34.50 +138.00 15320.50 12.27 0.40 1.30 13.67 10.89 1.50 0.00 0.00 0.25 1.22 0.30 -1.00 0.00 0.00 -38.86 216.50 +139.00 15323.60 8.90 3.60 1.10 28.91 11.33 -1.52 255.00 0.00 3.41 1.53 1.00 -1.00 0.00 0.00 -2.09 66.00 +140.00 15393.00 7.83 7.70 2.00 37.65 10.96 1.32 0.00 0.00 6.28 1.66 0.40 -1.00 0.00 0.00 -1.00 33.00 +141.00 15448.30 6.37 2.50 1.40 14.04 10.06 -1.67 0.00 0.00 2.35 1.49 0.40 -1.00 0.00 0.00 -2.16 88.30 +142.00 15463.50 16.21 0.80 1.60 24.61 9.56 0.40 0.00 0.00 0.60 1.51 0.60 -1.00 0.00 0.00 -21.44 103.50 +143.00 15478.20 46.36 1.90 3.10 119.60 9.45 -0.18 0.00 0.00 0.54 2.31 0.90 -1.00 0.00 0.00 -68.44 118.20 +144.00 15490.60 19.50 13.50 8.50 284.36 8.08 0.79 255.00 0.00 13.35 3.66 1.00 -1.00 0.00 0.00 -1.17 28.20 +145.00 15649.90 8.18 0.40 2.70 16.69 9.61 -0.13 0.00 0.00 0.27 2.31 0.30 -1.00 0.00 0.00 -24.50 33.90 +146.00 15759.20 14.31 1.10 1.90 24.97 10.41 0.87 0.00 0.00 0.44 1.98 0.50 -1.00 0.00 0.00 -26.29 15.20 +147.00 15775.60 9.67 0.70 1.60 15.31 8.15 -0.28 0.00 0.00 0.57 1.71 0.60 -1.00 0.00 0.00 -13.59 31.60 +148.00 15782.20 6.49 7.30 1.70 36.58 8.28 0.64 255.00 0.00 2.00 1.14 0.30 -1.00 0.00 0.00 -2.60 12.60 +149.00 15879.60 10.66 2.60 9.10 117.24 11.42 -0.59 0.00 0.00 2.40 9.56 1.80 -1.00 0.00 0.00 -3.55 7.60 +150.00 15882.10 23.86 5.10 4.70 103.47 11.22 0.53 255.00 0.00 4.43 2.88 0.60 -1.00 0.00 0.00 -4.31 10.10 +151.00 15969.20 13.52 0.90 2.10 22.30 9.14 -0.96 0.00 0.00 0.61 1.44 0.50 -1.00 0.00 0.00 -17.75 97.20 +152.00 16217.30 17.80 1.20 1.90 28.28 11.14 -0.18 0.00 0.00 0.56 1.56 0.60 -1.00 0.00 0.00 -25.46 89.30 +153.00 16269.70 6.58 1.10 1.00 5.80 9.61 0.68 0.00 0.00 0.55 0.61 0.30 -1.00 0.00 0.00 -9.52 13.70 +154.00 16419.50 6.60 1.00 2.30 12.92 11.73 0.24 0.00 0.00 0.76 1.41 0.70 -1.00 0.00 0.00 -6.92 35.50 +155.00 16585.40 6.62 1.80 0.80 10.13 9.81 0.43 0.00 0.00 1.59 1.11 0.50 -1.00 0.00 0.00 -3.34 73.40 +156.00 16602.70 8.87 1.90 1.50 15.60 9.99 0.21 0.00 0.00 1.13 1.58 1.00 -1.00 0.00 0.00 -6.28 90.70 +157.00 16684.60 7.32 0.70 3.70 18.19 11.66 0.46 0.00 0.00 0.47 1.64 0.30 -1.00 0.00 0.00 -12.53 44.60 +158.00 17067.80 10.83 0.80 1.70 15.96 11.87 -1.03 0.00 0.00 0.52 1.47 0.60 -1.00 0.00 0.00 -16.78 43.80 +159.00 17725.60 6.55 1.00 1.50 9.91 12.32 -0.01 0.00 0.00 0.87 1.42 0.60 -1.00 0.00 0.00 -5.99 61.60 +160.00 17895.10 13.40 3.70 2.10 34.76 13.04 1.60 0.00 0.00 2.66 2.60 0.70 -1.00 0.00 0.00 -4.03 26.30 +161.00 17978.10 9.20 0.80 1.50 13.22 11.51 0.24 0.00 0.00 0.54 1.42 0.50 -1.00 0.00 0.00 -13.54 58.10 +162.00 18027.60 24.14 1.60 1.60 50.70 10.19 -0.06 0.00 0.00 1.33 2.20 1.30 -1.00 0.00 0.00 -14.54 107.60 +163.00 18053.20 6.48 1.70 0.60 6.93 9.61 2.37 0.00 0.00 1.37 0.68 0.40 -1.00 0.00 0.00 -3.79 5.20 +164.00 18144.00 15.40 1.70 1.40 25.64 11.10 0.35 0.00 0.00 0.43 1.64 0.80 -1.00 0.00 0.00 -28.77 96.00 +165.00 18240.40 25.80 0.90 2.40 51.64 11.07 0.20 0.00 0.00 0.46 1.94 0.60 -1.00 0.00 0.00 -45.33 64.40 +166.00 18246.90 10.53 11.00 5.40 109.68 11.41 -0.02 255.00 0.00 1.11 1.72 0.50 -1.00 0.00 0.00 -7.59 19.70 +167.00 18493.30 6.49 2.60 1.30 11.30 12.38 -1.07 0.00 0.00 2.37 1.29 0.40 -1.00 0.00 0.00 -2.19 61.30 +168.00 18524.10 7.61 1.10 1.50 12.10 12.05 -0.95 0.00 0.00 0.94 1.39 0.50 -1.00 0.00 0.00 -6.48 92.10 +169.00 18549.90 10.96 0.90 1.90 17.46 11.66 1.64 0.00 0.00 0.65 1.72 0.70 -1.00 0.00 0.00 -13.56 15.50 +170.00 18725.10 24.82 1.10 3.70 75.15 9.92 1.07 0.00 0.00 0.41 2.62 0.90 -1.00 0.00 0.00 -48.89 62.70 +171.00 18755.20 10.63 0.80 1.90 16.46 8.04 -0.03 0.00 0.00 0.53 1.32 0.40 -1.00 0.00 0.00 -16.09 92.80 +172.00 18809.30 18.21 0.90 4.20 57.27 8.77 1.00 0.00 0.00 0.50 3.18 0.60 -1.00 0.00 0.00 -29.37 18.90 +173.00 18870.20 14.89 0.70 1.40 18.91 10.00 -2.65 0.00 0.00 0.44 1.09 0.50 -1.00 0.00 0.00 -27.07 79.80 +174.00 18936.30 7.90 1.90 2.30 20.77 11.71 0.27 0.00 0.00 1.68 1.95 1.50 -1.00 0.00 0.00 -3.77 17.90 +175.00 19244.40 16.58 1.00 2.50 33.55 11.17 0.43 0.00 0.00 0.52 1.96 0.40 -1.00 0.00 0.00 -25.42 70.00 +176.00 19386.40 6.91 1.70 1.30 9.84 12.59 1.67 0.00 0.00 1.47 0.73 0.30 -1.00 0.00 0.00 -3.77 84.00 +177.00 19442.50 19.08 0.80 3.00 43.88 11.99 1.68 0.00 0.00 0.46 2.02 0.50 -1.00 0.00 0.00 -33.16 12.10 +178.00 19454.50 14.22 0.60 1.90 23.41 10.14 -0.50 0.00 0.00 0.37 2.06 0.40 -1.00 0.00 0.00 -30.62 24.10 +179.00 19549.40 7.10 1.20 6.80 34.81 11.86 -0.03 0.00 0.00 1.01 1.38 0.90 -1.00 0.00 0.00 -5.63 119.00 +180.00 19742.10 6.11 1.00 0.90 5.24 10.79 1.65 0.00 0.00 0.83 0.53 0.30 -1.00 0.00 0.00 -5.91 55.70 +181.00 19749.90 19.36 1.10 2.50 40.69 8.65 2.02 0.00 0.00 0.73 2.13 0.70 -1.00 0.00 0.00 -21.31 63.50 +182.00 19770.30 6.37 1.50 0.40 7.25 8.00 0.60 0.00 0.00 1.36 0.66 0.40 -1.00 0.00 0.00 -3.75 83.90 +183.00 19781.00 6.22 1.30 0.60 6.43 8.07 0.42 0.00 0.00 1.15 0.57 0.20 -1.00 0.00 0.00 -4.33 94.60 +184.00 19918.90 9.28 1.60 2.90 22.57 11.29 -0.13 0.00 0.00 0.56 1.44 0.40 -1.00 0.00 0.00 -13.23 78.90 +185.00 19930.70 15.61 1.00 1.80 25.68 8.79 -0.07 0.00 0.00 0.51 1.90 0.50 -1.00 0.00 0.00 -24.41 116.30 +186.00 19943.90 10.53 0.80 1.60 17.89 8.99 -1.36 0.00 0.00 0.58 1.88 0.50 -1.00 0.00 0.00 -14.64 1.50 +187.00 19946.80 6.75 3.70 1.30 24.18 7.91 -1.68 255.00 0.00 3.57 0.88 0.40 -1.00 0.00 0.00 -1.51 81.20 +188.00 19955.50 9.34 1.60 1.50 18.57 9.13 0.10 0.00 0.00 1.39 2.24 1.10 -1.00 0.00 0.00 -5.38 13.10 +189.00 20048.50 15.66 0.90 2.70 31.56 9.16 1.31 0.00 0.00 0.62 2.01 0.50 -1.00 0.00 0.00 -20.32 106.10 +190.00 20163.60 6.94 2.10 1.10 12.67 10.80 0.95 0.00 0.00 1.90 1.75 0.90 -1.00 0.00 0.00 -2.91 93.20 +191.00 20348.10 8.63 0.80 1.50 12.00 9.66 -0.34 0.00 0.00 0.50 1.35 0.60 -1.00 0.00 0.00 -13.83 21.70 +192.00 20463.60 17.05 0.80 2.90 42.37 12.39 -0.83 0.00 0.00 0.49 3.13 0.50 -1.00 0.00 0.00 -27.61 9.20 +193.00 20725.10 11.60 1.60 2.20 24.08 10.94 0.79 0.00 0.00 1.38 1.60 1.20 -1.00 0.00 0.00 -6.71 14.70 +194.00 20949.40 6.36 1.60 1.20 8.82 10.76 -0.87 0.00 0.00 1.10 0.99 0.80 -1.00 0.00 0.00 -4.64 85.40 +195.00 21119.60 15.06 0.90 3.90 44.04 11.49 -0.49 0.00 0.00 0.59 2.36 0.60 -1.00 0.00 0.00 -20.53 25.20 +196.00 21142.00 21.24 3.20 1.70 39.19 8.16 0.26 0.00 0.00 0.69 1.65 0.60 -1.00 0.00 0.00 -24.73 47.60 +197.00 21160.30 13.21 0.90 2.70 31.38 8.47 0.65 0.00 0.00 0.36 2.43 0.40 -1.00 0.00 0.00 -29.35 65.90 +198.00 21167.80 11.83 4.00 2.30 31.32 7.51 1.05 255.00 0.00 1.74 2.05 0.50 -1.00 0.00 0.00 -5.43 73.40 +199.00 21177.10 16.25 1.00 2.30 31.64 7.13 -0.03 0.00 0.00 0.71 1.46 0.70 -1.00 0.00 0.00 -18.19 82.70 +200.00 21180.80 12.57 7.90 1.40 66.60 9.70 -0.36 255.00 0.00 4.73 1.59 0.50 -1.00 0.00 0.00 -2.13 86.40 +201.00 21209.30 8.66 0.90 2.10 15.18 8.27 -1.11 0.00 0.00 0.75 1.72 0.30 -1.00 0.00 0.00 -9.29 114.90 +202.00 21564.20 6.07 2.20 1.10 9.03 9.57 -0.46 0.00 0.00 1.85 0.95 0.30 -1.00 0.00 0.00 -2.63 85.80 +203.00 21689.00 8.02 0.50 2.50 16.80 10.58 -0.66 0.00 0.00 0.39 2.30 0.30 -1.00 0.00 0.00 -16.62 82.60 +204.00 21710.00 8.59 6.40 1.70 31.07 10.62 0.05 0.00 0.00 6.24 1.86 0.80 -1.00 0.00 0.00 -1.10 1.20 +205.00 21746.20 9.46 2.20 3.20 27.63 11.67 2.60 0.00 0.00 0.91 1.82 1.00 -1.00 0.00 0.00 -8.32 11.80 +206.00 21806.90 11.74 0.60 1.80 17.01 10.87 0.17 0.00 0.00 0.38 1.21 0.30 -1.00 0.00 0.00 -24.97 72.50 +207.00 21930.80 7.14 2.90 1.50 16.76 11.23 -2.98 0.00 0.00 2.44 0.99 0.20 -1.00 0.00 0.00 -2.34 68.40 +208.00 22102.20 14.37 1.00 2.50 31.27 11.68 -0.60 0.00 0.00 0.65 2.26 0.70 -1.00 0.00 0.00 -17.70 111.80 +209.00 22199.70 6.47 1.50 0.30 6.53 11.59 -0.86 0.00 0.00 1.25 0.99 0.90 -1.00 0.00 0.00 -4.13 81.30 +210.00 22325.50 9.67 5.00 3.10 36.44 12.41 -0.51 255.00 0.00 3.32 1.70 0.80 -1.00 0.00 0.00 -2.33 2.30 +211.00 22407.60 9.74 1.60 1.60 15.96 12.13 0.80 0.00 0.00 1.03 1.21 0.60 -1.00 0.00 0.00 -7.58 33.20 +212.00 22622.50 9.51 0.70 2.40 17.74 11.54 -0.13 0.00 0.00 0.50 1.68 0.60 -1.00 0.00 0.00 -15.18 120.10 +213.00 22733.60 13.86 1.20 2.50 30.52 11.78 0.42 0.00 0.00 0.73 1.86 0.80 -1.00 0.00 0.00 -15.28 103.20 +214.00 22855.30 12.96 1.60 2.10 24.90 11.62 -1.90 0.00 0.00 0.59 1.84 0.60 -1.00 0.00 0.00 -17.67 96.90 +215.00 22896.30 17.37 1.20 3.20 44.54 13.42 -0.06 0.00 0.00 0.44 2.75 0.30 -1.00 0.00 0.00 -31.88 9.90 +216.00 22904.80 11.37 1.30 18.50 195.06 11.98 -0.91 0.00 0.00 1.14 2.33 1.00 -1.00 0.00 0.00 -7.97 120.80 +217.00 22907.50 16.26 4.00 2.90 63.18 10.92 0.47 255.00 0.00 3.29 2.43 1.00 -1.00 0.00 0.00 -3.95 72.30 +218.00 22912.30 26.36 8.80 3.10 135.55 11.19 1.38 255.00 0.00 8.43 2.68 0.50 -1.00 0.00 0.00 -2.50 77.10 +219.00 23126.30 6.50 1.10 0.80 5.33 10.81 0.72 0.00 0.00 0.98 0.40 0.30 -1.00 0.00 0.00 -5.32 111.90 +220.00 23242.00 6.79 1.70 1.60 13.15 11.48 -0.70 0.00 0.00 1.52 1.13 1.00 -1.00 0.00 0.00 -3.57 74.00 +221.00 23326.20 16.93 1.00 4.60 52.84 10.30 -1.97 0.00 0.00 0.36 2.09 0.80 -1.00 0.00 0.00 -37.38 55.80 +222.00 23371.30 21.07 3.40 4.40 65.74 9.50 -0.49 0.00 0.00 0.48 1.43 0.50 -1.00 0.00 0.00 -35.26 100.90 +223.00 23390.60 9.75 1.30 2.10 19.70 7.48 0.88 0.00 0.00 0.85 2.28 0.70 -1.00 0.00 0.00 -9.14 17.80 +224.00 23395.30 7.91 1.60 2.10 16.20 7.40 -0.87 255.00 0.00 1.49 0.93 0.20 -1.00 0.00 0.00 -4.24 48.10 +225.00 23400.90 24.94 0.80 2.50 51.07 3.65 1.08 255.00 0.00 0.34 2.35 0.40 -1.00 0.00 0.00 -58.08 28.10 +226.00 23556.70 12.21 0.90 1.80 17.98 11.64 0.01 0.00 0.00 0.54 1.41 0.30 -1.00 0.00 0.00 -18.06 55.90 +227.00 23626.10 21.52 0.50 3.30 50.16 10.32 1.05 0.00 0.00 0.33 2.28 0.40 -1.00 0.00 0.00 -51.42 125.30 +228.00 23642.20 8.50 0.80 4.00 22.97 9.05 0.59 0.00 0.00 0.60 1.40 0.60 -1.00 0.00 0.00 -11.32 13.40 +229.00 23670.90 8.88 0.70 3.00 17.85 10.97 0.74 0.00 0.00 0.45 1.13 0.30 -1.00 0.00 0.00 -15.67 42.10 +230.00 23802.70 19.59 1.10 3.20 47.43 11.17 -2.79 0.00 0.00 0.47 1.82 0.80 -1.00 0.00 0.00 -33.66 45.90 +231.00 23877.80 8.38 1.60 1.60 13.82 11.11 0.65 0.00 0.00 0.76 1.72 0.80 -1.00 0.00 0.00 -8.80 121.00 +232.00 23923.30 10.01 1.60 1.90 21.28 10.81 1.69 0.00 0.00 1.46 2.22 1.40 -1.00 0.00 0.00 -5.49 38.50 +233.00 24064.90 9.34 1.20 1.30 11.20 11.24 -0.25 0.00 0.00 0.62 1.17 0.50 -1.00 0.00 0.00 -12.12 52.10 +234.00 24185.20 10.42 0.60 2.00 16.71 11.86 1.16 0.00 0.00 0.49 1.35 0.40 -1.00 0.00 0.00 -16.89 44.40 +235.00 24202.20 12.29 0.80 2.20 24.02 10.26 0.29 0.00 0.00 0.49 2.13 0.40 -1.00 0.00 0.00 -20.06 61.40 +236.00 24244.20 15.04 1.10 2.80 34.55 10.56 0.32 0.00 0.00 0.43 1.77 0.50 -1.00 0.00 0.00 -28.25 103.40 +237.00 24269.20 9.02 0.50 2.20 13.99 10.72 0.81 0.00 0.00 0.30 1.11 0.30 -1.00 0.00 0.00 -23.88 128.40 +238.00 24317.00 15.87 0.90 2.60 31.14 8.97 0.01 0.00 0.00 0.48 1.69 0.60 -1.00 0.00 0.00 -26.58 48.20 +239.00 24567.20 8.09 1.10 1.10 9.50 11.26 0.43 0.00 0.00 0.91 1.00 0.60 -1.00 0.00 0.00 -7.10 42.40 +240.00 24586.30 11.14 0.80 1.40 13.74 9.44 -0.74 0.00 0.00 0.52 1.51 0.50 -1.00 0.00 0.00 -17.20 61.50 +241.00 25310.20 6.16 1.20 0.70 6.23 10.85 1.24 0.00 0.00 1.07 1.17 0.70 -1.00 0.00 0.00 -4.60 17.40 +242.00 25408.80 6.07 1.90 1.00 9.23 10.35 1.00 0.00 0.00 1.55 1.25 0.50 -1.00 0.00 0.00 -3.13 116.00 +243.00 25417.50 8.38 1.00 3.30 23.53 11.42 0.13 0.00 0.00 0.84 3.72 0.80 -1.00 0.00 0.00 -7.97 124.70 +244.00 25429.00 8.40 1.00 1.20 12.28 10.62 0.46 0.00 0.00 0.81 1.71 0.70 -1.00 0.00 0.00 -8.29 8.20 +245.00 25615.10 15.17 0.90 3.00 36.93 10.26 2.51 0.00 0.00 0.63 2.09 0.70 -1.00 0.00 0.00 -19.27 66.30 +246.00 25715.50 19.57 0.90 1.90 38.08 11.79 -1.22 0.00 0.00 0.48 2.07 0.60 -1.00 0.00 0.00 -32.83 38.70 +247.00 25725.10 7.49 1.00 1.20 9.12 9.00 -2.16 255.00 0.00 0.61 1.25 0.60 -1.00 0.00 0.00 -9.75 125.10 +248.00 25800.70 12.39 2.00 3.50 35.91 11.03 0.35 0.00 0.00 1.17 2.22 1.10 -1.00 0.00 0.00 -8.46 123.90 +249.00 26417.80 13.80 0.60 1.80 21.06 10.03 0.53 0.00 0.00 0.51 1.37 0.40 -1.00 0.00 0.00 -21.67 101.00 +250.00 26451.40 11.81 1.60 3.90 37.14 9.17 -0.38 0.00 0.00 1.03 1.99 1.00 -1.00 0.00 0.00 -9.15 6.60 +251.00 26453.90 11.74 6.40 3.50 64.51 11.34 -1.03 255.00 0.00 4.05 4.87 3.50 -1.00 0.00 0.00 -2.32 85.90 +252.00 26542.20 6.82 1.50 0.40 7.46 7.31 -0.54 0.00 0.00 1.34 1.27 1.00 -1.00 0.00 0.00 -4.08 97.40 +253.00 26545.60 6.35 1.20 0.70 6.29 8.07 -0.78 0.00 0.00 0.89 1.12 0.80 -1.00 0.00 0.00 -5.69 75.20 +254.00 26570.90 7.38 1.40 1.00 9.24 9.66 -0.80 0.00 0.00 1.12 0.70 0.30 -1.00 0.00 0.00 -5.28 126.10 +255.00 26578.60 8.92 1.30 2.30 19.66 9.82 0.74 0.00 0.00 0.75 2.63 0.60 -1.00 0.00 0.00 -9.58 5.80 +256.00 26580.30 7.88 2.90 0.50 17.05 9.13 -0.80 255.00 0.00 2.49 2.61 2.30 -1.00 0.00 0.00 -2.53 84.30 +257.00 26745.90 13.32 0.60 3.60 37.53 11.36 -0.80 0.00 0.00 0.34 3.76 0.50 -1.00 0.00 0.00 -31.53 45.10 +258.00 26812.70 6.13 1.30 0.60 5.56 9.54 -1.13 0.00 0.00 0.88 0.74 0.40 -1.00 0.00 0.00 -5.56 86.30 +259.00 26870.60 7.89 1.30 1.60 12.31 11.38 1.15 0.00 0.00 0.87 1.55 0.70 -1.00 0.00 0.00 -7.24 41.80 +260.00 27146.10 6.35 2.00 0.40 7.15 12.23 1.65 0.00 0.00 1.91 0.41 0.20 -1.00 0.00 0.00 -2.66 61.30 +261.00 27176.30 7.11 1.00 1.80 11.29 12.17 -0.89 0.00 0.00 0.83 1.32 0.50 -1.00 0.00 0.00 -6.84 91.50 +262.00 27292.30 13.78 0.60 1.90 20.82 10.80 -1.40 0.00 0.00 0.41 1.49 0.40 -1.00 0.00 0.00 -27.01 79.50 +263.00 27374.80 12.18 1.60 3.00 34.45 10.16 0.05 0.00 0.00 1.41 2.40 0.40 -1.00 0.00 0.00 -6.92 34.00 +264.00 27458.00 15.30 0.90 1.40 23.20 7.18 0.33 0.00 0.00 0.31 1.61 0.70 -1.00 0.00 0.00 -39.59 117.20 +265.00 27532.90 7.75 2.10 1.90 15.71 9.09 0.25 0.00 0.00 1.92 1.60 0.50 -1.00 0.00 0.00 -3.23 64.10 +266.00 27551.60 6.51 2.20 4.10 21.79 10.25 -0.16 0.00 0.00 2.05 1.01 0.30 -1.00 0.00 0.00 -2.54 57.20 +267.00 27672.10 6.08 1.00 1.80 9.29 10.14 -0.52 0.00 0.00 0.75 1.50 0.40 -1.00 0.00 0.00 -6.47 75.30 +268.00 28151.20 11.12 2.00 1.30 19.76 10.08 0.24 0.00 0.00 0.96 1.79 0.70 -1.00 0.00 0.00 -9.27 16.80 +269.00 28285.20 6.80 2.60 1.50 13.90 11.92 0.10 0.00 0.00 1.58 2.33 1.10 -1.00 0.00 0.00 -3.45 48.40 +270.00 28423.00 9.56 3.00 1.80 20.25 10.61 -0.42 0.00 0.00 2.10 1.25 0.50 -1.00 0.00 0.00 -3.64 58.20 +271.00 28663.10 16.06 1.40 1.20 20.36 10.16 -0.88 0.00 0.00 1.05 1.30 0.50 -1.00 0.00 0.00 -12.29 42.30 +272.00 28666.40 6.92 1.70 1.80 12.78 8.90 0.39 255.00 0.00 1.58 1.45 0.60 -1.00 0.00 0.00 -3.51 122.40 +273.00 28694.10 6.29 1.10 0.50 5.01 13.01 0.29 0.00 0.00 0.93 0.50 0.20 -1.00 0.00 0.00 -5.38 73.30 +274.00 28762.00 6.12 0.50 1.60 9.02 10.51 0.15 0.00 0.00 0.39 1.82 0.40 -1.00 0.00 0.00 -12.40 13.20 +275.00 28811.00 6.44 3.20 1.00 11.57 10.54 0.16 0.00 0.00 2.30 1.08 0.20 -1.00 0.00 0.00 -2.24 62.20 +276.00 28969.60 14.92 1.40 1.40 26.91 10.31 -0.35 0.00 0.00 0.48 1.96 1.10 -1.00 0.00 0.00 -24.94 92.80 +277.00 28991.50 15.73 1.50 1.70 33.57 7.85 1.51 0.00 0.00 1.11 2.49 1.30 -1.00 0.00 0.00 -11.35 114.70 +278.00 29189.00 9.67 1.30 3.20 24.75 11.02 0.67 0.00 0.00 1.10 1.46 0.70 -1.00 0.00 0.00 -7.01 56.20 +279.00 29245.30 12.46 2.80 1.70 32.90 11.51 0.23 0.00 0.00 1.94 2.71 1.60 -1.00 0.00 0.00 -5.13 112.50 +280.00 29603.80 17.15 0.70 2.50 35.61 11.50 -0.36 0.00 0.00 0.42 1.95 0.40 -1.00 0.00 0.00 -32.43 87.00 +281.00 29712.30 8.83 1.30 1.70 13.38 11.19 -0.42 0.00 0.00 0.69 1.36 0.30 -1.00 0.00 0.00 -10.17 67.50 +282.00 29843.00 20.52 1.00 2.80 47.30 11.62 -0.20 0.00 0.00 0.42 2.32 0.60 -1.00 0.00 0.00 -39.51 70.20 +283.00 29991.10 6.41 1.80 1.30 11.53 10.43 0.63 0.00 0.00 1.56 1.09 0.50 -1.00 0.00 0.00 -3.28 90.30 +284.00 30167.40 11.17 1.80 2.00 25.27 10.86 -1.91 0.00 0.00 1.67 2.49 1.30 -1.00 0.00 0.00 -5.36 10.60 +285.00 30268.10 7.71 6.70 0.80 24.39 10.81 0.98 0.00 0.00 5.25 1.12 0.80 -1.00 0.00 0.00 -1.18 60.10 +286.00 30436.30 19.77 1.20 3.10 53.12 10.49 0.21 0.00 0.00 0.91 2.20 1.00 -1.00 0.00 0.00 -17.39 23.50 +287.00 30508.00 12.21 1.40 2.50 22.88 10.19 -0.80 0.00 0.00 0.65 1.12 0.50 -1.00 0.00 0.00 -14.99 95.20 +288.00 30560.10 9.87 0.80 3.60 25.77 10.34 1.87 0.00 0.00 0.65 2.63 0.30 -1.00 0.00 0.00 -12.13 19.30 +289.00 30572.30 8.79 0.60 2.40 15.53 8.00 0.37 0.00 0.00 0.41 1.21 0.40 -1.00 0.00 0.00 -17.28 31.50 +290.00 30617.90 9.03 1.30 1.30 12.74 11.19 -1.97 0.00 0.00 0.94 1.14 0.50 -1.00 0.00 0.00 -7.66 77.10 +291.00 30657.00 18.06 1.90 4.60 76.15 12.55 0.01 0.00 0.00 0.99 4.66 1.10 -1.00 0.00 0.00 -14.61 116.20 +292.00 30779.50 14.13 0.90 3.30 32.69 11.63 -1.28 0.00 0.00 0.58 2.04 0.60 -1.00 0.00 0.00 -19.43 110.70 +293.00 30824.10 18.23 0.70 2.00 29.13 11.08 -1.34 0.00 0.00 0.35 1.36 0.50 -1.00 0.00 0.00 -41.74 27.30 +294.00 30831.60 20.76 8.30 2.30 98.04 11.45 0.20 255.00 0.00 7.86 2.16 0.70 -1.00 0.00 0.00 -2.11 111.60 +295.00 30951.70 7.76 0.60 1.00 8.07 10.28 -2.73 0.00 0.00 0.43 1.09 0.50 -1.00 0.00 0.00 -14.49 26.90 +296.00 30976.90 14.89 1.30 2.50 30.34 11.52 -1.18 0.00 0.00 0.75 1.67 0.70 -1.00 0.00 0.00 -15.81 52.10 +297.00 30984.90 11.00 9.10 1.80 69.74 11.08 -0.23 255.00 0.00 8.84 2.11 0.90 -1.00 0.00 0.00 -1.00 8.90 +298.00 31129.60 14.46 1.20 2.80 31.10 12.21 -0.64 0.00 0.00 0.36 1.86 0.40 -1.00 0.00 0.00 -32.35 76.80 +299.00 31155.10 8.77 1.60 0.80 9.75 10.79 -0.74 0.00 0.00 1.24 0.90 0.60 -1.00 0.00 0.00 -5.64 102.30 +300.00 31286.80 6.35 3.20 2.30 18.65 9.60 -0.34 0.00 0.00 2.42 1.86 1.10 -1.00 0.00 0.00 -2.10 54.80 +301.00 31383.00 28.78 0.90 4.90 97.82 10.18 0.06 0.00 0.00 0.67 1.80 0.70 -1.00 0.00 0.00 -34.20 23.00 +302.00 31390.10 18.88 11.80 6.30 217.40 13.09 -0.96 255.00 0.00 8.44 3.18 0.90 -1.00 0.00 0.00 -1.79 30.10 +303.00 31516.40 16.72 1.00 5.80 70.55 9.31 2.29 0.00 0.00 0.52 4.41 0.80 -1.00 0.00 0.00 -25.96 79.60 +304.00 31689.30 6.40 3.50 1.20 11.02 10.81 0.72 0.00 0.00 2.07 0.44 0.30 -1.00 0.00 0.00 -2.47 124.50 +305.00 31738.40 19.76 0.80 4.10 59.44 11.46 -0.80 0.00 0.00 0.50 3.50 0.50 -1.00 0.00 0.00 -31.45 45.60 +306.00 31783.60 26.43 0.70 2.10 45.81 10.26 0.07 0.00 0.00 0.50 1.80 0.50 -1.00 0.00 0.00 -42.34 90.80 +307.00 31987.60 8.08 0.60 3.10 18.72 9.10 -1.55 0.00 0.00 0.42 1.63 0.30 -1.00 0.00 0.00 -15.55 38.80 +308.00 32072.00 9.10 1.70 5.20 44.15 11.47 -1.17 255.00 0.00 1.44 3.22 0.70 -1.00 0.00 0.00 -5.07 97.60 +309.00 32073.30 13.82 3.00 3.80 49.09 12.23 -0.97 0.00 0.00 2.72 1.81 0.70 -1.00 0.00 0.00 -4.07 73.30 +310.00 32155.40 14.04 0.80 1.80 22.94 11.36 -0.22 0.00 0.00 0.55 1.47 0.60 -1.00 0.00 0.00 -20.61 78.60 +311.00 32267.10 9.52 0.80 4.10 29.43 11.39 0.95 0.00 0.00 0.34 3.11 0.20 -1.00 0.00 0.00 -22.63 62.30 +312.00 32356.40 17.16 0.80 2.10 29.68 11.17 -1.18 0.00 0.00 0.45 1.86 0.40 -1.00 0.00 0.00 -30.38 23.60 +313.00 32469.10 6.20 1.50 1.00 9.77 10.61 1.86 0.00 0.00 1.28 1.47 0.70 -1.00 0.00 0.00 -3.87 85.10 +314.00 32608.10 11.30 0.80 2.30 19.75 11.74 0.12 0.00 0.00 0.49 1.58 0.60 -1.00 0.00 0.00 -18.54 19.30 +315.00 32687.50 11.82 0.60 2.50 20.81 10.79 -0.94 0.00 0.00 0.33 1.58 0.50 -1.00 0.00 0.00 -28.60 98.70 +316.00 33050.50 7.45 0.70 1.70 9.40 10.81 0.10 0.00 0.00 0.52 0.64 0.50 -1.00 0.00 0.00 -11.40 77.70 +317.00 33165.90 6.60 0.80 1.30 8.63 11.03 1.00 0.00 0.00 0.62 1.44 0.30 -1.00 0.00 0.00 -8.50 65.10 +318.00 33206.40 10.72 0.80 2.90 25.12 11.04 -0.70 0.00 0.00 0.53 2.97 0.40 -1.00 0.00 0.00 -16.28 105.60 +319.00 33510.90 16.43 0.90 2.00 30.79 11.50 0.45 0.00 0.00 0.59 1.81 0.60 -1.00 0.00 0.00 -22.35 26.10 +320.00 33592.20 6.12 2.50 0.80 12.65 12.52 -0.25 0.00 0.00 1.74 2.27 1.70 -1.00 0.00 0.00 -2.81 56.20 +321.00 33645.70 6.14 2.30 1.20 9.82 12.16 -2.83 0.00 0.00 1.14 0.93 0.40 -1.00 0.00 0.00 -4.31 32.90 +322.00 33701.20 7.09 2.90 1.80 14.22 11.85 -1.84 0.00 0.00 1.90 1.39 0.40 -1.00 0.00 0.00 -2.99 88.40 +323.00 33752.30 12.94 0.60 1.70 18.60 10.48 -0.09 0.00 0.00 0.44 1.27 0.30 -1.00 0.00 0.00 -23.38 11.50 +324.00 33974.10 6.46 1.30 1.80 10.40 9.85 0.58 0.00 0.00 1.14 0.94 0.20 -1.00 0.00 0.00 -4.53 105.30 +325.00 34023.20 26.30 1.20 4.40 82.97 11.94 -1.10 0.00 0.00 0.64 2.66 0.70 -1.00 0.00 0.00 -32.80 26.40 +326.00 34129.90 12.45 0.80 2.30 23.61 9.69 -1.11 0.00 0.00 0.62 1.74 0.50 -1.00 0.00 0.00 -15.97 5.10 +327.00 34152.40 24.19 0.80 2.60 52.11 10.22 -0.14 0.00 0.00 0.42 2.21 0.40 -1.00 0.00 0.00 -46.47 27.60 +328.00 34311.90 7.33 7.60 0.60 22.21 11.29 0.10 0.00 0.00 4.15 1.51 1.10 -1.00 0.00 0.00 -1.41 7.90 +329.00 34498.70 31.93 1.00 3.00 74.95 12.06 0.70 0.00 0.00 0.49 2.31 0.60 -1.00 0.00 0.00 -51.65 117.90 +330.00 34539.90 7.74 1.60 0.60 8.77 9.97 -0.53 0.00 0.00 1.19 0.87 0.70 -1.00 0.00 0.00 -5.21 31.10 +331.00 34611.30 6.45 1.70 0.90 10.04 9.76 -2.08 0.00 0.00 1.50 1.53 1.40 -1.00 0.00 0.00 -3.44 51.30 +332.00 34630.80 6.14 1.10 0.50 4.66 8.45 1.72 0.00 0.00 0.94 0.62 0.40 -1.00 0.00 0.00 -5.23 122.00 +333.00 34632.20 9.31 2.60 1.10 16.84 9.03 0.29 255.00 0.00 0.70 1.46 0.60 -1.00 0.00 0.00 -10.67 72.20 +334.00 34700.60 21.80 1.20 7.70 112.68 10.35 -1.08 0.00 0.00 0.44 2.78 0.60 -1.00 0.00 0.00 -39.88 63.80 +335.00 34705.10 16.47 5.60 3.40 111.66 10.11 -0.05 255.00 0.00 4.85 8.00 5.10 -1.00 0.00 0.00 -2.72 17.10 +336.00 34875.50 12.63 0.90 1.60 19.14 11.84 -0.93 0.00 0.00 0.68 1.60 0.60 -1.00 0.00 0.00 -14.80 110.70 +337.00 34879.00 9.42 4.40 1.40 39.54 12.74 -0.75 255.00 0.00 4.20 1.17 0.50 -1.00 0.00 0.00 -1.79 63.00 +338.00 34985.40 12.52 2.60 3.20 34.60 11.70 -0.81 0.00 0.00 0.39 2.13 0.40 -1.00 0.00 0.00 -25.86 92.60 +339.00 35389.70 10.88 3.20 1.70 24.84 12.79 0.32 0.00 0.00 2.56 1.73 0.80 -1.00 0.00 0.00 -3.40 112.90 +340.00 35510.80 7.88 0.90 1.70 12.72 10.44 2.70 0.00 0.00 0.78 1.37 0.60 -1.00 0.00 0.00 -8.09 106.00 +341.00 35553.80 13.21 0.50 1.90 21.82 8.57 -1.35 0.00 0.00 0.29 1.76 0.30 -1.00 0.00 0.00 -37.07 21.00 +342.00 35661.90 13.59 1.10 4.10 40.84 10.70 0.23 0.00 0.00 0.79 2.87 0.40 -1.00 0.00 0.00 -13.71 1.10 +343.00 35690.20 14.93 0.80 3.70 38.86 9.79 -0.16 0.00 0.00 0.58 2.34 0.30 -1.00 0.00 0.00 -20.71 29.40 +344.00 35895.20 6.12 2.20 1.40 11.16 12.11 0.53 0.00 0.00 1.82 1.48 0.80 -1.00 0.00 0.00 -2.69 55.20 +345.00 36050.20 11.88 1.20 2.10 24.12 11.36 1.20 0.00 0.00 0.44 1.61 1.00 -1.00 0.00 0.00 -21.81 5.40 +346.00 36209.70 15.66 0.70 1.80 25.92 11.18 -0.19 0.00 0.00 0.46 1.97 0.50 -1.00 0.00 0.00 -27.46 36.90 +347.00 36283.40 6.11 1.60 0.80 6.86 10.54 1.12 0.00 0.00 1.32 0.77 0.40 -1.00 0.00 0.00 -3.71 110.60 +348.00 36557.00 9.25 0.60 1.80 13.18 9.53 -0.64 0.00 0.00 0.53 0.88 0.40 -1.00 0.00 0.00 -13.89 77.00 +349.00 36568.10 28.59 1.00 2.00 52.76 9.14 0.58 0.00 0.00 0.48 1.77 0.70 -1.00 0.00 0.00 -47.83 11.30 +350.00 36794.10 7.06 0.80 0.40 4.41 11.08 0.55 0.00 0.00 0.69 0.60 0.50 -1.00 0.00 0.00 -8.23 58.10 +351.00 36827.50 12.67 0.50 1.90 19.14 9.23 1.06 0.00 0.00 0.39 1.43 0.30 -1.00 0.00 0.00 -25.96 14.70 +352.00 36837.50 6.48 1.70 2.70 16.32 9.51 0.21 255.00 0.00 1.55 0.95 0.50 -1.00 0.00 0.00 -3.34 101.50 +353.00 36911.70 6.89 3.60 1.50 15.72 10.22 1.57 0.00 0.00 1.45 1.41 0.30 -1.00 0.00 0.00 -3.80 22.10 +354.00 36917.90 7.13 1.20 3.20 18.10 11.12 -0.46 0.00 0.00 0.99 1.02 0.70 -1.00 0.00 0.00 -5.76 53.90 +355.00 37046.60 7.62 1.40 2.60 20.19 11.62 0.39 0.00 0.00 1.11 3.26 1.00 -1.00 0.00 0.00 -5.49 29.00 +356.00 37133.80 33.31 1.30 3.20 86.12 11.56 -0.79 0.00 0.00 0.67 2.52 0.80 -1.00 0.00 0.00 -40.02 116.20 +357.00 37217.10 6.67 3.80 0.90 16.17 10.58 -1.35 0.00 0.00 3.25 1.95 1.40 -1.00 0.00 0.00 -1.64 97.10 +358.00 37322.80 7.09 2.20 2.50 19.02 12.95 -0.13 0.00 0.00 2.05 2.13 0.50 -1.00 0.00 0.00 -2.77 49.20 +359.00 37332.00 6.21 1.10 1.60 9.82 9.57 0.41 0.00 0.00 0.86 1.21 0.80 -1.00 0.00 0.00 -5.77 58.40 +360.00 37568.70 13.85 1.10 3.00 32.15 10.69 -0.26 0.00 0.00 0.33 1.98 0.30 -1.00 0.00 0.00 -33.21 39.10 +361.00 37595.90 11.18 10.40 3.00 68.01 9.32 2.14 255.00 0.00 6.23 2.39 0.70 -1.00 0.00 0.00 -1.44 91.90 +362.00 37618.90 7.14 1.70 0.40 5.76 9.58 0.03 0.00 0.00 0.64 0.51 0.30 -1.00 0.00 0.00 -8.86 89.30 +363.00 37711.70 6.71 4.10 1.50 18.07 11.79 0.93 0.00 0.00 3.69 1.05 0.30 -1.00 0.00 0.00 -1.45 79.70 +364.00 37790.20 6.07 0.70 1.60 8.69 10.39 2.28 0.00 0.00 0.56 1.74 0.40 -1.00 0.00 0.00 -8.66 4.60 +365.00 37849.90 31.42 1.30 3.50 88.78 12.68 -0.24 0.00 0.00 0.81 3.13 0.80 -1.00 0.00 0.00 -30.88 64.30 +366.00 37855.50 12.70 10.00 2.70 146.62 13.34 -0.01 255.00 0.00 6.56 8.73 6.60 -1.00 0.00 0.00 -1.55 95.50 +367.00 38032.50 20.14 1.00 1.90 36.30 10.44 0.23 0.00 0.00 0.61 1.89 0.70 -1.00 0.00 0.00 -26.24 118.90 +368.00 38123.20 7.89 1.70 1.20 10.67 11.44 -1.29 0.00 0.00 0.69 1.11 0.30 -1.00 0.00 0.00 -9.20 81.60 +369.00 38226.80 19.71 1.30 3.10 56.95 12.66 0.20 0.00 0.00 0.97 3.01 0.90 -1.00 0.00 0.00 -16.28 57.20 +370.00 38303.00 10.02 3.60 4.50 46.75 12.17 0.31 0.00 0.00 1.14 5.11 1.00 -1.00 0.00 0.00 -7.03 5.40 +371.00 38306.80 10.22 7.40 0.70 48.71 12.41 0.85 255.00 0.00 4.82 5.13 4.80 -1.00 0.00 0.00 -1.70 34.80 +372.00 38688.60 24.03 0.80 2.00 43.48 12.04 0.18 0.00 0.00 0.61 1.84 0.60 -1.00 0.00 0.00 -31.68 7.00 +373.00 38750.70 8.99 2.30 2.20 21.68 10.59 1.32 0.00 0.00 2.07 2.22 0.40 -1.00 0.00 0.00 -3.48 69.10 +374.00 38978.50 6.25 0.60 0.80 4.53 10.83 0.69 0.00 0.00 0.26 0.59 0.30 -1.00 0.00 0.00 -18.91 40.90 +375.00 39014.10 11.24 0.80 2.40 19.97 11.33 -0.32 0.00 0.00 0.51 1.34 0.50 -1.00 0.00 0.00 -17.57 76.50 +376.00 39043.30 9.02 1.20 1.90 17.11 11.63 1.11 0.00 0.00 0.76 1.62 0.70 -1.00 0.00 0.00 -9.46 105.70 +377.00 39123.50 6.32 2.50 1.70 15.06 11.55 -1.85 0.00 0.00 1.25 2.16 1.20 -1.00 0.00 0.00 -4.05 57.90 +378.00 39174.40 7.23 4.70 1.30 15.52 13.35 -1.32 0.00 0.00 1.44 0.74 0.20 -1.00 0.00 0.00 -4.02 108.80 +379.00 39387.00 7.04 2.50 3.40 22.68 11.98 -0.09 0.00 0.00 1.55 3.30 0.40 -1.00 0.00 0.00 -3.63 65.40 +380.00 39553.30 18.55 0.80 1.80 29.68 10.53 -2.64 0.00 0.00 0.47 1.30 0.50 -1.00 0.00 0.00 -31.81 103.70 +381.00 39586.70 7.47 3.30 1.50 18.14 11.09 1.29 0.00 0.00 3.16 0.62 0.20 -1.00 0.00 0.00 -1.89 9.10 +382.00 39596.80 17.05 1.40 3.30 48.41 11.06 -0.78 0.00 0.00 0.81 2.65 0.80 -1.00 0.00 0.00 -16.83 19.20 +383.00 39629.60 12.24 0.70 2.20 22.16 9.29 0.02 0.00 0.00 0.49 1.34 0.60 -1.00 0.00 0.00 -20.06 52.00 +384.00 39653.50 7.21 4.20 1.90 19.45 11.12 -1.36 0.00 0.00 0.57 1.96 0.20 -1.00 0.00 0.00 -10.17 75.90 +385.00 39705.20 11.11 1.20 1.50 17.41 10.90 -0.35 0.00 0.00 0.88 1.68 0.60 -1.00 0.00 0.00 -10.09 -0.40 +386.00 39711.10 6.26 7.80 0.60 34.46 11.26 -0.15 255.00 0.00 7.03 0.66 0.20 -1.00 0.00 0.00 -0.71 31.10 +387.00 40122.80 11.49 1.40 1.20 18.82 10.78 -0.32 0.00 0.00 0.67 1.84 0.90 -1.00 0.00 0.00 -13.64 33.20 +388.00 40206.70 6.56 1.50 2.10 12.11 11.91 -1.26 0.00 0.00 1.39 0.46 0.20 -1.00 0.00 0.00 -3.78 14.70 +389.00 40636.40 19.36 1.80 3.90 66.69 12.65 -0.97 0.00 0.00 1.33 3.23 1.30 -1.00 0.00 0.00 -11.62 34.80 +390.00 40703.30 7.65 1.10 3.70 22.06 10.15 0.42 0.00 0.00 0.88 2.88 0.80 -1.00 0.00 0.00 -6.92 101.70 +391.00 41039.20 6.29 4.30 2.40 21.99 12.62 -0.97 0.00 0.00 4.14 1.89 0.60 -1.00 0.00 0.00 -1.22 79.20 +392.00 41531.20 30.04 1.80 3.40 83.31 11.92 -1.76 0.00 0.00 0.58 2.44 0.70 -1.00 0.00 0.00 -41.48 33.60 +393.00 41640.30 16.57 0.90 3.40 44.71 9.73 -0.14 0.00 0.00 0.44 2.61 0.70 -1.00 0.00 0.00 -30.04 14.70 +394.00 41729.80 19.16 0.60 7.10 90.48 10.60 -0.89 0.00 0.00 0.35 3.85 0.30 -1.00 0.00 0.00 -43.23 104.20 +395.00 41735.80 13.61 7.10 2.20 109.63 11.95 1.36 255.00 0.00 6.42 7.42 6.40 -1.00 0.00 0.00 -1.70 7.80 +396.00 41778.90 6.98 1.00 2.90 18.12 9.44 0.54 0.00 0.00 0.91 2.43 0.60 -1.00 0.00 0.00 -6.11 25.30 +397.00 41785.90 6.77 9.00 1.10 40.39 11.15 0.20 255.00 0.00 0.71 1.17 0.50 -1.00 0.00 0.00 -7.58 57.90 +398.00 41807.00 13.07 0.70 2.40 21.93 11.02 1.58 0.00 0.00 0.53 1.61 0.50 -1.00 0.00 0.00 -19.62 53.40 +399.00 41862.20 8.16 0.70 1.10 9.40 9.49 1.13 0.00 0.00 0.45 1.39 0.50 -1.00 0.00 0.00 -14.36 108.60 +400.00 41877.00 7.96 3.90 1.90 25.03 9.78 -0.42 0.00 0.00 3.74 2.10 1.00 -1.00 0.00 0.00 -1.70 123.40 +401.00 41992.70 16.15 1.10 1.60 27.05 10.77 0.92 0.00 0.00 0.72 1.77 0.80 -1.00 0.00 0.00 -18.02 111.10 +402.00 42107.90 6.68 2.20 0.80 13.67 12.75 -0.13 0.00 0.00 2.07 2.31 2.00 -1.00 0.00 0.00 -2.58 21.50 +403.00 42142.00 6.34 0.40 1.60 10.20 12.50 -0.23 0.00 0.00 0.31 1.70 0.30 -1.00 0.00 0.00 -16.61 30.00 +404.00 42242.50 6.77 4.60 2.00 20.98 11.23 -0.97 0.00 0.00 4.18 1.55 1.20 -1.00 0.00 0.00 -1.30 104.90 +405.00 42284.00 7.81 3.80 0.80 13.32 11.11 0.04 0.00 0.00 3.45 0.77 0.60 -1.00 0.00 0.00 -1.81 18.40 +406.00 42347.90 6.25 3.10 2.00 15.70 10.74 0.34 0.00 0.00 2.71 0.90 0.60 -1.00 0.00 0.00 -1.85 82.30 +407.00 42539.30 9.00 2.50 4.10 31.18 12.74 -0.39 0.00 0.00 0.57 2.61 0.60 -1.00 0.00 0.00 -12.55 17.70 +408.00 42556.40 17.02 0.90 3.90 48.80 13.01 -0.67 0.00 0.00 0.43 2.30 0.70 -1.00 0.00 0.00 -31.91 34.80 +409.00 42580.40 6.06 1.80 0.90 8.58 12.08 -0.30 0.00 0.00 1.57 1.23 1.20 -1.00 0.00 0.00 -3.08 58.80 +410.00 42752.40 6.49 4.00 1.00 14.36 11.19 2.66 0.00 0.00 0.75 1.20 0.60 -1.00 0.00 0.00 -6.90 102.80 +411.00 42876.40 27.91 1.20 1.90 53.35 11.88 -0.61 0.00 0.00 0.53 2.27 0.90 -1.00 0.00 0.00 -42.47 98.80 +412.00 43107.10 6.20 0.90 0.90 5.82 12.15 -0.83 0.00 0.00 0.73 0.71 0.40 -1.00 0.00 0.00 -6.81 73.50 +413.00 43359.10 17.65 0.90 2.10 37.44 11.53 -0.68 0.00 0.00 0.60 2.15 0.60 -1.00 0.00 0.00 -23.68 18.30 +414.00 43418.60 8.97 1.20 2.00 17.48 10.98 0.57 0.00 0.00 0.96 1.72 0.80 -1.00 0.00 0.00 -7.50 129.00 +415.00 43447.90 19.12 0.90 2.60 44.31 10.54 0.99 0.00 0.00 0.44 2.47 0.70 -1.00 0.00 0.00 -34.92 30.30 +416.00 43635.10 6.55 1.60 1.30 9.61 11.01 2.31 0.00 0.00 1.24 0.55 0.40 -1.00 0.00 0.00 -4.24 89.50 +417.00 43672.50 7.83 6.40 2.60 25.45 12.90 0.63 0.00 0.00 0.68 1.44 0.40 -1.00 0.00 0.00 -9.15 24.50 +418.00 43762.70 10.90 1.30 2.50 27.35 11.83 0.79 0.00 0.00 1.06 1.89 0.90 -1.00 0.00 0.00 -8.26 89.10 +419.00 43891.80 6.07 0.90 3.10 15.62 12.13 -0.29 0.00 0.00 0.52 2.62 0.50 -1.00 0.00 0.00 -9.31 90.20 +420.00 44264.40 9.60 0.80 1.50 13.32 13.00 0.68 0.00 0.00 0.58 1.54 0.60 -1.00 0.00 0.00 -13.22 78.80 +421.00 44343.60 6.33 2.50 0.50 10.15 13.67 -1.39 0.00 0.00 2.40 1.34 1.10 -1.00 0.00 0.00 -2.11 30.00 +422.00 44465.20 14.02 0.90 2.40 30.82 12.08 0.05 0.00 0.00 0.76 2.52 0.70 -1.00 0.00 0.00 -14.69 23.60 +423.00 44650.10 20.94 0.80 4.10 63.64 13.21 0.34 0.00 0.00 0.46 2.53 0.60 -1.00 0.00 0.00 -36.32 80.50 +424.00 45072.10 6.99 1.40 2.40 13.03 11.79 0.23 0.00 0.00 0.91 1.35 0.50 -1.00 0.00 0.00 -6.13 118.50 +425.00 45140.60 22.67 1.00 2.90 49.61 12.01 0.77 0.00 0.00 0.49 1.79 0.50 -1.00 0.00 0.00 -36.90 59.00 +426.00 45638.70 7.27 1.60 0.70 8.17 11.82 -0.30 0.00 0.00 1.23 0.97 0.50 -1.00 0.00 0.00 -4.74 45.10 +427.00 45665.50 6.68 1.10 1.50 9.36 11.57 -0.76 0.00 0.00 0.46 1.28 0.40 -1.00 0.00 0.00 -11.54 71.90 +428.00 45678.00 7.97 1.40 1.60 14.91 10.60 -1.40 0.00 0.00 1.18 2.04 1.20 -1.00 0.00 0.00 -5.39 84.40 +429.00 45901.20 13.35 1.00 1.50 22.24 11.00 1.14 0.00 0.00 0.87 1.71 0.90 -1.00 0.00 0.00 -12.25 51.60 +430.00 45901.30 13.87 1.10 1.40 22.42 11.05 0.08 0.00 0.00 0.90 1.69 1.00 -1.00 0.00 0.00 -12.36 51.70 +431.00 46063.00 11.10 0.90 2.50 22.60 10.99 -1.99 0.00 0.00 0.76 1.90 0.60 -1.00 0.00 0.00 -11.63 85.40 +432.00 46333.60 6.77 2.80 1.10 12.24 13.24 -1.08 0.00 0.00 2.13 0.55 0.40 -1.00 0.00 0.00 -2.54 100.00 +433.00 46463.50 35.48 0.80 2.30 75.07 10.52 0.10 0.00 0.00 0.39 2.26 0.60 -1.00 0.00 0.00 -72.79 101.90 +434.00 46786.10 14.94 0.80 2.50 26.65 11.09 0.58 0.00 0.00 0.44 1.46 0.50 -1.00 0.00 0.00 -27.02 40.50 +435.00 46904.70 7.22 0.90 0.70 7.62 10.08 -1.77 0.00 0.00 0.70 1.09 0.80 -1.00 0.00 0.00 -8.20 31.10 +436.00 46928.20 24.85 0.80 3.70 71.29 10.28 -2.24 0.00 0.00 0.48 2.75 0.50 -1.00 0.00 0.00 -41.09 54.60 +437.00 47121.50 9.80 1.30 2.00 18.79 10.71 0.81 0.00 0.00 1.12 1.90 0.80 -1.00 0.00 0.00 -7.02 119.90 +438.00 47155.60 9.02 3.60 3.30 34.80 11.87 0.96 0.00 0.00 2.55 2.96 0.50 -1.00 0.00 0.00 -2.83 51.60 +439.00 47249.10 8.26 1.40 1.30 12.21 10.28 1.36 0.00 0.00 1.26 1.42 0.40 -1.00 0.00 0.00 -5.23 119.50 +440.00 47312.20 13.22 1.10 3.20 36.61 10.07 2.56 0.00 0.00 0.84 2.92 0.90 -1.00 0.00 0.00 -12.60 54.60 +441.00 47342.50 12.95 1.20 2.20 23.98 10.10 1.34 0.00 0.00 0.65 1.74 0.40 -1.00 0.00 0.00 -16.04 84.90 +442.00 47357.80 13.71 1.20 2.90 34.72 10.48 1.30 0.00 0.00 0.78 2.28 0.70 -1.00 0.00 0.00 -14.01 100.20 +443.00 47389.90 8.15 3.10 1.40 19.50 10.01 0.02 0.00 0.00 2.90 0.85 0.60 -1.00 0.00 0.00 -2.25 4.30 +444.00 47405.90 10.51 2.30 2.90 29.81 9.63 -0.91 0.00 0.00 1.33 2.96 1.20 -1.00 0.00 0.00 -6.34 20.30 +445.00 47430.00 39.24 1.00 2.70 90.85 10.58 0.04 0.00 0.00 0.49 2.53 0.70 -1.00 0.00 0.00 -63.83 44.40 +446.00 47437.40 9.78 8.30 1.90 125.02 9.24 1.39 255.00 0.00 8.02 1.57 0.70 -1.00 0.00 0.00 -0.97 77.40 +447.00 47530.50 7.48 1.30 2.80 18.30 11.04 -0.41 0.00 0.00 1.15 1.13 0.90 -1.00 0.00 0.00 -5.21 16.90 +448.00 47587.00 6.63 1.00 2.50 13.12 11.24 -0.27 0.00 0.00 0.77 0.90 0.60 -1.00 0.00 0.00 -6.88 73.40 +449.00 48062.60 7.03 2.40 1.30 13.24 12.10 0.07 0.00 0.00 2.19 1.49 0.90 -1.00 0.00 0.00 -2.56 62.60 +450.00 48077.10 28.24 1.20 4.30 93.31 10.61 -1.73 0.00 0.00 0.36 3.02 0.80 -1.00 0.00 0.00 -62.29 51.50 +451.00 48193.20 9.75 0.80 3.30 22.97 11.49 -1.00 0.00 0.00 0.67 2.40 0.40 -1.00 0.00 0.00 -11.65 39.60 +452.00 48288.10 15.34 1.50 1.90 27.96 11.91 -0.57 0.00 0.00 0.54 2.16 0.60 -1.00 0.00 0.00 -22.81 6.50 +453.00 48380.80 13.51 1.10 2.50 25.01 11.63 -0.08 0.00 0.00 0.41 1.99 0.40 -1.00 0.00 0.00 -26.46 99.20 +454.00 48524.50 13.79 1.10 2.90 37.03 12.16 -0.10 0.00 0.00 0.96 2.34 1.00 -1.00 0.00 0.00 -11.49 114.90 +455.00 48692.90 26.18 1.00 2.90 60.56 12.02 -0.31 0.00 0.00 0.36 2.07 0.70 -1.00 0.00 0.00 -58.25 27.30 +456.00 48714.80 10.04 2.20 1.80 20.70 8.08 -0.44 255.00 0.00 1.89 1.77 0.40 -1.00 0.00 0.00 -4.25 74.80 +457.00 48764.80 27.87 1.10 2.80 71.57 10.09 1.28 0.00 0.00 0.50 2.52 0.80 -1.00 0.00 0.00 -44.83 99.20 +458.00 49009.80 6.36 2.50 1.20 11.13 10.78 0.54 0.00 0.00 1.54 1.64 0.60 -1.00 0.00 0.00 -3.30 88.20 +459.00 49028.80 6.79 2.20 1.10 10.68 9.81 -0.70 0.00 0.00 1.99 1.22 0.60 -1.00 0.00 0.00 -2.73 107.20 +460.00 49219.10 13.32 0.80 1.60 21.12 9.43 -0.64 0.00 0.00 0.49 1.91 0.60 -1.00 0.00 0.00 -21.98 41.50 +461.00 49374.70 26.15 2.60 8.30 145.82 9.36 1.18 0.00 0.00 0.50 3.50 1.10 -1.00 0.00 0.00 -41.92 69.10 +462.00 49405.00 7.49 0.80 0.80 7.45 5.33 -1.11 255.00 0.00 0.63 1.11 0.60 -1.00 0.00 0.00 -9.51 125.00 +463.00 49457.50 7.19 1.70 0.30 6.37 9.39 -1.07 0.00 0.00 1.56 0.59 0.50 -1.00 0.00 0.00 -3.69 23.90 +464.00 49496.90 11.44 0.60 3.80 27.07 10.15 -0.99 0.00 0.00 0.38 1.55 0.40 -1.00 0.00 0.00 -23.92 63.30 +465.00 49522.00 7.62 2.40 0.90 9.66 8.21 0.24 0.00 0.00 0.37 0.97 0.30 -1.00 0.00 0.00 -16.30 114.00 +466.00 49595.80 26.56 1.00 4.60 84.79 9.70 0.33 0.00 0.00 0.61 3.27 0.60 -1.00 0.00 0.00 -34.91 34.20 +467.00 49753.50 15.36 1.60 1.60 24.69 9.15 -1.35 0.00 0.00 0.55 1.53 0.60 -1.00 0.00 0.00 -22.17 63.90 +468.00 49807.10 6.75 9.70 0.70 36.67 9.45 1.34 0.00 0.00 2.94 0.85 0.30 -1.00 0.00 0.00 -1.84 117.50 +469.00 49880.30 9.66 0.80 2.80 25.34 10.50 1.41 0.00 0.00 0.38 2.82 0.40 -1.00 0.00 0.00 -20.26 62.70 +470.00 49961.00 19.31 0.70 3.10 40.09 10.43 1.05 0.00 0.00 0.43 1.55 0.50 -1.00 0.00 0.00 -36.04 15.40 +471.00 50074.70 6.87 0.90 2.00 11.36 12.17 0.96 0.00 0.00 0.67 1.22 0.70 -1.00 0.00 0.00 -8.22 1.10 +472.00 50107.30 9.41 0.30 2.30 20.45 10.23 -1.33 0.00 0.00 0.19 2.21 0.20 -1.00 0.00 0.00 -40.38 8.10 +473.00 50268.00 21.34 0.90 4.70 73.88 11.39 2.63 0.00 0.00 0.36 3.64 0.60 -1.00 0.00 0.00 -47.65 66.40 +474.00 50305.60 12.40 0.80 2.70 29.84 9.90 0.63 0.00 0.00 0.59 2.65 0.60 -1.00 0.00 0.00 -16.89 104.00 +475.00 50350.10 6.09 1.00 0.50 4.87 7.53 -0.68 0.00 0.00 0.66 0.80 0.50 -1.00 0.00 0.00 -7.36 20.50 +476.00 50585.60 6.33 4.10 4.10 28.45 12.55 -0.14 0.00 0.00 3.62 2.16 1.30 -1.00 0.00 0.00 -1.40 25.60 +477.00 50633.30 9.46 1.10 1.70 16.37 11.24 0.49 0.00 0.00 0.88 1.97 0.70 -1.00 0.00 0.00 -8.60 47.70 +478.00 50666.70 7.27 1.10 2.20 15.39 9.97 0.69 0.00 0.00 0.92 2.04 0.80 -1.00 0.00 0.00 -6.31 81.10 +479.00 51052.70 15.74 0.90 2.20 35.40 11.17 -2.29 0.00 0.00 0.38 2.70 0.80 -1.00 0.00 0.00 -32.73 83.10 +480.00 51675.80 16.91 0.90 4.50 53.74 11.89 0.59 0.00 0.00 0.57 2.73 0.60 -1.00 0.00 0.00 -23.54 66.20 +481.00 51831.60 27.03 1.10 3.20 71.41 12.15 -0.87 0.00 0.00 0.55 2.62 0.80 -1.00 0.00 0.00 -39.67 94.00 +482.00 51849.80 22.00 1.00 1.60 36.29 8.94 -0.93 0.00 0.00 0.72 1.91 0.60 -1.00 0.00 0.00 -24.58 112.20 +483.00 52043.00 7.55 4.60 1.50 20.40 12.25 0.09 0.00 0.00 4.22 1.28 0.80 -1.00 0.00 0.00 -1.43 49.40 +484.00 52122.60 8.82 1.50 3.10 25.14 9.45 1.07 0.00 0.00 1.31 1.92 1.40 -1.00 0.00 0.00 -5.38 1.00 +485.00 52165.20 14.77 1.50 2.20 30.09 12.12 -0.74 0.00 0.00 0.51 1.67 0.90 -1.00 0.00 0.00 -22.95 43.60 +486.00 52336.90 17.65 0.60 2.20 32.02 10.65 0.78 0.00 0.00 0.30 1.74 0.40 -1.00 0.00 0.00 -47.82 10.50 +487.00 52390.70 6.81 2.60 1.40 13.37 11.34 -1.00 0.00 0.00 2.06 0.57 0.30 -1.00 0.00 0.00 -2.64 13.10 +488.00 52410.30 17.53 0.90 3.00 44.18 11.64 -1.48 0.00 0.00 0.43 2.84 0.70 -1.00 0.00 0.00 -32.77 83.90 +489.00 52448.00 17.24 0.90 2.20 35.15 9.24 -0.37 0.00 0.00 0.67 2.42 0.70 -1.00 0.00 0.00 -20.60 121.60 +490.00 52706.80 12.49 0.90 4.80 41.47 10.34 -0.98 0.00 0.00 0.39 3.14 0.60 -1.00 0.00 0.00 -25.90 124.40 +491.00 52764.20 7.17 2.00 0.90 10.24 11.68 0.56 0.00 0.00 1.18 0.87 0.50 -1.00 0.00 0.00 -4.88 53.80 +492.00 52772.40 16.23 0.90 2.20 30.04 11.37 -0.10 0.00 0.00 0.55 1.50 0.60 -1.00 0.00 0.00 -23.42 62.00 +493.00 52784.80 6.85 1.10 0.60 6.23 10.52 -0.13 0.00 0.00 1.00 0.69 0.20 -1.00 0.00 0.00 -5.47 23.20 +494.00 53048.20 22.27 1.00 2.20 42.24 11.09 1.19 0.00 0.00 0.52 1.65 0.70 -1.00 0.00 0.00 -34.55 81.80 +495.00 53114.90 13.48 1.20 2.50 33.08 10.43 -1.74 0.00 0.00 0.95 2.48 1.00 -1.00 0.00 0.00 -11.32 20.50 +496.00 53268.90 8.43 2.30 6.60 39.46 11.54 0.29 0.00 0.00 1.53 3.34 1.30 -1.00 0.00 0.00 -4.41 123.30 +497.00 53375.00 7.73 1.40 2.10 15.76 10.99 0.14 0.00 0.00 1.25 1.59 1.20 -1.00 0.00 0.00 -4.96 24.60 +498.00 53503.50 15.43 0.70 4.40 47.48 11.33 -0.95 0.00 0.00 0.51 2.44 0.50 -1.00 0.00 0.00 -23.99 25.10 +499.00 53618.40 17.64 0.80 2.60 37.32 11.21 0.02 0.00 0.00 0.47 1.80 0.60 -1.00 0.00 0.00 -29.75 12.00 +500.00 53647.30 7.78 1.10 1.60 14.49 10.33 -1.65 0.00 0.00 0.93 2.20 1.00 -1.00 0.00 0.00 -6.66 40.90 +501.00 53681.90 6.31 3.00 1.00 12.73 10.56 -1.14 0.00 0.00 2.47 0.73 0.40 -1.00 0.00 0.00 -2.05 75.50 +502.00 53848.10 6.30 2.90 1.40 11.52 11.67 -0.82 0.00 0.00 1.19 1.17 1.00 -1.00 0.00 0.00 -4.22 113.70 +503.00 54151.80 12.02 0.80 4.00 33.48 11.96 0.44 0.00 0.00 0.52 1.84 0.60 -1.00 0.00 0.00 -18.32 33.40 +504.00 54326.20 9.48 1.30 1.40 14.84 12.02 -0.20 0.00 0.00 0.78 1.60 0.70 -1.00 0.00 0.00 -9.67 79.80 +505.00 54357.10 13.87 1.40 3.90 40.26 11.92 -0.96 0.00 0.00 0.99 2.18 0.90 -1.00 0.00 0.00 -11.23 110.70 +506.00 54420.70 11.64 1.50 2.40 31.71 11.57 1.78 0.00 0.00 1.25 2.61 1.30 -1.00 0.00 0.00 -7.45 123.10 +507.00 54449.10 6.30 1.50 0.40 6.53 9.56 -0.16 0.00 0.00 1.36 0.62 0.30 -1.00 0.00 0.00 -3.71 74.70 +508.00 54481.20 13.67 1.10 1.50 21.03 8.69 -0.58 0.00 0.00 0.69 1.41 0.70 -1.00 0.00 0.00 -15.95 106.80 +509.00 54512.40 12.81 0.70 1.80 18.95 8.67 0.89 0.00 0.00 0.47 1.57 0.50 -1.00 0.00 0.00 -21.66 10.00 +510.00 54790.80 8.83 0.80 5.00 31.49 8.33 0.02 0.00 0.00 0.46 1.18 0.30 -1.00 0.00 0.00 -15.19 32.40 +511.00 54793.50 8.49 3.60 2.40 34.44 8.81 0.17 255.00 0.00 3.18 2.51 0.80 -1.00 0.00 0.00 -2.13 9.50 +512.00 54826.70 18.54 1.00 3.20 45.64 10.53 -0.67 0.00 0.00 0.74 2.04 0.70 -1.00 0.00 0.00 -20.05 68.30 +513.00 55055.40 15.31 1.80 2.70 37.18 9.63 0.52 0.00 0.00 0.57 2.63 0.60 -1.00 0.00 0.00 -21.65 41.00 +514.00 55111.80 19.36 1.50 2.40 39.74 11.79 0.57 0.00 0.00 1.00 2.11 0.60 -1.00 0.00 0.00 -15.47 97.40 +515.00 55172.50 13.97 0.70 3.30 33.41 9.41 0.22 0.00 0.00 0.53 2.48 0.40 -1.00 0.00 0.00 -20.91 4.50 +516.00 55191.80 8.19 1.90 0.60 8.37 9.77 -0.60 0.00 0.00 0.89 1.18 0.80 -1.00 0.00 0.00 -7.40 49.40 +517.00 55214.90 18.52 0.90 6.60 77.33 9.48 -1.72 0.00 0.00 0.38 2.35 0.50 -1.00 0.00 0.00 -38.79 72.50 +518.00 55288.20 6.49 2.70 2.10 13.62 10.57 -0.51 0.00 0.00 0.70 1.10 0.70 -1.00 0.00 0.00 -7.39 94.60 +519.00 55327.90 9.05 2.10 2.30 20.29 11.18 0.94 0.00 0.00 1.89 1.42 0.50 -1.00 0.00 0.00 -3.83 57.50 +520.00 55472.10 21.12 1.10 7.20 93.36 11.51 -0.39 0.00 0.00 0.48 3.26 0.70 -1.00 0.00 0.00 -35.53 73.70 +521.00 55496.40 14.04 2.50 2.00 43.05 8.68 0.80 0.00 0.00 2.17 3.80 2.10 -1.00 0.00 0.00 -5.17 98.00 +522.00 55551.20 6.14 1.70 0.40 6.26 9.14 0.59 0.00 0.00 1.47 0.65 0.50 -1.00 0.00 0.00 -3.34 101.60 +523.00 55560.90 15.12 0.60 3.90 41.05 9.27 -0.32 0.00 0.00 0.41 2.38 0.40 -1.00 0.00 0.00 -29.45 34.50 +524.00 55879.50 7.79 4.10 1.20 17.66 11.27 0.23 0.00 0.00 2.23 1.52 0.80 -1.00 0.00 0.00 -2.79 97.10 +525.00 56347.70 17.21 0.80 3.30 37.16 11.05 -0.76 0.00 0.00 0.47 1.70 0.50 -1.00 0.00 0.00 -29.14 53.30 +526.00 56411.60 10.47 1.90 2.70 27.02 10.57 0.43 0.00 0.00 0.51 2.41 0.40 -1.00 0.00 0.00 -16.45 117.20 +527.00 56634.50 11.38 1.00 5.70 43.80 11.18 -1.48 0.00 0.00 0.82 2.37 0.70 -1.00 0.00 0.00 -11.17 84.10 +528.00 56829.30 7.25 0.90 1.00 7.73 11.99 -0.11 0.00 0.00 0.74 1.04 0.50 -1.00 0.00 0.00 -7.86 22.90 +529.00 56879.10 6.87 1.70 0.80 9.79 12.06 -1.04 0.00 0.00 1.47 1.39 1.20 -1.00 0.00 0.00 -3.74 72.70 +530.00 57013.30 17.74 0.80 2.30 33.77 12.22 0.07 0.00 0.00 0.46 1.78 0.50 -1.00 0.00 0.00 -31.12 27.70 +531.00 57025.30 7.34 0.60 5.20 25.18 10.33 1.66 0.00 0.00 0.40 0.93 0.40 -1.00 0.00 0.00 -14.70 90.90 +532.00 57035.20 7.51 1.00 2.20 15.74 11.46 1.65 0.00 0.00 0.77 1.95 0.60 -1.00 0.00 0.00 -7.80 100.80 +533.00 57066.70 6.27 3.20 2.60 15.36 11.34 1.12 255.00 0.00 2.31 1.56 0.60 -1.00 0.00 0.00 -2.17 4.30 +534.00 57595.20 6.52 1.90 1.70 14.90 10.62 0.86 0.00 0.00 1.69 1.72 1.60 -1.00 0.00 0.00 -3.09 20.80 +535.00 57803.90 6.26 1.10 2.60 13.72 11.86 -2.14 0.00 0.00 0.96 2.24 0.50 -1.00 0.00 0.00 -5.22 75.90 +536.00 57925.90 8.10 1.50 2.60 17.79 12.73 -2.50 0.00 0.00 0.93 1.31 0.50 -1.00 0.00 0.00 -7.00 95.50 +537.00 57948.80 6.61 4.00 0.40 11.07 12.80 0.85 0.00 0.00 1.40 0.96 0.70 -1.00 0.00 0.00 -3.78 92.80 +538.00 57976.50 16.55 0.90 2.20 35.82 10.95 0.75 0.00 0.00 0.55 2.17 0.60 -1.00 0.00 0.00 -23.94 18.10 +539.00 58130.20 13.07 1.20 3.10 33.05 12.20 -0.41 0.00 0.00 0.59 2.03 1.00 -1.00 0.00 0.00 -17.66 43.80 +540.00 58135.70 6.08 0.60 0.80 4.49 11.54 -1.17 0.00 0.00 0.39 0.45 0.30 -1.00 0.00 0.00 -12.56 126.10 +541.00 58156.60 7.72 1.10 1.60 12.39 9.98 -0.74 0.00 0.00 0.90 1.53 0.80 -1.00 0.00 0.00 -6.89 70.20 +542.00 58159.20 10.00 3.70 2.00 29.33 9.51 0.93 255.00 0.00 0.77 1.99 0.40 -1.00 0.00 0.00 -10.41 47.20 +543.00 58249.00 6.15 0.90 3.00 13.68 11.79 0.75 0.00 0.00 0.34 1.04 0.20 -1.00 0.00 0.00 -14.46 34.60 +544.00 58549.40 6.28 1.50 1.30 11.23 11.87 -1.16 0.00 0.00 1.04 1.90 0.80 -1.00 0.00 0.00 -4.84 53.40 +545.00 58583.20 19.47 1.30 7.30 92.18 12.55 -0.78 0.00 0.00 0.50 2.72 0.60 -1.00 0.00 0.00 -30.85 112.80 +546.00 58733.10 16.48 1.50 2.50 38.30 11.55 -0.57 0.00 0.00 0.40 2.60 0.70 -1.00 0.00 0.00 -32.85 6.70 +547.00 58800.00 19.79 1.10 2.20 40.80 11.00 0.04 0.00 0.00 0.88 1.78 1.00 -1.00 0.00 0.00 -18.00 73.60 +548.00 58825.30 8.73 1.20 0.60 9.16 11.40 0.28 0.00 0.00 1.04 1.17 0.80 -1.00 0.00 0.00 -6.70 98.90 +549.00 58847.30 7.14 1.00 1.50 9.77 8.75 -1.19 0.00 0.00 0.70 1.08 0.70 -1.00 0.00 0.00 -8.22 95.30 +550.00 58989.10 20.85 0.60 3.00 43.33 11.47 -0.06 0.00 0.00 0.36 2.18 0.40 -1.00 0.00 0.00 -46.09 6.70 +551.00 59064.50 8.46 1.60 3.30 17.87 11.86 -0.75 0.00 0.00 0.75 1.02 0.40 -1.00 0.00 0.00 -9.04 82.10 +552.00 59162.40 8.76 1.30 1.50 15.51 11.88 0.47 0.00 0.00 1.10 1.89 1.00 -1.00 0.00 0.00 -6.35 26.40 +553.00 59276.30 15.78 0.80 2.80 34.36 11.99 0.95 0.00 0.00 0.35 1.92 0.40 -1.00 0.00 0.00 -36.13 37.90 +554.00 59294.10 11.34 0.60 2.00 18.36 9.56 0.44 0.00 0.00 0.33 1.88 0.30 -1.00 0.00 0.00 -27.47 55.70 +555.00 59299.90 7.31 0.50 0.80 5.78 0.35 -0.07 255.00 0.00 0.29 0.84 0.30 -1.00 0.00 0.00 -20.22 35.90 +556.00 59360.90 6.70 2.70 2.20 16.18 9.62 -1.33 0.00 0.00 2.12 1.02 0.20 -1.00 0.00 0.00 -2.52 122.50 +557.00 59625.60 6.17 0.80 0.80 5.66 11.50 1.43 0.00 0.00 0.65 1.01 0.40 -1.00 0.00 0.00 -7.55 3.20 +558.00 59785.80 6.09 0.50 1.20 4.53 12.93 -0.35 0.00 0.00 0.40 0.39 0.20 -1.00 0.00 0.00 -12.22 35.40 +559.00 59809.40 10.42 2.20 1.80 27.53 13.72 -0.24 0.00 0.00 2.00 2.79 1.50 -1.00 0.00 0.00 -4.16 59.00 +560.00 59893.80 29.29 0.80 2.60 64.01 12.12 0.72 0.00 0.00 0.41 2.33 0.60 -1.00 0.00 0.00 -57.18 15.40 +561.00 60064.70 9.09 0.70 2.70 18.01 12.22 -0.40 0.00 0.00 0.48 1.69 0.50 -1.00 0.00 0.00 -15.03 58.30 +562.00 60101.30 8.33 1.80 1.00 14.76 12.77 1.59 0.00 0.00 1.64 1.87 1.00 -1.00 0.00 0.00 -4.05 69.30 +563.00 60105.60 6.15 0.90 1.40 7.66 12.80 0.20 0.00 0.00 0.66 0.99 0.30 -1.00 0.00 0.00 -7.42 73.60 +564.00 60445.80 7.15 2.00 1.40 11.20 13.14 -1.61 0.00 0.00 1.41 0.93 0.70 -1.00 0.00 0.00 -4.06 55.40 +565.00 60726.90 8.78 1.20 3.40 26.03 11.89 0.08 0.00 0.00 0.95 2.71 0.90 -1.00 0.00 0.00 -7.42 80.50 +566.00 60748.40 12.86 1.00 2.30 25.90 11.55 -0.46 0.00 0.00 0.74 1.74 0.70 -1.00 0.00 0.00 -13.96 102.00 +567.00 60813.90 6.58 1.90 0.90 8.72 11.82 -0.37 0.00 0.00 1.12 1.06 0.80 -1.00 0.00 0.00 -4.70 13.90 +568.00 60890.80 6.46 1.30 3.50 18.73 13.61 1.28 0.00 0.00 1.10 2.36 0.60 -1.00 0.00 0.00 -4.70 90.80 +569.00 60924.90 23.72 0.80 3.40 68.74 12.69 0.35 0.00 0.00 0.58 3.44 0.50 -1.00 0.00 0.00 -32.69 124.90 +570.00 60976.50 8.08 3.90 1.00 18.91 10.91 0.93 0.00 0.00 3.31 1.66 1.00 -1.00 0.00 0.00 -1.95 48.50 +571.00 61089.50 7.25 1.80 1.10 12.71 11.85 0.06 0.00 0.00 1.68 1.49 0.60 -1.00 0.00 0.00 -3.45 33.50 +572.00 61790.70 7.72 1.40 1.40 13.06 12.26 -0.33 0.00 0.00 1.20 1.63 0.90 -1.00 0.00 0.00 -5.15 94.70 +573.00 62059.20 9.40 4.20 2.70 30.88 12.64 0.31 0.00 0.00 2.96 1.90 0.70 -1.00 0.00 0.00 -2.54 107.20 diff --git a/data/mEPSCs/washout1.txt b/data/mEPSCs/washout1.txt new file mode 100644 index 00000000..97a63761 --- /dev/null +++ b/data/mEPSCs/washout1.txt @@ -0,0 +1,678 @@ + Time (ms) Amplitude Rise (ms) Decay (ms) Area Baseline Noise Group Channel 10-90Rise HalfWidth Rise50 Peak Dir Burst# BurstE# 10-90Slope Rel Time +1.00 1941.00 13.89 1.00 2.10 28.77 -0.82 0.08 0.00 0.00 0.85 2.32 0.80 -1.00 0.00 0.00 -13.09 661.00 +2.00 3555.50 23.85 0.80 2.10 45.38 -0.75 -0.70 0.00 0.00 0.63 2.37 0.60 -1.00 0.00 0.00 -30.35 995.50 +3.00 4933.90 11.25 1.10 2.10 24.78 0.11 -0.06 0.00 0.00 0.78 2.56 0.60 -1.00 0.00 0.00 -11.57 1093.90 +4.00 8736.80 10.22 1.80 2.10 17.54 0.76 -0.93 0.00 0.00 0.67 1.42 0.70 -1.00 0.00 0.00 -12.21 1056.80 +5.00 9905.70 13.00 1.30 2.10 27.37 0.32 -0.95 0.00 0.00 1.04 1.74 0.90 -1.00 0.00 0.00 -9.99 945.70 +6.00 10659.80 13.57 1.70 2.10 34.58 0.57 0.99 0.00 0.00 1.04 2.61 1.50 -1.00 0.00 0.00 -10.47 419.80 +7.00 11480.30 12.47 3.00 2.10 33.47 0.89 -0.61 0.00 0.00 1.19 2.84 0.90 -1.00 0.00 0.00 -8.39 1240.30 +8.00 16838.50 13.03 1.50 2.10 27.55 -0.03 0.32 0.00 0.00 1.23 2.05 0.90 -1.00 0.00 0.00 -8.45 198.50 +9.00 17921.10 24.01 1.10 2.10 44.52 -0.53 1.43 0.00 0.00 0.44 2.38 0.40 -1.00 0.00 0.00 -43.27 1.10 +10.00 18029.80 12.47 0.80 2.10 21.95 -1.01 2.02 0.00 0.00 0.68 0.79 0.70 -1.00 0.00 0.00 -14.58 109.80 +11.00 18890.80 14.04 1.30 2.10 29.25 -0.59 0.43 0.00 0.00 1.06 2.20 0.90 -1.00 0.00 0.00 -10.64 970.80 +12.00 22306.20 24.71 1.70 2.10 56.34 0.14 -1.83 0.00 0.00 0.58 2.70 0.80 -1.00 0.00 0.00 -33.94 546.20 +13.00 24436.00 20.83 1.30 2.10 43.51 1.10 0.17 0.00 0.00 0.55 2.49 0.50 -1.00 0.00 0.00 -30.04 116.00 +14.00 25301.70 11.26 2.40 2.10 32.14 0.06 -1.82 0.00 0.00 2.17 3.00 1.90 -1.00 0.00 0.00 -4.15 981.70 +15.00 27392.00 21.09 1.00 2.10 42.05 0.30 -0.13 0.00 0.00 0.38 2.37 0.40 -1.00 0.00 0.00 -44.24 512.00 +16.00 27473.80 11.83 1.80 2.10 28.23 -0.15 0.75 0.00 0.00 1.32 1.93 1.00 -1.00 0.00 0.00 -7.19 593.80 +17.00 27886.20 10.57 1.70 2.10 24.78 0.48 1.85 0.00 0.00 1.43 1.24 1.10 -1.00 0.00 0.00 -5.91 1006.20 +18.00 31161.90 12.78 1.00 2.10 28.70 0.26 0.93 0.00 0.00 0.64 2.82 0.90 -1.00 0.00 0.00 -15.96 441.90 +19.00 31785.20 18.81 0.60 2.10 29.15 -0.23 -0.79 0.00 0.00 0.43 1.67 0.40 -1.00 0.00 0.00 -35.31 1065.20 +20.00 32170.40 15.23 1.50 2.10 36.36 1.15 -0.91 0.00 0.00 1.14 3.02 1.10 -1.00 0.00 0.00 -10.64 170.40 +21.00 35500.50 14.08 2.10 2.10 38.04 0.31 0.76 0.00 0.00 1.86 3.41 1.50 -1.00 0.00 0.00 -6.07 940.50 +22.00 36166.10 10.64 1.90 2.10 26.08 0.39 0.31 0.00 0.00 0.96 3.14 1.20 -1.00 0.00 0.00 -8.89 326.10 +23.00 38347.30 13.77 1.60 2.10 27.58 0.19 -1.49 0.00 0.00 1.47 1.41 1.10 -1.00 0.00 0.00 -7.47 1227.30 +24.00 40540.10 13.51 1.80 2.10 30.61 -0.34 -1.18 0.00 0.00 1.30 2.23 1.40 -1.00 0.00 0.00 -8.33 860.10 +25.00 40737.00 17.04 1.00 2.10 30.74 -0.44 0.81 0.00 0.00 0.32 1.98 0.20 -1.00 0.00 0.00 -42.66 1057.00 +26.00 41084.20 11.80 2.90 2.10 34.65 -1.00 0.24 0.00 0.00 2.66 2.49 2.30 -1.00 0.00 0.00 -3.55 124.20 +27.00 41775.90 10.51 4.40 2.10 32.23 0.35 0.48 0.00 0.00 4.28 1.02 0.50 -1.00 0.00 0.00 -1.96 815.90 +28.00 42236.10 15.16 1.50 2.10 35.18 -0.24 1.41 0.00 0.00 1.24 2.30 1.30 -1.00 0.00 0.00 -9.78 1276.10 +29.00 44560.80 15.17 1.40 2.10 31.17 -1.21 0.54 0.00 0.00 1.09 2.61 0.70 -1.00 0.00 0.00 -11.15 1040.80 +30.00 45110.30 11.76 3.20 2.10 37.45 -0.51 -0.36 0.00 0.00 2.91 3.07 2.40 -1.00 0.00 0.00 -3.24 310.30 +31.00 45120.50 19.08 1.00 2.10 41.98 -2.38 0.49 0.00 0.00 0.77 2.66 0.70 -1.00 0.00 0.00 -19.94 320.50 +32.00 47928.00 21.37 1.40 2.10 48.60 -0.12 -1.65 0.00 0.00 0.82 2.73 0.80 -1.00 0.00 0.00 -20.93 568.00 +33.00 48123.70 10.53 1.20 2.10 24.54 -0.68 -2.90 0.00 0.00 1.09 3.05 1.10 -1.00 0.00 0.00 -7.71 763.70 +34.00 49403.20 17.78 1.40 2.10 42.11 -0.24 1.77 0.00 0.00 1.21 2.92 1.00 -1.00 0.00 0.00 -11.75 763.20 +35.00 49668.20 10.14 1.40 2.10 20.77 -0.29 -0.59 0.00 0.00 1.22 1.62 0.40 -1.00 0.00 0.00 -6.65 1028.20 +36.00 50773.40 21.88 1.80 2.10 49.62 -0.24 -0.24 0.00 0.00 0.93 2.50 0.90 -1.00 0.00 0.00 -18.85 853.40 +37.00 52578.10 11.64 2.40 2.10 29.53 0.64 -0.90 0.00 0.00 1.89 1.64 0.50 -1.00 0.00 0.00 -4.93 98.10 +38.00 54234.50 10.50 0.90 2.10 20.34 -0.62 0.13 0.00 0.00 0.74 1.95 0.70 -1.00 0.00 0.00 -11.34 474.50 +39.00 54691.00 10.54 1.40 2.10 26.21 0.22 -0.47 0.00 0.00 1.26 3.15 1.20 -1.00 0.00 0.00 -6.71 931.00 +40.00 55407.20 12.03 0.70 2.10 22.04 0.30 1.33 0.00 0.00 0.41 2.07 0.50 -1.00 0.00 0.00 -23.48 367.20 +41.00 56997.30 10.00 1.60 2.10 22.23 -0.81 -0.74 0.00 0.00 1.40 2.27 0.50 -1.00 0.00 0.00 -5.73 677.30 +42.00 62679.30 15.37 0.60 2.10 23.20 0.44 3.98 0.00 0.00 0.50 1.79 0.40 -1.00 0.00 0.00 -24.47 1239.30 +43.00 63448.10 12.61 1.70 2.10 28.60 1.36 1.52 0.00 0.00 1.46 2.56 1.40 -1.00 0.00 0.00 -6.92 728.10 +44.00 63789.30 21.98 1.00 2.10 46.35 -0.17 -0.08 0.00 0.00 0.64 2.37 0.60 -1.00 0.00 0.00 -27.56 1069.30 +45.00 68330.80 10.39 1.30 2.10 19.04 0.72 1.66 0.00 0.00 1.07 1.91 0.60 -1.00 0.00 0.00 -7.75 490.80 +46.00 68358.70 12.88 0.60 2.10 18.37 -0.85 0.54 0.00 0.00 0.46 1.35 0.40 -1.00 0.00 0.00 -22.25 518.70 +47.00 76133.40 16.14 1.70 2.10 34.45 0.80 -1.57 0.00 0.00 1.02 1.84 0.70 -1.00 0.00 0.00 -12.71 613.40 +48.00 77043.10 11.57 1.10 2.10 26.96 0.26 -0.95 0.00 0.00 0.91 2.90 1.00 -1.00 0.00 0.00 -10.16 243.10 +49.00 78644.50 11.09 1.40 2.10 25.60 0.56 0.35 0.00 0.00 1.17 2.42 1.20 -1.00 0.00 0.00 -7.60 564.50 +50.00 80162.00 11.17 0.90 2.10 14.91 0.56 1.60 0.00 0.00 0.81 1.09 0.80 -1.00 0.00 0.00 -10.99 802.00 +51.00 80478.90 13.68 0.70 2.10 22.77 -1.25 -1.68 0.00 0.00 0.57 1.45 0.40 -1.00 0.00 0.00 -19.36 1118.90 +52.00 82584.90 20.61 1.80 2.10 51.64 -0.06 1.48 0.00 0.00 1.16 3.13 1.20 -1.00 0.00 0.00 -14.21 664.90 +53.00 83025.70 10.67 1.40 2.10 19.15 0.22 -1.70 0.00 0.00 1.00 2.46 0.80 -1.00 0.00 0.00 -8.55 1105.70 +54.00 83619.20 11.70 1.50 2.10 23.73 -0.73 -0.75 0.00 0.00 1.08 1.67 1.20 -1.00 0.00 0.00 -8.68 419.20 +55.00 83691.90 10.35 2.50 2.10 32.05 -0.33 -1.32 0.00 0.00 2.23 2.70 2.40 -1.00 0.00 0.00 -3.72 491.90 +56.00 84163.90 18.16 1.00 2.10 37.88 -0.23 0.07 0.00 0.00 0.83 2.50 0.50 -1.00 0.00 0.00 -17.42 963.90 +57.00 84333.90 13.16 2.30 2.10 39.21 -0.32 -4.03 0.00 0.00 2.14 2.42 2.20 -1.00 0.00 0.00 -4.91 1133.90 +58.00 85656.20 16.87 2.20 2.10 44.51 -1.16 -0.92 0.00 0.00 1.60 2.86 1.40 -1.00 0.00 0.00 -8.46 1176.20 +59.00 85782.70 11.41 1.00 2.10 23.27 0.38 1.30 0.00 0.00 0.80 2.64 0.70 -1.00 0.00 0.00 -11.45 22.70 +60.00 85881.40 13.64 1.30 2.10 29.21 -0.75 0.88 0.00 0.00 1.04 1.96 0.80 -1.00 0.00 0.00 -10.50 121.40 +61.00 89340.40 14.31 1.40 2.10 32.56 0.37 -0.21 0.00 0.00 1.19 3.00 1.10 -1.00 0.00 0.00 -9.59 1020.40 +62.00 90240.40 19.96 2.50 2.10 52.49 0.68 2.39 0.00 0.00 0.74 2.91 1.20 -1.00 0.00 0.00 -21.63 640.40 +63.00 90924.10 11.26 1.30 2.10 22.98 1.31 -0.11 0.00 0.00 1.11 1.64 1.00 -1.00 0.00 0.00 -8.11 44.10 +64.00 93572.10 13.75 0.80 2.10 23.65 0.50 2.61 0.00 0.00 0.43 1.45 0.30 -1.00 0.00 0.00 -25.63 132.10 +65.00 93676.90 10.77 2.10 2.10 25.62 -0.84 -0.45 0.00 0.00 2.01 2.37 1.70 -1.00 0.00 0.00 -4.29 236.90 +66.00 99778.70 23.91 1.80 2.10 57.92 -0.75 1.22 0.00 0.00 1.29 2.97 1.00 -1.00 0.00 0.00 -14.88 1218.70 +67.00 100427.20 15.44 1.10 2.10 35.23 0.02 0.58 0.00 0.00 0.65 2.70 0.70 -1.00 0.00 0.00 -18.94 587.20 +68.00 104136.20 13.77 1.20 2.10 27.23 -1.54 0.72 0.00 0.00 0.98 2.06 0.60 -1.00 0.00 0.00 -11.27 456.20 +69.00 105869.40 21.03 1.30 2.10 52.44 -1.15 -2.20 0.00 0.00 0.94 2.76 0.80 -1.00 0.00 0.00 -17.90 909.40 +70.00 110130.80 16.74 1.50 2.10 38.49 0.69 1.04 0.00 0.00 0.93 2.71 0.80 -1.00 0.00 0.00 -14.45 50.80 +71.00 110602.50 10.53 1.40 2.10 21.35 0.27 1.61 0.00 0.00 1.22 1.89 0.90 -1.00 0.00 0.00 -6.90 522.50 +72.00 111210.60 17.38 2.20 2.10 53.51 -0.51 -1.01 0.00 0.00 1.90 3.70 1.70 -1.00 0.00 0.00 -7.32 1130.60 +73.00 112048.70 11.43 1.70 2.10 22.20 -1.36 2.39 0.00 0.00 1.59 1.37 1.20 -1.00 0.00 0.00 -5.76 688.70 +74.00 112349.60 18.26 1.90 2.10 50.16 0.02 -0.23 0.00 0.00 1.55 3.22 1.50 -1.00 0.00 0.00 -9.43 989.60 +75.00 113276.30 14.34 1.20 2.10 35.05 -0.30 -0.80 0.00 0.00 0.78 2.82 0.90 -1.00 0.00 0.00 -14.68 636.30 +76.00 113564.20 20.03 1.40 2.10 51.55 -0.70 1.34 0.00 0.00 1.07 2.93 1.00 -1.00 0.00 0.00 -15.03 924.20 +77.00 113854.00 11.41 1.20 2.10 21.87 -0.75 0.31 0.00 0.00 0.73 2.42 0.50 -1.00 0.00 0.00 -12.50 1214.00 +78.00 115266.90 21.68 1.40 2.10 54.68 -1.07 -1.60 0.00 0.00 0.91 2.64 1.00 -1.00 0.00 0.00 -19.03 66.90 +79.00 115747.20 10.94 1.10 2.10 23.13 -0.36 -0.45 0.00 0.00 0.91 2.90 1.00 -1.00 0.00 0.00 -9.66 547.20 +80.00 116033.70 10.05 1.70 2.10 19.74 -0.59 -0.13 0.00 0.00 1.11 2.03 0.90 -1.00 0.00 0.00 -7.22 833.70 +81.00 116913.30 19.24 1.80 2.10 40.87 -0.61 -2.50 0.00 0.00 1.13 2.67 0.80 -1.00 0.00 0.00 -13.58 433.30 +82.00 118931.50 22.61 2.20 2.10 59.82 -0.79 2.16 0.00 0.00 0.92 3.05 1.10 -1.00 0.00 0.00 -19.57 1171.50 +83.00 119518.70 18.15 1.50 2.10 40.49 0.08 0.51 0.00 0.00 1.27 2.67 1.10 -1.00 0.00 0.00 -11.41 478.70 +84.00 122569.30 13.08 1.30 2.10 29.77 -0.30 1.24 0.00 0.00 1.18 2.95 1.00 -1.00 0.00 0.00 -8.88 969.30 +85.00 123382.10 15.03 1.70 2.10 41.80 0.62 -0.75 0.00 0.00 1.23 3.37 1.40 -1.00 0.00 0.00 -9.80 502.10 +86.00 124540.30 23.76 1.60 2.10 56.39 -0.39 -1.54 0.00 0.00 1.18 2.72 0.80 -1.00 0.00 0.00 -16.11 380.30 +87.00 125948.90 17.79 1.50 2.10 42.74 -0.70 -1.06 0.00 0.00 1.34 2.91 1.30 -1.00 0.00 0.00 -10.58 508.90 +88.00 130310.00 10.88 2.00 2.10 27.77 -0.81 0.66 0.00 0.00 1.58 2.91 1.40 -1.00 0.00 0.00 -5.50 1030.00 +89.00 133845.40 14.94 1.20 2.10 32.89 -0.28 1.29 0.00 0.00 1.02 1.77 0.80 -1.00 0.00 0.00 -11.75 725.40 +90.00 133912.00 17.47 2.00 2.10 40.15 -0.50 -2.05 0.00 0.00 0.73 2.38 0.90 -1.00 0.00 0.00 -19.22 792.00 +91.00 134092.40 15.10 4.20 2.10 55.52 -1.40 1.94 0.00 0.00 3.10 3.84 1.90 -1.00 0.00 0.00 -3.89 972.40 +92.00 137185.80 13.21 2.80 2.10 40.59 -0.47 -0.86 0.00 0.00 2.64 3.01 2.00 -1.00 0.00 0.00 -4.00 225.80 +93.00 137459.90 14.81 1.40 2.10 31.62 -0.22 0.51 0.00 0.00 1.17 2.14 1.00 -1.00 0.00 0.00 -10.15 499.90 +94.00 138518.60 12.45 0.80 2.10 18.24 0.12 -0.35 0.00 0.00 0.72 0.97 0.60 -1.00 0.00 0.00 -13.81 278.60 +95.00 138902.30 13.42 2.10 2.10 40.30 0.46 0.16 0.00 0.00 1.89 2.96 1.90 -1.00 0.00 0.00 -5.67 662.30 +96.00 143004.60 12.50 3.50 2.10 47.23 -0.48 -0.42 0.00 0.00 3.39 4.41 3.30 -1.00 0.00 0.00 -2.95 924.60 +97.00 143863.20 14.26 2.10 2.10 34.82 -0.62 0.04 0.00 0.00 1.27 2.42 1.20 -1.00 0.00 0.00 -8.96 503.20 +98.00 144486.20 19.84 0.90 2.10 35.65 -0.41 0.57 0.00 0.00 0.47 1.97 0.40 -1.00 0.00 0.00 -33.48 1126.20 +99.00 145280.90 11.81 0.80 2.10 17.96 -0.41 1.04 0.00 0.00 0.48 1.27 0.60 -1.00 0.00 0.00 -19.58 640.90 +100.00 147120.00 18.88 1.30 2.10 40.51 -0.47 -0.16 0.00 0.00 0.80 2.38 0.60 -1.00 0.00 0.00 -18.89 1200.00 +101.00 147151.40 24.32 1.30 2.10 54.76 -0.77 1.04 0.00 0.00 0.87 2.58 0.60 -1.00 0.00 0.00 -22.26 1231.40 +102.00 147779.50 15.68 2.10 2.10 39.80 -2.64 -0.67 0.00 0.00 1.13 2.56 1.20 -1.00 0.00 0.00 -11.08 579.50 +103.00 147852.00 22.75 1.20 2.10 49.64 -1.95 0.35 0.00 0.00 0.96 2.78 0.80 -1.00 0.00 0.00 -19.04 652.00 +104.00 149252.90 12.58 2.30 2.10 29.91 -0.20 -0.94 0.00 0.00 1.48 3.06 1.40 -1.00 0.00 0.00 -6.78 772.90 +105.00 149262.60 11.58 1.10 2.10 24.08 -4.02 1.73 0.00 0.00 0.96 2.49 0.80 -1.00 0.00 0.00 -9.60 782.60 +106.00 149573.80 16.84 3.60 2.10 56.38 -0.75 -0.35 0.00 0.00 3.21 2.88 1.10 -1.00 0.00 0.00 -4.20 1093.80 +107.00 155414.10 12.72 1.30 2.10 30.11 -0.67 -2.30 0.00 0.00 1.09 2.38 0.90 -1.00 0.00 0.00 -9.31 534.10 +108.00 163418.00 10.70 1.30 2.10 23.16 -0.72 1.97 0.00 0.00 0.83 2.46 0.90 -1.00 0.00 0.00 -10.26 858.00 +109.00 164520.80 18.13 1.00 2.10 39.01 -0.20 -1.05 0.00 0.00 0.75 2.62 0.70 -1.00 0.00 0.00 -19.46 680.80 +110.00 165173.40 17.28 2.40 2.10 51.96 -0.85 1.92 0.00 0.00 2.25 3.30 2.00 -1.00 0.00 0.00 -6.16 53.40 +111.00 165649.50 11.48 1.30 2.10 24.52 -1.39 2.00 0.00 0.00 1.00 2.45 0.70 -1.00 0.00 0.00 -9.19 529.50 +112.00 170259.20 10.24 0.60 2.10 17.34 -0.36 -1.36 0.00 0.00 0.50 1.90 0.20 -1.00 0.00 0.00 -16.54 19.20 +113.00 172830.00 19.28 1.30 2.10 44.88 -1.68 0.85 0.00 0.00 0.83 2.75 0.80 -1.00 0.00 0.00 -18.57 30.00 +114.00 173662.60 13.18 1.80 2.10 32.90 -2.82 -0.86 0.00 0.00 1.60 3.38 1.40 -1.00 0.00 0.00 -6.61 862.60 +115.00 174754.60 12.04 1.80 2.10 28.73 -0.80 0.10 0.00 0.00 1.74 2.51 1.70 -1.00 0.00 0.00 -5.54 674.60 +116.00 175720.60 14.32 1.40 2.10 33.44 -0.06 0.02 0.00 0.00 0.72 2.49 1.00 -1.00 0.00 0.00 -16.00 360.60 +117.00 177274.80 13.02 2.00 2.10 28.92 0.11 -0.13 0.00 0.00 1.37 1.60 0.90 -1.00 0.00 0.00 -7.61 634.80 +118.00 184543.50 16.71 2.30 2.10 46.43 -2.11 0.84 0.00 0.00 1.85 3.41 1.50 -1.00 0.00 0.00 -7.22 223.50 +119.00 185384.70 17.45 1.40 2.10 38.93 -0.02 1.45 0.00 0.00 1.17 2.81 0.90 -1.00 0.00 0.00 -11.89 1064.70 +120.00 186575.20 15.97 2.80 2.10 38.85 0.53 -1.93 0.00 0.00 1.07 2.53 1.00 -1.00 0.00 0.00 -11.90 975.20 +121.00 190443.40 16.50 1.90 2.10 37.75 -1.71 1.77 0.00 0.00 1.65 2.21 0.70 -1.00 0.00 0.00 -8.03 1003.40 +122.00 190953.90 18.60 2.70 2.10 41.18 -0.36 0.30 0.00 0.00 1.03 2.20 0.80 -1.00 0.00 0.00 -14.42 233.90 +123.00 191815.10 12.04 1.40 2.10 27.06 -0.05 -0.08 0.00 0.00 0.86 2.84 0.90 -1.00 0.00 0.00 -11.23 1095.10 +124.00 192085.50 18.45 2.20 2.10 55.36 -1.02 0.13 0.00 0.00 1.04 3.47 1.80 -1.00 0.00 0.00 -14.20 85.50 +125.00 192225.50 13.82 1.30 2.10 27.06 -0.15 -2.84 0.00 0.00 1.05 1.33 0.70 -1.00 0.00 0.00 -10.57 225.50 +126.00 192499.50 17.64 0.80 2.10 34.22 -1.03 -1.39 0.00 0.00 0.47 1.82 0.50 -1.00 0.00 0.00 -30.28 499.50 +127.00 192894.90 23.03 1.20 2.10 49.29 -1.14 -0.56 0.00 0.00 0.96 2.73 0.80 -1.00 0.00 0.00 -19.21 894.90 +128.00 193828.40 16.01 1.40 2.10 40.81 -0.87 -1.88 0.00 0.00 1.10 2.91 1.00 -1.00 0.00 0.00 -11.66 548.40 +129.00 195025.90 14.62 1.90 2.10 38.69 0.16 -1.35 0.00 0.00 1.63 3.31 1.40 -1.00 0.00 0.00 -7.15 465.90 +130.00 195532.90 16.23 1.30 2.10 32.80 -1.36 0.60 0.00 0.00 1.02 2.01 0.60 -1.00 0.00 0.00 -12.76 972.90 +131.00 196628.90 23.60 1.80 2.10 62.09 -0.79 -2.30 0.00 0.00 1.19 2.92 1.00 -1.00 0.00 0.00 -15.81 788.90 +132.00 198192.30 16.61 1.00 2.10 35.72 -1.22 -0.71 0.00 0.00 0.79 2.62 0.70 -1.00 0.00 0.00 -16.81 1072.30 +133.00 200340.30 16.81 0.80 2.10 30.83 -0.55 -0.91 0.00 0.00 0.52 2.35 0.40 -1.00 0.00 0.00 -25.94 660.30 +134.00 200470.30 10.96 1.60 2.10 22.50 -0.39 3.62 0.00 0.00 1.05 1.95 1.10 -1.00 0.00 0.00 -8.38 790.30 +135.00 201125.20 21.70 2.10 2.10 54.17 0.04 0.05 0.00 0.00 1.42 2.70 1.20 -1.00 0.00 0.00 -12.23 165.20 +136.00 201660.60 14.99 1.80 2.10 38.14 -1.01 -3.49 0.00 0.00 1.38 3.12 1.20 -1.00 0.00 0.00 -8.66 700.60 +137.00 203272.70 12.57 1.30 2.10 28.78 0.70 0.12 0.00 0.00 1.10 2.25 1.00 -1.00 0.00 0.00 -9.12 1032.70 +138.00 206639.10 17.48 2.50 2.10 53.48 -1.14 0.33 0.00 0.00 2.12 3.33 1.70 -1.00 0.00 0.00 -6.60 559.10 +139.00 207116.60 16.12 1.50 2.10 32.47 -0.72 0.14 0.00 0.00 0.64 2.51 0.60 -1.00 0.00 0.00 -20.08 1036.60 +140.00 207517.60 13.72 1.20 2.10 29.73 -1.26 0.44 0.00 0.00 1.00 2.68 0.70 -1.00 0.00 0.00 -10.92 157.60 +141.00 209099.20 12.68 2.20 2.10 37.83 -1.59 0.04 0.00 0.00 1.92 3.69 1.70 -1.00 0.00 0.00 -5.28 459.20 +142.00 212122.10 17.32 2.90 2.10 46.59 0.29 2.07 0.00 0.00 2.09 2.85 0.90 -1.00 0.00 0.00 -6.63 922.10 +143.00 212446.00 23.84 1.00 2.10 48.90 -1.60 0.30 0.00 0.00 0.78 2.69 0.70 -1.00 0.00 0.00 -24.45 1246.00 +144.00 212603.30 15.58 2.00 2.10 38.69 -0.49 -1.07 0.00 0.00 1.13 2.88 0.90 -1.00 0.00 0.00 -11.03 123.30 +145.00 213022.10 17.65 1.50 2.10 47.26 0.24 -0.53 0.00 0.00 1.29 3.12 1.20 -1.00 0.00 0.00 -10.92 183.70 +146.00 213309.10 13.97 1.50 2.10 32.88 0.25 -0.84 0.00 0.00 1.36 2.58 1.30 -1.00 0.00 0.00 -8.19 829.10 +147.00 213474.20 11.66 1.30 2.10 25.57 -0.65 -1.55 0.00 0.00 1.14 2.16 1.10 -1.00 0.00 0.00 -8.16 994.20 +148.00 214437.70 24.20 1.30 2.10 56.24 0.01 0.91 0.00 0.00 0.80 2.96 1.00 -1.00 0.00 0.00 -24.26 677.70 +149.00 215915.60 17.32 1.90 2.10 47.11 -1.50 0.38 0.00 0.00 1.56 3.46 1.50 -1.00 0.00 0.00 -8.85 875.60 +150.00 217691.80 14.92 1.60 2.10 33.49 -0.41 1.55 0.00 0.00 1.32 2.66 1.10 -1.00 0.00 0.00 -9.02 91.80 +151.00 218856.30 13.92 2.30 2.10 44.18 -2.03 1.74 0.00 0.00 2.13 4.00 2.10 -1.00 0.00 0.00 -5.24 1256.30 +152.00 220309.10 15.62 0.90 2.10 34.85 -0.89 0.17 0.00 0.00 0.76 2.40 0.40 -1.00 0.00 0.00 -16.44 149.10 +153.00 220318.40 15.40 10.20 2.10 103.14 -0.55 -1.12 255.00 0.00 1.11 2.78 0.80 -1.00 0.00 0.00 -11.10 184.00 +154.00 221316.30 14.79 1.10 2.10 31.44 -1.05 -0.94 0.00 0.00 0.65 2.45 0.50 -1.00 0.00 0.00 -18.32 1156.30 +155.00 221327.60 18.43 1.60 2.10 48.10 -3.15 2.83 255.00 0.00 1.40 3.18 1.20 -1.00 0.00 0.00 -10.51 41.20 +156.00 221445.80 11.89 1.10 2.10 21.05 -3.39 1.14 0.00 0.00 0.55 1.63 0.50 -1.00 0.00 0.00 -17.23 5.80 +157.00 221533.60 10.44 0.60 2.10 20.02 -1.31 -1.16 0.00 0.00 0.50 2.34 0.40 -1.00 0.00 0.00 -16.69 93.60 +158.00 222254.50 12.28 1.30 1.60 10.10 -1.22 0.25 0.00 0.00 1.15 0.24 0.20 -1.00 0.00 0.00 -8.51 814.50 +159.00 224907.70 14.72 2.20 2.10 40.35 -1.25 0.02 0.00 0.00 1.97 3.29 1.60 -1.00 0.00 0.00 -5.98 907.70 +160.00 226045.70 17.29 2.00 2.10 44.66 -1.25 1.38 0.00 0.00 1.79 3.40 1.50 -1.00 0.00 0.00 -7.71 765.70 +161.00 226888.90 14.49 2.40 2.10 31.25 -0.48 2.13 0.00 0.00 1.13 2.12 0.80 -1.00 0.00 0.00 -10.25 328.90 +162.00 227447.40 25.60 1.20 2.10 62.12 -0.68 0.83 0.00 0.00 0.95 2.70 0.70 -1.00 0.00 0.00 -21.46 887.40 +163.00 228670.30 15.03 3.00 2.10 50.88 -0.95 -1.35 0.00 0.00 2.78 4.11 2.30 -1.00 0.00 0.00 -4.32 830.30 +164.00 230266.80 20.20 1.60 2.10 53.40 -2.20 2.69 0.00 0.00 1.11 3.05 1.10 -1.00 0.00 0.00 -14.61 1146.80 +165.00 234951.30 22.72 1.50 2.10 57.42 -0.87 -1.25 0.00 0.00 1.20 3.02 1.10 -1.00 0.00 0.00 -15.10 711.30 +166.00 235419.40 21.35 1.10 2.10 48.94 -1.27 -0.39 0.00 0.00 0.81 2.58 0.60 -1.00 0.00 0.00 -20.97 1179.40 +167.00 236050.80 21.92 1.20 2.10 52.12 -1.37 1.24 0.00 0.00 0.95 2.84 0.90 -1.00 0.00 0.00 -18.54 530.80 +168.00 236355.30 14.14 2.30 2.10 41.75 -1.24 -0.75 0.00 0.00 1.72 3.64 1.70 -1.00 0.00 0.00 -6.57 835.30 +169.00 237244.90 15.12 1.80 2.10 38.97 -1.54 1.69 0.00 0.00 1.58 3.23 1.40 -1.00 0.00 0.00 -7.68 444.90 +170.00 237263.20 10.95 2.80 2.10 35.02 -3.76 -1.94 0.00 0.00 2.62 3.34 2.50 -1.00 0.00 0.00 -3.34 463.20 +171.00 238214.60 10.71 1.80 2.10 27.98 -0.58 0.86 0.00 0.00 1.46 3.22 1.40 -1.00 0.00 0.00 -5.89 134.60 +172.00 238875.00 13.49 1.90 2.10 36.48 -1.85 0.96 0.00 0.00 1.53 3.33 1.40 -1.00 0.00 0.00 -7.06 795.00 +173.00 239098.90 15.97 1.50 2.10 38.57 -1.87 -0.15 0.00 0.00 1.10 2.99 1.00 -1.00 0.00 0.00 -11.65 1018.90 +174.00 239726.00 10.36 2.70 2.10 25.24 -1.80 0.58 0.00 0.00 2.37 0.94 0.70 -1.00 0.00 0.00 -3.50 366.00 +175.00 240006.60 17.68 1.30 2.10 37.73 -1.11 -2.01 0.00 0.00 0.89 2.55 0.60 -1.00 0.00 0.00 -15.97 646.60 +176.00 240162.00 12.73 1.40 2.10 30.33 -2.25 0.75 0.00 0.00 1.20 3.10 1.20 -1.00 0.00 0.00 -8.48 802.00 +177.00 240564.90 17.16 1.50 2.10 41.33 -1.64 -1.41 0.00 0.00 1.20 3.01 1.10 -1.00 0.00 0.00 -11.44 1204.90 +178.00 241128.60 12.14 2.70 2.10 33.13 -1.24 2.08 0.00 0.00 2.55 2.80 2.20 -1.00 0.00 0.00 -3.81 488.60 +179.00 243820.20 13.62 2.50 2.10 42.60 -0.49 -0.24 0.00 0.00 2.29 3.63 1.80 -1.00 0.00 0.00 -4.75 620.20 +180.00 243856.90 10.04 1.50 2.10 26.57 -1.02 0.79 0.00 0.00 1.33 3.24 1.30 -1.00 0.00 0.00 -6.05 656.90 +181.00 244364.80 16.46 3.10 2.10 61.36 -1.44 -0.18 0.00 0.00 2.92 3.71 2.50 -1.00 0.00 0.00 -4.50 1164.80 +182.00 244726.80 28.98 1.50 2.10 72.18 -0.81 -0.42 0.00 0.00 1.19 2.89 0.90 -1.00 0.00 0.00 -19.46 16.40 +183.00 244828.50 10.37 0.80 2.10 22.35 -1.76 0.71 0.00 0.00 0.68 2.62 0.70 -1.00 0.00 0.00 -12.13 118.10 +184.00 245542.70 12.19 1.30 2.10 24.61 -2.03 -1.91 0.00 0.00 0.93 2.52 0.60 -1.00 0.00 0.00 -10.47 64.30 +185.00 247127.60 10.81 2.00 2.10 26.88 -2.07 0.00 0.00 0.00 1.81 2.58 1.20 -1.00 0.00 0.00 -4.79 87.60 +186.00 248180.90 12.89 2.40 2.10 33.17 -1.23 -0.66 0.00 0.00 1.66 2.62 1.40 -1.00 0.00 0.00 -6.23 1140.90 +187.00 248323.30 17.54 2.10 2.10 47.78 -1.32 3.78 0.00 0.00 1.51 3.36 1.40 -1.00 0.00 0.00 -9.31 3.30 +188.00 249436.90 10.97 2.00 2.10 26.96 -1.29 -0.37 0.00 0.00 1.55 2.60 0.60 -1.00 0.00 0.00 -5.66 1116.90 +189.00 250063.10 10.18 2.70 2.10 25.97 -1.86 -0.55 0.00 0.00 2.54 0.81 0.40 -1.00 0.00 0.00 -3.21 463.10 +190.00 250289.70 12.30 2.40 2.10 39.60 -2.23 -0.99 0.00 0.00 2.22 3.97 2.00 -1.00 0.00 0.00 -4.43 689.70 +191.00 250686.50 11.21 1.60 2.10 28.71 -1.67 0.32 0.00 0.00 1.43 2.78 1.20 -1.00 0.00 0.00 -6.29 1086.50 +192.00 251230.00 10.43 2.40 2.10 33.73 -1.69 0.25 0.00 0.00 2.27 3.84 1.90 -1.00 0.00 0.00 -3.67 350.00 +193.00 251493.00 11.61 1.70 2.10 30.50 -1.28 -0.60 0.00 0.00 1.39 2.93 1.00 -1.00 0.00 0.00 -6.66 254.60 +194.00 251559.10 11.60 2.20 2.10 25.52 -1.66 1.27 0.00 0.00 2.01 1.28 0.40 -1.00 0.00 0.00 -4.61 679.10 +195.00 251704.10 10.21 2.70 2.10 32.13 -2.15 0.11 0.00 0.00 2.43 2.91 2.00 -1.00 0.00 0.00 -3.37 824.10 +196.00 252270.20 10.30 2.00 2.10 26.97 -1.16 0.47 0.00 0.00 1.77 2.70 0.70 -1.00 0.00 0.00 -4.65 110.20 +197.00 252678.50 22.68 3.30 2.10 79.54 -0.03 -0.23 0.00 0.00 2.22 3.90 1.90 -1.00 0.00 0.00 -8.16 518.50 +198.00 252870.50 10.11 2.40 2.10 24.79 -1.55 1.53 0.00 0.00 1.78 1.76 0.60 -1.00 0.00 0.00 -4.54 710.50 +199.00 253279.10 10.77 0.80 2.10 19.08 -1.79 -0.17 0.00 0.00 0.60 1.90 0.40 -1.00 0.00 0.00 -14.29 1119.10 +200.00 253638.50 10.96 3.30 2.10 35.62 -1.19 -0.52 0.00 0.00 2.72 3.15 1.80 -1.00 0.00 0.00 -3.22 96.10 +201.00 253872.80 15.99 2.30 2.10 46.88 -2.05 -0.20 0.00 0.00 2.05 3.72 1.80 -1.00 0.00 0.00 -6.25 432.80 +202.00 254445.00 12.85 2.90 2.10 39.81 -0.50 2.11 0.00 0.00 2.42 2.77 1.90 -1.00 0.00 0.00 -4.25 1005.00 +203.00 254852.90 10.30 3.80 2.10 37.23 -0.88 -0.47 0.00 0.00 3.22 3.24 2.40 -1.00 0.00 0.00 -2.56 132.90 +204.00 254876.90 12.44 3.40 2.10 43.52 -2.01 0.52 0.00 0.00 3.15 3.37 1.90 -1.00 0.00 0.00 -3.16 156.90 +205.00 255259.40 14.28 1.60 2.10 32.02 -1.64 0.38 0.00 0.00 1.44 2.53 1.10 -1.00 0.00 0.00 -7.94 539.40 +206.00 255446.20 11.30 2.60 2.10 31.04 -1.19 1.55 0.00 0.00 2.26 1.74 1.30 -1.00 0.00 0.00 -3.99 726.20 +207.00 256183.90 11.48 1.30 2.10 24.40 -0.30 -0.53 0.00 0.00 1.02 2.53 0.60 -1.00 0.00 0.00 -8.97 183.90 +208.00 257352.90 11.86 2.90 2.10 37.75 -3.30 -1.76 0.00 0.00 2.49 3.86 1.90 -1.00 0.00 0.00 -3.82 72.90 +209.00 257632.40 22.34 1.00 2.10 45.03 -3.81 -0.75 0.00 0.00 0.53 2.40 0.80 -1.00 0.00 0.00 -33.63 352.40 +210.00 257700.00 18.71 1.80 2.10 54.43 -2.30 -0.09 0.00 0.00 1.51 3.42 1.50 -1.00 0.00 0.00 -9.93 420.00 +211.00 258490.00 11.44 2.10 2.10 32.30 -1.94 -2.12 0.00 0.00 1.93 3.08 1.90 -1.00 0.00 0.00 -4.73 1210.00 +212.00 258668.20 10.61 1.90 2.10 26.35 -2.55 0.02 0.00 0.00 1.47 2.72 1.30 -1.00 0.00 0.00 -5.78 108.20 +213.00 258785.30 16.98 0.90 2.10 28.98 -2.51 -0.26 0.00 0.00 0.74 1.44 0.60 -1.00 0.00 0.00 -18.28 225.30 +214.00 259601.50 23.85 2.10 2.10 69.93 -1.21 -2.49 0.00 0.00 1.79 3.47 1.50 -1.00 0.00 0.00 -10.68 1041.50 +215.00 261456.00 18.48 1.80 2.10 50.49 -1.80 -2.45 0.00 0.00 1.62 3.36 1.40 -1.00 0.00 0.00 -9.15 336.00 +216.00 262017.00 16.85 3.20 2.10 48.56 -1.96 -0.94 0.00 0.00 3.09 2.77 0.80 -1.00 0.00 0.00 -4.36 897.00 +217.00 262798.90 12.61 1.80 2.10 29.54 -2.63 -0.92 0.00 0.00 1.12 2.88 1.00 -1.00 0.00 0.00 -9.02 398.90 +218.00 263982.50 25.35 1.70 2.10 68.63 -1.31 1.04 0.00 0.00 1.39 3.07 1.10 -1.00 0.00 0.00 -14.62 302.50 +219.00 264231.30 15.61 1.80 2.10 44.27 -3.28 -0.80 0.00 0.00 1.23 3.25 1.30 -1.00 0.00 0.00 -10.19 551.30 +220.00 264488.60 12.86 1.80 2.10 29.16 -3.42 -0.93 0.00 0.00 1.19 2.74 0.80 -1.00 0.00 0.00 -8.67 808.60 +221.00 264741.10 15.57 1.00 2.10 36.17 -2.22 -1.04 0.00 0.00 0.86 2.69 0.70 -1.00 0.00 0.00 -14.43 318.70 +222.00 265321.60 21.29 2.30 2.10 68.28 -1.72 -0.30 0.00 0.00 1.92 3.66 1.70 -1.00 0.00 0.00 -8.88 361.60 +223.00 265333.50 18.07 14.20 2.10 179.41 -1.70 -0.21 255.00 0.00 1.66 2.79 0.80 -1.00 0.00 0.00 -8.72 143.10 +224.00 265720.90 10.06 2.40 2.10 33.01 -2.22 0.77 0.00 0.00 2.16 3.68 2.20 -1.00 0.00 0.00 -3.72 760.90 +225.00 266304.40 13.54 1.00 2.10 30.85 -2.89 0.79 0.00 0.00 0.82 2.65 0.70 -1.00 0.00 0.00 -13.15 346.00 +226.00 266791.40 11.36 1.50 2.10 29.04 -2.14 -0.24 0.00 0.00 1.15 3.05 1.10 -1.00 0.00 0.00 -7.90 551.40 +227.00 266853.10 23.76 1.20 2.10 59.02 -2.97 -1.25 0.00 0.00 0.97 2.77 0.80 -1.00 0.00 0.00 -19.70 613.10 +228.00 267187.30 17.98 1.20 2.10 44.99 -2.57 2.13 0.00 0.00 1.00 2.74 0.80 -1.00 0.00 0.00 -14.32 76.90 +229.00 267301.90 19.10 1.50 2.10 49.77 -2.23 0.33 0.00 0.00 1.13 3.06 1.10 -1.00 0.00 0.00 -13.53 1061.90 +230.00 267307.00 17.48 6.60 2.10 116.87 -2.63 0.55 255.00 0.00 6.33 8.19 6.20 -1.00 0.00 0.00 -2.21 196.60 +231.00 267343.90 14.46 2.10 2.10 39.95 -2.77 -1.82 0.00 0.00 1.86 2.96 1.80 -1.00 0.00 0.00 -6.22 1103.90 +232.00 267774.90 18.52 0.80 2.10 33.39 -1.80 1.26 0.00 0.00 0.58 2.18 0.40 -1.00 0.00 0.00 -25.44 254.90 +233.00 267846.60 15.11 4.60 2.10 55.69 -2.73 1.01 0.00 0.00 4.34 3.36 2.00 -1.00 0.00 0.00 -2.79 326.60 +234.00 268100.60 16.19 3.10 2.10 52.60 -2.29 -0.45 0.00 0.00 2.02 3.68 1.70 -1.00 0.00 0.00 -6.40 580.60 +235.00 268241.60 14.91 2.10 2.10 44.83 -1.47 -1.12 0.00 0.00 1.76 3.72 1.80 -1.00 0.00 0.00 -6.76 363.20 +236.00 268545.20 11.62 1.50 2.10 29.59 -2.07 1.40 0.00 0.00 1.32 3.00 1.00 -1.00 0.00 0.00 -7.03 1025.20 +237.00 268586.40 22.12 0.90 2.10 43.80 -1.30 0.96 0.00 0.00 0.46 2.15 0.70 -1.00 0.00 0.00 -38.52 1066.40 +238.00 269077.20 12.50 1.70 2.10 33.56 -1.60 0.77 0.00 0.00 1.30 3.15 1.20 -1.00 0.00 0.00 -7.71 277.20 +239.00 269242.40 15.80 1.20 2.10 37.81 -2.09 1.76 0.00 0.00 0.97 2.56 0.60 -1.00 0.00 0.00 -13.06 442.40 +240.00 269349.00 10.89 0.60 2.10 21.49 -2.08 1.75 0.00 0.00 0.47 2.38 0.40 -1.00 0.00 0.00 -18.39 549.00 +241.00 269569.10 19.97 1.10 2.10 40.84 -1.73 -1.14 0.00 0.00 0.51 2.32 0.70 -1.00 0.00 0.00 -31.21 769.10 +242.00 270898.00 13.72 3.20 2.10 55.37 -1.47 0.86 0.00 0.00 2.73 4.69 2.70 -1.00 0.00 0.00 -4.02 818.00 +243.00 271162.00 19.07 1.60 2.10 46.26 -2.12 1.08 0.00 0.00 1.15 3.12 1.20 -1.00 0.00 0.00 -13.32 1082.00 +244.00 271282.00 10.87 2.00 2.10 27.00 -2.91 1.14 0.00 0.00 1.83 2.64 0.70 -1.00 0.00 0.00 -4.75 331.60 +245.00 271818.20 12.45 1.70 2.10 35.39 -2.76 -0.08 0.00 0.00 1.56 2.71 1.60 -1.00 0.00 0.00 -6.39 458.20 +246.00 272094.30 11.71 1.80 2.10 32.23 -2.90 -0.75 0.00 0.00 1.60 3.46 1.50 -1.00 0.00 0.00 -5.87 734.30 +247.00 272171.10 15.48 2.60 2.10 45.49 -2.01 0.67 0.00 0.00 1.87 3.51 1.60 -1.00 0.00 0.00 -6.62 811.10 +248.00 272796.60 11.30 2.00 2.10 30.26 -1.61 -0.96 0.00 0.00 1.75 3.23 1.30 -1.00 0.00 0.00 -5.17 156.60 +249.00 273222.00 16.64 1.60 2.10 45.16 -2.42 0.70 0.00 0.00 1.31 3.15 1.20 -1.00 0.00 0.00 -10.13 582.00 +250.00 273237.50 13.90 1.30 2.10 31.87 -4.74 -0.42 0.00 0.00 1.08 2.66 1.00 -1.00 0.00 0.00 -10.33 597.50 +251.00 273356.60 20.55 1.90 2.10 52.81 -2.26 -1.00 0.00 0.00 1.20 2.83 0.90 -1.00 0.00 0.00 -13.67 716.60 +252.00 273738.40 16.22 1.00 2.10 35.30 -2.75 -0.13 0.00 0.00 0.78 2.56 0.60 -1.00 0.00 0.00 -16.61 1098.40 +253.00 273802.10 12.29 3.00 2.10 40.42 -3.14 -1.76 0.00 0.00 2.80 3.52 2.50 -1.00 0.00 0.00 -3.52 1162.10 +254.00 274083.10 18.28 2.60 2.10 59.92 -2.63 -0.21 0.00 0.00 1.46 3.80 2.00 -1.00 0.00 0.00 -10.05 163.10 +255.00 274297.30 22.30 0.90 2.10 43.36 -2.77 -1.04 0.00 0.00 0.62 2.53 0.70 -1.00 0.00 0.00 -28.62 377.30 +256.00 274341.00 10.73 2.30 2.10 33.16 -2.87 -0.77 0.00 0.00 2.04 3.41 1.50 -1.00 0.00 0.00 -4.20 421.00 +257.00 275032.70 14.35 1.10 2.10 32.96 -3.56 2.59 0.00 0.00 0.91 2.56 0.70 -1.00 0.00 0.00 -12.63 1112.70 +258.00 277019.30 13.26 2.10 2.10 39.43 -1.99 0.99 0.00 0.00 1.76 3.58 1.60 -1.00 0.00 0.00 -6.01 539.30 +259.00 278643.50 11.19 2.40 2.10 33.80 -4.36 0.90 0.00 0.00 2.21 3.50 1.60 -1.00 0.00 0.00 -4.05 883.50 +260.00 279589.00 11.87 3.30 2.10 38.58 -2.44 -0.26 0.00 0.00 1.78 3.69 1.70 -1.00 0.00 0.00 -5.35 549.00 +261.00 279956.30 20.62 2.20 2.10 64.32 -3.11 -0.19 0.00 0.00 1.87 3.62 1.70 -1.00 0.00 0.00 -8.82 916.30 +262.00 280348.80 13.81 2.00 2.10 38.71 -2.64 1.30 0.00 0.00 1.56 3.38 1.40 -1.00 0.00 0.00 -7.07 28.80 +263.00 280420.80 12.54 2.70 2.10 37.31 -3.35 -1.76 0.00 0.00 2.50 2.93 2.00 -1.00 0.00 0.00 -4.01 100.80 +264.00 281241.60 15.08 1.10 2.10 32.42 -4.43 0.95 0.00 0.00 0.90 2.65 0.70 -1.00 0.00 0.00 -13.42 921.60 +265.00 282760.10 15.72 2.50 2.10 49.86 -3.28 0.01 0.00 0.00 2.00 3.91 2.00 -1.00 0.00 0.00 -6.28 1160.10 +266.00 283782.00 11.57 1.30 2.10 24.36 -3.42 -0.93 0.00 0.00 1.14 2.48 1.00 -1.00 0.00 0.00 -8.13 902.00 +267.00 285619.50 20.86 2.70 2.10 70.33 -3.84 -1.76 0.00 0.00 2.38 4.12 2.20 -1.00 0.00 0.00 -7.00 179.50 +268.00 286190.10 17.52 2.30 2.10 51.23 -3.05 1.70 0.00 0.00 1.37 3.19 1.50 -1.00 0.00 0.00 -10.26 750.10 +269.00 286347.10 20.07 2.60 2.10 54.72 -2.79 -0.35 0.00 0.00 1.66 3.05 1.20 -1.00 0.00 0.00 -9.70 907.10 +270.00 287192.40 15.91 2.80 2.10 50.57 -2.73 -1.04 0.00 0.00 2.26 3.29 2.10 -1.00 0.00 0.00 -5.62 472.40 +271.00 289733.90 12.27 2.20 2.10 32.35 -3.55 -1.83 0.00 0.00 1.62 2.89 1.40 -1.00 0.00 0.00 -6.05 453.90 +272.00 290770.60 17.28 3.10 2.10 59.83 -4.08 -1.70 0.00 0.00 2.78 3.97 2.00 -1.00 0.00 0.00 -4.97 210.60 +273.00 290836.10 16.32 1.50 2.10 38.80 -3.91 1.90 0.00 0.00 1.11 2.76 0.90 -1.00 0.00 0.00 -11.78 276.10 +274.00 291363.30 11.99 3.30 2.10 36.80 -3.06 -0.27 0.00 0.00 2.58 3.66 1.70 -1.00 0.00 0.00 -3.73 803.30 +275.00 292090.50 11.30 1.20 2.10 26.79 -1.41 -1.24 0.00 0.00 0.93 2.83 0.90 -1.00 0.00 0.00 -9.75 250.50 +276.00 292254.80 11.12 2.20 2.10 33.22 -2.84 0.87 0.00 0.00 2.04 3.86 1.90 -1.00 0.00 0.00 -4.35 414.80 +277.00 292835.30 14.83 2.60 2.10 46.38 -1.70 0.89 0.00 0.00 1.97 3.65 1.70 -1.00 0.00 0.00 -6.03 995.30 +278.00 293170.20 12.24 1.40 2.10 30.56 -2.28 0.10 0.00 0.00 1.20 2.74 0.80 -1.00 0.00 0.00 -8.19 50.20 +279.00 293337.50 15.24 1.50 2.10 37.16 -1.14 0.27 0.00 0.00 1.26 2.88 0.90 -1.00 0.00 0.00 -9.69 217.50 +280.00 293801.80 11.26 2.80 2.10 32.06 -1.87 0.52 0.00 0.00 1.54 3.20 1.30 -1.00 0.00 0.00 -5.83 681.80 +281.00 294656.30 17.76 2.00 2.10 52.76 -3.59 1.90 0.00 0.00 1.14 3.56 1.60 -1.00 0.00 0.00 -12.44 256.30 +282.00 295609.10 10.01 2.60 2.10 26.96 -2.57 0.91 0.00 0.00 2.31 2.03 1.80 -1.00 0.00 0.00 -3.47 1209.10 +283.00 297925.60 13.65 3.00 2.10 47.11 -4.24 -1.82 0.00 0.00 2.36 3.77 1.80 -1.00 0.00 0.00 -4.64 965.60 +284.00 299062.80 14.32 1.70 2.10 39.71 -3.47 -2.04 0.00 0.00 1.33 3.30 1.40 -1.00 0.00 0.00 -8.60 822.80 +285.00 299962.20 11.85 3.10 2.10 29.49 -1.90 0.30 0.00 0.00 2.98 0.68 0.40 -1.00 0.00 0.00 -3.18 442.20 +286.00 300162.70 12.89 2.80 2.10 33.15 -2.02 0.15 0.00 0.00 1.33 2.74 1.00 -1.00 0.00 0.00 -7.77 642.70 +287.00 301663.10 13.40 2.30 2.10 32.48 -3.19 -1.07 0.00 0.00 1.55 3.00 1.20 -1.00 0.00 0.00 -6.92 863.10 +288.00 301802.10 17.55 1.90 2.10 37.67 -3.96 1.26 0.00 0.00 1.34 2.52 1.00 -1.00 0.00 0.00 -10.48 1002.10 +289.00 302515.60 15.69 1.30 2.10 35.28 -4.53 2.09 0.00 0.00 1.14 2.91 1.00 -1.00 0.00 0.00 -11.01 435.60 +290.00 302526.20 10.36 1.40 2.10 20.84 -4.08 -0.17 255.00 0.00 1.29 1.35 1.10 -1.00 0.00 0.00 -6.43 87.80 +291.00 303090.50 11.14 1.30 2.10 23.33 -3.22 1.00 0.00 0.00 1.06 1.46 0.90 -1.00 0.00 0.00 -8.44 1010.50 +292.00 304593.50 11.87 1.30 2.10 23.03 -3.68 -0.70 0.00 0.00 0.76 1.50 0.70 -1.00 0.00 0.00 -12.43 1233.50 +293.00 304910.50 12.26 1.50 2.10 28.92 -3.84 1.29 0.00 0.00 1.29 2.78 0.80 -1.00 0.00 0.00 -7.62 270.50 +294.00 305463.60 18.67 2.00 2.10 57.95 -2.49 -0.52 0.00 0.00 1.56 3.65 1.70 -1.00 0.00 0.00 -9.55 823.60 +295.00 309140.80 12.48 2.60 2.10 34.56 -3.49 0.30 0.00 0.00 2.38 3.28 1.30 -1.00 0.00 0.00 -4.19 660.80 +296.00 310686.60 16.63 1.60 2.10 45.61 -4.13 0.64 0.00 0.00 1.32 3.14 1.20 -1.00 0.00 0.00 -10.08 926.60 +297.00 311075.40 11.97 2.20 2.10 35.93 -4.80 -1.99 0.00 0.00 1.99 3.65 1.70 -1.00 0.00 0.00 -4.82 35.40 +298.00 312560.80 11.54 2.70 2.10 36.94 -3.11 0.44 0.00 0.00 2.43 3.23 2.30 -1.00 0.00 0.00 -3.80 240.80 +299.00 312647.20 14.49 1.60 2.10 37.96 -4.84 -1.48 0.00 0.00 1.37 3.13 1.20 -1.00 0.00 0.00 -8.45 327.20 +300.00 312876.20 23.07 2.80 2.10 67.52 -2.99 -1.07 0.00 0.00 1.26 3.52 1.60 -1.00 0.00 0.00 -14.59 556.20 +301.00 313475.20 13.24 0.90 2.10 21.48 -3.57 -0.42 0.00 0.00 0.48 1.56 0.40 -1.00 0.00 0.00 -21.94 1155.20 +302.00 314857.50 16.21 2.30 2.10 52.13 -2.93 0.55 0.00 0.00 2.14 3.78 1.80 -1.00 0.00 0.00 -6.07 1257.50 +303.00 314882.50 12.71 2.60 2.10 33.50 -4.91 0.03 0.00 0.00 1.53 3.12 1.20 -1.00 0.00 0.00 -6.66 2.50 +304.00 314966.60 14.36 1.90 2.10 39.00 -3.49 -1.16 0.00 0.00 1.67 2.98 1.00 -1.00 0.00 0.00 -6.87 86.60 +305.00 316080.40 19.65 1.70 2.10 53.10 -4.52 0.54 0.00 0.00 1.36 3.02 1.10 -1.00 0.00 0.00 -11.56 1200.40 +306.00 316764.50 13.25 3.50 2.10 40.44 -3.88 1.23 0.00 0.00 2.37 2.50 1.80 -1.00 0.00 0.00 -4.48 604.50 +307.00 316949.40 11.27 2.10 2.10 27.81 -3.67 0.69 0.00 0.00 1.97 2.30 1.30 -1.00 0.00 0.00 -4.57 789.40 +308.00 317438.90 15.32 1.50 2.10 37.13 -4.69 0.66 0.00 0.00 1.23 2.97 1.00 -1.00 0.00 0.00 -9.96 1278.90 +309.00 317439.60 13.41 2.20 2.10 42.39 -4.86 -1.13 0.00 0.00 1.93 3.70 1.70 -1.00 0.00 0.00 -5.57 -0.40 +310.00 318088.20 12.44 1.60 2.10 31.73 -2.80 -0.41 0.00 0.00 1.27 2.99 1.00 -1.00 0.00 0.00 -7.85 648.20 +311.00 318846.90 14.15 2.50 2.10 40.83 -3.28 0.57 0.00 0.00 2.14 3.06 2.00 -1.00 0.00 0.00 -5.30 126.90 +312.00 319044.80 10.46 4.00 2.10 47.76 -3.86 -1.95 0.00 0.00 3.70 5.43 3.50 -1.00 0.00 0.00 -2.26 324.80 +313.00 319575.10 13.05 2.20 2.10 36.81 -3.72 -1.29 0.00 0.00 2.08 3.44 1.50 -1.00 0.00 0.00 -5.03 855.10 +314.00 319877.50 10.44 3.70 2.10 37.39 -3.24 -1.14 0.00 0.00 3.49 3.13 2.70 -1.00 0.00 0.00 -2.40 1157.50 +315.00 320173.90 10.40 2.00 2.10 26.22 -4.58 1.33 0.00 0.00 1.88 2.83 1.30 -1.00 0.00 0.00 -4.43 173.90 +316.00 320340.60 18.12 2.30 2.10 58.30 -3.78 -0.09 0.00 0.00 2.01 3.81 1.90 -1.00 0.00 0.00 -7.22 340.60 +317.00 321030.10 12.80 1.80 2.10 28.21 -3.72 -2.00 0.00 0.00 1.43 2.14 1.00 -1.00 0.00 0.00 -7.15 1030.10 +318.00 321199.70 10.40 2.20 2.10 32.59 -3.75 -0.85 0.00 0.00 2.04 3.77 1.80 -1.00 0.00 0.00 -4.08 1199.70 +319.00 321409.80 12.44 1.70 2.10 32.89 -3.10 0.62 0.00 0.00 1.53 3.47 1.50 -1.00 0.00 0.00 -6.49 129.80 +320.00 322469.60 14.17 3.30 2.10 47.29 -2.91 0.19 0.00 0.00 2.31 3.83 2.00 -1.00 0.00 0.00 -4.90 1189.60 +321.00 323129.80 21.83 3.60 2.10 65.50 -4.51 0.67 0.00 0.00 1.98 3.33 1.40 -1.00 0.00 0.00 -8.80 569.80 +322.00 323155.30 12.03 2.80 2.10 33.75 -4.88 1.05 0.00 0.00 1.47 3.26 1.30 -1.00 0.00 0.00 -6.54 364.90 +323.00 323271.30 14.07 3.30 2.10 49.57 -3.52 1.40 0.00 0.00 3.13 3.99 2.70 -1.00 0.00 0.00 -3.60 711.30 +324.00 323447.40 11.48 2.00 2.10 29.07 -4.62 0.04 0.00 0.00 1.82 2.05 1.10 -1.00 0.00 0.00 -5.05 887.40 +325.00 323734.70 15.76 1.90 2.10 40.60 -4.75 1.78 0.00 0.00 1.64 3.15 1.20 -1.00 0.00 0.00 -7.70 1174.70 +326.00 323742.50 12.89 10.00 2.10 116.29 -3.59 0.08 255.00 0.00 9.02 3.57 1.60 -1.00 0.00 0.00 -1.14 184.10 +327.00 324382.80 10.58 3.30 2.10 39.88 -2.79 0.15 0.00 0.00 2.88 4.41 2.80 -1.00 0.00 0.00 -2.94 542.80 +328.00 324403.90 10.02 2.40 2.10 27.10 -2.89 -0.91 0.00 0.00 1.50 3.28 1.30 -1.00 0.00 0.00 -5.33 77.50 +329.00 324908.10 12.65 2.50 2.10 39.37 -4.08 2.28 0.00 0.00 1.92 3.34 1.70 -1.00 0.00 0.00 -5.27 1068.10 +330.00 325518.60 11.83 1.30 2.10 29.33 -4.36 -0.05 0.00 0.00 0.83 3.12 1.20 -1.00 0.00 0.00 -11.47 398.60 +331.00 326055.50 21.22 1.60 2.10 55.32 -3.13 0.24 0.00 0.00 1.06 2.92 1.00 -1.00 0.00 0.00 -16.06 935.50 +332.00 327010.30 15.77 1.80 2.10 42.91 -3.67 1.00 0.00 0.00 1.10 3.14 1.20 -1.00 0.00 0.00 -11.44 610.30 +333.00 327181.90 22.12 1.50 2.10 52.62 -4.26 0.49 0.00 0.00 1.25 2.92 1.00 -1.00 0.00 0.00 -14.12 781.90 +334.00 330248.70 15.28 3.40 2.10 57.77 -3.56 0.45 0.00 0.00 3.17 4.03 2.70 -1.00 0.00 0.00 -3.86 8.70 +335.00 330340.60 11.71 2.50 2.10 30.12 -2.59 0.21 0.00 0.00 2.28 2.83 1.40 -1.00 0.00 0.00 -4.10 100.60 +336.00 331346.40 12.92 1.70 2.10 32.96 -3.69 -0.84 0.00 0.00 1.35 3.07 1.10 -1.00 0.00 0.00 -7.63 1106.40 +337.00 331386.00 20.66 1.50 2.10 49.43 -3.58 0.33 0.00 0.00 1.00 2.64 0.70 -1.00 0.00 0.00 -16.46 1146.00 +338.00 332225.80 16.99 3.00 2.10 45.30 -3.38 -0.51 0.00 0.00 1.49 3.03 1.10 -1.00 0.00 0.00 -9.11 705.80 +339.00 333143.90 17.26 2.30 2.10 41.32 -2.67 -0.21 0.00 0.00 1.89 2.86 0.90 -1.00 0.00 0.00 -7.32 343.90 +340.00 333339.70 10.21 1.50 2.10 23.17 -3.71 -1.87 0.00 0.00 1.11 2.55 0.60 -1.00 0.00 0.00 -7.34 539.70 +341.00 333470.50 11.88 3.60 2.10 41.05 -3.07 1.58 0.00 0.00 3.40 3.45 2.70 -1.00 0.00 0.00 -2.80 670.50 +342.00 333612.90 20.18 1.80 2.10 55.76 -3.65 -0.67 0.00 0.00 1.52 3.34 1.40 -1.00 0.00 0.00 -10.64 812.90 +343.00 334650.10 15.02 1.00 2.10 30.70 -4.25 0.17 0.00 0.00 0.88 2.59 0.60 -1.00 0.00 0.00 -13.68 570.10 +344.00 335741.50 17.39 2.80 2.10 57.53 -3.56 -0.11 0.00 0.00 1.61 3.80 1.90 -1.00 0.00 0.00 -8.62 381.50 +345.00 335943.80 10.91 1.70 2.10 29.57 -3.97 -0.07 0.00 0.00 1.46 3.23 1.40 -1.00 0.00 0.00 -5.99 583.80 +346.00 336065.20 13.32 1.90 2.10 34.37 -3.00 0.07 0.00 0.00 1.73 2.72 1.30 -1.00 0.00 0.00 -6.16 705.20 +347.00 336320.70 15.67 2.10 2.10 39.74 -3.93 -0.24 0.00 0.00 1.42 3.15 1.20 -1.00 0.00 0.00 -8.85 960.70 +348.00 336841.80 16.18 1.60 2.10 40.94 -7.39 -0.39 0.00 0.00 1.31 3.05 1.10 -1.00 0.00 0.00 -9.90 201.80 +349.00 338665.50 11.52 1.20 2.10 24.50 -5.57 0.12 0.00 0.00 1.11 2.26 0.30 -1.00 0.00 0.00 -8.32 745.50 +350.00 338672.60 12.92 8.30 2.10 78.03 -5.58 0.08 255.00 0.00 8.07 2.42 1.40 -1.00 0.00 0.00 -1.28 138.20 +351.00 338719.30 12.28 1.70 2.10 31.52 -5.24 0.89 0.00 0.00 1.42 3.14 1.20 -1.00 0.00 0.00 -6.91 799.30 +352.00 338768.90 13.88 2.90 2.10 46.57 -5.18 1.99 0.00 0.00 2.49 3.95 2.10 -1.00 0.00 0.00 -4.46 848.90 +353.00 339850.80 17.10 2.20 2.10 43.04 -5.44 -0.03 0.00 0.00 1.48 2.91 1.20 -1.00 0.00 0.00 -9.24 650.80 +354.00 340419.90 13.03 2.20 2.10 37.81 -6.28 3.20 0.00 0.00 1.93 3.32 1.70 -1.00 0.00 0.00 -5.40 1219.90 +355.00 340657.30 11.61 2.80 2.10 32.99 -4.12 -1.47 0.00 0.00 2.63 3.64 2.50 -1.00 0.00 0.00 -3.53 177.30 +356.00 340730.10 13.41 2.00 2.10 36.82 -3.19 -1.70 0.00 0.00 0.93 3.06 1.10 -1.00 0.00 0.00 -11.58 250.10 +357.00 341369.70 13.89 2.20 2.10 43.75 -4.79 -0.38 0.00 0.00 1.92 3.72 1.80 -1.00 0.00 0.00 -5.80 147.30 +358.00 341586.00 22.71 1.90 2.10 58.26 -4.74 -1.40 0.00 0.00 1.40 3.06 1.10 -1.00 0.00 0.00 -12.97 1106.00 +359.00 341856.90 10.83 3.70 2.10 33.79 -5.47 2.00 0.00 0.00 2.79 2.98 2.10 -1.00 0.00 0.00 -3.10 96.90 +360.00 341909.70 10.70 2.70 2.10 27.03 -5.22 -0.30 0.00 0.00 1.67 1.96 1.40 -1.00 0.00 0.00 -5.11 149.70 +361.00 341925.10 15.40 1.20 2.10 35.32 -5.55 -1.36 0.00 0.00 0.92 2.50 0.50 -1.00 0.00 0.00 -13.43 165.10 +362.00 342825.40 28.94 2.00 2.10 88.38 -5.46 -1.06 0.00 0.00 1.04 3.36 1.40 -1.00 0.00 0.00 -22.20 1065.40 +363.00 343412.10 17.45 1.60 2.10 38.14 -4.65 -2.59 0.00 0.00 1.06 2.63 0.70 -1.00 0.00 0.00 -13.22 372.10 +364.00 343515.50 11.03 1.50 2.10 22.66 -5.70 0.61 0.00 0.00 1.04 1.92 0.80 -1.00 0.00 0.00 -8.45 475.50 +365.00 343873.00 11.70 2.00 2.10 31.84 -5.01 0.02 0.00 0.00 1.33 2.73 1.40 -1.00 0.00 0.00 -7.06 833.00 +366.00 344046.10 14.81 3.00 2.10 52.21 -4.52 0.04 0.00 0.00 2.57 4.20 2.30 -1.00 0.00 0.00 -4.61 1006.10 +367.00 344177.30 13.80 4.20 2.10 51.61 -5.97 1.77 0.00 0.00 3.09 3.96 2.00 -1.00 0.00 0.00 -3.57 1137.30 +368.00 345563.90 10.63 1.80 2.10 25.51 -6.17 0.28 0.00 0.00 1.62 1.79 0.80 -1.00 0.00 0.00 -5.26 1243.90 +369.00 346127.80 13.92 2.20 2.10 39.70 -5.25 0.41 0.00 0.00 1.80 3.15 1.20 -1.00 0.00 0.00 -6.18 527.80 +370.00 348366.20 16.28 1.70 2.10 44.17 -5.01 -0.93 0.00 0.00 1.41 3.27 1.30 -1.00 0.00 0.00 -9.23 206.20 +371.00 348835.10 11.84 2.40 2.10 30.18 -4.41 -1.18 0.00 0.00 1.87 2.76 1.40 -1.00 0.00 0.00 -5.06 675.10 +372.00 349036.00 10.55 1.40 2.10 25.17 -4.40 -0.97 0.00 0.00 1.04 2.84 0.90 -1.00 0.00 0.00 -8.11 876.00 +373.00 349192.50 10.91 2.70 2.10 38.32 -4.14 1.39 0.00 0.00 2.52 4.33 2.40 -1.00 0.00 0.00 -3.47 1032.50 +374.00 349549.60 11.01 1.40 2.10 24.63 -5.07 0.08 0.00 0.00 1.27 2.79 0.80 -1.00 0.00 0.00 -6.91 109.60 +375.00 350169.50 13.54 1.40 2.10 32.25 -4.78 -0.33 0.00 0.00 1.08 2.63 0.70 -1.00 0.00 0.00 -10.01 729.50 +376.00 350939.40 12.66 2.30 2.10 40.90 -3.63 -1.03 0.00 0.00 1.95 3.42 1.50 -1.00 0.00 0.00 -5.19 117.00 +377.00 351345.80 12.14 2.20 2.10 34.50 -7.94 0.83 0.00 0.00 1.94 3.29 1.80 -1.00 0.00 0.00 -5.00 625.80 +378.00 353520.30 13.82 2.90 2.10 47.70 -2.97 0.82 0.00 0.00 2.17 4.00 2.00 -1.00 0.00 0.00 -5.10 240.30 +379.00 353982.70 11.68 1.20 2.10 26.93 -5.79 0.62 0.00 0.00 0.80 2.72 0.80 -1.00 0.00 0.00 -11.72 702.70 +380.00 354008.00 17.60 2.10 2.10 48.02 -5.75 -0.62 0.00 0.00 1.32 3.04 1.10 -1.00 0.00 0.00 -10.63 113.60 +381.00 355423.60 21.21 2.50 2.10 67.35 -5.43 0.56 0.00 0.00 1.68 3.82 2.00 -1.00 0.00 0.00 -10.11 863.60 +382.00 355706.30 16.02 1.30 2.10 37.85 -5.31 1.52 0.00 0.00 1.10 2.76 0.80 -1.00 0.00 0.00 -11.65 1146.30 +383.00 355922.20 16.89 1.90 2.10 48.33 -5.57 0.82 0.00 0.00 1.66 3.33 1.40 -1.00 0.00 0.00 -8.13 82.20 +384.00 356372.90 11.10 1.50 2.10 22.58 -5.13 0.78 0.00 0.00 0.96 1.66 0.90 -1.00 0.00 0.00 -9.28 532.90 +385.00 357486.90 13.60 1.90 2.10 35.38 -6.89 -0.93 0.00 0.00 1.61 2.73 1.40 -1.00 0.00 0.00 -6.74 366.90 +386.00 358346.50 15.16 3.00 2.10 37.83 -4.97 -0.27 0.00 0.00 1.27 2.63 1.00 -1.00 0.00 0.00 -9.58 1226.50 +387.00 359215.60 13.03 3.30 2.10 42.73 -6.50 -0.52 0.00 0.00 2.59 3.96 2.00 -1.00 0.00 0.00 -4.03 815.60 +388.00 359271.10 20.31 2.80 2.10 65.72 -5.03 0.98 0.00 0.00 2.32 3.99 2.00 -1.00 0.00 0.00 -7.02 871.10 +389.00 359586.80 12.70 1.50 2.10 25.57 -6.02 0.15 0.00 0.00 0.93 1.85 0.60 -1.00 0.00 0.00 -10.88 1186.80 +390.00 360112.60 10.91 1.40 2.10 26.62 -4.65 -0.99 0.00 0.00 1.15 2.78 0.80 -1.00 0.00 0.00 -7.56 432.60 +391.00 363150.20 19.29 1.60 2.10 53.06 -6.56 0.85 0.00 0.00 1.25 3.07 1.10 -1.00 0.00 0.00 -12.35 910.20 +392.00 363364.80 15.32 3.40 2.10 51.80 -5.20 -1.97 0.00 0.00 2.47 4.12 2.20 -1.00 0.00 0.00 -4.96 1124.80 +393.00 364661.80 13.04 2.60 2.10 36.62 -5.33 -0.44 0.00 0.00 2.08 3.41 1.50 -1.00 0.00 0.00 -5.02 1141.80 +394.00 364827.70 11.10 1.10 2.10 26.79 -6.08 1.73 0.00 0.00 0.90 2.63 0.70 -1.00 0.00 0.00 -9.87 27.70 +395.00 365703.90 12.17 1.90 2.10 31.69 -6.66 -0.85 0.00 0.00 1.68 3.35 1.40 -1.00 0.00 0.00 -5.81 903.90 +396.00 365831.90 13.04 1.80 2.10 30.79 -5.97 1.20 0.00 0.00 1.15 2.66 0.70 -1.00 0.00 0.00 -9.08 1031.90 +397.00 365983.90 11.57 1.80 2.10 27.18 -5.04 1.15 0.00 0.00 1.23 2.25 0.90 -1.00 0.00 0.00 -7.51 1183.90 +398.00 367140.20 11.76 1.50 2.10 28.23 -6.24 0.37 0.00 0.00 1.27 2.48 1.00 -1.00 0.00 0.00 -7.41 1060.20 +399.00 367666.40 14.66 2.00 2.10 38.88 -5.95 -0.58 0.00 0.00 1.14 3.01 1.10 -1.00 0.00 0.00 -10.29 306.40 +400.00 367899.80 13.80 1.40 2.10 36.45 -5.31 -0.67 0.00 0.00 1.23 2.90 0.90 -1.00 0.00 0.00 -8.94 539.80 +401.00 368276.90 10.47 2.60 2.10 28.99 -4.92 -0.67 0.00 0.00 2.39 2.14 1.70 -1.00 0.00 0.00 -3.51 916.90 +402.00 369411.20 12.32 3.40 2.10 36.47 -4.90 0.56 0.00 0.00 2.25 3.63 1.80 -1.00 0.00 0.00 -4.38 771.20 +403.00 370109.20 10.66 2.20 2.10 30.20 -5.34 -1.11 0.00 0.00 2.04 3.10 1.20 -1.00 0.00 0.00 -4.17 189.20 +404.00 370134.60 10.02 2.40 2.10 28.57 -7.05 0.60 0.00 0.00 1.79 3.39 1.40 -1.00 0.00 0.00 -4.47 214.60 +405.00 370182.20 10.51 1.70 2.10 24.94 -7.40 1.59 0.00 0.00 1.49 2.31 1.00 -1.00 0.00 0.00 -5.64 262.20 +406.00 370324.90 14.13 2.20 2.10 42.57 -6.53 -0.31 0.00 0.00 1.95 3.65 1.70 -1.00 0.00 0.00 -5.78 404.90 +407.00 370681.70 16.32 1.60 2.10 42.04 -6.08 -0.96 0.00 0.00 1.35 3.07 1.10 -1.00 0.00 0.00 -9.65 761.70 +408.00 370803.90 14.15 2.60 2.10 45.36 -7.77 1.30 0.00 0.00 2.43 3.94 2.00 -1.00 0.00 0.00 -4.66 883.90 +409.00 370943.90 10.39 2.20 2.10 28.97 -7.73 -0.47 0.00 0.00 1.40 2.54 1.60 -1.00 0.00 0.00 -5.93 1023.90 +410.00 371967.20 13.06 1.80 2.10 35.95 -5.42 1.43 0.00 0.00 1.61 3.52 1.60 -1.00 0.00 0.00 -6.49 767.20 +411.00 372308.70 11.04 1.80 2.10 25.94 -6.68 -0.04 0.00 0.00 1.58 2.60 0.90 -1.00 0.00 0.00 -5.59 1108.70 +412.00 372554.80 11.01 1.40 2.10 20.73 -6.25 -1.09 0.00 0.00 1.22 1.94 0.60 -1.00 0.00 0.00 -7.20 74.80 +413.00 372921.40 19.46 3.30 2.10 67.65 -5.71 -0.33 0.00 0.00 2.46 4.16 2.20 -1.00 0.00 0.00 -6.34 441.40 +414.00 372999.40 11.36 0.90 2.10 23.53 -6.26 -0.35 0.00 0.00 0.75 1.91 0.80 -1.00 0.00 0.00 -12.05 519.40 +415.00 373590.20 11.19 2.80 2.10 38.69 -5.86 -0.28 0.00 0.00 2.46 4.10 2.10 -1.00 0.00 0.00 -3.64 1110.20 +416.00 373638.70 15.06 1.90 2.10 33.81 -4.55 -0.63 0.00 0.00 1.63 2.82 1.10 -1.00 0.00 0.00 -7.39 1158.70 +417.00 373654.20 12.10 1.00 2.10 26.68 -5.41 -0.07 0.00 0.00 0.90 2.76 0.80 -1.00 0.00 0.00 -10.81 175.80 +418.00 374056.30 10.35 1.50 2.10 24.13 -6.18 1.60 0.00 0.00 1.24 2.45 1.00 -1.00 0.00 0.00 -6.67 296.30 +419.00 374251.10 10.37 1.70 2.10 26.71 -6.93 -0.35 0.00 0.00 1.54 2.95 1.30 -1.00 0.00 0.00 -5.38 491.10 +420.00 374376.00 10.08 1.80 2.10 24.43 -6.38 0.20 0.00 0.00 1.54 1.78 0.90 -1.00 0.00 0.00 -5.24 616.00 +421.00 374728.70 16.38 1.90 2.10 49.76 -5.47 1.24 0.00 0.00 1.20 3.43 1.50 -1.00 0.00 0.00 -10.90 98.30 +422.00 375172.00 11.79 1.00 2.10 26.48 -6.03 1.40 0.00 0.00 0.70 2.81 0.90 -1.00 0.00 0.00 -13.52 132.00 +423.00 375203.10 11.20 2.10 2.10 25.47 -6.60 -1.74 0.00 0.00 1.15 2.61 0.70 -1.00 0.00 0.00 -7.79 163.10 +424.00 375361.70 10.43 1.20 2.10 24.56 -5.65 1.38 0.00 0.00 1.06 2.90 0.90 -1.00 0.00 0.00 -7.88 321.70 +425.00 375528.40 12.00 2.70 2.10 28.98 -6.13 1.48 0.00 0.00 1.52 2.50 0.60 -1.00 0.00 0.00 -6.32 488.40 +426.00 375856.20 11.89 3.00 2.10 40.75 -5.49 0.13 0.00 0.00 2.53 4.14 2.20 -1.00 0.00 0.00 -3.76 73.80 +427.00 376409.10 11.31 2.10 2.10 31.80 -5.50 0.25 0.00 0.00 1.32 3.23 1.30 -1.00 0.00 0.00 -6.87 114.70 +428.00 376513.30 14.57 1.90 2.10 40.72 -7.80 1.06 0.00 0.00 1.50 3.23 1.30 -1.00 0.00 0.00 -7.78 193.30 +429.00 377359.90 20.20 2.10 2.10 58.15 -5.77 0.82 0.00 0.00 1.73 3.36 1.40 -1.00 0.00 0.00 -9.35 1039.90 +430.00 377383.80 18.48 2.90 2.10 53.66 -5.78 -0.74 0.00 0.00 1.12 3.02 1.10 -1.00 0.00 0.00 -13.22 65.40 +431.00 379001.90 12.35 2.40 2.10 36.21 -5.55 -1.58 0.00 0.00 2.14 3.25 1.70 -1.00 0.00 0.00 -4.63 121.90 +432.00 379532.00 17.00 1.60 2.10 40.47 -5.95 1.76 0.00 0.00 1.13 2.64 0.80 -1.00 0.00 0.00 -12.04 652.00 +433.00 379900.60 18.32 2.00 2.10 57.33 -6.16 1.84 0.00 0.00 1.21 3.43 1.50 -1.00 0.00 0.00 -12.07 1020.60 +434.00 380970.30 18.23 1.90 2.10 51.84 -6.23 -0.70 0.00 0.00 1.70 3.39 1.40 -1.00 0.00 0.00 -8.60 810.30 +435.00 381100.30 14.56 2.20 2.10 41.87 -6.95 0.30 0.00 0.00 1.82 3.16 1.70 -1.00 0.00 0.00 -6.39 940.30 +436.00 381546.80 10.61 3.60 2.10 39.91 -6.32 1.03 0.00 0.00 3.31 3.64 2.70 -1.00 0.00 0.00 -2.56 106.80 +437.00 382280.90 12.40 1.80 2.10 33.28 -6.89 -0.48 0.00 0.00 1.51 3.25 1.30 -1.00 0.00 0.00 -6.57 840.90 +438.00 382370.90 13.03 2.60 2.10 40.20 -8.26 -0.80 0.00 0.00 2.34 3.91 2.00 -1.00 0.00 0.00 -4.45 60.50 +439.00 383182.70 18.71 4.30 2.10 56.30 -6.11 1.42 0.00 0.00 1.72 3.09 1.10 -1.00 0.00 0.00 -8.71 462.70 +440.00 383729.10 12.91 1.90 2.10 39.45 -6.56 0.30 0.00 0.00 1.22 3.57 1.60 -1.00 0.00 0.00 -8.49 1009.10 +441.00 383770.80 13.37 2.30 2.10 37.32 -5.98 0.14 0.00 0.00 2.11 3.53 1.60 -1.00 0.00 0.00 -5.07 1050.80 +442.00 384804.90 18.37 2.80 2.10 54.27 -6.59 2.44 0.00 0.00 1.29 3.38 1.40 -1.00 0.00 0.00 -11.41 804.90 +443.00 385037.40 22.00 1.90 2.10 63.17 -6.35 0.74 0.00 0.00 1.16 3.36 1.40 -1.00 0.00 0.00 -15.23 1037.40 +444.00 385082.60 11.29 1.70 2.10 27.86 -6.07 -0.57 0.00 0.00 0.92 2.81 0.90 -1.00 0.00 0.00 -9.80 1082.60 +445.00 385854.20 12.13 1.90 2.10 29.41 -6.50 0.62 0.00 0.00 1.63 2.74 0.80 -1.00 0.00 0.00 -5.94 574.20 +446.00 386545.50 15.85 2.30 2.10 48.71 -6.71 -0.73 0.00 0.00 1.87 3.64 1.70 -1.00 0.00 0.00 -6.77 1265.50 +447.00 386568.60 10.91 2.20 2.10 29.82 -7.97 0.35 0.00 0.00 1.86 2.86 1.20 -1.00 0.00 0.00 -4.70 8.60 +448.00 386779.20 16.09 1.90 2.10 40.44 -6.47 -0.24 0.00 0.00 1.69 3.36 1.40 -1.00 0.00 0.00 -7.62 219.20 +449.00 387238.30 12.70 2.90 2.10 43.70 -6.08 -1.70 0.00 0.00 2.69 3.67 2.00 -1.00 0.00 0.00 -3.78 678.30 +450.00 387830.00 13.24 2.10 2.10 37.17 -6.29 -0.43 0.00 0.00 1.72 3.22 1.30 -1.00 0.00 0.00 -6.15 1270.00 +451.00 387848.00 22.62 2.10 2.10 64.68 -9.02 0.57 255.00 0.00 1.78 3.43 1.50 -1.00 0.00 0.00 -10.18 8.00 +452.00 387869.50 29.18 2.80 2.10 100.20 -11.45 -0.34 255.00 0.00 1.91 4.08 2.10 -1.00 0.00 0.00 -12.20 29.50 +453.00 388448.60 10.87 2.90 2.10 37.44 -5.06 1.04 0.00 0.00 2.71 4.33 2.40 -1.00 0.00 0.00 -3.21 608.60 +454.00 389032.20 13.86 2.10 2.10 40.87 -6.45 -1.42 0.00 0.00 1.79 3.52 1.90 -1.00 0.00 0.00 -6.20 1192.20 +455.00 389052.40 10.35 1.00 2.10 21.52 -6.32 1.62 0.00 0.00 0.92 2.25 0.30 -1.00 0.00 0.00 -8.98 86.00 +456.00 389961.40 12.86 3.40 2.10 43.62 -6.01 1.79 0.00 0.00 2.70 4.01 2.60 -1.00 0.00 0.00 -3.82 841.40 +457.00 390202.00 12.44 2.50 2.10 33.83 -5.02 1.11 0.00 0.00 1.29 3.01 1.10 -1.00 0.00 0.00 -7.70 211.60 +458.00 390446.40 12.67 1.60 2.10 33.33 -5.94 -0.17 0.00 0.00 1.42 3.11 1.20 -1.00 0.00 0.00 -7.13 46.40 +459.00 390604.40 14.89 2.30 2.10 44.30 -6.83 -0.38 0.00 0.00 1.79 3.55 1.70 -1.00 0.00 0.00 -6.67 204.40 +460.00 390635.80 10.20 2.30 2.10 29.21 -6.82 -0.92 0.00 0.00 1.94 3.45 1.50 -1.00 0.00 0.00 -4.20 235.80 +461.00 391835.40 18.43 3.00 2.10 68.18 -5.80 -0.29 0.00 0.00 2.86 4.56 2.60 -1.00 0.00 0.00 -5.16 155.40 +462.00 391930.70 14.12 1.60 2.10 30.41 -6.64 0.91 0.00 0.00 1.16 1.58 1.00 -1.00 0.00 0.00 -9.74 250.70 +463.00 392127.70 14.54 2.70 2.10 47.99 -5.02 1.84 0.00 0.00 2.41 3.99 2.00 -1.00 0.00 0.00 -4.82 447.70 +464.00 393136.40 12.66 1.70 2.10 31.57 -6.30 0.40 0.00 0.00 1.46 2.90 0.90 -1.00 0.00 0.00 -6.96 74.00 +465.00 393230.50 12.17 2.10 2.10 33.68 -6.47 1.76 0.00 0.00 1.66 3.52 1.60 -1.00 0.00 0.00 -5.86 270.50 +466.00 393403.30 24.19 2.20 2.10 77.04 -5.06 2.21 0.00 0.00 1.15 3.70 1.70 -1.00 0.00 0.00 -16.76 443.30 +467.00 394239.00 15.19 2.40 2.10 42.63 -5.50 1.81 0.00 0.00 1.91 3.41 1.50 -1.00 0.00 0.00 -6.37 152.60 +468.00 394500.60 10.96 2.40 2.10 32.43 -6.86 -0.48 0.00 0.00 2.15 3.39 2.00 -1.00 0.00 0.00 -4.08 260.60 +469.00 395544.10 11.26 1.10 2.10 27.09 -5.91 -0.71 0.00 0.00 0.90 2.76 0.80 -1.00 0.00 0.00 -10.04 24.10 +470.00 395555.50 11.43 12.50 2.10 90.76 -5.47 0.33 255.00 0.00 2.91 2.75 0.80 -1.00 0.00 0.00 -3.15 189.10 +471.00 396069.10 15.17 1.50 2.10 36.98 -5.38 -1.23 0.00 0.00 1.02 2.92 1.00 -1.00 0.00 0.00 -11.86 549.10 +472.00 396106.80 15.63 2.00 2.10 36.42 -6.73 -1.34 0.00 0.00 1.47 2.51 0.80 -1.00 0.00 0.00 -8.51 586.80 +473.00 396159.30 14.68 2.80 2.10 41.94 -6.17 -1.32 0.00 0.00 1.92 3.60 1.80 -1.00 0.00 0.00 -6.12 639.30 +474.00 396358.00 13.98 2.60 2.10 40.87 -5.98 1.23 0.00 0.00 2.18 3.64 1.70 -1.00 0.00 0.00 -5.12 838.00 +475.00 396694.00 11.47 1.50 2.10 24.05 -8.04 2.01 0.00 0.00 1.38 2.16 1.00 -1.00 0.00 0.00 -6.65 1174.00 +476.00 396749.10 10.90 1.40 2.10 24.77 -6.13 -0.78 0.00 0.00 1.22 2.93 1.00 -1.00 0.00 0.00 -7.17 1229.10 +477.00 396907.70 12.09 2.00 2.10 35.22 -6.02 2.26 0.00 0.00 1.73 3.18 1.50 -1.00 0.00 0.00 -5.60 107.70 +478.00 397686.90 10.02 2.40 2.10 25.74 -6.04 -0.75 0.00 0.00 2.23 2.90 0.90 -1.00 0.00 0.00 -3.59 886.90 +479.00 398730.40 10.58 1.60 2.10 22.49 -6.32 2.19 0.00 0.00 1.23 2.20 0.80 -1.00 0.00 0.00 -6.88 36.00 +480.00 398783.70 14.60 1.20 2.10 33.39 -8.28 0.84 0.00 0.00 0.94 2.51 0.60 -1.00 0.00 0.00 -12.38 89.30 +481.00 399517.20 14.20 2.50 2.10 45.57 -7.17 0.74 0.00 0.00 2.06 3.92 2.00 -1.00 0.00 0.00 -5.51 157.20 +482.00 400640.90 10.06 2.30 2.10 29.08 -4.97 -1.38 0.00 0.00 2.07 1.16 1.00 -1.00 0.00 0.00 -3.88 1280.90 +483.00 403083.70 11.58 3.50 2.10 43.77 -7.36 -0.67 0.00 0.00 3.29 4.06 2.50 -1.00 0.00 0.00 -2.82 37.30 +484.00 404541.70 20.90 2.20 2.10 67.93 -7.05 0.39 0.00 0.00 1.56 3.52 1.60 -1.00 0.00 0.00 -10.70 61.70 +485.00 406297.30 15.73 1.70 2.10 38.67 -5.39 -0.39 0.00 0.00 1.27 3.03 1.10 -1.00 0.00 0.00 -9.92 537.30 +486.00 406586.60 17.84 3.20 2.10 64.30 -6.17 0.33 0.00 0.00 2.35 4.52 2.60 -1.00 0.00 0.00 -6.08 826.60 +487.00 406612.80 11.32 2.60 2.10 38.99 -7.79 -0.80 0.00 0.00 2.28 4.22 2.30 -1.00 0.00 0.00 -3.96 852.80 +488.00 406830.00 11.92 1.90 2.10 31.75 -5.60 0.95 0.00 0.00 1.66 3.18 1.20 -1.00 0.00 0.00 -5.76 1070.00 +489.00 407618.40 15.31 2.00 2.10 41.72 -6.91 1.75 0.00 0.00 1.44 2.89 0.90 -1.00 0.00 0.00 -8.49 578.40 +490.00 408142.30 11.94 3.20 2.10 42.03 -6.89 -1.09 0.00 0.00 2.65 4.23 2.40 -1.00 0.00 0.00 -3.61 231.90 +491.00 408242.60 10.76 3.90 2.10 44.74 -5.97 0.27 0.00 0.00 3.58 4.97 3.00 -1.00 0.00 0.00 -2.41 76.20 +492.00 408304.80 12.03 1.40 2.10 28.03 -7.23 -0.91 0.00 0.00 1.14 2.86 0.90 -1.00 0.00 0.00 -8.41 138.40 +493.00 408434.80 12.87 1.20 2.10 29.75 -7.91 -1.14 0.00 0.00 0.83 2.83 0.90 -1.00 0.00 0.00 -12.46 114.80 +494.00 408469.40 12.28 1.90 2.10 27.92 -7.30 -1.68 0.00 0.00 1.68 2.81 1.30 -1.00 0.00 0.00 -5.86 149.40 +495.00 408697.80 13.09 2.20 2.10 40.57 -6.97 1.03 0.00 0.00 1.84 3.58 1.60 -1.00 0.00 0.00 -5.68 377.80 +496.00 409464.70 14.59 2.70 2.10 39.29 -5.84 1.72 0.00 0.00 2.40 2.15 1.80 -1.00 0.00 0.00 -4.87 1144.70 +497.00 410207.60 18.64 1.60 2.10 47.81 -5.00 0.20 0.00 0.00 1.41 3.14 1.20 -1.00 0.00 0.00 -10.59 607.60 +498.00 410364.80 19.28 2.10 2.10 60.12 -5.59 0.58 0.00 0.00 1.53 3.57 1.60 -1.00 0.00 0.00 -10.06 764.80 +499.00 411586.40 15.43 2.30 2.10 48.16 -6.08 -0.63 0.00 0.00 1.80 3.60 1.60 -1.00 0.00 0.00 -6.85 92.00 +500.00 411712.40 10.02 2.60 2.10 31.85 -5.13 -1.24 0.00 0.00 2.41 3.22 2.00 -1.00 0.00 0.00 -3.33 832.40 +501.00 412746.40 15.33 1.70 2.10 42.57 -5.85 -2.50 0.00 0.00 1.18 3.16 1.20 -1.00 0.00 0.00 -10.35 586.40 +502.00 412871.30 11.94 1.80 2.10 30.46 -5.13 0.65 0.00 0.00 1.44 3.21 1.30 -1.00 0.00 0.00 -6.62 711.30 +503.00 413600.00 20.19 1.80 2.10 53.65 -6.11 -0.89 0.00 0.00 1.52 3.11 1.20 -1.00 0.00 0.00 -10.64 57.60 +504.00 414431.60 12.44 3.90 2.10 47.75 -6.16 0.35 0.00 0.00 3.48 3.62 2.80 -1.00 0.00 0.00 -2.86 991.60 +505.00 414957.40 17.57 3.20 2.10 65.41 -5.94 0.24 0.00 0.00 2.99 4.67 2.70 -1.00 0.00 0.00 -4.70 237.40 +506.00 415124.00 10.82 2.00 2.10 28.94 -6.32 0.75 0.00 0.00 1.80 3.06 1.50 -1.00 0.00 0.00 -4.81 404.00 +507.00 415372.20 14.02 1.50 2.10 34.13 -6.11 0.20 0.00 0.00 0.95 2.58 0.60 -1.00 0.00 0.00 -11.80 37.80 +508.00 415464.70 10.06 1.60 2.10 24.85 -5.29 1.07 0.00 0.00 1.41 2.76 0.80 -1.00 0.00 0.00 -5.69 130.30 +509.00 415834.40 11.87 3.00 2.10 43.55 -5.88 0.71 0.00 0.00 2.85 3.93 2.50 -1.00 0.00 0.00 -3.33 1114.40 +510.00 416429.00 10.15 1.70 2.10 22.07 -5.86 1.56 0.00 0.00 1.02 2.31 0.40 -1.00 0.00 0.00 -7.92 70.60 +511.00 416787.60 11.98 1.10 2.10 24.54 -4.93 -1.58 0.00 0.00 0.89 2.37 0.40 -1.00 0.00 0.00 -10.78 787.60 +512.00 416964.40 13.10 1.10 2.10 27.58 -8.15 1.65 0.00 0.00 0.96 2.29 0.30 -1.00 0.00 0.00 -10.86 94.00 +513.00 417057.00 16.46 2.70 2.10 52.39 -5.78 -0.86 0.00 0.00 1.29 3.80 1.90 -1.00 0.00 0.00 -10.20 186.60 +514.00 418270.40 17.23 5.10 2.10 68.72 -7.62 0.01 0.00 0.00 3.85 4.14 2.60 -1.00 0.00 0.00 -3.58 990.40 +515.00 418517.70 17.84 2.90 2.10 63.43 -6.06 -2.02 0.00 0.00 2.42 4.07 2.10 -1.00 0.00 0.00 -5.89 1237.70 +516.00 419164.10 16.47 2.50 2.10 53.19 -7.27 0.21 0.00 0.00 2.27 3.95 2.00 -1.00 0.00 0.00 -5.81 604.10 +517.00 419174.00 13.82 12.40 2.10 128.92 -7.72 1.43 255.00 0.00 12.07 3.40 1.50 -1.00 0.00 0.00 -0.92 127.60 +518.00 420441.50 15.79 1.50 2.10 38.16 -6.63 1.73 0.00 0.00 1.27 2.94 1.00 -1.00 0.00 0.00 -9.92 115.10 +519.00 420498.10 13.93 2.80 2.10 43.63 -6.19 1.17 0.00 0.00 2.60 3.23 1.60 -1.00 0.00 0.00 -4.29 658.10 +520.00 420959.10 10.97 1.60 2.10 25.52 -8.07 1.64 0.00 0.00 0.93 2.66 0.70 -1.00 0.00 0.00 -9.44 1119.10 +521.00 421198.20 13.01 0.60 2.10 24.53 -7.66 -0.20 0.00 0.00 0.40 2.26 0.30 -1.00 0.00 0.00 -25.99 78.20 +522.00 421535.70 18.16 2.50 2.10 57.81 -7.96 -0.31 0.00 0.00 2.21 3.75 1.90 -1.00 0.00 0.00 -6.56 415.70 +523.00 421566.50 12.27 2.20 2.10 31.91 -7.03 1.43 0.00 0.00 1.98 2.98 2.00 -1.00 0.00 0.00 -4.97 446.50 +524.00 421614.60 10.34 3.00 2.10 27.61 -6.85 -2.85 0.00 0.00 2.87 2.02 0.70 -1.00 0.00 0.00 -2.89 494.60 +525.00 421822.50 12.03 2.20 2.10 30.60 -6.46 0.44 0.00 0.00 1.62 3.35 1.40 -1.00 0.00 0.00 -5.95 702.50 +526.00 422019.70 16.43 1.20 2.10 37.74 -6.94 -1.29 0.00 0.00 1.01 2.68 0.70 -1.00 0.00 0.00 -13.00 899.70 +527.00 422319.70 13.13 2.00 2.10 35.98 -6.38 1.38 0.00 0.00 1.75 3.30 1.40 -1.00 0.00 0.00 -6.01 1199.70 +528.00 423037.10 15.51 2.90 2.10 50.00 -6.17 0.39 0.00 0.00 2.54 3.77 2.40 -1.00 0.00 0.00 -4.89 637.10 +529.00 424345.90 14.30 3.30 2.10 54.17 -7.05 -0.09 0.00 0.00 2.54 4.18 2.20 -1.00 0.00 0.00 -4.50 665.90 +530.00 424719.50 11.95 2.90 2.10 43.81 -6.42 -0.27 0.00 0.00 2.68 3.50 2.40 -1.00 0.00 0.00 -3.57 1039.50 +531.00 426511.80 20.00 4.80 2.10 58.42 -5.14 0.32 0.00 0.00 1.58 3.23 1.30 -1.00 0.00 0.00 -10.11 271.80 +532.00 426849.40 14.67 1.90 2.10 36.71 -6.79 0.93 0.00 0.00 1.64 2.81 1.30 -1.00 0.00 0.00 -7.14 609.40 +533.00 427040.60 12.52 2.00 2.10 31.65 -7.57 -1.68 0.00 0.00 1.64 2.58 1.30 -1.00 0.00 0.00 -6.11 800.60 +534.00 427856.40 11.77 2.10 2.10 35.06 -5.55 1.53 0.00 0.00 1.72 3.29 1.30 -1.00 0.00 0.00 -5.48 106.00 +535.00 427939.80 10.02 1.60 2.10 26.70 -5.05 0.52 0.00 0.00 1.43 3.08 1.10 -1.00 0.00 0.00 -5.63 189.40 +536.00 428053.90 10.36 3.00 2.10 31.67 -6.02 -0.20 0.00 0.00 2.12 3.63 1.70 -1.00 0.00 0.00 -3.91 533.90 +537.00 428303.70 10.83 2.40 2.10 27.95 -5.92 0.47 0.00 0.00 2.22 2.46 2.00 -1.00 0.00 0.00 -3.89 41.30 +538.00 428367.10 10.78 2.10 2.10 29.77 -5.89 0.56 0.00 0.00 2.01 2.60 2.00 -1.00 0.00 0.00 -4.29 847.10 +539.00 428619.00 14.72 1.60 2.10 37.94 -5.69 -0.20 0.00 0.00 1.32 2.91 1.00 -1.00 0.00 0.00 -8.93 1099.00 +540.00 428664.80 16.79 2.70 2.10 61.04 -6.54 0.74 0.00 0.00 2.46 4.15 2.20 -1.00 0.00 0.00 -5.45 146.40 +541.00 428884.90 10.53 3.70 2.10 33.17 -5.76 -1.12 0.00 0.00 2.93 2.82 2.20 -1.00 0.00 0.00 -2.87 84.90 +542.00 429513.70 12.20 2.20 2.10 32.59 -5.02 -0.53 0.00 0.00 1.61 2.93 1.00 -1.00 0.00 0.00 -6.06 713.70 +543.00 429673.20 27.89 1.70 2.10 77.09 -5.32 0.67 0.00 0.00 1.44 3.06 1.10 -1.00 0.00 0.00 -15.45 130.80 +544.00 429830.30 10.98 2.00 2.10 28.86 -8.21 -0.65 0.00 0.00 1.74 2.64 1.50 -1.00 0.00 0.00 -5.04 1030.30 +545.00 429862.80 10.74 1.90 2.10 21.35 -7.61 0.14 0.00 0.00 1.31 1.83 0.70 -1.00 0.00 0.00 -6.55 64.40 +546.00 429938.90 12.29 1.90 2.10 34.06 -6.51 -0.93 0.00 0.00 1.63 3.44 1.50 -1.00 0.00 0.00 -6.03 1138.90 +547.00 429999.80 18.43 1.90 2.10 47.59 -6.50 1.12 0.00 0.00 1.02 2.96 1.00 -1.00 0.00 0.00 -14.53 1199.80 +548.00 431265.20 11.56 2.20 2.10 33.22 -5.87 1.58 0.00 0.00 2.00 3.35 1.40 -1.00 0.00 0.00 -4.63 1185.20 +549.00 431305.50 10.42 2.00 2.10 27.76 -7.73 1.17 0.00 0.00 1.74 3.41 1.50 -1.00 0.00 0.00 -4.80 1225.50 +550.00 431794.50 11.60 3.00 2.10 36.06 -6.84 0.87 0.00 0.00 2.83 3.30 2.30 -1.00 0.00 0.00 -3.28 434.50 +551.00 431861.70 20.47 2.60 2.10 67.72 -6.70 -1.10 0.00 0.00 2.29 3.77 1.80 -1.00 0.00 0.00 -7.16 501.70 +552.00 432090.00 15.86 2.70 2.10 51.36 -6.65 -0.06 0.00 0.00 2.43 3.58 1.60 -1.00 0.00 0.00 -5.23 730.00 +553.00 433101.90 18.99 1.90 2.10 53.05 -7.57 -0.84 0.00 0.00 1.50 3.23 1.30 -1.00 0.00 0.00 -10.10 461.90 +554.00 433350.20 10.78 1.60 2.10 29.09 -7.28 -2.52 0.00 0.00 1.38 3.26 1.30 -1.00 0.00 0.00 -6.26 223.80 +555.00 433470.80 17.02 2.20 2.10 52.31 -7.10 -0.70 0.00 0.00 1.59 3.71 1.80 -1.00 0.00 0.00 -8.58 830.80 +556.00 433739.10 16.33 3.80 2.10 72.24 -5.05 -0.70 0.00 0.00 3.19 5.06 3.10 -1.00 0.00 0.00 -4.09 100.70 +557.00 433809.60 18.59 2.20 2.10 55.16 -7.65 -0.17 0.00 0.00 1.92 3.60 1.60 -1.00 0.00 0.00 -7.74 1169.60 +558.00 433879.10 13.11 1.50 2.10 34.06 -8.06 0.53 0.00 0.00 1.10 3.04 1.10 -1.00 0.00 0.00 -9.50 1239.10 +559.00 433957.60 15.13 2.20 2.10 38.19 -6.30 0.66 0.00 0.00 1.19 2.81 0.90 -1.00 0.00 0.00 -10.15 63.20 +560.00 434127.10 11.23 0.80 2.10 23.17 -8.01 0.51 0.00 0.00 0.54 2.40 0.50 -1.00 0.00 0.00 -16.70 207.10 +561.00 434260.70 12.50 1.50 2.10 32.71 -9.62 1.23 0.00 0.00 1.30 2.95 1.00 -1.00 0.00 0.00 -7.71 110.30 +562.00 434709.10 11.14 3.30 2.10 32.74 -6.24 1.58 0.00 0.00 2.73 2.88 2.50 -1.00 0.00 0.00 -3.27 789.10 +563.00 434799.30 13.59 2.60 2.10 43.14 -6.92 -1.17 0.00 0.00 2.34 3.76 1.80 -1.00 0.00 0.00 -4.64 879.30 +564.00 435818.90 11.19 2.10 2.10 28.39 -7.62 -1.69 0.00 0.00 1.65 2.91 1.20 -1.00 0.00 0.00 -5.41 618.90 +565.00 436241.60 21.52 1.30 2.10 55.47 -7.51 -0.64 0.00 0.00 0.88 2.86 0.90 -1.00 0.00 0.00 -19.62 1041.60 +566.00 436278.10 14.49 3.60 2.10 45.18 -6.61 -0.34 0.00 0.00 2.71 2.96 1.50 -1.00 0.00 0.00 -4.28 1078.10 +567.00 436560.40 12.38 3.00 2.10 42.02 -6.51 -0.21 0.00 0.00 2.75 4.34 2.40 -1.00 0.00 0.00 -3.61 80.40 +568.00 436589.20 14.82 2.60 2.10 48.06 -7.85 -0.83 0.00 0.00 1.79 3.52 1.60 -1.00 0.00 0.00 -6.63 109.20 +569.00 437177.90 12.46 1.80 2.10 33.89 -9.18 -1.72 0.00 0.00 1.62 3.36 1.40 -1.00 0.00 0.00 -6.16 697.90 +570.00 437397.00 11.67 1.60 2.10 26.61 -7.59 0.12 0.00 0.00 1.44 1.39 1.10 -1.00 0.00 0.00 -6.48 917.00 +571.00 439170.40 10.41 1.90 2.10 26.58 -8.37 1.09 0.00 0.00 1.76 3.03 1.10 -1.00 0.00 0.00 -4.73 130.40 +572.00 439218.40 20.04 2.50 2.10 53.47 -8.66 -0.71 0.00 0.00 1.30 2.96 1.00 -1.00 0.00 0.00 -12.30 178.40 +573.00 439271.70 11.90 1.90 2.10 31.04 -7.61 1.59 0.00 0.00 1.65 3.06 1.10 -1.00 0.00 0.00 -5.77 231.70 +574.00 439461.40 19.76 2.40 2.10 62.23 -8.64 -0.44 0.00 0.00 2.03 3.70 1.80 -1.00 0.00 0.00 -7.77 421.40 +575.00 439669.90 10.79 2.00 2.10 32.49 -6.91 0.47 0.00 0.00 1.46 3.39 1.40 -1.00 0.00 0.00 -5.93 629.90 +576.00 440195.80 13.94 1.70 2.10 31.43 -7.82 0.37 0.00 0.00 1.42 2.81 1.00 -1.00 0.00 0.00 -7.86 1155.80 +577.00 440588.10 15.29 1.60 2.10 41.19 -6.29 0.33 0.00 0.00 1.22 3.02 1.10 -1.00 0.00 0.00 -10.01 268.10 +578.00 440784.40 10.33 2.90 2.10 33.84 -7.41 -1.10 0.00 0.00 2.65 3.53 1.80 -1.00 0.00 0.00 -3.12 234.00 +579.00 440915.00 19.57 1.50 2.10 53.02 -8.34 1.75 0.00 0.00 1.22 3.07 1.10 -1.00 0.00 0.00 -12.83 595.00 +580.00 441558.00 20.27 1.80 2.10 53.18 -9.07 -2.86 0.00 0.00 0.88 2.99 1.00 -1.00 0.00 0.00 -18.39 1238.00 +581.00 441616.50 10.54 1.40 2.10 26.32 -8.14 -0.17 0.00 0.00 1.19 2.90 1.00 -1.00 0.00 0.00 -7.10 42.10 +582.00 442259.30 13.84 1.60 2.10 29.80 -7.87 -1.70 0.00 0.00 1.06 2.07 0.70 -1.00 0.00 0.00 -10.46 659.30 +583.00 442365.20 21.79 1.20 2.10 50.79 -7.65 -0.91 0.00 0.00 0.93 2.80 0.80 -1.00 0.00 0.00 -18.67 765.20 +584.00 442473.80 18.45 1.40 2.10 43.27 -7.17 -0.02 0.00 0.00 1.13 2.84 0.90 -1.00 0.00 0.00 -13.08 873.80 +585.00 442596.60 18.21 3.60 2.10 48.27 -6.16 -1.26 0.00 0.00 1.60 2.97 1.20 -1.00 0.00 0.00 -9.10 996.60 +586.00 442934.90 17.53 2.30 2.10 55.25 -7.58 -1.18 0.00 0.00 1.39 3.65 1.70 -1.00 0.00 0.00 -10.08 54.90 +587.00 442986.40 10.65 4.40 2.10 44.49 -7.67 -0.71 255.00 0.00 4.17 4.42 3.80 -1.00 0.00 0.00 -2.04 132.00 +588.00 443064.30 10.20 1.90 2.10 28.32 -6.59 -3.43 0.00 0.00 1.66 3.56 1.60 -1.00 0.00 0.00 -4.93 184.30 +589.00 443070.30 13.40 7.90 2.10 80.71 -6.76 0.56 255.00 0.00 7.71 4.21 2.30 -1.00 0.00 0.00 -1.39 215.90 +590.00 443279.20 19.32 2.00 2.10 52.46 -7.51 -0.54 0.00 0.00 1.63 3.25 1.30 -1.00 0.00 0.00 -9.49 399.20 +591.00 443559.60 10.86 3.20 2.10 30.99 -6.53 0.97 255.00 0.00 2.97 1.51 0.60 -1.00 0.00 0.00 -2.92 679.60 +592.00 443688.10 26.76 2.70 2.10 94.02 -4.85 0.64 0.00 0.00 1.39 4.15 2.20 -1.00 0.00 0.00 -15.42 808.10 +593.00 444457.10 17.87 2.10 2.10 50.38 -6.23 -0.25 0.00 0.00 1.35 3.41 1.50 -1.00 0.00 0.00 -10.58 297.10 +594.00 444510.70 11.05 2.90 2.10 27.44 -7.12 0.48 0.00 0.00 1.82 2.41 1.20 -1.00 0.00 0.00 -4.85 248.30 +595.00 444514.20 17.49 5.20 2.10 61.19 -9.81 2.40 255.00 0.00 2.13 3.35 1.40 -1.00 0.00 0.00 -6.57 354.20 +596.00 444561.70 16.39 2.20 2.10 43.94 -7.26 1.54 0.00 0.00 1.90 3.01 1.60 -1.00 0.00 0.00 -6.88 401.70 +597.00 444837.70 18.03 7.00 2.10 73.51 -6.19 -0.72 0.00 0.00 3.65 3.06 1.10 -1.00 0.00 0.00 -3.95 63.30 +598.00 444843.80 19.42 10.00 2.10 138.42 -7.36 0.64 255.00 0.00 9.59 3.95 2.00 -1.00 0.00 0.00 -1.62 69.40 +599.00 444892.30 12.22 2.00 2.10 38.31 -6.42 -0.80 0.00 0.00 1.71 3.61 1.70 -1.00 0.00 0.00 -5.71 732.30 +600.00 444947.00 17.69 4.40 2.10 61.27 -6.13 0.58 0.00 0.00 2.20 3.84 2.00 -1.00 0.00 0.00 -6.44 787.00 +601.00 444981.90 13.00 2.20 2.10 26.18 -6.32 0.48 0.00 0.00 1.06 0.84 0.70 -1.00 0.00 0.00 -9.83 821.90 +602.00 445486.80 10.02 3.10 2.10 30.45 -6.65 1.56 0.00 0.00 2.21 2.44 1.60 -1.00 0.00 0.00 -3.63 46.80 +603.00 445888.90 16.09 2.10 2.10 40.60 -6.66 -1.05 0.00 0.00 1.67 3.18 1.20 -1.00 0.00 0.00 -7.70 448.90 +604.00 447646.90 17.62 2.20 2.10 51.87 -6.56 -1.36 0.00 0.00 1.74 3.30 1.30 -1.00 0.00 0.00 -8.10 926.90 +605.00 448460.70 12.35 2.90 2.10 42.44 -8.95 -0.58 0.00 0.00 2.67 3.89 2.20 -1.00 0.00 0.00 -3.71 460.70 +606.00 449104.00 10.59 1.50 2.10 24.45 -8.46 -0.42 0.00 0.00 1.37 2.30 1.30 -1.00 0.00 0.00 -6.18 1104.00 +607.00 449220.80 21.70 3.10 2.10 52.41 -6.51 1.88 0.00 0.00 0.84 2.71 0.80 -1.00 0.00 0.00 -20.77 1220.80 +608.00 449357.70 10.96 1.30 2.10 24.01 -7.66 -0.31 0.00 0.00 0.91 2.78 0.80 -1.00 0.00 0.00 -9.67 77.70 +609.00 450139.00 12.71 2.40 2.10 35.89 -5.73 0.65 0.00 0.00 1.91 3.06 1.10 -1.00 0.00 0.00 -5.33 859.00 +610.00 450250.00 11.26 2.60 2.10 31.24 -5.75 0.69 0.00 0.00 1.65 3.10 1.20 -1.00 0.00 0.00 -5.47 970.00 +611.00 452299.40 17.42 1.40 2.10 41.26 -6.22 -0.53 0.00 0.00 0.90 2.63 0.70 -1.00 0.00 0.00 -15.48 101.00 +612.00 453880.70 13.23 1.80 2.10 32.42 -6.92 1.03 0.00 0.00 1.09 2.59 0.60 -1.00 0.00 0.00 -9.74 760.70 +613.00 454305.20 13.12 1.50 2.10 34.42 -8.16 1.22 0.00 0.00 1.32 2.86 0.90 -1.00 0.00 0.00 -7.97 1185.20 +614.00 455223.30 16.62 1.70 2.10 45.63 -8.19 0.87 0.00 0.00 1.31 3.07 1.10 -1.00 0.00 0.00 -10.14 823.30 +615.00 455307.60 16.61 3.30 2.10 56.03 -8.21 -0.32 0.00 0.00 2.86 4.60 2.60 -1.00 0.00 0.00 -4.65 907.60 +616.00 455929.80 11.59 2.10 2.10 31.92 -7.38 -1.90 0.00 0.00 1.87 3.65 1.70 -1.00 0.00 0.00 -4.97 249.80 +617.00 456876.90 33.44 4.30 2.10 132.74 -6.62 -0.47 0.00 0.00 3.47 3.59 1.60 -1.00 0.00 0.00 -7.71 1196.90 +618.00 456916.90 18.73 2.50 2.10 55.93 -8.16 -0.22 0.00 0.00 2.14 3.34 1.40 -1.00 0.00 0.00 -7.00 1236.90 +619.00 457108.50 15.13 3.20 2.10 44.83 -8.84 0.89 0.00 0.00 2.32 3.54 1.60 -1.00 0.00 0.00 -5.22 148.50 +620.00 457865.70 15.28 1.30 2.10 35.38 -7.93 -0.74 0.00 0.00 1.15 2.80 0.80 -1.00 0.00 0.00 -10.65 905.70 +621.00 458060.30 16.85 2.10 2.10 44.54 -8.14 -1.59 0.00 0.00 1.44 2.85 0.90 -1.00 0.00 0.00 -9.36 229.90 +622.00 458585.70 18.48 2.30 2.10 61.20 -7.30 -0.44 0.00 0.00 2.06 3.76 1.80 -1.00 0.00 0.00 -7.19 345.70 +623.00 458654.90 18.81 1.00 2.10 41.67 -8.02 0.20 0.00 0.00 0.72 2.62 0.70 -1.00 0.00 0.00 -20.86 414.90 +624.00 459650.90 16.77 2.00 2.10 45.39 -7.84 1.02 0.00 0.00 1.45 3.24 1.30 -1.00 0.00 0.00 -9.23 130.90 +625.00 459738.20 15.21 1.90 2.10 38.45 -8.65 -1.75 0.00 0.00 1.27 2.90 1.00 -1.00 0.00 0.00 -9.59 218.20 +626.00 459756.80 10.25 2.20 2.10 25.64 -11.24 -0.15 0.00 0.00 2.06 3.00 1.80 -1.00 0.00 0.00 -3.97 236.80 +627.00 459933.60 13.95 1.50 2.10 29.57 -9.04 1.61 0.00 0.00 1.14 2.56 0.60 -1.00 0.00 0.00 -9.78 413.60 +628.00 460387.50 11.63 2.90 2.10 36.17 -7.43 -1.07 0.00 0.00 2.15 3.41 1.50 -1.00 0.00 0.00 -4.33 867.50 +629.00 461369.20 16.36 2.40 2.10 44.33 -8.10 0.87 0.00 0.00 1.80 3.10 1.20 -1.00 0.00 0.00 -7.26 569.20 +630.00 461979.80 12.08 2.30 2.10 29.69 -7.25 1.17 0.00 0.00 2.05 1.76 1.50 -1.00 0.00 0.00 -4.72 1179.80 +631.00 462538.50 10.76 3.50 2.10 31.61 -7.96 -1.55 0.00 0.00 2.14 2.50 1.80 -1.00 0.00 0.00 -4.01 458.50 +632.00 462553.10 13.35 2.20 2.10 34.16 -9.21 -1.25 0.00 0.00 1.97 3.03 1.50 -1.00 0.00 0.00 -5.42 473.10 +633.00 462809.30 12.34 3.90 2.10 55.24 -8.53 -0.04 0.00 0.00 3.79 5.61 3.70 -1.00 0.00 0.00 -2.61 729.30 +634.00 462862.10 17.08 2.20 2.10 53.94 -9.56 1.07 0.00 0.00 1.11 3.68 1.70 -1.00 0.00 0.00 -12.28 782.10 +635.00 463330.70 15.55 2.30 2.10 43.46 -9.08 0.83 0.00 0.00 2.01 3.44 1.50 -1.00 0.00 0.00 -6.20 1250.70 +636.00 463573.10 14.06 2.20 2.10 38.24 -8.48 -0.12 0.00 0.00 1.51 2.97 1.00 -1.00 0.00 0.00 -7.43 213.10 +637.00 463902.70 18.86 4.00 2.10 71.04 -8.48 -0.53 0.00 0.00 3.26 3.98 2.00 -1.00 0.00 0.00 -4.63 542.70 +638.00 463982.40 10.42 2.10 2.10 23.91 -9.35 0.55 0.00 0.00 1.02 2.92 1.00 -1.00 0.00 0.00 -8.19 622.40 +639.00 464016.50 10.42 1.80 2.10 24.61 -8.66 -2.30 0.00 0.00 1.53 2.69 0.70 -1.00 0.00 0.00 -5.46 656.50 +640.00 464637.40 11.82 2.60 2.10 35.77 -7.60 -1.58 0.00 0.00 2.44 2.56 1.40 -1.00 0.00 0.00 -3.88 1277.40 +641.00 464770.50 12.42 2.30 2.10 35.44 -8.62 1.76 0.00 0.00 1.71 3.31 1.70 -1.00 0.00 0.00 -5.81 130.50 +642.00 464802.10 14.20 3.90 2.10 42.54 -7.97 0.70 0.00 0.00 1.51 3.27 1.30 -1.00 0.00 0.00 -7.53 162.10 +643.00 464803.20 13.91 3.60 2.10 47.39 -8.38 0.56 0.00 0.00 2.57 3.53 2.40 -1.00 0.00 0.00 -4.33 163.20 +644.00 464847.50 10.52 1.70 2.10 25.34 -9.20 -1.22 0.00 0.00 1.44 2.25 0.80 -1.00 0.00 0.00 -5.84 207.50 +645.00 465182.60 11.00 2.00 2.10 31.38 -7.88 -0.36 0.00 0.00 1.73 3.27 1.60 -1.00 0.00 0.00 -5.07 542.60 +646.00 465551.10 16.48 1.90 2.10 45.62 -7.73 -0.10 0.00 0.00 1.44 3.33 1.40 -1.00 0.00 0.00 -9.15 911.10 +647.00 465744.50 19.19 1.20 2.10 42.66 -7.32 -0.33 0.00 0.00 0.95 2.76 0.80 -1.00 0.00 0.00 -16.13 1104.50 +648.00 465846.30 13.28 3.00 2.10 47.47 -8.56 -0.92 0.00 0.00 2.74 4.34 2.40 -1.00 0.00 0.00 -3.88 1206.30 +649.00 465951.50 11.85 1.60 2.10 31.97 -8.88 -1.97 0.00 0.00 0.87 2.97 1.50 -1.00 0.00 0.00 -10.91 31.50 +650.00 466202.60 11.88 2.40 2.10 35.80 -6.31 -0.27 0.00 0.00 1.96 3.60 1.60 -1.00 0.00 0.00 -4.84 282.60 +651.00 466605.10 15.32 1.40 2.10 34.59 -6.93 0.93 0.00 0.00 1.24 2.55 0.60 -1.00 0.00 0.00 -9.89 685.10 +652.00 467603.30 19.43 8.60 2.10 101.85 -6.32 -1.89 255.00 0.00 7.87 3.63 1.70 -1.00 0.00 0.00 -1.98 44.90 +653.00 469755.30 10.40 1.70 2.10 27.64 -8.18 -0.21 0.00 0.00 1.54 3.07 1.10 -1.00 0.00 0.00 -5.41 148.90 +654.00 471022.00 10.35 1.80 2.10 25.91 -6.57 -0.40 0.00 0.00 1.43 2.75 0.90 -1.00 0.00 0.00 -5.80 135.60 +655.00 471118.10 23.30 2.40 2.10 73.61 -8.42 1.49 0.00 0.00 1.27 3.71 1.80 -1.00 0.00 0.00 -14.67 78.10 +656.00 471996.90 14.87 1.40 2.10 31.25 -6.82 -0.61 0.00 0.00 1.13 2.48 0.50 -1.00 0.00 0.00 -10.48 956.90 +657.00 472547.70 14.52 2.20 2.10 42.94 -7.79 0.18 0.00 0.00 1.82 3.49 1.50 -1.00 0.00 0.00 -6.38 227.70 +658.00 472638.40 13.98 3.30 2.10 50.39 -8.46 -0.02 0.00 0.00 2.60 4.30 2.30 -1.00 0.00 0.00 -4.30 318.40 +659.00 472889.30 11.37 1.90 2.10 27.41 -9.37 0.48 0.00 0.00 1.75 3.05 1.10 -1.00 0.00 0.00 -5.20 569.30 +660.00 473022.00 16.18 1.70 2.10 42.65 -9.67 0.73 0.00 0.00 1.56 3.15 1.20 -1.00 0.00 0.00 -8.29 702.00 +661.00 474235.60 12.14 1.80 2.10 28.75 -8.58 0.60 0.00 0.00 1.65 2.96 1.30 -1.00 0.00 0.00 -5.88 635.60 +662.00 474441.70 15.13 2.20 2.10 41.58 -8.10 -2.67 0.00 0.00 1.55 2.68 1.70 -1.00 0.00 0.00 -7.81 841.70 +663.00 474514.80 15.27 1.80 2.10 38.90 -6.84 0.35 0.00 0.00 1.60 3.21 1.30 -1.00 0.00 0.00 -7.65 914.80 +664.00 475680.50 22.76 2.40 2.10 65.40 -8.15 -0.51 0.00 0.00 1.96 3.71 1.80 -1.00 0.00 0.00 -9.28 800.50 +665.00 475730.70 15.41 3.70 2.10 44.08 -9.69 -1.57 0.00 0.00 1.29 3.01 1.10 -1.00 0.00 0.00 -9.56 850.70 +666.00 475872.80 13.21 1.90 2.10 31.14 -8.55 0.95 0.00 0.00 1.65 2.83 1.00 -1.00 0.00 0.00 -6.41 992.80 +667.00 476092.80 13.07 2.70 2.10 34.20 -9.06 -2.15 0.00 0.00 1.91 3.41 1.50 -1.00 0.00 0.00 -5.46 1212.80 +668.00 476122.80 11.40 2.10 2.10 32.29 -9.69 -2.95 0.00 0.00 1.87 2.95 1.60 -1.00 0.00 0.00 -4.87 1242.80 +669.00 476632.80 12.00 2.00 2.10 31.33 -7.97 -0.68 0.00 0.00 1.88 3.66 1.70 -1.00 0.00 0.00 -5.11 472.80 +670.00 476978.30 12.71 2.20 2.10 38.27 -8.54 -0.24 0.00 0.00 2.04 3.68 1.70 -1.00 0.00 0.00 -4.98 818.30 +671.00 477137.10 10.03 2.10 2.10 26.08 -8.24 -0.86 0.00 0.00 1.89 3.10 1.50 -1.00 0.00 0.00 -4.25 977.10 +672.00 477404.50 11.29 2.40 2.10 32.64 -7.71 -1.16 0.00 0.00 1.22 3.24 1.30 -1.00 0.00 0.00 -7.42 1244.50 +673.00 478003.20 12.78 1.60 2.10 33.12 -8.23 -0.22 0.00 0.00 1.33 3.16 1.20 -1.00 0.00 0.00 -7.71 563.20 +674.00 478443.10 17.44 2.60 2.10 46.44 -8.48 1.18 0.00 0.00 1.86 3.32 1.40 -1.00 0.00 0.00 -7.49 1003.10 +675.00 479195.00 10.10 3.60 2.10 24.08 -7.33 -0.51 0.00 0.00 2.85 0.34 0.20 -1.00 0.00 0.00 -2.83 475.00 +676.00 479456.00 14.92 2.20 2.10 40.33 -8.38 0.34 0.00 0.00 2.05 2.63 1.40 -1.00 0.00 0.00 -5.82 736.00 +677.00 479600.60 13.57 5.30 2.10 50.54 -8.55 1.53 0.00 0.00 4.51 3.76 2.20 -1.00 0.00 0.00 -2.41 880.60 diff --git a/data/mEPSCs/washout2.txt b/data/mEPSCs/washout2.txt new file mode 100644 index 00000000..24f17e7c --- /dev/null +++ b/data/mEPSCs/washout2.txt @@ -0,0 +1,1194 @@ + Time (ms) Amplitude Rise (ms) Decay (ms) Area Baseline Noise Group Channel 10-90Rise HalfWidth Rise50 Peak Dir Burst# BurstE# 10-90Slope Rel Time +1.00 340662.50 10.05 1.30 3.70 30.40 -10.49 -0.63 0.00 0.00 0.87 3.01 0.50 -1.00 0.00 0.00 -9.24 156.90 +2.00 236835.30 10.47 1.30 5.50 42.49 -9.85 -0.22 0.00 0.00 1.07 4.07 0.80 -1.00 0.00 0.00 -7.83 188.90 +3.00 315480.10 10.45 1.90 5.60 49.71 -13.24 0.89 0.00 0.00 1.79 4.74 1.20 -1.00 0.00 0.00 -4.66 190.50 +4.00 338301.10 10.79 1.90 5.20 52.91 -11.31 0.95 0.00 0.00 1.44 4.99 1.10 -1.00 0.00 0.00 -5.98 99.50 +5.00 181690.60 14.66 2.10 4.30 53.33 -8.00 1.37 0.00 0.00 1.86 3.39 1.10 -1.00 0.00 0.00 -6.30 84.20 +6.00 111066.80 20.60 1.50 8.70 155.73 -7.99 0.55 0.00 0.00 1.21 7.75 1.00 -1.00 0.00 0.00 -13.66 372.40 +7.00 75063.20 12.72 2.00 13.50 151.99 -7.69 -0.45 0.00 0.00 1.75 4.81 1.60 -1.00 0.00 0.00 -5.80 80.80 +8.00 59650.70 19.28 1.90 14.50 227.47 -8.58 -1.01 0.00 0.00 1.47 4.95 1.10 -1.00 0.00 0.00 -10.52 28.30 +9.00 57656.80 16.03 2.10 12.00 163.73 -9.34 1.80 0.00 0.00 1.50 3.90 1.30 -1.00 0.00 0.00 -8.56 338.40 +10.00 304254.50 13.67 1.70 9.90 100.03 -10.36 -1.74 0.00 0.00 1.10 2.25 1.00 -1.00 0.00 0.00 -9.94 100.90 +11.00 239259.40 12.15 2.20 2.90 38.88 -9.19 0.64 0.00 0.00 1.78 3.30 1.60 -1.00 0.00 0.00 -5.46 309.00 +12.00 203728.80 11.16 1.80 7.60 85.62 -9.98 2.45 0.00 0.00 1.67 8.61 1.30 -1.00 0.00 0.00 -5.34 234.40 +13.00 128468.90 10.21 2.80 5.10 47.28 -8.92 0.64 0.00 0.00 2.57 4.60 2.00 -1.00 0.00 0.00 -3.17 238.50 +14.00 65163.50 11.93 1.70 6.30 55.08 -6.56 -0.39 0.00 0.00 1.39 4.38 0.80 -1.00 0.00 0.00 -6.87 165.10 +15.00 227531.70 14.91 2.00 8.00 112.58 -9.52 3.31 0.00 0.00 1.79 3.59 1.50 -1.00 0.00 0.00 -6.68 101.30 +16.00 227714.10 10.04 1.30 6.80 53.40 -7.89 1.87 0.00 0.00 1.12 5.01 0.60 -1.00 0.00 0.00 -7.18 283.70 +17.00 27492.70 13.47 2.30 2.10 41.69 -8.91 1.05 0.00 0.00 1.99 3.72 1.80 -1.00 0.00 0.00 -5.41 126.30 +18.00 232096.10 11.89 1.60 13.50 166.69 -9.27 2.09 0.00 0.00 1.19 3.39 1.00 -1.00 0.00 0.00 -8.00 57.70 +19.00 130752.40 10.94 2.20 2.20 30.43 -11.45 0.94 0.00 0.00 2.02 2.78 1.80 -1.00 0.00 0.00 -4.34 38.80 +20.00 31521.80 15.59 2.80 2.10 48.24 -7.38 0.06 0.00 0.00 2.17 3.52 1.60 -1.00 0.00 0.00 -5.75 315.40 +21.00 190609.30 12.46 2.30 5.10 61.64 -8.58 -1.07 0.00 0.00 2.09 5.53 1.80 -1.00 0.00 0.00 -4.77 170.90 +22.00 188632.60 10.04 1.00 4.10 32.68 -8.66 -0.16 0.00 0.00 0.78 3.40 0.60 -1.00 0.00 0.00 -10.32 114.20 +23.00 194125.90 10.30 1.90 6.60 56.65 -9.21 -0.96 0.00 0.00 1.67 5.53 1.40 -1.00 0.00 0.00 -4.94 231.50 +24.00 332064.40 13.86 2.10 6.00 70.02 -13.28 -0.38 0.00 0.00 1.90 4.60 1.40 -1.00 0.00 0.00 -5.83 6.80 +25.00 334156.00 10.76 1.60 5.10 43.75 -11.56 0.26 0.00 0.00 1.34 4.00 0.30 -1.00 0.00 0.00 -6.42 50.40 +26.00 134924.60 15.48 1.90 15.30 214.20 -6.98 -0.14 0.00 0.00 1.34 11.53 0.90 -1.00 0.00 0.00 -9.21 89.40 +27.00 333215.70 13.85 1.50 17.40 249.06 -11.08 -1.64 0.00 0.00 1.10 15.59 1.10 -1.00 0.00 0.00 -10.11 134.10 +28.00 196138.90 11.52 2.30 6.70 59.53 -8.48 1.40 0.00 0.00 1.31 3.87 0.80 -1.00 0.00 0.00 -7.02 324.50 +29.00 184009.60 10.21 1.40 9.00 62.33 -7.04 0.42 0.00 0.00 1.27 5.34 0.40 -1.00 0.00 0.00 -6.45 99.20 +30.00 80465.30 12.69 2.60 3.10 46.60 -8.01 -0.29 0.00 0.00 2.37 3.46 2.00 -1.00 0.00 0.00 -4.28 106.90 +31.00 112311.30 10.46 2.60 3.00 35.61 -8.55 -1.32 0.00 0.00 2.34 3.54 2.30 -1.00 0.00 0.00 -3.58 80.90 +32.00 360205.30 10.10 2.60 3.90 37.85 -12.01 -0.87 0.00 0.00 2.41 3.81 1.80 -1.00 0.00 0.00 -3.35 243.70 +33.00 48976.70 14.39 1.60 7.40 91.43 -7.77 1.08 0.00 0.00 1.28 7.10 1.20 -1.00 0.00 0.00 -8.97 106.30 +34.00 83095.60 11.28 2.30 4.50 42.38 -8.26 1.18 0.00 0.00 1.28 3.44 0.50 -1.00 0.00 0.00 -7.07 49.20 +35.00 252734.90 12.48 1.80 6.80 64.30 -7.77 -1.88 0.00 0.00 1.46 4.73 0.90 -1.00 0.00 0.00 -6.83 37.30 +36.00 160942.70 12.01 2.00 6.40 62.09 -8.33 1.42 0.00 0.00 1.77 4.65 1.40 -1.00 0.00 0.00 -5.43 123.50 +37.00 156125.10 10.65 1.40 5.30 42.79 -7.66 -0.42 0.00 0.00 0.58 3.40 0.60 -1.00 0.00 0.00 -14.68 41.90 +38.00 88365.50 12.03 3.50 7.20 109.86 -10.06 -0.07 0.00 0.00 3.16 9.42 2.80 -1.00 0.00 0.00 -3.04 327.10 +39.00 223598.10 12.48 1.40 10.10 88.00 -9.39 2.59 0.00 0.00 1.13 4.52 0.40 -1.00 0.00 0.00 -8.80 7.70 +40.00 222362.70 25.14 4.20 2.10 78.63 -7.58 -0.73 0.00 0.00 1.38 3.39 1.40 -1.00 0.00 0.00 -14.63 436.30 +41.00 220925.10 26.39 1.90 2.10 78.21 -10.02 2.60 0.00 0.00 1.11 3.29 1.30 -1.00 0.00 0.00 -19.00 278.70 +42.00 220893.70 25.94 2.00 5.00 116.80 -8.17 2.79 0.00 0.00 1.71 4.86 1.60 -1.00 0.00 0.00 -12.16 119.30 +43.00 228193.70 11.69 3.30 2.10 40.51 -8.43 0.11 0.00 0.00 2.97 4.13 2.50 -1.00 0.00 0.00 -3.15 1147.30 +44.00 228042.60 12.42 2.30 2.10 36.61 -9.24 -0.59 0.00 0.00 1.96 3.96 2.00 -1.00 0.00 0.00 -5.06 996.20 +45.00 221118.20 22.57 2.40 4.40 95.16 -9.00 0.39 0.00 0.00 1.77 4.38 1.30 -1.00 0.00 0.00 -10.20 343.80 +46.00 220580.10 17.99 3.00 2.10 66.26 -10.33 -0.10 0.00 0.00 2.72 4.43 2.50 -1.00 0.00 0.00 -5.29 1213.70 +47.00 227727.90 14.63 2.00 2.10 39.90 -11.56 1.66 0.00 0.00 1.38 3.51 1.60 -1.00 0.00 0.00 -8.50 681.50 +48.00 221519.50 17.83 1.90 2.10 50.76 -8.51 -0.59 0.00 0.00 1.50 3.19 1.20 -1.00 0.00 0.00 -9.52 873.10 +49.00 227896.50 16.46 3.40 2.10 59.76 -7.70 0.46 0.00 0.00 2.76 4.15 2.20 -1.00 0.00 0.00 -4.78 850.10 +50.00 221333.70 11.80 2.10 2.10 31.80 -8.47 0.46 0.00 0.00 1.43 3.30 1.40 -1.00 0.00 0.00 -6.59 687.30 +51.00 219976.50 19.37 2.40 2.10 67.13 -7.92 0.19 0.00 0.00 1.24 3.71 1.80 -1.00 0.00 0.00 -12.52 610.10 +52.00 217817.50 18.64 1.90 2.10 46.32 -10.94 -1.11 0.00 0.00 1.58 3.09 1.10 -1.00 0.00 0.00 -9.41 1011.10 +53.00 218236.00 14.21 2.90 2.10 44.47 -7.82 0.03 0.00 0.00 2.43 3.67 2.00 -1.00 0.00 0.00 -4.68 149.60 +54.00 229742.30 26.90 2.70 2.10 89.89 -9.93 -0.17 0.00 0.00 1.80 3.84 1.90 -1.00 0.00 0.00 -11.97 135.90 +55.00 229765.90 10.96 3.10 2.10 35.89 -9.93 1.32 0.00 0.00 2.28 4.03 2.10 -1.00 0.00 0.00 -3.85 159.50 +56.00 229844.60 25.78 2.40 2.10 84.67 -10.18 -1.11 0.00 0.00 1.35 3.74 1.80 -1.00 0.00 0.00 -15.33 238.20 +57.00 218857.50 19.03 2.00 2.10 53.45 -8.81 -1.76 0.00 0.00 1.49 3.11 1.20 -1.00 0.00 0.00 -10.22 771.10 +58.00 229322.80 22.01 2.70 2.10 71.78 -9.85 0.23 0.00 0.00 1.76 3.60 1.60 -1.00 0.00 0.00 -10.02 996.40 +59.00 227414.10 13.50 3.20 2.10 46.69 -7.68 -1.69 0.00 0.00 2.96 3.44 2.20 -1.00 0.00 0.00 -3.65 367.70 +60.00 228401.40 21.40 1.60 2.10 56.94 -8.59 0.70 0.00 0.00 1.38 3.07 1.10 -1.00 0.00 0.00 -12.40 75.00 +61.00 228561.40 14.40 2.90 2.10 42.52 -9.19 -2.52 0.00 0.00 1.56 3.35 1.40 -1.00 0.00 0.00 -7.37 235.00 +62.00 219652.10 24.73 2.10 2.10 73.27 -9.29 1.04 0.00 0.00 1.61 3.32 1.40 -1.00 0.00 0.00 -12.32 285.70 +63.00 228865.20 10.32 1.40 2.10 25.09 -9.35 1.34 0.00 0.00 1.17 2.91 1.00 -1.00 0.00 0.00 -7.07 538.80 +64.00 220012.20 12.78 3.00 2.10 46.60 -10.56 -1.64 0.00 0.00 2.72 4.39 2.40 -1.00 0.00 0.00 -3.76 645.80 +65.00 227325.10 15.59 2.80 2.10 55.41 -8.19 0.27 0.00 0.00 2.59 4.19 2.20 -1.00 0.00 0.00 -4.82 278.70 +66.00 223513.50 17.14 2.90 2.10 55.09 -9.01 -1.44 0.00 0.00 2.19 3.82 1.90 -1.00 0.00 0.00 -6.26 307.10 +67.00 224464.70 15.66 2.60 2.10 47.63 -8.19 0.38 0.00 0.00 1.84 3.54 1.60 -1.00 0.00 0.00 -6.82 1258.30 +68.00 224940.60 18.07 2.00 2.10 56.48 -8.08 -1.22 0.00 0.00 1.19 3.49 1.50 -1.00 0.00 0.00 -12.14 454.20 +69.00 224967.90 14.25 2.60 2.10 42.79 -9.08 1.43 0.00 0.00 1.44 3.26 1.30 -1.00 0.00 0.00 -7.91 481.50 +70.00 223272.60 16.55 3.20 2.10 58.56 -9.13 0.06 0.00 0.00 2.07 3.88 1.90 -1.00 0.00 0.00 -6.40 66.20 +71.00 223543.00 19.92 3.60 2.10 62.38 -10.47 1.35 0.00 0.00 2.08 3.82 1.90 -1.00 0.00 0.00 -7.65 336.60 +72.00 224430.50 19.51 3.00 2.10 67.31 -7.32 0.15 0.00 0.00 2.50 4.21 2.30 -1.00 0.00 0.00 -6.23 1224.10 +73.00 223866.30 14.03 2.90 2.10 41.47 -8.62 -1.60 0.00 0.00 1.38 3.43 1.50 -1.00 0.00 0.00 -8.12 659.90 +74.00 223659.10 11.80 3.50 2.10 46.37 -10.03 -1.19 0.00 0.00 3.05 4.29 2.80 -1.00 0.00 0.00 -3.10 452.70 +75.00 223956.00 13.99 2.10 2.10 39.96 -8.65 0.49 0.00 0.00 1.41 3.38 1.40 -1.00 0.00 0.00 -7.93 749.60 +76.00 224016.00 19.85 3.20 2.10 56.36 -7.51 -2.46 0.00 0.00 1.88 3.21 1.30 -1.00 0.00 0.00 -8.44 809.60 +77.00 224263.80 11.23 1.30 2.10 23.20 -8.01 1.34 0.00 0.00 1.11 1.95 0.70 -1.00 0.00 0.00 -8.10 1057.40 +78.00 225228.60 18.82 1.80 2.10 50.98 -9.27 -0.11 0.00 0.00 1.58 3.10 1.10 -1.00 0.00 0.00 -9.54 742.20 +79.00 225287.20 11.50 1.60 2.10 29.99 -10.24 -0.44 0.00 0.00 1.38 2.87 1.20 -1.00 0.00 0.00 -6.66 800.80 +80.00 222516.30 17.92 4.20 2.10 77.24 -8.37 0.06 0.00 0.00 3.52 5.10 3.10 -1.00 0.00 0.00 -4.07 589.90 +81.00 226791.10 16.69 1.70 2.10 41.90 -9.33 -0.60 0.00 0.00 1.44 2.89 0.90 -1.00 0.00 0.00 -9.25 1024.70 +82.00 226974.50 20.67 2.70 2.10 58.63 -9.05 0.02 0.00 0.00 1.62 3.31 1.40 -1.00 0.00 0.00 -10.22 1208.10 +83.00 227011.00 15.77 3.50 2.10 67.11 -11.82 -2.09 0.00 0.00 3.16 4.99 3.00 -1.00 0.00 0.00 -4.00 1244.60 +84.00 223625.00 16.87 1.90 2.10 51.46 -10.61 -1.05 0.00 0.00 1.60 3.47 1.50 -1.00 0.00 0.00 -8.44 418.60 +85.00 226158.20 11.32 1.10 2.10 25.18 -10.47 -1.59 0.00 0.00 0.90 2.59 0.60 -1.00 0.00 0.00 -10.09 391.80 +86.00 226099.90 13.43 4.10 2.10 45.54 -9.38 0.90 0.00 0.00 3.99 3.62 3.50 -1.00 0.00 0.00 -2.69 333.50 +87.00 222940.20 19.07 2.90 2.10 66.04 -7.41 0.10 0.00 0.00 1.48 3.79 1.80 -1.00 0.00 0.00 -10.32 1013.80 +88.00 225587.00 11.25 1.90 2.10 30.64 -9.63 -0.20 0.00 0.00 1.67 3.26 1.50 -1.00 0.00 0.00 -5.38 1100.60 +89.00 222731.30 16.09 2.10 2.10 46.61 -8.73 0.10 0.00 0.00 1.79 3.04 1.50 -1.00 0.00 0.00 -7.18 804.90 +90.00 222528.20 23.79 2.50 2.10 73.89 -13.01 1.88 0.00 0.00 1.54 3.62 1.70 -1.00 0.00 0.00 -12.37 601.80 +91.00 225747.10 15.75 2.30 2.10 44.26 -7.34 -0.08 0.00 0.00 2.09 3.54 1.60 -1.00 0.00 0.00 -6.03 1260.70 +92.00 222410.80 14.03 2.50 2.10 41.71 -11.02 0.58 0.00 0.00 2.30 3.27 2.00 -1.00 0.00 0.00 -4.88 484.40 +93.00 232248.60 10.05 1.10 2.10 20.82 -11.44 2.36 0.00 0.00 1.01 2.18 0.20 -1.00 0.00 0.00 -7.99 82.20 +94.00 240796.60 16.55 1.80 2.10 50.97 -8.15 0.47 0.00 0.00 0.89 3.32 1.40 -1.00 0.00 0.00 -14.87 950.20 +95.00 240608.60 13.16 2.30 2.10 41.99 -8.89 -0.27 0.00 0.00 1.96 3.64 1.70 -1.00 0.00 0.00 -5.36 762.20 +96.00 240314.80 20.01 3.90 2.10 98.92 -8.09 -0.34 0.00 0.00 3.13 5.45 3.50 -1.00 0.00 0.00 -5.11 468.40 +97.00 241100.80 15.34 2.60 2.10 51.86 -7.84 -1.21 0.00 0.00 2.38 4.06 2.10 -1.00 0.00 0.00 -5.17 1254.40 +98.00 241535.10 11.75 2.10 2.10 32.79 -8.64 -1.45 0.00 0.00 1.53 3.41 1.50 -1.00 0.00 0.00 -6.15 408.70 +99.00 241739.70 10.13 2.60 2.10 30.68 -8.72 1.36 0.00 0.00 2.45 3.65 1.70 -1.00 0.00 0.00 -3.30 613.30 +100.00 241713.20 27.16 2.30 2.10 83.57 -8.09 0.20 0.00 0.00 1.72 3.37 1.40 -1.00 0.00 0.00 -12.62 586.80 +101.00 240171.50 11.61 4.10 2.10 43.86 -9.46 0.52 0.00 0.00 3.85 3.03 1.10 -1.00 0.00 0.00 -2.42 325.10 +102.00 240113.70 12.64 2.50 2.10 38.28 -9.70 1.98 0.00 0.00 2.08 3.76 1.80 -1.00 0.00 0.00 -4.87 267.30 +103.00 239391.90 12.94 1.50 2.10 27.54 -10.65 -1.38 0.00 0.00 1.26 2.20 1.00 -1.00 0.00 0.00 -8.20 825.50 +104.00 239186.20 15.91 2.50 2.10 53.25 -10.16 -1.23 0.00 0.00 1.91 3.91 2.00 -1.00 0.00 0.00 -6.66 619.80 +105.00 239095.60 15.03 1.50 2.10 34.14 -10.71 -1.81 0.00 0.00 1.02 2.80 0.80 -1.00 0.00 0.00 -11.81 529.20 +106.00 239501.40 12.18 1.30 2.10 29.29 -8.66 0.92 0.00 0.00 1.02 2.86 0.90 -1.00 0.00 0.00 -9.53 935.00 +107.00 239669.80 17.45 2.60 2.10 55.05 -8.43 0.78 0.00 0.00 2.18 3.75 1.80 -1.00 0.00 0.00 -6.41 1103.40 +108.00 239986.70 13.97 2.20 2.10 39.03 -7.50 1.93 0.00 0.00 1.16 3.02 1.10 -1.00 0.00 0.00 -9.62 140.30 +109.00 239755.70 17.64 3.50 2.10 60.23 -7.33 0.72 0.00 0.00 2.23 3.86 1.90 -1.00 0.00 0.00 -6.32 1189.30 +110.00 241780.30 10.45 1.90 2.10 27.64 -12.25 0.61 0.00 0.00 1.69 3.37 1.60 -1.00 0.00 0.00 -4.95 653.90 +111.00 241865.60 10.63 3.10 2.10 37.68 -8.42 -1.78 0.00 0.00 2.83 3.72 2.60 -1.00 0.00 0.00 -3.01 739.20 +112.00 245314.60 11.98 2.80 2.10 32.80 -10.05 0.58 0.00 0.00 1.87 2.87 1.40 -1.00 0.00 0.00 -5.12 348.20 +113.00 245048.90 14.77 2.50 2.10 41.86 -8.89 1.14 0.00 0.00 1.89 3.47 1.50 -1.00 0.00 0.00 -6.24 82.50 +114.00 244699.80 12.57 3.10 2.10 37.32 -9.12 -1.37 0.00 0.00 2.24 3.46 1.50 -1.00 0.00 0.00 -4.49 1013.40 +115.00 245858.50 21.91 5.50 2.10 99.10 -10.28 2.55 0.00 0.00 4.99 4.76 2.80 -1.00 0.00 0.00 -3.51 892.10 +116.00 246372.30 18.34 1.90 2.10 52.58 -7.99 -0.08 0.00 0.00 1.36 3.10 1.20 -1.00 0.00 0.00 -10.78 125.90 +117.00 246579.60 15.98 2.20 2.10 46.04 -7.96 1.62 0.00 0.00 1.64 3.37 1.40 -1.00 0.00 0.00 -7.79 333.20 +118.00 246450.10 17.97 2.10 2.10 52.01 -10.45 -0.62 0.00 0.00 1.82 3.40 1.50 -1.00 0.00 0.00 -7.92 203.70 +119.00 244536.90 13.21 2.50 2.10 38.20 -8.58 0.34 0.00 0.00 1.91 3.38 1.40 -1.00 0.00 0.00 -5.54 850.50 +120.00 244040.00 17.11 2.60 2.10 54.45 -8.13 0.26 0.00 0.00 1.10 3.75 1.80 -1.00 0.00 0.00 -12.42 353.60 +121.00 243041.10 14.28 2.20 2.10 34.08 -8.83 -1.55 0.00 0.00 1.67 2.70 1.30 -1.00 0.00 0.00 -6.86 634.70 +122.00 242490.30 15.08 3.20 2.10 58.36 -8.45 0.35 0.00 0.00 2.95 4.19 2.50 -1.00 0.00 0.00 -4.09 83.90 +123.00 242261.80 15.24 2.00 2.10 40.37 -8.17 2.57 0.00 0.00 1.69 3.23 1.30 -1.00 0.00 0.00 -7.23 1135.40 +124.00 243091.70 12.32 2.50 2.10 34.13 -10.63 0.46 0.00 0.00 2.06 3.19 1.70 -1.00 0.00 0.00 -4.79 685.30 +125.00 243309.70 19.40 2.00 2.10 57.86 -7.94 0.09 0.00 0.00 1.45 3.28 1.30 -1.00 0.00 0.00 -10.72 903.30 +126.00 243744.00 24.57 2.30 2.10 78.83 -8.86 -1.24 0.00 0.00 1.73 3.46 1.50 -1.00 0.00 0.00 -11.33 57.60 +127.00 243583.20 11.84 4.10 2.10 38.56 -7.87 -0.24 0.00 0.00 2.78 3.12 2.20 -1.00 0.00 0.00 -3.40 1176.80 +128.00 239045.50 16.62 4.10 2.10 63.71 -12.12 1.15 0.00 0.00 3.80 4.45 2.50 -1.00 0.00 0.00 -3.50 479.10 +129.00 238982.40 18.90 2.10 2.10 57.23 -8.78 0.17 0.00 0.00 1.89 3.56 1.60 -1.00 0.00 0.00 -8.01 416.00 +130.00 233039.70 22.58 2.10 2.10 65.35 -8.21 -0.24 0.00 0.00 1.02 3.37 1.40 -1.00 0.00 0.00 -17.68 873.30 +131.00 232989.20 11.93 1.40 2.10 28.14 -7.98 -1.26 0.00 0.00 1.23 2.95 1.00 -1.00 0.00 0.00 -7.78 822.80 +132.00 232599.50 12.08 5.10 2.10 56.98 -8.69 -2.13 0.00 0.00 3.77 5.13 3.20 -1.00 0.00 0.00 -2.56 433.10 +133.00 233201.40 18.00 2.00 2.10 51.81 -9.16 1.21 0.00 0.00 1.66 3.32 1.40 -1.00 0.00 0.00 -8.69 1035.00 +134.00 233695.60 11.87 1.80 2.10 30.09 -9.56 0.80 0.00 0.00 1.56 3.38 1.40 -1.00 0.00 0.00 -6.09 249.20 +135.00 233966.00 17.31 3.70 2.10 75.54 -9.49 0.29 0.00 0.00 3.44 4.87 2.90 -1.00 0.00 0.00 -4.02 519.60 +136.00 233758.40 15.14 1.50 2.10 37.93 -10.03 0.43 0.00 0.00 1.29 2.90 0.90 -1.00 0.00 0.00 -9.40 312.00 +137.00 232450.80 16.38 2.80 2.10 58.41 -9.41 0.67 0.00 0.00 1.73 4.24 2.30 -1.00 0.00 0.00 -7.56 284.40 +138.00 217795.70 28.05 2.00 2.10 88.73 -8.25 -0.16 0.00 0.00 1.33 3.44 1.50 -1.00 0.00 0.00 -16.91 989.30 +139.00 231362.60 10.58 3.40 2.10 36.77 -9.93 0.11 0.00 0.00 2.03 4.25 2.30 -1.00 0.00 0.00 -4.17 476.20 +140.00 230853.50 18.59 1.60 2.10 52.67 -9.18 -0.59 0.00 0.00 1.41 3.14 1.20 -1.00 0.00 0.00 -10.58 1247.10 +141.00 230560.20 18.06 2.60 2.10 53.43 -9.24 1.34 0.00 0.00 1.93 3.76 1.80 -1.00 0.00 0.00 -7.50 953.80 +142.00 231849.50 24.90 2.30 2.10 78.79 -9.37 -0.64 0.00 0.00 2.00 3.70 1.80 -1.00 0.00 0.00 -9.98 963.10 +143.00 231880.10 13.89 2.80 2.10 43.82 -10.19 -0.76 0.00 0.00 2.54 3.86 1.90 -1.00 0.00 0.00 -4.38 993.70 +144.00 232134.60 12.96 1.90 2.10 34.54 -11.24 -0.37 0.00 0.00 1.75 3.43 1.50 -1.00 0.00 0.00 -5.93 1248.20 +145.00 232053.90 14.65 1.60 2.10 38.45 -8.36 0.39 0.00 0.00 1.37 2.89 0.90 -1.00 0.00 0.00 -8.54 1167.50 +146.00 234305.60 10.32 1.80 2.10 25.62 -9.09 -1.64 0.00 0.00 1.43 2.69 0.70 -1.00 0.00 0.00 -5.77 859.20 +147.00 234437.60 10.35 2.40 2.10 30.43 -9.21 0.21 0.00 0.00 2.21 2.93 1.00 -1.00 0.00 0.00 -3.75 991.20 +148.00 237744.20 18.44 2.10 2.10 50.53 -8.33 -0.54 0.00 0.00 1.41 3.22 1.30 -1.00 0.00 0.00 -10.48 457.80 +149.00 237221.50 18.54 2.10 2.10 50.28 -8.26 -1.72 0.00 0.00 1.49 3.27 1.30 -1.00 0.00 0.00 -9.94 1215.10 +150.00 236991.20 18.91 3.90 2.10 59.04 -9.64 1.06 0.00 0.00 1.76 3.66 1.70 -1.00 0.00 0.00 -8.60 984.80 +151.00 238116.70 14.47 1.60 2.10 38.88 -8.16 -0.31 0.00 0.00 1.45 3.12 1.20 -1.00 0.00 0.00 -8.00 830.30 +152.00 238532.40 12.12 2.20 2.10 35.10 -9.21 -0.84 0.00 0.00 1.70 3.29 1.30 -1.00 0.00 0.00 -5.71 1246.00 +153.00 238899.80 18.60 3.20 2.10 73.40 -8.75 0.03 0.00 0.00 2.66 4.67 2.70 -1.00 0.00 0.00 -5.60 333.40 +154.00 238687.80 13.71 1.60 2.10 33.65 -10.01 -0.39 0.00 0.00 1.33 3.23 1.30 -1.00 0.00 0.00 -8.27 121.40 +155.00 236959.70 17.54 2.00 2.10 46.00 -10.24 -0.69 0.00 0.00 1.63 3.20 1.30 -1.00 0.00 0.00 -8.59 953.30 +156.00 236682.10 12.17 2.80 2.10 35.38 -10.00 0.55 0.00 0.00 2.23 3.03 1.30 -1.00 0.00 0.00 -4.37 675.70 +157.00 235144.40 21.21 3.90 2.10 85.23 -8.73 0.44 0.00 0.00 3.54 4.51 2.60 -1.00 0.00 0.00 -4.79 418.00 +158.00 234891.80 14.95 2.40 2.10 47.23 -8.81 -1.37 0.00 0.00 2.08 3.78 1.80 -1.00 0.00 0.00 -5.74 165.40 +159.00 234568.70 21.58 3.30 2.10 60.88 -8.57 -0.68 0.00 0.00 1.46 3.06 1.10 -1.00 0.00 0.00 -11.85 1122.30 +160.00 235277.20 18.58 1.80 2.10 48.21 -9.63 2.14 0.00 0.00 1.53 3.09 1.10 -1.00 0.00 0.00 -9.74 550.80 +161.00 235829.40 21.61 2.20 2.10 62.25 -7.96 -0.59 0.00 0.00 1.65 3.22 1.30 -1.00 0.00 0.00 -10.45 1103.00 +162.00 236561.00 14.98 2.10 2.10 39.21 -9.94 -1.28 0.00 0.00 1.63 3.21 1.30 -1.00 0.00 0.00 -7.36 554.60 +163.00 236425.80 23.12 1.90 2.10 66.65 -8.82 -1.16 0.00 0.00 1.72 3.30 1.40 -1.00 0.00 0.00 -10.78 419.40 +164.00 229961.00 12.01 2.80 2.10 44.97 -9.27 0.42 0.00 0.00 2.60 4.39 2.40 -1.00 0.00 0.00 -3.70 354.60 +165.00 211924.90 18.82 1.70 2.10 48.31 -8.94 0.27 0.00 0.00 1.31 2.90 0.90 -1.00 0.00 0.00 -11.49 238.50 +166.00 173261.10 13.16 2.40 2.10 38.52 -8.74 -0.72 0.00 0.00 2.28 3.21 1.80 -1.00 0.00 0.00 -4.61 1254.70 +167.00 173176.30 22.45 2.20 2.10 72.95 -7.63 -0.51 0.00 0.00 1.69 3.52 1.60 -1.00 0.00 0.00 -10.62 1169.90 +168.00 172901.70 13.09 1.60 2.10 34.67 -7.65 -0.31 0.00 0.00 1.34 2.95 1.00 -1.00 0.00 0.00 -7.80 895.30 +169.00 173580.60 24.14 2.10 2.10 74.73 -8.64 -0.30 0.00 0.00 1.62 3.63 1.70 -1.00 0.00 0.00 -11.90 294.20 +170.00 174165.70 18.16 1.90 2.10 53.84 -7.93 -0.81 0.00 0.00 1.67 3.44 1.50 -1.00 0.00 0.00 -8.72 879.30 +171.00 175321.60 25.65 1.90 2.10 72.55 -9.07 2.20 0.00 0.00 1.55 3.41 1.50 -1.00 0.00 0.00 -13.26 755.20 +172.00 174819.30 13.70 3.20 2.10 46.02 -7.87 0.81 0.00 0.00 2.64 4.29 2.30 -1.00 0.00 0.00 -4.16 252.90 +173.00 172458.70 14.12 1.90 2.10 35.74 -9.38 0.17 0.00 0.00 1.68 3.15 1.20 -1.00 0.00 0.00 -6.70 452.30 +174.00 172229.80 15.26 3.00 2.10 50.47 -8.06 1.26 0.00 0.00 2.81 3.77 1.80 -1.00 0.00 0.00 -4.34 223.40 +175.00 170552.90 12.34 2.60 2.10 30.11 -8.72 0.33 0.00 0.00 1.41 2.80 1.00 -1.00 0.00 0.00 -6.98 1106.50 +176.00 170469.00 20.16 2.30 2.10 62.20 -8.33 -1.70 0.00 0.00 2.10 3.50 1.50 -1.00 0.00 0.00 -7.69 1022.60 +177.00 169593.70 13.08 1.60 2.10 34.66 -8.05 0.15 0.00 0.00 1.22 3.14 1.20 -1.00 0.00 0.00 -8.57 147.30 +178.00 170862.00 15.18 2.00 2.10 38.52 -10.28 -0.80 0.00 0.00 1.76 3.13 1.20 -1.00 0.00 0.00 -6.89 135.60 +179.00 171497.50 14.06 1.90 2.10 37.81 -7.11 -0.27 0.00 0.00 1.69 2.90 1.70 -1.00 0.00 0.00 -6.65 771.10 +180.00 171792.80 12.31 1.90 2.10 31.62 -9.47 -0.04 0.00 0.00 1.55 3.14 1.40 -1.00 0.00 0.00 -6.34 1066.40 +181.00 171704.30 16.21 2.80 2.10 48.34 -8.86 -1.57 0.00 0.00 1.56 3.22 1.30 -1.00 0.00 0.00 -8.29 977.90 +182.00 175472.50 12.35 2.30 2.10 31.08 -9.58 -0.57 0.00 0.00 2.18 2.71 1.20 -1.00 0.00 0.00 -4.53 906.10 +183.00 176004.10 13.51 2.20 2.10 41.24 -7.29 -0.16 0.00 0.00 1.93 3.60 1.60 -1.00 0.00 0.00 -5.59 157.70 +184.00 183068.60 18.01 2.70 2.10 49.18 -7.99 -1.39 0.00 0.00 2.13 3.31 1.40 -1.00 0.00 0.00 -6.77 822.20 +185.00 182395.10 18.90 2.50 2.10 62.01 -8.64 1.76 0.00 0.00 2.05 3.85 1.90 -1.00 0.00 0.00 -7.37 148.70 +186.00 182061.60 11.87 2.60 2.10 35.85 -7.75 -0.80 0.00 0.00 2.38 1.92 1.80 -1.00 0.00 0.00 -3.99 1095.20 +187.00 183275.90 25.91 1.90 2.10 75.90 -8.38 -0.24 0.00 0.00 1.42 3.36 1.40 -1.00 0.00 0.00 -14.63 1029.50 +188.00 184198.70 11.34 1.70 2.10 30.45 -8.71 -0.90 0.00 0.00 1.37 2.67 0.70 -1.00 0.00 0.00 -6.62 672.30 +189.00 185875.70 14.38 2.00 2.10 40.21 -8.03 0.58 0.00 0.00 1.44 3.40 1.40 -1.00 0.00 0.00 -8.00 1069.30 +190.00 185536.90 23.49 3.30 2.10 88.34 -9.01 0.18 0.00 0.00 1.44 4.46 2.50 -1.00 0.00 0.00 -13.01 730.50 +191.00 181981.10 13.76 2.50 2.10 42.47 -7.63 0.24 0.00 0.00 1.70 3.60 1.60 -1.00 0.00 0.00 -6.46 1014.70 +192.00 181857.60 16.81 1.60 2.10 45.10 -9.73 -1.42 0.00 0.00 1.25 3.04 1.10 -1.00 0.00 0.00 -10.74 891.20 +193.00 179635.50 21.22 2.70 2.10 65.96 -8.33 -2.35 0.00 0.00 1.78 3.55 1.60 -1.00 0.00 0.00 -9.51 1229.10 +194.00 177649.80 17.08 2.40 2.10 51.11 -7.99 1.20 0.00 0.00 2.04 3.49 1.50 -1.00 0.00 0.00 -6.70 523.40 +195.00 177319.80 18.97 1.50 2.10 46.85 -8.83 0.99 0.00 0.00 1.31 2.77 0.80 -1.00 0.00 0.00 -11.59 193.40 +196.00 179790.30 13.25 2.40 2.10 36.67 -9.78 -1.20 0.00 0.00 2.16 3.02 1.80 -1.00 0.00 0.00 -4.90 103.90 +197.00 180356.30 10.33 1.90 2.10 27.71 -9.27 -0.18 0.00 0.00 1.61 3.16 1.20 -1.00 0.00 0.00 -5.12 669.90 +198.00 181780.00 21.79 2.60 2.10 73.80 -8.81 1.28 0.00 0.00 1.40 3.96 2.00 -1.00 0.00 0.00 -12.45 813.60 +199.00 180800.50 11.35 4.50 2.10 31.52 -7.48 0.18 0.00 0.00 0.97 2.48 0.50 -1.00 0.00 0.00 -9.34 1114.10 +200.00 169488.60 17.18 2.80 2.10 56.24 -7.93 0.30 0.00 0.00 2.28 3.84 1.90 -1.00 0.00 0.00 -6.04 42.20 +201.00 169298.80 12.64 2.00 2.10 31.07 -8.90 1.02 0.00 0.00 1.79 2.38 1.30 -1.00 0.00 0.00 -5.65 1132.40 +202.00 159827.70 15.89 1.50 2.10 31.08 -6.54 -1.59 0.00 0.00 0.54 2.45 0.50 -1.00 0.00 0.00 -23.67 621.30 +203.00 159602.20 14.30 1.90 2.10 41.50 -7.73 -0.52 0.00 0.00 1.72 3.43 1.50 -1.00 0.00 0.00 -6.64 395.80 +204.00 159061.20 11.67 2.00 2.10 33.19 -9.06 0.11 0.00 0.00 1.78 3.38 1.40 -1.00 0.00 0.00 -5.24 1134.80 +205.00 159898.80 23.69 2.10 2.10 67.29 -8.20 0.71 0.00 0.00 1.50 3.29 1.30 -1.00 0.00 0.00 -12.64 692.40 +206.00 159917.60 11.96 3.50 2.10 40.74 -10.90 2.41 0.00 0.00 3.38 3.40 2.60 -1.00 0.00 0.00 -2.83 711.20 +207.00 160335.00 10.07 3.70 2.10 35.38 -8.36 0.46 0.00 0.00 3.52 3.32 2.40 -1.00 0.00 0.00 -2.29 1128.60 +208.00 160127.90 13.28 2.20 2.10 37.14 -7.55 1.93 0.00 0.00 1.36 3.26 1.30 -1.00 0.00 0.00 -7.79 921.50 +209.00 158623.10 13.57 2.20 2.10 38.21 -7.10 0.29 0.00 0.00 2.05 3.26 1.50 -1.00 0.00 0.00 -5.30 696.70 +210.00 158446.60 15.15 2.50 2.10 46.97 -7.70 -1.69 0.00 0.00 1.61 3.57 1.60 -1.00 0.00 0.00 -7.53 520.20 +211.00 88.20 19.19 1.90 2.10 51.41 -8.04 1.11 0.00 0.00 1.02 3.46 1.50 -1.00 0.00 0.00 -15.02 88.20 +212.00 156619.30 22.08 2.60 2.10 75.11 -10.80 1.06 0.00 0.00 2.30 3.87 1.90 -1.00 0.00 0.00 -7.68 1252.90 +213.00 156553.60 37.74 4.90 2.10 174.04 -9.47 1.37 0.00 0.00 3.36 4.99 3.00 -1.00 0.00 0.00 -8.98 1187.20 +214.00 156898.30 10.63 2.60 2.10 35.76 -8.47 0.24 0.00 0.00 1.99 3.90 2.20 -1.00 0.00 0.00 -4.27 251.90 +215.00 156982.90 13.56 2.80 2.10 40.88 -6.94 -1.38 0.00 0.00 1.51 3.24 1.30 -1.00 0.00 0.00 -7.17 336.50 +216.00 157435.80 18.06 2.30 2.10 57.89 -7.83 -0.58 0.00 0.00 1.86 3.64 1.70 -1.00 0.00 0.00 -7.77 789.40 +217.00 157183.90 15.90 2.60 2.10 53.76 -9.59 -0.51 0.00 0.00 1.26 3.54 2.10 -1.00 0.00 0.00 -10.11 537.50 +218.00 161017.30 18.55 3.70 2.10 75.47 -10.10 0.95 0.00 0.00 3.29 4.65 2.90 -1.00 0.00 0.00 -4.51 530.90 +219.00 161211.80 16.51 2.30 2.10 45.85 -8.32 -2.12 0.00 0.00 1.76 3.41 1.60 -1.00 0.00 0.00 -7.50 725.40 +220.00 165987.20 10.10 1.50 2.10 24.43 -9.60 -1.11 0.00 0.00 1.22 2.32 0.80 -1.00 0.00 0.00 -6.64 380.80 +221.00 165622.90 10.50 4.60 2.10 37.08 -7.70 -0.40 0.00 0.00 4.01 3.79 3.30 -1.00 0.00 0.00 -2.09 16.50 +222.00 165347.50 12.91 2.50 2.10 37.22 -7.76 0.84 0.00 0.00 2.22 3.61 1.70 -1.00 0.00 0.00 -4.64 1021.10 +223.00 167108.80 15.70 1.90 2.10 44.07 -9.37 -2.32 0.00 0.00 1.72 3.26 1.30 -1.00 0.00 0.00 -7.29 222.40 +224.00 167262.00 19.61 2.30 2.10 60.96 -8.72 0.98 0.00 0.00 1.77 3.66 1.70 -1.00 0.00 0.00 -8.88 375.60 +225.00 168113.50 12.40 1.90 2.10 30.20 -9.24 -0.68 0.00 0.00 1.31 3.12 1.30 -1.00 0.00 0.00 -7.56 1227.10 +226.00 167694.20 13.89 2.30 2.10 40.02 -9.29 -0.14 0.00 0.00 2.15 3.68 1.90 -1.00 0.00 0.00 -5.17 807.80 +227.00 165063.70 15.39 1.80 2.10 44.89 -8.09 -0.49 0.00 0.00 1.18 3.06 1.10 -1.00 0.00 0.00 -10.46 737.30 +228.00 164884.60 19.21 2.80 2.10 72.36 -8.58 0.82 0.00 0.00 1.08 4.25 2.30 -1.00 0.00 0.00 -14.19 558.20 +229.00 162810.60 10.29 1.10 2.10 20.64 -7.96 1.97 0.00 0.00 1.01 2.44 0.50 -1.00 0.00 0.00 -8.15 1044.20 +230.00 161520.80 13.91 3.10 2.10 49.71 -6.54 -2.26 0.00 0.00 2.87 4.43 2.60 -1.00 0.00 0.00 -3.87 1034.40 +231.00 162956.50 16.73 2.30 2.10 49.58 -8.07 0.53 0.00 0.00 1.97 3.62 1.70 -1.00 0.00 0.00 -6.80 1190.10 +232.00 163087.40 13.44 1.90 2.10 31.73 -9.68 -0.72 0.00 0.00 1.24 2.94 1.00 -1.00 0.00 0.00 -8.69 41.00 +233.00 163535.60 17.72 2.90 2.10 64.09 -9.20 -0.36 0.00 0.00 2.63 4.17 2.20 -1.00 0.00 0.00 -5.38 489.20 +234.00 163265.10 20.83 1.20 2.10 46.25 -8.32 1.28 0.00 0.00 1.00 2.63 0.70 -1.00 0.00 0.00 -16.59 218.70 +235.00 186215.70 12.59 1.70 2.10 34.30 -8.65 -0.28 0.00 0.00 1.37 3.12 1.20 -1.00 0.00 0.00 -7.33 129.30 +236.00 186965.10 18.78 2.30 2.10 58.19 -9.28 0.38 0.00 0.00 1.92 3.50 1.60 -1.00 0.00 0.00 -7.81 878.70 +237.00 206181.40 13.18 1.60 2.10 29.99 -9.43 0.02 0.00 0.00 1.38 2.92 1.00 -1.00 0.00 0.00 -7.67 895.00 +238.00 206143.60 13.92 1.80 2.10 38.17 -9.65 -0.82 0.00 0.00 1.17 3.06 1.10 -1.00 0.00 0.00 -9.48 857.20 +239.00 205901.40 18.26 2.50 2.10 58.78 -12.30 -1.56 0.00 0.00 1.64 3.72 1.80 -1.00 0.00 0.00 -8.91 615.00 +240.00 206653.10 12.12 1.60 2.10 32.81 -9.15 -1.79 0.00 0.00 1.38 2.92 1.00 -1.00 0.00 0.00 -7.03 86.70 +241.00 206726.00 12.29 2.60 2.10 39.56 -10.05 0.24 0.00 0.00 2.36 3.67 2.10 -1.00 0.00 0.00 -4.17 159.60 +242.00 206957.70 20.70 3.00 2.10 66.21 -8.52 -0.40 0.00 0.00 2.06 3.66 1.70 -1.00 0.00 0.00 -8.03 391.30 +243.00 206820.10 20.75 2.50 2.10 64.35 -8.67 0.07 0.00 0.00 1.86 3.64 1.70 -1.00 0.00 0.00 -8.90 253.70 +244.00 205884.40 22.93 2.70 2.10 84.49 -9.44 -1.78 0.00 0.00 2.17 4.01 2.10 -1.00 0.00 0.00 -8.46 598.00 +245.00 205824.00 21.77 2.10 2.10 61.29 -9.23 -1.48 0.00 0.00 1.61 3.40 1.50 -1.00 0.00 0.00 -10.85 537.60 +246.00 203694.40 13.01 2.70 2.10 43.71 -9.08 2.85 0.00 0.00 2.43 4.16 2.20 -1.00 0.00 0.00 -4.27 968.00 +247.00 203659.20 17.29 1.50 2.10 40.81 -8.30 -0.70 0.00 0.00 1.31 2.84 0.90 -1.00 0.00 0.00 -10.56 932.80 +248.00 203173.30 12.26 3.20 2.40 47.99 -9.55 -0.70 0.00 0.00 2.89 2.71 2.40 -1.00 0.00 0.00 -3.39 62.90 +249.00 204585.00 18.63 2.30 2.10 57.17 -7.99 1.83 0.00 0.00 1.88 3.41 1.50 -1.00 0.00 0.00 -7.92 578.60 +250.00 204796.30 15.49 1.90 2.10 45.12 -7.46 0.17 0.00 0.00 1.38 3.50 1.60 -1.00 0.00 0.00 -8.97 789.90 +251.00 205593.00 21.70 1.70 2.10 60.20 -10.27 0.63 0.00 0.00 1.31 2.94 1.00 -1.00 0.00 0.00 -13.22 306.60 +252.00 205446.80 17.44 2.10 2.10 57.18 -8.90 -0.20 0.00 0.00 1.25 3.71 1.80 -1.00 0.00 0.00 -11.15 160.40 +253.00 207333.80 19.64 2.20 2.10 61.15 -8.62 -0.32 0.00 0.00 1.89 3.66 1.70 -1.00 0.00 0.00 -8.33 767.40 +254.00 207770.50 23.05 2.20 2.10 75.19 -9.16 -0.61 0.00 0.00 1.61 3.62 1.70 -1.00 0.00 0.00 -11.46 1204.10 +255.00 215447.40 18.16 2.70 2.10 62.71 -11.32 1.01 0.00 0.00 2.45 3.89 1.90 -1.00 0.00 0.00 -5.94 1201.00 +256.00 215149.50 14.84 2.50 2.10 44.67 -9.49 -0.61 0.00 0.00 2.14 3.59 1.60 -1.00 0.00 0.00 -5.55 903.10 +257.00 212730.00 21.12 2.00 2.10 56.76 -9.56 -0.13 0.00 0.00 1.62 3.16 1.20 -1.00 0.00 0.00 -10.40 1043.60 +258.00 215607.40 18.36 2.50 2.10 61.64 -9.69 1.26 0.00 0.00 1.45 3.80 1.90 -1.00 0.00 0.00 -10.11 81.00 +259.00 215660.80 11.74 1.70 2.10 29.19 -10.41 0.17 0.00 0.00 1.49 2.82 1.30 -1.00 0.00 0.00 -6.31 134.40 +260.00 216845.40 18.52 2.40 2.10 60.22 -8.12 0.59 0.00 0.00 1.86 3.74 1.80 -1.00 0.00 0.00 -7.96 39.00 +261.00 216225.90 29.10 2.40 2.10 85.02 -7.06 -1.37 0.00 0.00 1.48 3.35 1.40 -1.00 0.00 0.00 -15.70 699.50 +262.00 212468.00 24.20 2.30 2.10 70.62 -8.72 -0.93 0.00 0.00 1.83 3.50 1.60 -1.00 0.00 0.00 -10.59 781.60 +263.00 212129.40 20.92 4.10 2.10 81.11 -8.10 0.19 0.00 0.00 1.53 4.21 2.30 -1.00 0.00 0.00 -10.97 443.00 +264.00 209559.20 20.49 1.90 2.10 61.41 -8.85 0.17 0.00 0.00 1.65 3.42 1.50 -1.00 0.00 0.00 -9.91 432.80 +265.00 209353.90 17.86 3.20 2.10 68.19 -9.22 -1.83 0.00 0.00 2.08 4.38 2.40 -1.00 0.00 0.00 -6.86 227.50 +266.00 211429.80 11.44 2.00 2.10 28.43 -7.76 -1.10 0.00 0.00 1.78 3.11 1.20 -1.00 0.00 0.00 -5.14 1023.40 +267.00 211706.60 19.12 2.60 2.10 67.39 -7.65 0.41 0.00 0.00 1.73 4.01 2.10 -1.00 0.00 0.00 -8.84 20.20 +268.00 246818.40 25.06 2.30 2.10 72.80 -8.64 -0.90 0.00 0.00 1.67 3.15 1.20 -1.00 0.00 0.00 -11.97 572.00 +269.00 211761.60 16.69 1.60 2.10 41.46 -9.09 0.56 0.00 0.00 1.40 2.94 1.00 -1.00 0.00 0.00 -9.51 75.20 +270.00 202808.40 13.95 2.50 2.10 38.29 -8.17 -0.83 0.00 0.00 1.72 3.25 1.30 -1.00 0.00 0.00 -6.49 82.00 +271.00 202484.20 15.52 5.40 7.20 98.90 -8.42 -0.68 0.00 0.00 3.04 5.07 1.50 -1.00 0.00 0.00 -4.08 141.80 +272.00 191339.40 14.65 3.20 2.10 47.74 -9.04 -0.66 0.00 0.00 2.22 3.92 2.00 -1.00 0.00 0.00 -5.28 133.00 +273.00 191030.30 14.91 3.40 2.10 51.90 -7.72 -0.13 0.00 0.00 3.20 4.33 2.40 -1.00 0.00 0.00 -3.72 1103.90 +274.00 190656.80 10.26 2.80 2.10 35.59 -9.52 -1.31 0.00 0.00 2.30 3.96 2.00 -1.00 0.00 0.00 -3.57 730.40 +275.00 191698.30 12.45 1.60 2.10 31.07 -9.04 3.29 0.00 0.00 1.41 2.90 1.00 -1.00 0.00 0.00 -7.06 491.90 +276.00 192373.70 12.65 3.10 2.10 47.16 -9.24 -1.29 0.00 0.00 2.95 4.39 2.40 -1.00 0.00 0.00 -3.43 1167.30 +277.00 195864.90 15.54 2.80 2.10 51.50 -9.96 -0.86 0.00 0.00 2.57 3.66 1.70 -1.00 0.00 0.00 -4.83 818.50 +278.00 195302.60 15.05 2.30 2.10 47.34 -10.37 -0.17 0.00 0.00 2.03 3.60 1.70 -1.00 0.00 0.00 -5.94 256.20 +279.00 190495.80 28.49 2.00 2.10 84.18 -7.77 -1.00 0.00 0.00 1.32 3.35 1.40 -1.00 0.00 0.00 -17.28 569.40 +280.00 190215.90 14.27 1.80 2.10 36.31 -8.08 0.08 0.00 0.00 1.47 3.05 1.10 -1.00 0.00 0.00 -7.79 289.50 +281.00 187631.20 12.22 1.60 2.10 27.58 -9.82 -1.08 0.00 0.00 1.30 2.59 1.10 -1.00 0.00 0.00 -7.52 264.80 +282.00 187608.00 13.51 2.70 2.10 44.07 -9.80 2.29 0.00 0.00 2.43 4.27 2.30 -1.00 0.00 0.00 -4.44 241.60 +283.00 187420.10 21.87 2.30 2.10 68.04 -8.60 0.59 0.00 0.00 1.98 3.70 1.80 -1.00 0.00 0.00 -8.82 53.70 +284.00 188016.70 20.62 2.40 2.10 68.07 -8.09 0.24 0.00 0.00 1.42 3.74 1.80 -1.00 0.00 0.00 -11.62 650.30 +285.00 188504.40 14.07 2.60 2.10 42.96 -9.12 0.84 0.00 0.00 1.80 3.52 1.80 -1.00 0.00 0.00 -6.24 1138.00 +286.00 189976.00 12.17 2.70 2.10 35.53 -8.11 -0.23 0.00 0.00 2.50 3.77 1.80 -1.00 0.00 0.00 -3.90 49.60 +287.00 189760.40 15.32 2.30 2.10 46.18 -8.16 -0.17 0.00 0.00 2.11 3.66 1.70 -1.00 0.00 0.00 -5.81 1114.00 +288.00 196227.20 14.11 2.80 2.10 48.03 -8.59 -1.68 0.00 0.00 1.66 3.76 1.80 -1.00 0.00 0.00 -6.82 1180.80 +289.00 196809.50 32.13 2.00 2.10 98.69 -9.56 2.56 0.00 0.00 1.47 3.58 1.60 -1.00 0.00 0.00 -17.48 483.10 +290.00 201200.80 10.83 2.10 2.10 32.17 -10.23 -1.49 0.00 0.00 1.87 3.60 1.60 -1.00 0.00 0.00 -4.63 1034.40 +291.00 200303.30 19.27 1.80 2.10 49.53 -9.24 -0.42 0.00 0.00 1.51 2.99 1.00 -1.00 0.00 0.00 -10.20 136.90 +292.00 200067.70 12.07 2.50 8.10 85.77 -7.82 2.95 0.00 0.00 2.18 7.09 2.10 -1.00 0.00 0.00 -4.42 29.30 +293.00 201410.80 33.08 1.90 5.80 163.63 -9.74 -1.33 0.00 0.00 1.31 4.97 1.20 -1.00 0.00 0.00 -20.24 220.40 +294.00 201983.30 23.28 1.70 2.10 63.42 -9.41 0.48 0.00 0.00 1.28 3.13 1.20 -1.00 0.00 0.00 -14.55 536.90 +295.00 202459.30 16.53 1.20 2.10 37.09 -9.34 0.19 0.00 0.00 0.68 2.25 0.90 -1.00 0.00 0.00 -19.40 1012.90 +296.00 202181.50 16.85 3.20 2.10 60.33 -9.39 -0.82 0.00 0.00 2.39 3.88 1.90 -1.00 0.00 0.00 -5.64 735.10 +297.00 199923.40 20.76 2.90 2.10 72.93 -9.12 -0.29 0.00 0.00 2.06 4.16 2.20 -1.00 0.00 0.00 -8.08 1037.00 +298.00 199846.60 24.82 1.80 2.10 69.28 -9.37 0.53 0.00 0.00 1.45 3.12 1.20 -1.00 0.00 0.00 -13.68 960.20 +299.00 197224.80 16.47 4.20 2.10 59.40 -10.00 -0.37 0.00 0.00 2.76 4.07 2.10 -1.00 0.00 0.00 -4.78 898.40 +300.00 197167.70 20.54 2.40 2.10 57.71 -9.11 0.86 0.00 0.00 1.18 3.05 1.10 -1.00 0.00 0.00 -13.94 841.30 +301.00 198612.60 19.12 1.90 2.10 52.48 -9.34 -0.01 0.00 0.00 1.42 3.27 1.30 -1.00 0.00 0.00 -10.80 1006.20 +302.00 198783.80 20.70 2.40 2.10 65.17 -8.71 1.11 0.00 0.00 1.64 3.48 1.50 -1.00 0.00 0.00 -10.12 1177.40 +303.00 199646.00 15.70 1.40 2.10 36.11 -9.07 2.15 0.00 0.00 1.08 2.68 0.70 -1.00 0.00 0.00 -11.66 759.60 +304.00 199088.30 11.78 2.20 2.10 29.77 -8.92 -0.48 0.00 0.00 1.96 3.52 1.60 -1.00 0.00 0.00 -4.81 201.90 +305.00 217467.20 12.69 2.50 2.10 36.12 -8.73 -0.60 0.00 0.00 2.21 3.54 1.60 -1.00 0.00 0.00 -4.59 660.80 +306.00 248887.20 18.58 2.90 2.10 69.45 -8.10 -2.43 0.00 0.00 2.61 4.26 2.30 -1.00 0.00 0.00 -5.69 80.80 +307.00 319480.40 28.24 3.80 2.10 109.42 -12.30 -2.05 0.00 0.00 3.19 4.58 2.60 -1.00 0.00 0.00 -7.08 274.00 +308.00 319326.50 15.40 1.80 2.10 41.15 -11.83 -1.59 0.00 0.00 1.55 3.11 1.20 -1.00 0.00 0.00 -7.97 120.10 +309.00 318979.90 20.27 2.30 2.10 64.33 -11.51 0.03 0.00 0.00 1.75 3.77 1.80 -1.00 0.00 0.00 -9.25 1053.50 +310.00 319562.70 18.97 1.60 2.10 48.49 -12.33 0.28 0.00 0.00 1.31 2.89 0.90 -1.00 0.00 0.00 -11.56 356.30 +311.00 320106.70 13.83 1.50 2.10 33.42 -11.22 0.78 0.00 0.00 1.23 2.87 1.00 -1.00 0.00 0.00 -9.01 900.30 +312.00 321563.70 20.58 2.60 2.10 68.49 -10.20 -0.55 0.00 0.00 2.20 3.94 2.00 -1.00 0.00 0.00 -7.47 1077.30 +313.00 321222.00 11.07 2.90 2.10 30.97 -11.68 -1.33 0.00 0.00 1.97 3.10 1.10 -1.00 0.00 0.00 -4.50 735.60 +314.00 318530.70 15.29 1.30 2.10 35.45 -11.62 -1.87 0.00 0.00 1.14 2.60 0.60 -1.00 0.00 0.00 -10.72 604.30 +315.00 318236.20 22.30 2.40 2.10 73.42 -11.10 0.00 0.00 0.00 2.08 3.55 1.60 -1.00 0.00 0.00 -8.60 309.80 +316.00 316001.90 15.78 3.20 2.10 52.76 -13.18 -1.39 0.00 0.00 2.43 4.06 2.10 -1.00 0.00 0.00 -5.20 635.50 +317.00 315974.20 14.37 2.00 2.10 37.76 -12.03 -0.93 0.00 0.00 1.64 3.06 1.10 -1.00 0.00 0.00 -7.00 607.80 +318.00 315778.50 14.92 3.30 2.10 44.87 -12.92 -1.38 0.00 0.00 2.36 3.73 1.80 -1.00 0.00 0.00 -5.05 412.10 +319.00 316096.20 12.47 2.80 2.10 37.84 -11.85 -0.58 0.00 0.00 1.83 3.22 1.30 -1.00 0.00 0.00 -5.44 729.80 +320.00 316886.60 18.59 2.20 2.10 57.58 -11.05 1.96 0.00 0.00 1.85 3.50 1.50 -1.00 0.00 0.00 -8.05 240.20 +321.00 317555.90 16.15 2.20 2.10 51.66 -15.50 -3.58 0.00 0.00 1.99 3.56 1.60 -1.00 0.00 0.00 -6.49 909.50 +322.00 317521.60 40.18 5.00 2.10 164.29 -13.94 1.40 0.00 0.00 3.58 3.78 1.80 -1.00 0.00 0.00 -8.98 875.20 +323.00 322024.10 12.16 1.80 2.10 31.19 -11.14 0.80 0.00 0.00 1.33 3.03 1.10 -1.00 0.00 0.00 -7.33 257.70 +324.00 322430.70 11.86 2.00 2.10 36.26 -12.22 2.34 0.00 0.00 1.70 3.50 1.60 -1.00 0.00 0.00 -5.60 664.30 +325.00 328877.60 21.00 2.00 2.10 58.06 -10.75 0.50 0.00 0.00 1.60 3.25 1.30 -1.00 0.00 0.00 -10.50 711.20 +326.00 328626.70 17.77 3.80 2.10 72.09 -10.53 -0.36 0.00 0.00 3.07 4.81 2.90 -1.00 0.00 0.00 -4.64 460.30 +327.00 327956.70 17.69 2.30 2.10 54.00 -10.67 0.08 0.00 0.00 1.82 3.36 1.90 -1.00 0.00 0.00 -7.76 1070.30 +328.00 329356.70 21.62 4.10 2.10 91.37 -11.04 -0.18 0.00 0.00 3.07 4.67 2.70 -1.00 0.00 0.00 -5.63 1190.30 +329.00 329557.10 17.94 2.30 2.10 54.36 -11.71 1.38 0.00 0.00 1.68 3.65 1.70 -1.00 0.00 0.00 -8.54 110.70 +330.00 331535.80 23.35 2.70 2.10 77.70 -10.51 0.09 0.00 0.00 1.50 3.87 1.90 -1.00 0.00 0.00 -12.44 809.40 +331.00 330231.40 13.56 2.30 2.10 43.63 -10.13 -1.87 0.00 0.00 1.17 3.74 1.80 -1.00 0.00 0.00 -9.28 785.00 +332.00 327864.00 11.21 3.20 2.10 39.87 -10.57 -1.18 0.00 0.00 2.98 4.35 2.40 -1.00 0.00 0.00 -3.01 977.60 +333.00 327428.90 15.37 2.60 2.10 43.39 -11.37 -1.79 0.00 0.00 1.83 3.39 1.40 -1.00 0.00 0.00 -6.72 542.50 +334.00 323177.30 13.54 1.20 2.10 32.69 -11.77 -0.39 0.00 0.00 0.86 2.69 0.70 -1.00 0.00 0.00 -12.53 130.90 +335.00 322858.60 15.09 1.40 2.10 38.25 -10.57 -0.82 0.00 0.00 1.08 2.88 0.90 -1.00 0.00 0.00 -11.18 1092.20 +336.00 322683.40 16.76 3.40 2.10 63.09 -10.52 -1.37 0.00 0.00 2.79 4.46 2.50 -1.00 0.00 0.00 -4.80 917.00 +337.00 325951.90 18.17 2.60 2.10 52.21 -10.91 1.01 0.00 0.00 1.50 3.10 1.10 -1.00 0.00 0.00 -9.69 345.50 +338.00 326446.60 29.06 2.50 2.10 101.18 -12.13 1.19 0.00 0.00 1.20 3.84 1.90 -1.00 0.00 0.00 -19.33 840.20 +339.00 326656.50 11.66 4.40 2.10 50.65 -11.93 1.57 0.00 0.00 4.24 4.89 3.40 -1.00 0.00 0.00 -2.20 1050.10 +340.00 326609.30 12.67 1.70 2.10 33.76 -11.00 -0.21 0.00 0.00 1.47 2.87 0.90 -1.00 0.00 0.00 -6.92 1002.90 +341.00 315532.30 11.85 2.80 2.10 32.85 -13.42 -2.37 0.00 0.00 2.41 2.88 1.50 -1.00 0.00 0.00 -3.93 165.90 +342.00 315418.60 10.54 1.60 2.10 23.74 -13.56 -0.10 0.00 0.00 1.31 2.63 0.70 -1.00 0.00 0.00 -6.45 52.20 +343.00 302257.00 22.08 1.90 2.10 64.90 -12.92 -1.52 0.00 0.00 1.48 3.27 1.30 -1.00 0.00 0.00 -11.94 970.60 +344.00 302184.00 17.18 2.90 2.10 55.08 -8.92 -0.30 0.00 0.00 1.79 3.55 1.60 -1.00 0.00 0.00 -7.66 897.60 +345.00 302102.00 11.99 3.20 2.10 40.36 -12.16 1.44 0.00 0.00 2.97 3.81 2.10 -1.00 0.00 0.00 -3.23 815.60 +346.00 302489.60 26.08 1.50 2.10 63.86 -10.75 2.41 0.00 0.00 1.14 2.73 0.80 -1.00 0.00 0.00 -18.29 1203.20 +347.00 302719.50 14.02 1.60 2.10 31.52 -10.24 -0.27 0.00 0.00 0.79 2.53 0.60 -1.00 0.00 0.00 -14.24 153.10 +348.00 305304.60 23.30 2.70 2.10 74.67 -10.26 -2.42 0.00 0.00 2.02 3.58 1.60 -1.00 0.00 0.00 -9.24 178.20 +349.00 304613.40 20.21 1.80 2.10 59.39 -11.26 -0.56 0.00 0.00 1.49 3.28 1.30 -1.00 0.00 0.00 -10.89 767.00 +350.00 301777.80 16.01 2.40 2.10 53.76 -9.52 -0.07 0.00 0.00 1.69 3.74 1.80 -1.00 0.00 0.00 -7.60 491.40 +351.00 301296.30 23.37 2.50 2.10 83.18 -11.88 -0.60 0.00 0.00 1.98 4.04 2.10 -1.00 0.00 0.00 -9.45 9.90 +352.00 299761.40 17.18 3.60 2.10 62.10 -11.19 0.96 0.00 0.00 3.00 4.14 2.20 -1.00 0.00 0.00 -4.58 1035.00 +353.00 299556.30 11.61 1.70 2.10 29.83 -14.97 -1.35 0.00 0.00 1.37 3.09 1.10 -1.00 0.00 0.00 -6.80 829.90 +354.00 299538.80 26.05 2.40 2.10 80.85 -10.61 1.29 0.00 0.00 1.78 3.57 1.60 -1.00 0.00 0.00 -11.70 812.40 +355.00 299847.10 18.97 1.90 2.10 51.79 -12.41 -0.55 0.00 0.00 1.64 3.30 1.30 -1.00 0.00 0.00 -9.25 1120.70 +356.00 300115.10 19.18 3.60 2.10 70.02 -10.46 -2.43 0.00 0.00 2.72 3.91 2.00 -1.00 0.00 0.00 -5.65 108.70 +357.00 300408.30 15.37 2.50 2.10 52.63 -10.57 -0.89 0.00 0.00 1.34 3.79 1.80 -1.00 0.00 0.00 -9.17 401.90 +358.00 300313.80 29.90 3.60 2.10 109.97 -11.24 0.08 0.00 0.00 2.25 3.89 1.90 -1.00 0.00 0.00 -10.63 307.40 +359.00 305328.90 12.45 2.00 2.10 30.04 -10.58 -0.23 0.00 0.00 1.73 3.00 1.20 -1.00 0.00 0.00 -5.75 202.50 +360.00 305372.60 19.82 1.90 2.10 59.21 -12.09 0.05 0.00 0.00 1.50 3.44 1.50 -1.00 0.00 0.00 -10.60 246.20 +361.00 310538.10 25.43 4.10 2.10 107.60 -11.43 -1.40 0.00 0.00 2.45 4.25 2.30 -1.00 0.00 0.00 -8.29 291.70 +362.00 309736.90 11.15 2.20 2.10 27.86 -10.33 0.49 0.00 0.00 2.01 2.71 1.20 -1.00 0.00 0.00 -4.45 770.50 +363.00 309126.10 19.53 2.10 2.10 58.43 -10.37 -1.23 0.00 0.00 1.91 3.49 1.50 -1.00 0.00 0.00 -8.18 159.70 +364.00 311201.00 19.00 2.40 2.10 54.07 -12.38 -0.56 0.00 0.00 1.89 3.55 1.60 -1.00 0.00 0.00 -8.05 954.60 +365.00 311665.50 12.97 2.90 2.10 39.64 -10.84 2.06 0.00 0.00 2.05 3.78 1.80 -1.00 0.00 0.00 -5.06 139.10 +366.00 314722.60 12.19 4.10 2.10 50.73 -10.98 2.08 0.00 0.00 3.66 4.84 3.50 -1.00 0.00 0.00 -2.66 636.20 +367.00 311934.90 11.20 3.40 2.10 35.88 -10.22 2.25 0.00 0.00 1.87 3.64 1.70 -1.00 0.00 0.00 -4.80 408.50 +368.00 308582.90 14.23 1.80 2.10 39.16 -11.13 0.50 0.00 0.00 1.22 3.07 1.10 -1.00 0.00 0.00 -9.35 896.50 +369.00 308582.60 14.47 1.50 2.10 36.36 -11.03 1.54 0.00 0.00 1.23 2.77 0.80 -1.00 0.00 0.00 -9.42 896.20 +370.00 307445.50 18.35 2.40 2.10 60.63 -11.37 -0.57 0.00 0.00 1.78 3.73 1.80 -1.00 0.00 0.00 -8.24 1039.10 +371.00 306918.50 20.83 2.20 2.10 65.25 -10.52 0.73 0.00 0.00 2.03 3.58 1.60 -1.00 0.00 0.00 -8.19 512.10 +372.00 306564.60 19.19 1.50 2.10 48.45 -11.37 -0.23 0.00 0.00 1.29 2.93 1.00 -1.00 0.00 0.00 -11.88 158.20 +373.00 307713.90 17.91 3.20 2.10 67.22 -11.84 0.14 0.00 0.00 2.10 4.35 2.40 -1.00 0.00 0.00 -6.82 27.50 +374.00 307757.40 14.96 2.70 2.10 42.00 -12.52 1.95 0.00 0.00 2.39 3.14 2.10 -1.00 0.00 0.00 -5.01 71.00 +375.00 308383.40 14.79 3.30 2.10 53.96 -10.05 0.22 0.00 0.00 3.13 4.25 2.70 -1.00 0.00 0.00 -3.78 697.00 +376.00 307978.90 19.91 3.40 2.10 79.28 -10.69 -0.43 0.00 0.00 3.06 4.48 2.50 -1.00 0.00 0.00 -5.20 292.50 +377.00 332147.80 23.07 2.30 2.10 69.83 -11.01 -0.12 0.00 0.00 1.91 3.51 1.60 -1.00 0.00 0.00 -9.68 141.40 +378.00 332312.90 15.67 1.90 2.10 43.54 -11.80 -1.27 0.00 0.00 1.32 3.18 1.20 -1.00 0.00 0.00 -9.47 306.50 +379.00 356131.20 17.19 1.60 2.10 44.96 -12.63 -1.45 0.00 0.00 1.36 2.79 0.80 -1.00 0.00 0.00 -10.13 1084.80 +380.00 355051.20 10.72 2.80 2.10 33.22 -14.44 1.48 0.00 0.00 2.61 3.45 1.70 -1.00 0.00 0.00 -3.29 4.80 +381.00 354985.30 20.05 3.20 2.10 72.43 -15.13 -1.20 0.00 0.00 2.35 4.19 2.20 -1.00 0.00 0.00 -6.82 1218.90 +382.00 357010.20 25.19 3.20 2.10 100.72 -12.02 -0.60 0.00 0.00 1.36 4.52 2.60 -1.00 0.00 0.00 -14.87 683.80 +383.00 357939.30 11.54 3.60 2.10 44.66 -10.81 0.59 0.00 0.00 3.36 4.16 3.00 -1.00 0.00 0.00 -2.75 332.90 +384.00 359970.60 13.84 1.70 2.10 34.79 -11.51 0.66 0.00 0.00 1.42 3.08 1.10 -1.00 0.00 0.00 -7.80 1084.20 +385.00 359794.20 16.63 1.50 2.10 46.97 -13.24 1.18 0.00 0.00 1.04 3.17 1.20 -1.00 0.00 0.00 -12.80 907.80 +386.00 354875.40 13.96 2.00 2.10 38.88 -15.82 -0.78 0.00 0.00 1.76 3.25 1.30 -1.00 0.00 0.00 -6.33 1109.00 +387.00 354774.90 10.03 2.70 2.10 30.33 -14.45 0.32 0.00 0.00 2.40 3.10 1.90 -1.00 0.00 0.00 -3.34 1008.50 +388.00 351110.10 13.16 2.40 2.10 43.36 -14.46 -0.21 0.00 0.00 2.19 3.77 1.80 -1.00 0.00 0.00 -4.80 1183.70 +389.00 350683.20 23.33 2.70 2.10 62.32 -12.87 -0.43 0.00 0.00 1.25 2.97 1.00 -1.00 0.00 0.00 -14.97 756.80 +390.00 350202.00 10.78 1.90 2.10 27.81 -15.38 -0.78 0.00 0.00 1.57 2.59 1.50 -1.00 0.00 0.00 -5.49 275.60 +391.00 352186.60 12.57 1.80 2.10 32.11 -12.47 0.44 0.00 0.00 1.62 3.14 1.20 -1.00 0.00 0.00 -6.22 980.20 +392.00 352277.60 10.30 1.30 2.10 23.64 -11.88 -1.28 0.00 0.00 1.06 2.39 0.40 -1.00 0.00 0.00 -7.74 1071.20 +393.00 353200.90 15.98 2.50 2.10 49.61 -13.82 -2.11 0.00 0.00 2.25 3.65 1.70 -1.00 0.00 0.00 -5.69 714.50 +394.00 352986.40 19.90 2.40 2.10 61.43 -10.75 1.39 0.00 0.00 2.19 3.81 1.90 -1.00 0.00 0.00 -7.28 500.00 +395.00 360008.90 10.39 1.80 2.10 24.80 -12.15 -1.29 0.00 0.00 1.60 2.68 0.70 -1.00 0.00 0.00 -5.18 1122.50 +396.00 361609.40 14.28 3.00 4.10 64.84 -13.79 1.46 0.00 0.00 2.26 4.53 2.00 -1.00 0.00 0.00 -5.05 111.80 +397.00 368457.60 14.55 2.80 2.10 46.47 -12.67 0.68 0.00 0.00 2.41 4.00 2.00 -1.00 0.00 0.00 -4.83 611.20 +398.00 368297.00 12.59 2.70 2.10 40.29 -11.62 0.82 0.00 0.00 1.75 3.60 1.60 -1.00 0.00 0.00 -5.76 450.60 +399.00 368083.30 11.79 2.80 2.10 36.17 -12.93 -0.77 0.00 0.00 2.53 3.64 2.00 -1.00 0.00 0.00 -3.72 236.90 +400.00 368713.90 10.72 1.70 2.10 25.64 -12.19 -0.80 0.00 0.00 1.50 2.99 1.00 -1.00 0.00 0.00 -5.73 867.50 +401.00 369509.40 10.32 1.70 2.10 27.66 -11.12 -0.17 0.00 0.00 1.23 3.12 1.20 -1.00 0.00 0.00 -6.70 383.00 +402.00 373491.80 14.18 3.60 2.10 45.36 -11.46 1.23 0.00 0.00 2.23 3.35 1.40 -1.00 0.00 0.00 -5.09 525.40 +403.00 371438.90 12.20 2.40 2.10 42.00 -11.03 -0.71 0.00 0.00 2.16 3.79 1.80 -1.00 0.00 0.00 -4.51 1032.50 +404.00 367912.80 12.50 3.20 2.10 41.36 -12.19 0.86 0.00 0.00 3.04 3.66 2.20 -1.00 0.00 0.00 -3.29 66.40 +405.00 366765.80 11.75 2.20 2.10 30.18 -11.74 0.71 0.00 0.00 1.68 2.89 0.90 -1.00 0.00 0.00 -5.58 199.40 +406.00 364910.50 17.44 2.40 2.10 54.18 -13.25 -2.12 0.00 0.00 2.10 3.82 1.90 -1.00 0.00 0.00 -6.64 904.10 +407.00 363803.60 10.55 2.00 2.10 25.10 -11.57 0.20 0.00 0.00 1.81 3.17 1.50 -1.00 0.00 0.00 -4.67 1077.20 +408.00 362718.80 12.76 2.80 2.10 46.08 -12.40 -0.85 0.00 0.00 2.53 4.18 2.20 -1.00 0.00 0.00 -4.03 1272.40 +409.00 365447.80 16.02 1.90 2.10 47.93 -11.98 0.25 0.00 0.00 1.75 3.35 1.40 -1.00 0.00 0.00 -7.32 161.40 +410.00 365865.60 11.69 3.50 2.10 38.01 -13.08 1.46 0.00 0.00 3.03 3.48 1.50 -1.00 0.00 0.00 -3.08 579.20 +411.00 366664.10 10.07 1.80 2.10 23.01 -11.68 -1.18 0.00 0.00 0.90 2.52 0.60 -1.00 0.00 0.00 -8.93 97.70 +412.00 366185.90 15.37 2.90 2.10 56.49 -11.06 -0.89 0.00 0.00 2.66 4.54 2.60 -1.00 0.00 0.00 -4.62 899.50 +413.00 349786.90 16.41 1.90 2.10 40.13 -12.70 1.49 0.00 0.00 1.37 2.84 0.90 -1.00 0.00 0.00 -9.60 1140.50 +414.00 349667.00 18.60 2.90 2.10 72.06 -13.67 -1.01 0.00 0.00 2.44 4.37 2.40 -1.00 0.00 0.00 -6.11 1020.60 +415.00 338513.00 21.83 4.00 2.10 77.09 -10.66 0.13 0.00 0.00 2.55 3.88 1.90 -1.00 0.00 0.00 -6.83 106.60 +416.00 337414.60 11.76 3.30 2.10 39.37 -10.96 0.33 0.00 0.00 2.21 3.89 1.90 -1.00 0.00 0.00 -4.25 288.20 +417.00 335887.80 10.00 2.00 2.10 23.37 -11.47 0.98 0.00 0.00 1.04 2.42 0.60 -1.00 0.00 0.00 -7.67 41.40 +418.00 339025.10 17.91 2.40 2.10 53.13 -11.13 -0.61 0.00 0.00 1.59 3.43 1.50 -1.00 0.00 0.00 -9.04 618.70 +419.00 339404.00 16.46 1.90 2.10 41.51 -12.45 0.66 0.00 0.00 1.41 2.91 1.20 -1.00 0.00 0.00 -9.32 997.60 +420.00 341503.60 23.43 2.30 2.10 74.97 -9.85 -1.57 0.00 0.00 2.14 3.77 1.80 -1.00 0.00 0.00 -8.76 537.20 +421.00 339470.60 15.80 1.40 2.10 37.52 -13.15 -0.90 0.00 0.00 1.06 2.68 0.70 -1.00 0.00 0.00 -11.91 1064.20 +422.00 335510.30 11.86 3.00 2.10 36.76 -10.94 0.09 0.00 0.00 2.77 4.01 2.60 -1.00 0.00 0.00 -3.42 943.90 +423.00 335291.30 10.26 2.30 2.10 27.82 -11.76 0.77 0.00 0.00 1.47 2.70 0.70 -1.00 0.00 0.00 -5.59 724.90 +424.00 334253.50 11.59 1.80 2.10 29.81 -11.03 0.26 0.00 0.00 1.50 3.40 1.50 -1.00 0.00 0.00 -6.17 967.10 +425.00 332501.50 14.59 1.80 2.10 37.99 -12.13 -0.72 0.00 0.00 1.62 3.18 1.20 -1.00 0.00 0.00 -7.21 495.10 +426.00 332345.00 21.47 2.30 2.10 65.85 -13.04 -1.64 0.00 0.00 1.37 3.65 1.70 -1.00 0.00 0.00 -12.56 338.60 +427.00 334452.20 10.64 1.80 2.10 28.03 -12.58 -0.20 0.00 0.00 1.57 3.08 1.10 -1.00 0.00 0.00 -5.44 1165.80 +428.00 334716.80 16.02 1.80 2.10 44.78 -12.96 0.15 0.00 0.00 1.51 3.21 1.30 -1.00 0.00 0.00 -8.49 150.40 +429.00 335137.20 12.59 1.40 2.10 28.94 -13.69 -2.07 0.00 0.00 1.14 2.72 1.10 -1.00 0.00 0.00 -8.81 570.80 +430.00 335076.90 25.55 3.40 2.10 82.28 -12.46 -1.38 0.00 0.00 1.96 3.58 1.60 -1.00 0.00 0.00 -10.41 510.50 +431.00 344156.90 10.36 1.70 2.10 19.57 -11.16 0.96 0.00 0.00 1.56 1.08 0.90 -1.00 0.00 0.00 -5.31 630.50 +432.00 344729.00 14.65 2.80 2.10 45.58 -12.00 0.48 0.00 0.00 1.64 3.45 1.80 -1.00 0.00 0.00 -7.16 1202.60 +433.00 348417.10 25.10 3.00 2.10 90.40 -11.96 0.71 0.00 0.00 2.60 4.15 2.20 -1.00 0.00 0.00 -7.73 1050.70 +434.00 348144.30 18.20 2.30 2.10 55.89 -12.62 0.29 0.00 0.00 1.85 3.48 1.50 -1.00 0.00 0.00 -7.87 777.90 +435.00 347028.30 12.13 2.60 2.10 35.23 -14.14 2.30 0.00 0.00 2.47 3.51 2.00 -1.00 0.00 0.00 -3.93 941.90 +436.00 348549.20 18.16 1.40 2.10 45.11 -11.90 0.28 0.00 0.00 1.04 2.90 1.00 -1.00 0.00 0.00 -13.94 1182.80 +437.00 349164.90 14.66 2.80 2.10 43.93 -11.45 0.08 0.00 0.00 2.29 3.09 1.80 -1.00 0.00 0.00 -5.11 518.50 +438.00 349546.60 13.70 3.70 2.10 60.27 -12.15 0.25 0.00 0.00 3.36 4.89 2.90 -1.00 0.00 0.00 -3.26 900.20 +439.00 349447.70 14.33 2.30 2.10 35.76 -13.22 0.93 0.00 0.00 1.09 2.88 0.90 -1.00 0.00 0.00 -10.53 801.30 +440.00 346979.80 13.07 2.90 2.10 46.17 -11.58 -0.42 0.00 0.00 2.52 3.95 2.00 -1.00 0.00 0.00 -4.15 893.40 +441.00 346962.80 11.74 3.30 2.10 43.84 -10.25 -0.51 0.00 0.00 3.05 3.09 2.20 -1.00 0.00 0.00 -3.08 876.40 +442.00 345332.50 18.37 2.30 2.10 53.18 -12.34 1.85 0.00 0.00 1.85 3.26 1.30 -1.00 0.00 0.00 -7.94 526.10 +443.00 344971.30 22.32 2.40 2.10 67.05 -12.02 0.49 0.00 0.00 1.72 3.59 1.60 -1.00 0.00 0.00 -10.37 164.90 +444.00 344860.30 24.42 2.70 2.10 83.50 -10.68 0.23 0.00 0.00 1.94 3.70 1.70 -1.00 0.00 0.00 -10.07 53.90 +445.00 345639.40 12.20 1.50 2.10 28.91 -11.57 -1.23 0.00 0.00 1.09 2.94 1.00 -1.00 0.00 0.00 -8.98 833.00 +446.00 345861.20 20.29 2.80 2.10 61.96 -12.58 0.88 0.00 0.00 1.52 3.53 1.60 -1.00 0.00 0.00 -10.65 1054.80 +447.00 346259.10 17.34 2.80 2.10 60.34 -12.76 0.33 0.00 0.00 1.30 4.00 2.20 -1.00 0.00 0.00 -10.69 172.70 +448.00 346001.50 11.22 3.70 2.10 45.06 -12.54 -1.33 0.00 0.00 3.18 4.87 2.90 -1.00 0.00 0.00 -2.83 1195.10 +449.00 298676.10 16.71 4.00 2.10 68.00 -9.99 0.02 0.00 0.00 2.62 4.75 2.80 -1.00 0.00 0.00 -5.10 1229.70 +450.00 297821.00 14.90 3.40 2.10 57.54 -8.95 2.47 0.00 0.00 2.91 4.47 2.50 -1.00 0.00 0.00 -4.10 374.60 +451.00 260414.60 18.63 2.10 2.10 56.99 -7.68 0.29 0.00 0.00 1.82 3.43 1.50 -1.00 0.00 0.00 -8.17 88.20 +452.00 259941.30 20.80 2.30 2.10 63.60 -8.55 -0.88 0.00 0.00 1.40 3.48 1.50 -1.00 0.00 0.00 -11.91 894.90 +453.00 259844.60 10.31 2.80 2.10 34.25 -7.50 -1.10 0.00 0.00 2.63 3.52 2.20 -1.00 0.00 0.00 -3.13 798.20 +454.00 260549.50 17.04 2.20 2.10 52.69 -7.71 -1.08 0.00 0.00 1.69 3.34 1.40 -1.00 0.00 0.00 -8.04 223.10 +455.00 261143.90 10.93 1.10 2.10 22.89 -7.39 -0.47 0.00 0.00 0.89 2.25 0.30 -1.00 0.00 0.00 -9.84 817.50 +456.00 261991.20 16.70 4.70 2.10 59.31 -8.46 -2.05 0.00 0.00 1.72 3.84 1.90 -1.00 0.00 0.00 -7.77 384.80 +457.00 261178.60 26.85 2.80 2.10 87.39 -8.50 2.30 0.00 0.00 2.43 3.91 2.00 -1.00 0.00 0.00 -8.85 852.20 +458.00 259385.60 17.09 1.80 2.10 45.48 -7.43 -0.85 0.00 0.00 1.46 3.07 1.10 -1.00 0.00 0.00 -9.39 339.20 +459.00 258473.40 15.06 1.90 2.10 38.51 -9.41 0.67 0.00 0.00 1.72 2.87 1.30 -1.00 0.00 0.00 -7.01 707.00 +460.00 257092.40 17.29 3.10 2.10 56.12 -8.76 1.66 0.00 0.00 2.56 4.22 2.30 -1.00 0.00 0.00 -5.40 606.00 +461.00 257032.90 15.33 1.50 2.10 38.51 -7.78 -0.56 0.00 0.00 1.38 2.68 0.70 -1.00 0.00 0.00 -8.88 546.50 +462.00 256806.80 20.75 2.50 2.10 69.44 -10.65 1.24 0.00 0.00 2.05 3.84 1.90 -1.00 0.00 0.00 -8.11 320.40 +463.00 257112.20 16.51 2.30 2.10 45.89 -9.94 -1.32 0.00 0.00 1.65 3.35 1.40 -1.00 0.00 0.00 -8.00 625.80 +464.00 257291.40 16.68 3.00 2.10 55.89 -7.37 0.18 0.00 0.00 2.38 3.84 1.90 -1.00 0.00 0.00 -5.60 805.00 +465.00 258453.30 25.57 1.80 2.10 71.16 -7.15 1.62 0.00 0.00 1.36 3.25 1.30 -1.00 0.00 0.00 -15.08 686.90 +466.00 258066.90 19.49 3.90 2.10 92.77 -9.43 -0.37 0.00 0.00 3.27 5.31 3.40 -1.00 0.00 0.00 -4.77 300.50 +467.00 263003.40 17.26 2.30 2.10 52.14 -7.32 -0.62 0.00 0.00 1.76 3.47 1.50 -1.00 0.00 0.00 -7.85 117.00 +468.00 263172.00 20.14 1.80 2.10 56.15 -8.84 1.67 0.00 0.00 1.46 3.13 1.20 -1.00 0.00 0.00 -11.03 285.60 +469.00 267614.20 10.79 3.90 2.10 37.91 -9.70 0.51 0.00 0.00 2.64 3.26 2.60 -1.00 0.00 0.00 -3.27 887.80 +470.00 267521.40 17.36 1.50 2.10 44.33 -10.44 0.45 0.00 0.00 1.20 2.80 0.80 -1.00 0.00 0.00 -11.61 795.00 +471.00 267505.50 11.05 2.30 2.10 27.54 -10.23 0.10 0.00 0.00 2.17 2.05 1.30 -1.00 0.00 0.00 -4.08 779.10 +472.00 267893.20 24.13 2.20 2.10 81.82 -7.99 -2.02 0.00 0.00 1.35 3.68 1.70 -1.00 0.00 0.00 -14.34 1166.80 +473.00 268278.80 13.61 2.10 2.10 34.49 -9.49 0.48 0.00 0.00 1.90 3.34 1.40 -1.00 0.00 0.00 -5.73 272.40 +474.00 269556.60 10.01 2.20 2.10 27.34 -10.52 0.12 0.00 0.00 1.81 3.12 1.20 -1.00 0.00 0.00 -4.43 270.20 +475.00 268436.80 20.82 2.80 2.10 56.02 -8.34 0.83 0.00 0.00 1.51 2.97 1.00 -1.00 0.00 0.00 -11.00 430.40 +476.00 267037.70 27.75 4.70 2.10 116.11 -8.10 1.50 0.00 0.00 3.08 4.87 2.90 -1.00 0.00 0.00 -7.22 311.30 +477.00 266626.90 18.40 3.20 2.10 69.37 -7.28 2.38 0.00 0.00 2.87 4.72 2.80 -1.00 0.00 0.00 -5.13 1180.50 +478.00 263862.30 12.35 1.70 2.10 31.57 -8.93 1.57 0.00 0.00 1.57 2.93 1.00 -1.00 0.00 0.00 -6.28 975.90 +479.00 263695.90 17.14 2.60 2.10 61.28 -8.27 -0.22 0.00 0.00 1.47 3.96 2.00 -1.00 0.00 0.00 -9.34 809.50 +480.00 263246.20 11.41 2.30 2.10 28.72 -8.83 -1.72 0.00 0.00 2.16 2.04 1.60 -1.00 0.00 0.00 -4.23 359.80 +481.00 264152.60 12.75 2.30 2.10 40.18 -7.65 -0.90 0.00 0.00 2.12 3.67 1.90 -1.00 0.00 0.00 -4.81 1266.20 +482.00 264690.30 20.33 1.50 2.10 53.82 -8.37 -0.55 0.00 0.00 1.27 2.88 0.90 -1.00 0.00 0.00 -12.76 523.90 +483.00 266405.10 15.04 1.90 2.10 39.64 -7.31 -0.31 0.00 0.00 1.35 3.18 1.20 -1.00 0.00 0.00 -8.92 958.70 +484.00 265641.70 11.42 1.90 2.10 28.23 -7.96 -1.64 0.00 0.00 1.71 2.02 1.40 -1.00 0.00 0.00 -5.33 195.30 +485.00 256731.40 13.33 2.90 2.10 39.66 -7.18 -0.43 0.00 0.00 2.49 2.94 1.90 -1.00 0.00 0.00 -4.28 245.00 +486.00 256560.50 12.38 1.00 2.10 26.06 -7.48 0.71 0.00 0.00 0.63 2.64 0.70 -1.00 0.00 0.00 -15.64 74.10 +487.00 249111.60 12.06 2.20 2.10 31.64 -6.65 0.20 0.00 0.00 1.78 3.21 1.30 -1.00 0.00 0.00 -5.41 305.20 +488.00 248931.80 16.35 2.00 2.10 45.69 -9.92 0.03 0.00 0.00 1.42 3.30 1.40 -1.00 0.00 0.00 -9.21 125.40 +489.00 248913.20 16.12 1.80 2.10 45.99 -9.55 -0.36 0.00 0.00 1.59 3.28 1.30 -1.00 0.00 0.00 -8.13 106.80 +490.00 249203.60 10.62 2.90 2.10 31.50 -8.60 -1.44 0.00 0.00 2.32 3.61 2.10 -1.00 0.00 0.00 -3.66 397.20 +491.00 249715.50 22.38 2.80 2.10 78.73 -8.75 1.03 0.00 0.00 2.22 4.02 2.10 -1.00 0.00 0.00 -8.05 909.10 +492.00 250275.20 16.38 3.00 2.10 62.37 -10.86 -1.80 0.00 0.00 2.72 4.20 2.20 -1.00 0.00 0.00 -4.82 188.80 +493.00 249783.80 20.66 1.70 2.10 56.63 -8.80 0.24 0.00 0.00 1.21 3.08 1.10 -1.00 0.00 0.00 -13.61 977.40 +494.00 155912.70 14.38 1.40 2.10 33.23 -8.33 0.50 0.00 0.00 1.20 2.76 0.80 -1.00 0.00 0.00 -9.61 546.30 +495.00 248787.50 22.97 2.90 2.10 86.22 -8.08 -1.26 0.00 0.00 2.48 4.41 2.50 -1.00 0.00 0.00 -7.40 1261.10 +496.00 247844.30 13.12 2.70 2.10 41.09 -8.31 -0.52 0.00 0.00 2.13 3.49 1.50 -1.00 0.00 0.00 -4.93 317.90 +497.00 247615.80 11.22 1.70 2.10 26.72 -10.47 -1.43 0.00 0.00 1.51 2.69 1.30 -1.00 0.00 0.00 -5.92 89.40 +498.00 247269.90 22.50 2.90 2.10 81.75 -10.14 -0.46 0.00 0.00 1.96 3.97 2.00 -1.00 0.00 0.00 -9.18 1023.50 +499.00 247937.60 22.63 1.70 2.10 62.90 -10.16 1.18 0.00 0.00 1.25 3.21 1.30 -1.00 0.00 0.00 -14.46 411.20 +500.00 248229.90 18.27 3.10 2.10 69.35 -9.50 -1.20 0.00 0.00 2.46 4.24 2.30 -1.00 0.00 0.00 -5.95 703.50 +501.00 248591.80 19.17 2.50 2.10 55.12 -10.08 -0.19 0.00 0.00 1.77 3.40 1.40 -1.00 0.00 0.00 -8.69 1065.40 +502.00 248541.10 26.31 2.00 6.20 137.89 -7.91 -0.01 0.00 0.00 1.73 5.31 1.50 -1.00 0.00 0.00 -12.18 67.50 +503.00 250420.70 18.59 1.50 2.10 47.32 -6.63 0.24 0.00 0.00 1.32 2.72 0.80 -1.00 0.00 0.00 -11.23 334.30 +504.00 251066.10 18.03 2.00 2.10 56.90 -8.10 1.07 0.00 0.00 1.70 3.53 1.60 -1.00 0.00 0.00 -8.48 979.70 +505.00 255517.10 19.78 1.50 2.10 50.10 -9.70 -0.99 0.00 0.00 1.28 2.81 0.90 -1.00 0.00 0.00 -12.37 310.70 +506.00 255390.70 16.18 2.30 2.10 50.40 -9.55 -0.46 0.00 0.00 1.47 3.70 1.80 -1.00 0.00 0.00 -8.83 184.30 +507.00 255332.10 19.41 1.90 2.10 54.07 -11.25 -1.04 0.00 0.00 1.68 3.30 1.30 -1.00 0.00 0.00 -9.25 125.70 +508.00 255570.40 13.72 1.40 2.10 34.04 -9.48 -1.52 0.00 0.00 0.98 2.70 0.70 -1.00 0.00 0.00 -11.20 364.00 +509.00 255635.40 20.01 2.60 2.10 65.19 -11.85 -0.82 0.00 0.00 1.83 3.88 1.90 -1.00 0.00 0.00 -8.72 429.00 +510.00 256200.80 10.19 3.00 2.10 33.53 -9.11 -2.29 0.00 0.00 2.63 4.05 2.10 -1.00 0.00 0.00 -3.10 994.40 +511.00 256041.30 20.66 2.10 2.10 59.49 -9.86 0.75 0.00 0.00 1.39 3.36 1.40 -1.00 0.00 0.00 -11.87 834.90 +512.00 255154.20 26.53 4.30 2.10 98.04 -9.19 -1.69 0.00 0.00 3.98 3.14 1.20 -1.00 0.00 0.00 -5.33 1227.80 +513.00 254643.40 13.88 1.60 2.10 33.79 -9.57 -1.14 0.00 0.00 1.31 3.04 1.10 -1.00 0.00 0.00 -8.49 717.00 +514.00 252484.70 12.69 6.50 2.50 56.06 -8.65 -0.33 0.00 0.00 4.58 3.79 2.20 -1.00 0.00 0.00 -2.22 171.10 +515.00 251773.50 20.04 2.30 2.10 61.70 -9.04 -0.40 0.00 0.00 1.93 3.76 1.80 -1.00 0.00 0.00 -8.33 407.10 +516.00 251653.60 18.94 2.70 2.10 52.65 -8.21 0.59 0.00 0.00 1.50 3.08 1.10 -1.00 0.00 0.00 -10.10 287.20 +517.00 252621.60 19.78 2.00 6.00 95.87 -7.55 -0.85 0.00 0.00 1.65 4.41 1.30 -1.00 0.00 0.00 -9.59 308.00 +518.00 253307.80 10.74 1.00 2.10 20.12 -8.12 0.55 0.00 0.00 0.79 2.05 0.40 -1.00 0.00 0.00 -10.86 661.40 +519.00 254283.90 23.65 2.40 2.10 79.82 -8.40 -1.25 0.00 0.00 1.47 3.76 1.80 -1.00 0.00 0.00 -12.88 357.50 +520.00 253785.40 17.62 5.30 2.10 59.29 -8.81 0.05 0.00 0.00 2.47 3.63 1.70 -1.00 0.00 0.00 -5.70 1139.00 +521.00 269659.00 10.87 2.20 2.10 30.20 -9.74 0.28 0.00 0.00 2.01 3.23 1.90 -1.00 0.00 0.00 -4.33 372.60 +522.00 269848.20 11.52 2.40 2.10 33.25 -8.95 -0.79 0.00 0.00 2.28 3.67 1.70 -1.00 0.00 0.00 -4.05 561.80 +523.00 286049.40 17.93 2.80 2.10 59.41 -8.22 0.64 0.00 0.00 1.99 3.63 1.70 -1.00 0.00 0.00 -7.23 123.00 +524.00 285814.70 24.13 2.60 2.10 73.98 -8.94 -0.24 0.00 0.00 1.81 3.45 1.50 -1.00 0.00 0.00 -10.64 1168.30 +525.00 285659.00 20.04 4.60 2.10 86.73 -8.05 -0.01 0.00 0.00 2.62 4.81 2.90 -1.00 0.00 0.00 -6.12 1012.60 +526.00 286235.60 17.36 2.90 2.10 66.30 -8.83 0.00 0.00 0.00 1.67 4.37 2.40 -1.00 0.00 0.00 -8.33 309.20 +527.00 286541.00 10.25 2.90 2.10 33.82 -7.87 -0.21 0.00 0.00 2.40 4.15 2.20 -1.00 0.00 0.00 -3.42 614.60 +528.00 287449.00 24.84 2.80 2.10 81.29 -9.01 -1.25 0.00 0.00 2.12 3.73 1.80 -1.00 0.00 0.00 -9.38 242.60 +529.00 286874.00 22.31 2.40 2.10 76.96 -7.64 0.72 0.00 0.00 1.23 3.84 1.90 -1.00 0.00 0.00 -14.45 947.60 +530.00 285549.00 14.71 4.00 2.10 52.76 -9.22 -0.65 0.00 0.00 2.43 4.05 2.10 -1.00 0.00 0.00 -4.84 902.60 +531.00 285298.10 18.70 1.60 2.10 49.38 -9.23 -0.86 0.00 0.00 1.31 2.98 1.00 -1.00 0.00 0.00 -11.39 651.70 +532.00 282744.00 10.06 2.50 2.10 31.73 -7.61 0.79 0.00 0.00 2.33 3.90 1.90 -1.00 0.00 0.00 -3.45 657.60 +533.00 282469.20 13.38 2.60 2.10 44.14 -10.02 -1.16 0.00 0.00 1.81 3.91 2.00 -1.00 0.00 0.00 -5.91 382.80 +534.00 282426.80 25.17 2.60 2.10 86.63 -8.67 -0.13 0.00 0.00 2.28 3.74 1.80 -1.00 0.00 0.00 -8.82 340.40 +535.00 283020.10 21.01 1.40 2.10 52.69 -9.76 -1.34 0.00 0.00 1.12 2.65 0.70 -1.00 0.00 0.00 -15.03 933.70 +536.00 283927.70 15.27 2.30 2.10 50.53 -8.25 0.31 0.00 0.00 1.89 3.71 1.80 -1.00 0.00 0.00 -6.45 561.30 +537.00 284765.80 14.99 4.00 2.10 69.05 -8.80 -1.97 0.00 0.00 3.53 5.24 3.30 -1.00 0.00 0.00 -3.39 119.40 +538.00 284476.10 16.29 2.30 2.10 53.63 -8.39 -1.54 0.00 0.00 1.33 3.60 1.60 -1.00 0.00 0.00 -9.81 1109.70 +539.00 287826.80 13.10 3.40 2.10 44.50 -10.35 -0.40 0.00 0.00 2.94 3.69 2.40 -1.00 0.00 0.00 -3.56 620.40 +540.00 287947.50 15.95 1.60 2.10 42.22 -8.08 2.37 0.00 0.00 1.31 2.76 0.80 -1.00 0.00 0.00 -9.71 741.10 +541.00 294854.70 13.01 2.20 2.10 39.88 -11.68 -0.92 0.00 0.00 1.89 3.44 1.50 -1.00 0.00 0.00 -5.49 1248.30 +542.00 294165.00 11.95 2.80 2.10 40.55 -11.56 0.64 0.00 0.00 2.68 3.85 1.90 -1.00 0.00 0.00 -3.56 558.60 +543.00 294080.30 16.71 1.70 2.10 45.66 -10.44 0.49 0.00 0.00 1.33 3.01 1.10 -1.00 0.00 0.00 -10.07 473.90 +544.00 294946.50 21.82 1.90 2.10 61.96 -9.99 -0.39 0.00 0.00 1.41 3.28 1.30 -1.00 0.00 0.00 -12.36 60.10 +545.00 296694.40 18.38 3.10 2.10 60.60 -8.51 0.52 0.00 0.00 2.82 3.78 2.00 -1.00 0.00 0.00 -5.22 528.00 +546.00 297254.80 28.01 3.80 2.10 113.67 -9.96 0.78 0.00 0.00 2.81 4.72 2.80 -1.00 0.00 0.00 -7.98 1088.40 +547.00 297037.80 13.57 2.40 2.10 41.25 -9.64 -1.46 0.00 0.00 1.69 3.50 1.60 -1.00 0.00 0.00 -6.43 871.40 +548.00 293831.40 14.30 2.00 2.10 35.20 -9.45 1.33 0.00 0.00 1.64 3.04 1.10 -1.00 0.00 0.00 -6.96 225.00 +549.00 292609.70 28.93 2.60 2.10 94.50 -10.24 0.53 0.00 0.00 1.44 3.76 1.80 -1.00 0.00 0.00 -16.12 283.30 +550.00 289266.10 18.95 2.00 2.10 59.55 -9.53 0.56 0.00 0.00 1.04 3.42 1.50 -1.00 0.00 0.00 -14.59 779.70 +551.00 289245.90 12.26 3.90 2.10 45.33 -8.44 1.76 0.00 0.00 3.66 4.42 2.50 -1.00 0.00 0.00 -2.68 759.50 +552.00 288103.90 10.26 1.30 2.10 24.51 -9.89 0.50 0.00 0.00 1.04 2.79 0.80 -1.00 0.00 0.00 -7.87 897.50 +553.00 290124.90 16.77 3.50 2.10 68.44 -10.38 1.40 0.00 0.00 2.95 4.74 2.80 -1.00 0.00 0.00 -4.54 358.50 +554.00 290535.80 22.38 2.70 2.10 78.58 -9.03 -1.64 0.00 0.00 1.48 4.01 2.10 -1.00 0.00 0.00 -12.10 769.40 +555.00 292510.90 13.93 1.50 2.10 35.46 -10.00 2.12 0.00 0.00 1.38 2.93 1.00 -1.00 0.00 0.00 -8.08 184.50 +556.00 291943.50 15.41 2.50 2.10 49.92 -11.17 -0.35 0.00 0.00 1.34 3.80 1.90 -1.00 0.00 0.00 -9.20 897.10 +557.00 282292.80 12.13 2.50 2.10 40.43 -9.57 -0.30 0.00 0.00 1.65 3.87 1.90 -1.00 0.00 0.00 -5.87 206.40 +558.00 282235.90 29.26 2.20 2.10 94.49 -8.23 -0.98 0.00 0.00 1.26 3.53 1.60 -1.00 0.00 0.00 -18.57 149.50 +559.00 274580.50 16.03 2.30 2.10 48.42 -9.63 -0.01 0.00 0.00 2.01 3.44 1.50 -1.00 0.00 0.00 -6.39 174.10 +560.00 273939.60 13.84 3.50 2.10 54.95 -7.79 0.15 0.00 0.00 3.27 4.78 2.80 -1.00 0.00 0.00 -3.39 813.20 +561.00 273194.00 14.20 3.70 2.10 60.53 -9.35 -1.33 0.00 0.00 3.48 4.97 3.00 -1.00 0.00 0.00 -3.27 67.60 +562.00 275282.80 15.99 2.30 2.10 49.74 -7.59 1.75 0.00 0.00 1.41 3.35 1.40 -1.00 0.00 0.00 -9.05 876.40 +563.00 276194.00 12.49 1.40 2.10 27.16 -10.04 -1.04 0.00 0.00 1.05 2.39 0.80 -1.00 0.00 0.00 -9.53 507.60 +564.00 276386.70 11.84 3.10 2.10 39.99 -9.00 0.71 0.00 0.00 2.57 4.04 2.10 -1.00 0.00 0.00 -3.69 700.30 +565.00 276273.30 19.36 2.90 2.10 68.61 -9.72 1.18 0.00 0.00 2.35 4.03 2.10 -1.00 0.00 0.00 -6.60 586.90 +566.00 273099.00 12.75 2.70 2.10 41.51 -9.22 0.68 0.00 0.00 2.20 4.05 2.10 -1.00 0.00 0.00 -4.64 1252.60 +567.00 272875.30 18.30 1.70 2.10 45.09 -8.85 -1.40 0.00 0.00 1.52 2.88 0.90 -1.00 0.00 0.00 -9.66 1028.90 +568.00 270697.20 13.84 1.90 2.10 37.76 -8.26 -2.57 0.00 0.00 1.53 3.32 1.40 -1.00 0.00 0.00 -7.26 130.80 +569.00 270548.00 17.33 2.20 2.10 57.28 -8.63 -0.47 0.00 0.00 1.67 3.62 1.70 -1.00 0.00 0.00 -8.31 1261.60 +570.00 270153.50 19.50 3.20 2.10 65.74 -7.82 0.64 0.00 0.00 2.36 3.95 2.00 -1.00 0.00 0.00 -6.61 867.10 +571.00 271112.90 22.16 2.70 2.10 72.88 -9.31 1.58 0.00 0.00 2.26 3.76 1.80 -1.00 0.00 0.00 -7.84 546.50 +572.00 271840.10 20.82 2.30 2.10 66.66 -7.08 -0.10 0.00 0.00 1.56 3.46 1.50 -1.00 0.00 0.00 -10.67 1273.70 +573.00 272030.30 10.50 4.00 2.10 46.18 -9.05 -1.30 0.00 0.00 3.81 4.87 3.40 -1.00 0.00 0.00 -2.21 183.90 +574.00 271921.70 16.46 4.20 2.10 65.72 -8.10 0.23 0.00 0.00 3.45 4.33 3.10 -1.00 0.00 0.00 -3.81 75.30 +575.00 276902.40 25.56 3.60 2.10 97.39 -7.85 2.55 0.00 0.00 2.91 4.60 2.70 -1.00 0.00 0.00 -7.03 1216.00 +576.00 277090.00 11.69 1.80 2.10 26.53 -8.28 -1.00 0.00 0.00 1.59 2.66 0.70 -1.00 0.00 0.00 -5.89 123.60 +577.00 279085.10 17.01 1.70 2.10 48.84 -9.24 -2.30 0.00 0.00 1.34 3.16 1.20 -1.00 0.00 0.00 -10.18 838.70 +578.00 279008.60 10.23 1.50 2.10 23.73 -9.68 1.20 0.00 0.00 1.34 2.81 0.90 -1.00 0.00 0.00 -6.13 762.20 +579.00 278986.40 10.61 3.80 2.10 41.09 -8.44 0.11 0.00 0.00 3.37 2.95 2.80 -1.00 0.00 0.00 -2.52 740.00 +580.00 280031.50 14.31 3.10 2.10 49.47 -8.27 2.43 0.00 0.00 2.54 3.89 2.20 -1.00 0.00 0.00 -4.50 505.10 +581.00 280127.70 17.30 4.00 2.10 72.13 -7.25 0.92 0.00 0.00 3.58 4.75 3.30 -1.00 0.00 0.00 -3.87 601.30 +582.00 281353.70 14.63 1.40 2.10 35.03 -9.86 -0.72 0.00 0.00 1.23 2.62 0.70 -1.00 0.00 0.00 -9.55 547.30 +583.00 280577.10 10.43 2.40 2.10 33.14 -9.36 0.05 0.00 0.00 2.06 3.68 1.70 -1.00 0.00 0.00 -4.05 1050.70 +584.00 278766.10 27.75 2.60 2.10 89.21 -8.77 -2.26 0.00 0.00 1.83 3.84 1.90 -1.00 0.00 0.00 -12.16 519.70 +585.00 278459.50 20.55 2.00 2.10 64.63 -8.24 1.15 0.00 0.00 1.24 3.49 1.50 -1.00 0.00 0.00 -13.26 213.10 +586.00 277537.10 21.08 2.50 2.10 60.70 -9.60 -0.38 0.00 0.00 1.90 3.48 1.50 -1.00 0.00 0.00 -8.87 570.70 +587.00 277246.30 12.08 3.30 2.10 44.80 -8.69 0.84 0.00 0.00 3.14 3.78 2.50 -1.00 0.00 0.00 -3.08 279.90 +588.00 277734.00 15.85 3.20 2.10 64.69 -9.84 -1.12 0.00 0.00 2.92 4.70 2.80 -1.00 0.00 0.00 -4.34 767.60 +589.00 277785.00 14.32 2.40 2.10 43.77 -10.17 1.92 0.00 0.00 2.07 3.54 1.60 -1.00 0.00 0.00 -5.53 818.60 +590.00 278230.40 10.87 2.30 2.10 29.29 -9.42 0.87 0.00 0.00 2.14 2.79 1.70 -1.00 0.00 0.00 -4.06 1264.00 +591.00 278112.50 11.43 2.20 2.10 33.53 -9.59 -1.69 0.00 0.00 1.84 3.11 1.40 -1.00 0.00 0.00 -4.96 1146.10 +592.00 247197.30 17.98 1.70 2.10 48.92 -8.87 0.43 0.00 0.00 1.31 3.07 1.10 -1.00 0.00 0.00 -10.95 950.90 +593.00 156847.00 15.55 1.50 2.10 39.00 -7.28 0.02 0.00 0.00 1.24 2.83 0.90 -1.00 0.00 0.00 -10.04 200.60 +594.00 61377.40 13.51 2.00 2.10 35.46 -8.59 1.05 0.00 0.00 1.75 2.96 1.30 -1.00 0.00 0.00 -6.19 2497.40 +595.00 61348.80 11.40 0.70 2.10 20.33 -8.64 -1.28 0.00 0.00 0.43 1.99 0.50 -1.00 0.00 0.00 -21.17 2468.80 +596.00 61119.70 17.05 2.40 2.10 54.95 -7.16 -0.20 0.00 0.00 2.08 3.67 1.70 -1.00 0.00 0.00 -6.57 2239.70 +597.00 61618.60 15.39 2.00 2.10 38.86 -7.69 -1.47 0.00 0.00 1.50 3.03 1.10 -1.00 0.00 0.00 -8.18 127.40 +598.00 61651.70 18.18 3.30 2.10 73.26 -8.71 -0.37 0.00 0.00 1.76 4.52 2.60 -1.00 0.00 0.00 -8.26 160.50 +599.00 61797.20 15.31 2.30 2.10 50.62 -8.26 -0.46 0.00 0.00 1.85 3.78 1.80 -1.00 0.00 0.00 -6.63 306.00 +600.00 61699.10 14.54 2.60 2.10 44.86 -9.78 -1.65 0.00 0.00 2.03 3.59 1.60 -1.00 0.00 0.00 -5.74 207.90 +601.00 60741.00 11.43 3.30 2.10 36.60 -7.16 -0.11 0.00 0.00 2.81 3.20 1.20 -1.00 0.00 0.00 -3.26 1861.00 +602.00 60514.60 21.76 2.40 2.10 66.28 -6.92 -0.12 0.00 0.00 1.71 3.50 1.60 -1.00 0.00 0.00 -10.19 1634.60 +603.00 58494.50 26.16 1.70 2.10 68.66 -6.19 -0.27 0.00 0.00 1.08 2.76 0.80 -1.00 0.00 0.00 -19.42 2174.50 +604.00 58212.20 12.15 1.80 2.10 33.03 -8.02 0.21 0.00 0.00 1.54 3.00 1.30 -1.00 0.00 0.00 -6.29 1892.20 +605.00 58047.60 12.67 3.20 2.10 44.92 -6.62 1.23 0.00 0.00 2.98 4.17 2.20 -1.00 0.00 0.00 -3.40 1727.60 +606.00 58576.70 17.13 1.70 2.10 43.85 -6.37 -1.29 0.00 0.00 1.53 3.01 1.10 -1.00 0.00 0.00 -8.98 2256.70 +607.00 58924.80 12.85 1.80 2.10 36.63 -6.58 1.18 0.00 0.00 1.46 3.30 1.40 -1.00 0.00 0.00 -7.02 44.80 +608.00 59462.20 14.19 2.60 2.10 44.86 -7.62 0.17 0.00 0.00 2.34 3.73 1.80 -1.00 0.00 0.00 -4.86 582.20 +609.00 59145.30 19.72 2.20 2.10 62.01 -6.43 0.88 0.00 0.00 1.60 3.35 1.40 -1.00 0.00 0.00 -9.88 265.30 +610.00 61798.50 15.11 3.60 2.10 64.59 -8.50 2.21 0.00 0.00 3.48 5.07 3.10 -1.00 0.00 0.00 -3.47 307.30 +611.00 61879.50 14.61 1.60 2.10 34.56 -9.21 0.91 0.00 0.00 1.38 2.85 0.90 -1.00 0.00 0.00 -8.50 388.30 +612.00 65507.00 18.20 2.00 2.10 55.11 -6.31 0.61 0.00 0.00 1.32 3.41 1.50 -1.00 0.00 0.00 -11.06 1455.80 +613.00 65209.90 14.41 2.20 2.10 40.79 -7.12 0.27 0.00 0.00 1.77 2.91 1.50 -1.00 0.00 0.00 -6.53 1158.70 +614.00 64719.30 14.60 3.20 2.10 53.65 -7.85 -0.29 0.00 0.00 3.01 4.07 2.80 -1.00 0.00 0.00 -3.88 668.10 +615.00 65523.90 24.38 2.30 2.10 76.18 -7.61 0.08 0.00 0.00 1.80 3.60 1.70 -1.00 0.00 0.00 -10.83 1472.70 +616.00 65635.00 14.00 2.30 2.10 40.47 -5.77 1.41 0.00 0.00 1.74 3.43 1.50 -1.00 0.00 0.00 -6.44 1583.80 +617.00 66053.20 13.82 2.80 2.10 45.46 -6.61 1.14 0.00 0.00 2.11 3.96 2.00 -1.00 0.00 0.00 -5.24 2002.00 +618.00 65676.50 13.66 2.80 2.10 43.95 -6.29 -0.57 0.00 0.00 2.07 3.79 1.80 -1.00 0.00 0.00 -5.29 1625.30 +619.00 64206.90 18.04 1.70 2.10 46.13 -6.65 0.99 0.00 0.00 1.36 3.15 1.20 -1.00 0.00 0.00 -10.59 155.70 +620.00 63969.20 19.04 2.20 2.10 53.83 -7.04 0.62 0.00 0.00 1.94 3.51 1.60 -1.00 0.00 0.00 -7.85 2478.00 +621.00 62921.80 12.34 3.40 2.10 47.12 -7.51 -1.49 0.00 0.00 2.90 4.58 2.70 -1.00 0.00 0.00 -3.40 1430.60 +622.00 62522.80 13.59 1.90 2.10 36.90 -9.49 1.57 0.00 0.00 1.55 3.16 1.30 -1.00 0.00 0.00 -7.00 1031.60 +623.00 62336.80 13.52 2.30 2.10 37.54 -8.62 0.02 0.00 0.00 1.94 2.84 1.60 -1.00 0.00 0.00 -5.58 845.60 +624.00 63038.60 10.37 3.20 2.10 32.86 -9.02 -0.29 0.00 0.00 2.99 3.02 1.70 -1.00 0.00 0.00 -2.78 1547.40 +625.00 63171.70 14.85 2.10 2.10 43.01 -8.09 -1.34 0.00 0.00 1.72 3.24 1.40 -1.00 0.00 0.00 -6.90 1680.50 +626.00 63495.30 23.65 3.00 2.10 92.77 -7.18 0.37 0.00 0.00 2.29 4.35 2.40 -1.00 0.00 0.00 -8.26 2004.10 +627.00 63359.30 12.85 2.10 2.10 36.15 -6.37 2.23 0.00 0.00 1.23 3.33 1.40 -1.00 0.00 0.00 -8.38 1868.10 +628.00 57968.20 21.12 2.10 2.10 60.13 -9.53 0.43 0.00 0.00 1.21 3.27 1.30 -1.00 0.00 0.00 -13.94 1648.20 +629.00 57952.10 13.47 2.50 2.10 44.98 -7.66 -0.96 0.00 0.00 2.17 4.03 2.10 -1.00 0.00 0.00 -4.97 1632.10 +630.00 49726.00 16.26 4.00 2.10 63.09 -8.30 0.93 0.00 0.00 3.48 3.76 3.10 -1.00 0.00 0.00 -3.73 1086.00 +631.00 49697.80 15.63 2.60 2.10 51.91 -8.80 2.40 0.00 0.00 1.89 3.81 1.90 -1.00 0.00 0.00 -6.63 1057.80 +632.00 49513.30 17.47 1.30 2.10 45.40 -10.00 0.97 0.00 0.00 0.80 2.70 0.70 -1.00 0.00 0.00 -17.56 873.30 +633.00 50200.80 16.15 1.40 2.10 41.05 -7.98 2.00 0.00 0.00 1.06 2.74 0.80 -1.00 0.00 0.00 -12.20 1560.80 +634.00 50492.70 14.42 4.60 2.10 56.43 -8.35 -0.92 0.00 0.00 4.39 3.43 1.80 -1.00 0.00 0.00 -2.63 1852.70 +635.00 50912.90 14.86 3.70 2.10 56.55 -7.39 0.25 0.00 0.00 3.45 4.74 3.00 -1.00 0.00 0.00 -3.45 2272.90 +636.00 50745.80 10.98 2.60 2.10 36.34 -7.71 -1.30 0.00 0.00 1.76 3.74 1.80 -1.00 0.00 0.00 -4.99 2105.80 +637.00 49468.80 10.23 1.80 2.10 24.46 -7.90 -1.06 0.00 0.00 1.04 2.56 1.10 -1.00 0.00 0.00 -7.90 828.80 +638.00 49314.70 12.37 2.00 2.10 28.81 -8.24 -1.77 0.00 0.00 1.48 2.73 1.10 -1.00 0.00 0.00 -6.67 674.70 +639.00 48123.60 11.77 1.90 2.10 31.48 -7.18 -0.48 0.00 0.00 1.45 3.07 1.10 -1.00 0.00 0.00 -6.51 2043.60 +640.00 48038.80 16.37 2.10 2.10 44.48 -7.15 1.69 0.00 0.00 1.73 3.31 1.40 -1.00 0.00 0.00 -7.57 1958.80 +641.00 47717.80 10.66 1.70 2.10 24.84 -7.54 -1.01 0.00 0.00 1.46 2.55 1.00 -1.00 0.00 0.00 -5.85 1637.80 +642.00 48819.20 11.27 2.10 2.10 29.73 -8.84 0.41 0.00 0.00 1.88 3.42 1.70 -1.00 0.00 0.00 -4.80 179.20 +643.00 48882.80 16.42 1.60 2.10 41.63 -7.76 0.66 0.00 0.00 1.45 2.92 1.00 -1.00 0.00 0.00 -9.07 242.80 +644.00 49036.00 13.50 1.80 2.10 35.44 -7.15 -1.02 0.00 0.00 1.61 3.36 1.40 -1.00 0.00 0.00 -6.71 396.00 +645.00 49009.30 10.00 2.00 2.10 26.24 -6.78 -1.00 0.00 0.00 1.54 3.00 1.00 -1.00 0.00 0.00 -5.19 369.30 +646.00 51450.30 29.23 2.10 2.10 80.49 -6.05 1.56 0.00 0.00 1.45 3.03 1.10 -1.00 0.00 0.00 -16.09 250.30 +647.00 51636.40 13.67 1.60 2.10 33.19 -8.14 -1.22 0.00 0.00 1.29 3.13 1.20 -1.00 0.00 0.00 -8.47 436.40 +648.00 55590.40 16.00 3.10 2.10 54.47 -8.34 0.52 0.00 0.00 2.73 4.01 2.60 -1.00 0.00 0.00 -4.69 1830.40 +649.00 55126.80 28.10 2.50 2.10 96.58 -9.31 1.52 0.00 0.00 1.87 3.81 1.90 -1.00 0.00 0.00 -12.05 1366.80 +650.00 54682.90 16.78 2.00 2.10 47.40 -6.17 -2.01 0.00 0.00 1.71 3.16 1.20 -1.00 0.00 0.00 -7.84 922.90 +651.00 56014.80 21.31 2.70 2.10 72.56 -7.33 1.13 0.00 0.00 2.36 3.83 1.90 -1.00 0.00 0.00 -7.24 2254.80 +652.00 56997.60 13.95 2.60 2.10 39.27 -7.55 1.26 0.00 0.00 2.04 3.54 1.60 -1.00 0.00 0.00 -5.46 677.60 +653.00 57429.00 11.20 2.60 2.10 37.67 -7.96 -0.41 0.00 0.00 2.36 4.12 2.20 -1.00 0.00 0.00 -3.79 1109.00 +654.00 57350.20 16.78 3.30 2.10 50.75 -6.60 0.18 0.00 0.00 1.53 3.22 1.30 -1.00 0.00 0.00 -8.79 1030.20 +655.00 54162.90 18.07 3.10 2.10 63.13 -7.65 -0.91 0.00 0.00 2.25 4.01 2.10 -1.00 0.00 0.00 -6.42 402.90 +656.00 53889.40 10.92 4.20 2.10 45.16 -8.15 0.12 0.00 0.00 3.96 1.66 1.30 -1.00 0.00 0.00 -2.21 129.40 +657.00 52128.90 11.23 2.10 2.10 34.61 -6.65 -0.68 0.00 0.00 1.70 3.42 1.50 -1.00 0.00 0.00 -5.28 928.90 +658.00 51925.70 14.85 2.30 2.10 46.72 -7.39 -0.96 0.00 0.00 1.76 3.48 1.90 -1.00 0.00 0.00 -6.77 725.70 +659.00 51679.30 13.80 2.60 2.10 44.27 -7.69 1.83 0.00 0.00 2.24 3.69 2.00 -1.00 0.00 0.00 -4.92 69.70 +660.00 52363.60 16.90 1.60 2.10 41.05 -12.90 -1.58 0.00 0.00 1.34 3.15 1.20 -1.00 0.00 0.00 -10.06 1163.60 +661.00 52500.70 14.75 1.80 2.10 37.46 -8.01 1.20 0.00 0.00 1.58 3.34 1.40 -1.00 0.00 0.00 -7.46 1300.70 +662.00 53507.40 14.18 1.80 2.10 37.45 -6.40 -0.35 0.00 0.00 1.61 2.98 1.00 -1.00 0.00 0.00 -7.03 2307.40 +663.00 52985.90 18.80 1.90 2.10 51.45 -7.37 -0.51 0.00 0.00 1.63 3.11 1.20 -1.00 0.00 0.00 -9.20 1785.90 +664.00 66159.30 12.43 1.60 2.10 30.15 -6.78 2.12 0.00 0.00 1.37 2.89 0.90 -1.00 0.00 0.00 -7.23 2108.10 +665.00 66246.60 11.77 3.00 2.10 34.16 -7.29 0.78 0.00 0.00 1.82 3.16 1.60 -1.00 0.00 0.00 -5.19 2195.40 +666.00 84181.60 12.50 2.20 2.10 35.48 -8.23 -1.30 0.00 0.00 1.75 3.38 1.40 -1.00 0.00 0.00 -5.70 930.40 +667.00 83201.30 10.57 2.60 2.10 33.57 -7.25 -0.49 0.00 0.00 1.98 3.51 1.60 -1.00 0.00 0.00 -4.26 1230.10 +668.00 82670.70 15.17 1.80 2.10 42.91 -9.54 0.29 0.00 0.00 1.59 3.16 1.20 -1.00 0.00 0.00 -7.64 699.50 +669.00 84369.40 19.71 2.30 2.10 64.20 -6.58 -0.02 0.00 0.00 2.10 3.64 1.70 -1.00 0.00 0.00 -7.52 1118.20 +670.00 84983.40 25.23 2.00 2.10 73.09 -6.25 1.82 0.00 0.00 1.30 3.26 1.30 -1.00 0.00 0.00 -15.57 452.20 +671.00 85939.70 11.41 2.50 2.10 36.55 -6.79 2.12 0.00 0.00 2.30 3.10 1.80 -1.00 0.00 0.00 -3.97 128.50 +672.00 85006.40 16.87 2.00 2.10 47.78 -8.13 -0.17 0.00 0.00 1.54 3.33 1.40 -1.00 0.00 0.00 -8.75 475.20 +673.00 82607.00 11.80 2.00 2.10 31.43 -8.94 3.06 0.00 0.00 1.68 3.21 1.30 -1.00 0.00 0.00 -5.63 635.80 +674.00 82530.70 18.61 2.10 2.10 57.59 -8.88 0.28 0.00 0.00 0.98 3.65 1.70 -1.00 0.00 0.00 -15.16 559.50 +675.00 79807.40 12.30 1.90 2.10 31.17 -6.57 1.18 0.00 0.00 1.12 2.75 0.80 -1.00 0.00 0.00 -8.76 396.20 +676.00 79717.90 13.78 2.20 2.10 40.86 -7.86 1.90 0.00 0.00 1.96 3.69 1.70 -1.00 0.00 0.00 -5.63 306.70 +677.00 79435.20 16.74 2.80 2.10 58.09 -8.75 -0.54 0.00 0.00 1.81 3.98 2.00 -1.00 0.00 0.00 -7.38 24.00 +678.00 81031.60 21.65 2.70 2.10 77.20 -7.37 -0.95 0.00 0.00 2.05 4.05 2.10 -1.00 0.00 0.00 -8.46 340.40 +679.00 81185.10 14.62 3.60 2.10 57.06 -7.00 0.21 0.00 0.00 3.30 4.41 2.80 -1.00 0.00 0.00 -3.55 493.90 +680.00 81611.40 17.38 2.20 2.10 50.17 -8.43 -0.33 0.00 0.00 1.74 3.57 1.60 -1.00 0.00 0.00 -8.01 920.20 +681.00 81262.10 12.67 2.50 2.10 40.11 -8.17 1.18 0.00 0.00 2.22 3.83 1.90 -1.00 0.00 0.00 -4.56 570.90 +682.00 86085.10 18.36 1.90 2.10 49.13 -7.55 0.43 0.00 0.00 1.39 3.25 1.30 -1.00 0.00 0.00 -10.54 273.90 +683.00 86113.70 21.53 1.70 2.10 59.82 -12.02 -1.97 0.00 0.00 1.51 3.36 1.40 -1.00 0.00 0.00 -11.43 302.50 +684.00 89985.60 12.04 2.00 2.10 32.58 -7.69 -1.35 0.00 0.00 1.65 3.48 1.50 -1.00 0.00 0.00 -5.84 334.40 +685.00 89064.20 13.78 2.30 2.10 38.24 -9.89 1.00 0.00 0.00 2.03 3.37 1.60 -1.00 0.00 0.00 -5.43 693.00 +686.00 89047.70 10.26 1.40 2.10 22.49 -8.32 0.23 0.00 0.00 1.14 2.39 0.40 -1.00 0.00 0.00 -7.23 676.50 +687.00 90280.00 11.26 2.10 2.10 28.81 -6.83 1.65 0.00 0.00 1.93 1.77 1.20 -1.00 0.00 0.00 -4.66 628.80 +688.00 90354.80 12.40 2.30 2.10 37.40 -7.82 1.46 0.00 0.00 1.99 3.58 1.60 -1.00 0.00 0.00 -4.98 703.60 +689.00 91220.20 13.71 2.40 2.10 38.74 -8.71 1.18 0.00 0.00 2.03 2.69 1.30 -1.00 0.00 0.00 -5.40 289.00 +690.00 90619.00 11.57 2.60 2.10 32.44 -6.53 0.67 0.00 0.00 2.24 3.52 1.70 -1.00 0.00 0.00 -4.14 967.80 +691.00 88760.80 12.84 1.40 4.40 50.49 -7.29 -0.55 0.00 0.00 1.16 4.69 0.70 -1.00 0.00 0.00 -8.86 338.40 +692.00 88336.40 24.00 3.10 2.10 85.29 -6.32 0.95 0.00 0.00 2.36 4.08 2.10 -1.00 0.00 0.00 -8.14 1245.20 +693.00 86778.50 12.13 1.70 2.10 31.52 -9.60 0.40 0.00 0.00 1.53 3.36 1.40 -1.00 0.00 0.00 -6.35 967.30 +694.00 86486.70 21.00 3.40 2.10 86.50 -6.66 2.06 0.00 0.00 2.44 4.58 2.60 -1.00 0.00 0.00 -6.88 675.50 +695.00 86145.60 22.96 2.10 2.10 69.46 -9.22 0.82 0.00 0.00 1.82 3.40 1.40 -1.00 0.00 0.00 -10.07 334.40 +696.00 86905.90 11.28 2.40 2.10 34.86 -7.99 -1.12 0.00 0.00 2.08 3.27 1.90 -1.00 0.00 0.00 -4.34 1094.70 +697.00 87166.30 19.04 2.90 2.10 68.66 -7.24 -0.01 0.00 0.00 2.51 4.16 2.20 -1.00 0.00 0.00 -6.06 75.10 +698.00 88185.90 11.94 2.70 2.10 42.97 -6.65 -0.56 0.00 0.00 2.10 4.19 2.20 -1.00 0.00 0.00 -4.55 1094.70 +699.00 155792.40 20.91 2.50 2.10 69.10 -9.10 -1.31 0.00 0.00 1.84 3.71 1.80 -1.00 0.00 0.00 -9.07 426.00 +700.00 79139.50 13.48 3.70 2.10 52.08 -7.12 -0.55 0.00 0.00 3.12 4.48 2.80 -1.00 0.00 0.00 -3.46 1008.30 +701.00 78333.70 19.48 1.30 2.10 48.04 -7.12 -1.53 0.00 0.00 1.15 2.80 0.80 -1.00 0.00 0.00 -13.55 202.50 +702.00 69679.80 14.38 2.10 2.10 42.40 -6.72 -0.18 0.00 0.00 0.88 3.34 1.40 -1.00 0.00 0.00 -13.07 508.60 +703.00 69456.70 10.07 2.20 2.10 25.91 -7.48 0.15 0.00 0.00 1.88 2.44 1.60 -1.00 0.00 0.00 -4.29 285.50 +704.00 69430.50 15.17 1.80 2.10 37.94 -7.12 -0.46 0.00 0.00 1.47 3.11 1.20 -1.00 0.00 0.00 -8.25 259.30 +705.00 69765.00 15.12 2.20 2.10 45.04 -7.20 -1.14 0.00 0.00 1.97 3.47 1.50 -1.00 0.00 0.00 -6.15 593.80 +706.00 70093.40 13.52 2.90 2.10 47.29 -7.36 0.41 0.00 0.00 2.63 4.25 2.30 -1.00 0.00 0.00 -4.11 922.20 +707.00 70464.10 39.01 3.40 2.10 145.90 -7.67 1.17 0.00 0.00 1.72 3.98 2.00 -1.00 0.00 0.00 -18.11 12.90 +708.00 70463.80 39.11 3.10 2.10 137.43 -7.54 0.21 0.00 0.00 1.73 3.68 1.70 -1.00 0.00 0.00 -18.12 12.60 +709.00 69390.20 15.96 4.40 2.10 61.06 -6.41 1.38 0.00 0.00 2.90 4.62 2.70 -1.00 0.00 0.00 -4.40 219.00 +710.00 68708.10 10.92 2.80 2.10 32.88 -7.18 0.71 0.00 0.00 2.65 3.26 2.10 -1.00 0.00 0.00 -3.30 816.90 +711.00 67437.80 10.12 2.30 2.10 25.89 -7.09 -0.91 0.00 0.00 2.01 2.41 1.50 -1.00 0.00 0.00 -4.02 826.60 +712.00 66762.10 13.20 2.40 2.10 33.84 -7.71 -1.54 0.00 0.00 2.12 3.22 1.30 -1.00 0.00 0.00 -4.99 150.90 +713.00 66737.40 11.80 3.40 2.10 40.93 -7.86 0.02 0.00 0.00 3.08 4.04 2.70 -1.00 0.00 0.00 -3.06 126.20 +714.00 67507.80 11.76 3.00 2.10 43.57 -8.24 0.48 0.00 0.00 2.69 4.03 2.40 -1.00 0.00 0.00 -3.50 896.60 +715.00 67699.20 14.20 2.40 2.10 43.24 -7.39 -1.32 0.00 0.00 2.13 3.80 2.00 -1.00 0.00 0.00 -5.34 1088.00 +716.00 68561.70 10.02 1.90 2.10 24.67 -7.36 -0.74 0.00 0.00 1.68 3.09 1.10 -1.00 0.00 0.00 -4.78 670.50 +717.00 68438.80 11.69 1.40 2.10 29.24 -7.93 0.67 0.00 0.00 1.27 2.80 1.30 -1.00 0.00 0.00 -7.38 547.60 +718.00 71303.90 11.88 1.90 2.10 30.45 -7.10 -1.07 0.00 0.00 1.70 2.49 1.30 -1.00 0.00 0.00 -5.57 852.70 +719.00 71821.70 22.25 2.60 2.10 78.61 -6.80 -0.43 0.00 0.00 2.19 4.04 2.10 -1.00 0.00 0.00 -8.12 90.50 +720.00 77540.20 14.18 2.70 2.10 50.20 -5.87 -0.08 0.00 0.00 2.34 3.97 2.00 -1.00 0.00 0.00 -4.86 689.00 +721.00 77014.80 12.21 3.40 2.10 41.05 -6.99 1.21 0.00 0.00 3.13 3.70 1.90 -1.00 0.00 0.00 -3.12 163.60 +722.00 76947.50 24.84 1.60 2.10 67.82 -7.72 1.85 0.00 0.00 1.33 3.05 1.10 -1.00 0.00 0.00 -14.91 96.30 +723.00 77651.10 19.47 3.00 2.10 66.88 -6.96 0.68 0.00 0.00 2.31 4.04 2.10 -1.00 0.00 0.00 -6.75 799.90 +724.00 77669.60 13.87 2.90 2.10 44.49 -9.07 1.52 0.00 0.00 2.34 3.85 1.90 -1.00 0.00 0.00 -4.74 818.40 +725.00 77948.40 10.86 4.50 2.10 51.97 -8.17 0.93 0.00 0.00 4.04 2.29 0.40 -1.00 0.00 0.00 -2.15 1097.20 +726.00 77927.90 11.32 2.10 2.10 30.60 -6.26 2.48 0.00 0.00 1.93 2.96 1.40 -1.00 0.00 0.00 -4.69 1076.70 +727.00 76158.30 12.38 2.90 2.10 33.26 -7.40 1.65 0.00 0.00 1.70 3.25 1.30 -1.00 0.00 0.00 -5.81 587.10 +728.00 75939.90 14.21 5.40 2.10 70.87 -9.60 3.50 0.00 0.00 4.70 6.01 4.10 -1.00 0.00 0.00 -2.42 368.70 +729.00 73247.00 17.03 2.00 2.10 50.27 -6.30 -0.85 0.00 0.00 1.81 3.26 1.30 -1.00 0.00 0.00 -7.51 235.80 +730.00 72831.00 16.75 3.50 2.10 66.72 -6.20 0.28 0.00 0.00 2.91 4.58 2.60 -1.00 0.00 0.00 -4.61 1099.80 +731.00 71919.60 15.03 2.60 2.10 46.93 -8.83 -1.20 0.00 0.00 2.39 3.89 1.90 -1.00 0.00 0.00 -5.03 188.40 +732.00 74865.90 13.32 1.50 2.10 29.39 -7.03 0.47 0.00 0.00 1.20 2.40 0.40 -1.00 0.00 0.00 -8.86 574.70 +733.00 74884.60 21.69 2.60 2.10 69.01 -9.23 -0.07 0.00 0.00 1.80 3.87 1.90 -1.00 0.00 0.00 -9.65 593.40 +734.00 75874.10 16.02 1.90 2.10 44.57 -8.31 -1.05 0.00 0.00 1.60 3.43 1.50 -1.00 0.00 0.00 -7.99 302.90 +735.00 75466.20 12.78 3.50 2.10 47.88 -7.81 0.58 0.00 0.00 2.98 4.63 2.70 -1.00 0.00 0.00 -3.43 1175.00 +736.00 47141.30 13.39 4.20 2.10 60.65 -8.36 -0.11 0.00 0.00 4.06 5.13 3.70 -1.00 0.00 0.00 -2.64 1061.30 +737.00 47101.70 12.03 2.90 2.10 41.10 -6.62 -0.97 0.00 0.00 2.54 4.38 2.40 -1.00 0.00 0.00 -3.79 1021.70 +738.00 19867.70 11.48 1.60 2.10 26.09 -8.94 1.53 0.00 0.00 1.29 3.14 1.20 -1.00 0.00 0.00 -7.11 1947.70 +739.00 19834.40 13.15 2.40 2.10 35.97 -7.47 1.01 0.00 0.00 1.57 3.26 1.30 -1.00 0.00 0.00 -6.68 1914.40 +740.00 19214.40 22.84 2.40 2.10 69.33 -7.44 -0.08 0.00 0.00 1.73 3.50 1.50 -1.00 0.00 0.00 -10.56 1294.40 +741.00 20018.00 23.28 1.60 2.10 64.63 -8.13 -1.30 0.00 0.00 1.35 3.13 1.20 -1.00 0.00 0.00 -13.84 203.60 +742.00 20048.10 13.60 2.20 2.10 43.06 -11.19 -1.15 0.00 0.00 1.72 3.69 1.70 -1.00 0.00 0.00 -6.31 2128.10 +743.00 20313.90 13.27 3.20 2.10 51.33 -7.81 0.19 0.00 0.00 2.91 4.84 2.90 -1.00 0.00 0.00 -3.65 141.10 +744.00 20189.70 11.51 2.80 2.10 33.93 -6.96 0.46 0.00 0.00 1.93 3.32 1.60 -1.00 0.00 0.00 -4.76 2269.70 +745.00 17549.90 13.64 3.30 2.10 41.14 -7.11 -0.27 0.00 0.00 1.83 3.42 1.50 -1.00 0.00 0.00 -5.96 141.90 +746.00 17520.30 12.06 2.30 2.10 31.69 -6.75 0.99 0.00 0.00 2.06 2.70 1.60 -1.00 0.00 0.00 -4.68 2160.30 +747.00 14007.30 13.03 1.90 2.10 38.95 -8.95 -1.69 0.00 0.00 1.37 3.30 1.30 -1.00 0.00 0.00 -7.63 1207.30 +748.00 13712.00 12.34 1.60 2.10 30.27 -8.78 2.65 0.00 0.00 1.33 2.91 1.00 -1.00 0.00 0.00 -7.41 912.00 +749.00 12198.50 17.10 2.20 2.10 51.99 -7.55 1.52 0.00 0.00 1.97 3.68 1.70 -1.00 0.00 0.00 -6.95 1958.50 +750.00 14032.00 12.22 1.70 2.10 29.49 -10.06 -1.65 0.00 0.00 1.43 2.77 1.30 -1.00 0.00 0.00 -6.83 1232.00 +751.00 16060.40 14.13 2.10 2.10 40.06 -8.43 0.60 0.00 0.00 1.94 3.42 1.50 -1.00 0.00 0.00 -5.83 700.40 +752.00 17124.10 13.90 2.00 2.10 33.59 -9.23 0.39 0.00 0.00 1.87 3.03 1.40 -1.00 0.00 0.00 -5.95 1764.10 +753.00 17077.80 10.77 0.80 2.10 20.62 -6.56 -1.50 0.00 0.00 0.63 2.31 0.40 -1.00 0.00 0.00 -13.58 1717.80 +754.00 20430.80 12.56 1.50 2.10 30.41 -7.76 1.32 0.00 0.00 1.33 2.69 0.70 -1.00 0.00 0.00 -7.56 2510.80 +755.00 20959.70 16.62 2.30 2.10 46.93 -6.34 0.00 0.00 0.00 1.64 3.18 1.50 -1.00 0.00 0.00 -8.11 479.70 +756.00 23758.70 10.35 1.30 2.10 26.43 -7.59 1.67 0.00 0.00 1.13 2.57 1.20 -1.00 0.00 0.00 -7.31 718.70 +757.00 23668.50 15.20 2.60 2.10 53.33 -7.26 -1.40 0.00 0.00 2.31 4.08 2.10 -1.00 0.00 0.00 -5.25 628.50 +758.00 23447.90 17.51 4.10 2.10 58.99 -7.43 0.54 0.00 0.00 3.18 4.13 2.30 -1.00 0.00 0.00 -4.41 407.90 +759.00 23952.80 11.45 1.80 2.10 28.81 -8.39 -0.75 0.00 0.00 1.45 3.16 1.20 -1.00 0.00 0.00 -6.30 912.80 +760.00 24797.70 13.82 2.80 2.10 42.20 -8.73 -0.14 0.00 0.00 2.52 2.43 1.90 -1.00 0.00 0.00 -4.39 1757.70 +761.00 25780.50 18.33 3.10 2.10 55.90 -9.63 -0.43 0.00 0.00 2.00 3.31 1.40 -1.00 0.00 0.00 -7.34 180.50 +762.00 24988.20 16.04 1.60 2.10 40.04 -9.34 0.53 0.00 0.00 1.36 2.94 1.00 -1.00 0.00 0.00 -9.46 1948.20 +763.00 23402.00 10.33 2.40 2.10 26.86 -8.40 -1.05 0.00 0.00 2.19 2.07 1.90 -1.00 0.00 0.00 -3.77 362.00 +764.00 23235.80 12.70 2.20 2.10 35.40 -7.78 1.09 0.00 0.00 1.72 3.49 1.50 -1.00 0.00 0.00 -5.91 195.80 +765.00 21485.90 14.48 1.30 2.10 33.57 -8.12 -0.69 0.00 0.00 0.81 2.56 0.60 -1.00 0.00 0.00 -14.24 1005.90 +766.00 21369.70 10.23 2.10 2.10 29.29 -7.10 -0.58 0.00 0.00 1.76 3.49 1.50 -1.00 0.00 0.00 -4.66 889.70 +767.00 21143.40 14.02 2.80 2.10 42.65 -7.11 0.77 0.00 0.00 1.96 3.63 1.70 -1.00 0.00 0.00 -5.73 663.40 +768.00 21823.80 13.21 1.00 2.10 23.03 -6.66 1.49 0.00 0.00 0.86 1.30 0.80 -1.00 0.00 0.00 -12.34 1343.80 +769.00 22259.60 19.52 1.60 2.10 55.88 -7.54 -0.20 0.00 0.00 1.00 3.14 1.20 -1.00 0.00 0.00 -15.54 1779.60 +770.00 22921.90 18.07 2.10 2.10 52.57 -7.66 0.38 0.00 0.00 1.54 3.29 1.30 -1.00 0.00 0.00 -9.38 2441.90 +771.00 22394.90 20.20 2.10 2.10 58.82 -7.76 0.87 0.00 0.00 1.35 3.51 1.60 -1.00 0.00 0.00 -11.95 1914.90 +772.00 12067.70 11.77 2.70 2.10 36.99 -7.25 -0.92 0.00 0.00 2.08 3.24 1.80 -1.00 0.00 0.00 -4.52 1827.70 +773.00 11469.10 10.89 1.40 2.10 25.39 -7.13 0.58 0.00 0.00 1.17 2.40 0.40 -1.00 0.00 0.00 -7.46 1229.10 +774.00 3216.10 12.48 1.80 2.10 25.62 -7.27 -0.61 0.00 0.00 1.32 2.64 0.70 -1.00 0.00 0.00 -7.57 656.10 +775.00 2965.70 12.49 1.40 2.10 31.58 -7.05 1.69 0.00 0.00 1.19 3.15 1.20 -1.00 0.00 0.00 -8.41 405.70 +776.00 2521.50 10.05 3.00 2.10 33.22 -8.14 -0.83 0.00 0.00 2.82 3.78 2.40 -1.00 0.00 0.00 -2.86 2521.50 +777.00 3513.50 11.03 1.10 2.10 22.62 -8.12 1.18 0.00 0.00 0.91 2.12 0.70 -1.00 0.00 0.00 -9.67 953.50 +778.00 3691.80 12.33 1.70 2.10 27.09 -8.88 1.73 0.00 0.00 1.51 1.45 1.20 -1.00 0.00 0.00 -6.54 1131.80 +779.00 4019.90 18.34 2.00 2.10 51.91 -7.10 2.40 0.00 0.00 1.28 3.19 1.20 -1.00 0.00 0.00 -11.42 1459.90 +780.00 3703.90 12.65 1.50 2.10 27.41 -10.71 0.95 0.00 0.00 1.36 2.91 1.00 -1.00 0.00 0.00 -7.42 1143.90 +781.00 2132.40 12.00 1.80 2.10 28.82 -7.66 -0.15 0.00 0.00 1.49 2.80 1.30 -1.00 0.00 0.00 -6.45 2132.40 +782.00 2087.30 11.66 3.10 2.10 39.26 -6.72 1.76 0.00 0.00 2.41 3.79 2.20 -1.00 0.00 0.00 -3.87 2087.30 +783.00 1155.60 13.25 1.20 2.10 31.42 -8.22 0.87 0.00 0.00 0.98 2.68 0.70 -1.00 0.00 0.00 -10.78 1155.60 +784.00 930.80 10.38 1.70 2.10 20.97 -6.82 -0.17 0.00 0.00 1.54 1.32 0.80 -1.00 0.00 0.00 -5.39 930.80 +785.00 459.00 14.09 2.80 2.10 45.63 -5.57 0.20 0.00 0.00 2.49 3.69 1.70 -1.00 0.00 0.00 -4.53 459.00 +786.00 1301.90 10.04 2.20 2.10 24.92 -8.26 0.08 0.00 0.00 1.83 2.43 1.50 -1.00 0.00 0.00 -4.39 1301.90 +787.00 1363.30 14.15 3.00 2.10 50.99 -7.00 0.66 0.00 0.00 2.49 3.87 2.30 -1.00 0.00 0.00 -4.55 1363.30 +788.00 1761.10 11.10 1.20 2.10 24.17 -8.16 0.46 0.00 0.00 0.79 2.48 0.50 -1.00 0.00 0.00 -11.24 1761.10 +789.00 1624.30 12.89 1.20 2.10 26.38 -7.25 0.54 0.00 0.00 1.06 2.11 0.50 -1.00 0.00 0.00 -9.72 1624.30 +790.00 4268.50 16.16 2.40 2.10 52.92 -7.11 0.65 0.00 0.00 1.95 3.73 1.80 -1.00 0.00 0.00 -6.64 1708.50 +791.00 4372.30 11.52 1.80 2.10 32.83 -7.90 0.27 0.00 0.00 1.33 2.99 1.00 -1.00 0.00 0.00 -6.92 1812.30 +792.00 10897.40 11.63 1.60 2.10 28.56 -8.19 -0.32 0.00 0.00 1.28 3.05 1.10 -1.00 0.00 0.00 -7.27 657.40 +793.00 9722.50 14.00 1.70 2.10 39.02 -8.32 0.25 0.00 0.00 1.50 3.17 1.20 -1.00 0.00 0.00 -7.45 2042.50 +794.00 8900.00 11.84 1.70 2.10 28.36 -8.02 -1.73 0.00 0.00 1.44 3.33 1.40 -1.00 0.00 0.00 -6.60 1220.00 +795.00 10958.40 12.80 1.10 2.10 27.41 -8.80 1.11 0.00 0.00 0.96 2.21 0.50 -1.00 0.00 0.00 -10.71 718.40 +796.00 11127.60 14.90 2.00 2.10 44.16 -8.03 0.30 0.00 0.00 1.83 3.43 1.50 -1.00 0.00 0.00 -6.50 887.60 +797.00 11249.40 15.57 3.40 2.10 58.96 -8.61 -0.87 0.00 0.00 2.42 4.33 2.40 -1.00 0.00 0.00 -5.15 1009.40 +798.00 11149.30 13.21 2.80 2.10 43.08 -9.03 -0.09 0.00 0.00 2.30 3.70 1.70 -1.00 0.00 0.00 -4.60 909.30 +799.00 8472.70 10.67 1.40 2.10 24.68 -8.88 -0.17 0.00 0.00 1.24 2.79 0.80 -1.00 0.00 0.00 -6.87 792.70 +800.00 8367.70 14.12 1.80 2.10 35.95 -8.12 0.91 0.00 0.00 1.44 2.85 1.30 -1.00 0.00 0.00 -7.82 687.70 +801.00 5539.30 12.31 2.60 2.10 39.13 -7.38 1.19 0.00 0.00 2.42 3.99 2.00 -1.00 0.00 0.00 -4.07 419.30 +802.00 5017.60 13.04 2.80 2.10 44.74 -6.90 -1.66 0.00 0.00 2.43 4.13 2.20 -1.00 0.00 0.00 -4.30 2457.60 +803.00 4910.70 11.07 1.50 2.10 24.08 -7.85 0.67 0.00 0.00 1.29 1.36 1.00 -1.00 0.00 0.00 -6.85 2350.70 +804.00 6122.60 15.33 1.90 2.10 42.92 -7.17 0.41 0.00 0.00 1.64 3.32 1.40 -1.00 0.00 0.00 -7.48 1002.60 +805.00 6390.40 11.61 1.70 2.10 31.61 -7.48 -0.82 0.00 0.00 1.41 3.10 1.10 -1.00 0.00 0.00 -6.57 1270.40 +806.00 7367.90 10.85 2.00 2.10 30.65 -7.56 0.54 0.00 0.00 1.86 2.98 1.70 -1.00 0.00 0.00 -4.66 2247.90 +807.00 6430.80 15.41 3.10 2.10 51.41 -6.48 -0.49 0.00 0.00 2.62 3.81 2.30 -1.00 0.00 0.00 -4.71 1310.80 +808.00 25835.70 10.61 1.50 2.10 23.18 -9.40 0.05 0.00 0.00 1.17 2.47 0.50 -1.00 0.00 0.00 -7.25 235.70 +809.00 25878.70 13.01 1.80 2.10 33.79 -9.31 -0.47 0.00 0.00 1.53 3.00 1.20 -1.00 0.00 0.00 -6.81 278.70 +810.00 38492.20 10.04 2.20 2.10 29.89 -7.22 0.02 0.00 0.00 2.07 3.67 1.80 -1.00 0.00 0.00 -3.87 92.20 +811.00 38246.70 16.73 1.70 2.10 40.59 -7.96 -0.06 0.00 0.00 1.39 3.02 1.10 -1.00 0.00 0.00 -9.65 2406.70 +812.00 38107.00 10.26 3.90 2.10 32.04 -8.24 1.59 0.00 0.00 1.86 2.99 1.80 -1.00 0.00 0.00 -4.42 2267.00 +813.00 38625.80 11.05 2.60 2.10 30.84 -8.15 -0.12 0.00 0.00 2.48 2.99 2.00 -1.00 0.00 0.00 -3.57 225.80 +814.00 39226.80 11.50 1.50 2.10 28.95 -8.19 -0.09 0.00 0.00 1.36 2.41 1.10 -1.00 0.00 0.00 -6.77 7.60 +815.00 39380.20 18.02 2.00 2.10 55.21 -10.90 -0.27 0.00 0.00 0.97 3.38 1.40 -1.00 0.00 0.00 -14.81 980.20 +816.00 39305.60 12.49 2.50 2.10 41.46 -7.59 0.70 0.00 0.00 1.56 3.75 1.80 -1.00 0.00 0.00 -6.42 905.60 +817.00 37951.90 10.32 3.20 2.10 31.45 -8.70 0.75 0.00 0.00 2.70 3.94 2.30 -1.00 0.00 0.00 -3.06 2111.90 +818.00 37851.30 24.14 2.20 2.10 72.75 -7.96 0.68 0.00 0.00 1.77 3.41 1.50 -1.00 0.00 0.00 -10.93 2011.30 +819.00 36106.20 13.17 2.20 2.10 41.44 -7.12 0.89 0.00 0.00 1.40 3.46 1.50 -1.00 0.00 0.00 -7.55 266.20 +820.00 35966.50 14.82 3.40 2.10 56.04 -6.73 0.82 0.00 0.00 3.24 4.85 2.90 -1.00 0.00 0.00 -3.66 152.10 +821.00 35833.90 15.47 2.90 2.10 50.68 -8.02 -0.11 0.00 0.00 2.53 3.82 1.90 -1.00 0.00 0.00 -4.89 2553.90 +822.00 36684.20 12.94 1.80 2.10 34.39 -6.92 -0.14 0.00 0.00 1.39 3.08 1.10 -1.00 0.00 0.00 -7.44 844.20 +823.00 37272.70 15.31 2.70 2.10 47.27 -5.07 0.59 0.00 0.00 2.50 3.74 1.80 -1.00 0.00 0.00 -4.90 1432.70 +824.00 37609.90 10.04 3.30 2.10 35.21 -7.43 -0.20 0.00 0.00 2.82 3.95 2.40 -1.00 0.00 0.00 -2.85 1769.90 +825.00 37344.50 17.23 1.80 2.10 46.63 -7.55 -0.92 0.00 0.00 1.58 3.13 1.20 -1.00 0.00 0.00 -8.71 1504.50 +826.00 39696.50 14.37 1.80 2.10 35.33 -8.36 0.07 0.00 0.00 1.32 3.01 1.10 -1.00 0.00 0.00 -8.74 1296.50 +827.00 40228.40 23.01 2.20 2.10 75.34 -7.72 0.35 0.00 0.00 2.00 3.75 1.80 -1.00 0.00 0.00 -9.21 1828.40 +828.00 46003.30 14.54 4.60 2.10 68.95 -7.54 0.87 0.00 0.00 4.21 5.82 3.90 -1.00 0.00 0.00 -2.76 2483.30 +829.00 45737.80 13.10 2.00 2.10 31.63 -6.52 1.25 0.00 0.00 1.81 2.74 1.60 -1.00 0.00 0.00 -5.79 2217.80 +830.00 45228.70 14.60 4.60 2.10 68.46 -7.52 0.32 0.00 0.00 3.75 5.45 3.50 -1.00 0.00 0.00 -3.11 1708.70 +831.00 46113.20 13.38 1.30 2.10 30.48 -7.36 0.76 0.00 0.00 1.11 2.70 0.80 -1.00 0.00 0.00 -9.65 33.20 +832.00 46144.30 13.48 2.00 2.10 39.66 -8.68 0.13 0.00 0.00 1.82 3.54 1.60 -1.00 0.00 0.00 -5.91 64.30 +833.00 46719.10 17.91 1.70 2.10 46.35 -8.15 -0.31 0.00 0.00 1.47 3.13 1.20 -1.00 0.00 0.00 -9.75 639.10 +834.00 46165.50 11.28 4.10 2.10 40.98 -8.62 1.41 0.00 0.00 3.84 3.75 2.30 -1.00 0.00 0.00 -2.35 85.50 +835.00 45195.20 22.01 2.00 2.10 59.85 -6.85 1.14 0.00 0.00 1.39 2.97 1.00 -1.00 0.00 0.00 -12.63 1675.20 +836.00 44873.60 24.37 2.80 2.10 80.72 -8.03 0.39 0.00 0.00 1.72 3.63 1.70 -1.00 0.00 0.00 -11.37 1353.60 +837.00 42614.70 22.17 3.20 2.10 74.92 -7.60 0.43 0.00 0.00 1.81 3.59 1.60 -1.00 0.00 0.00 -9.78 246.70 +838.00 42395.90 11.98 2.10 2.10 33.88 -8.13 0.29 0.00 0.00 1.27 3.38 1.40 -1.00 0.00 0.00 -7.57 1435.90 +839.00 41752.10 10.50 4.00 2.10 38.98 -6.85 -0.98 0.00 0.00 3.42 4.44 3.10 -1.00 0.00 0.00 -2.46 792.10 +840.00 42999.80 19.01 2.40 2.10 56.80 -7.30 -2.57 0.00 0.00 2.07 3.63 1.70 -1.00 0.00 0.00 -7.35 2039.80 +841.00 44207.50 11.57 1.70 2.10 29.15 -6.29 1.29 0.00 0.00 1.59 3.06 1.20 -1.00 0.00 0.00 -5.80 687.50 +842.00 44484.40 21.20 2.80 2.10 69.02 -7.38 -0.82 0.00 0.00 2.20 3.85 1.90 -1.00 0.00 0.00 -7.70 964.40 +843.00 44366.30 11.90 2.70 2.10 39.95 -8.01 -0.07 0.00 0.00 2.47 4.08 2.10 -1.00 0.00 0.00 -3.85 846.30 +844.00 35730.60 25.75 2.00 2.10 74.12 -7.17 -0.39 0.00 0.00 1.83 3.38 1.40 -1.00 0.00 0.00 -11.28 2450.60 +845.00 35672.00 10.95 2.10 2.10 32.40 -6.82 -1.05 0.00 0.00 1.85 3.56 1.60 -1.00 0.00 0.00 -4.74 2392.00 +846.00 29058.20 14.00 2.40 2.10 43.27 -6.18 -0.19 0.00 0.00 2.16 3.42 1.50 -1.00 0.00 0.00 -5.18 27.80 +847.00 28816.00 10.99 2.90 2.10 37.74 -9.70 -1.08 0.00 0.00 2.44 4.12 2.20 -1.00 0.00 0.00 -3.60 656.00 +848.00 28795.20 25.62 3.00 2.10 88.40 -7.50 1.98 0.00 0.00 2.64 4.05 2.10 -1.00 0.00 0.00 -7.76 635.20 +849.00 29209.90 14.00 2.20 2.10 39.19 -8.08 -0.35 0.00 0.00 1.85 3.12 1.80 -1.00 0.00 0.00 -6.06 1049.90 +850.00 29743.80 11.99 2.70 2.10 38.99 -8.00 -0.69 0.00 0.00 2.30 4.07 2.10 -1.00 0.00 0.00 -4.18 1583.80 +851.00 30578.90 16.36 2.70 2.10 44.61 -6.70 0.97 0.00 0.00 2.11 3.57 1.60 -1.00 0.00 0.00 -6.21 2418.90 +852.00 30388.50 19.81 2.60 2.10 68.10 -6.88 0.34 0.00 0.00 1.31 3.98 2.00 -1.00 0.00 0.00 -12.12 2228.50 +853.00 28647.20 15.72 2.70 2.10 54.71 -6.25 -0.25 0.00 0.00 1.72 4.22 2.30 -1.00 0.00 0.00 -7.31 487.20 +854.00 27731.40 13.82 2.50 2.10 46.53 -8.75 1.17 0.00 0.00 2.09 3.92 2.00 -1.00 0.00 0.00 -5.29 2131.40 +855.00 26915.80 12.34 3.20 2.10 35.78 -7.19 -0.11 0.00 0.00 2.66 3.09 2.20 -1.00 0.00 0.00 -3.72 1315.80 +856.00 26657.80 13.19 2.10 2.10 36.24 -7.07 -0.33 0.00 0.00 1.72 3.39 1.40 -1.00 0.00 0.00 -6.14 1057.80 +857.00 26319.30 16.29 3.80 2.10 61.56 -6.36 -1.09 0.00 0.00 2.82 4.02 2.70 -1.00 0.00 0.00 -4.63 719.30 +858.00 27021.10 12.90 2.90 2.10 45.00 -7.61 2.76 0.00 0.00 2.43 4.15 2.20 -1.00 0.00 0.00 -4.24 1421.10 +859.00 27047.20 14.53 2.20 2.10 47.52 -8.50 -0.64 0.00 0.00 1.77 3.61 1.70 -1.00 0.00 0.00 -6.57 1447.20 +860.00 27420.80 10.63 2.20 2.10 34.76 -8.68 -0.72 0.00 0.00 2.06 3.71 1.90 -1.00 0.00 0.00 -4.14 1820.80 +861.00 27080.80 13.90 3.40 2.10 43.74 -8.62 1.93 0.00 0.00 3.09 3.43 2.20 -1.00 0.00 0.00 -3.60 1480.80 +862.00 30781.40 17.59 2.60 2.10 59.14 -6.88 -0.44 0.00 0.00 1.73 3.91 2.00 -1.00 0.00 0.00 -8.14 61.40 +863.00 31098.50 14.63 3.40 2.10 53.31 -6.75 1.56 0.00 0.00 3.15 4.28 2.70 -1.00 0.00 0.00 -3.72 378.50 +864.00 34992.50 13.24 2.60 2.10 37.37 -7.10 -1.02 0.00 0.00 2.29 3.19 1.90 -1.00 0.00 0.00 -4.62 1712.50 +865.00 34292.40 13.04 2.00 2.10 39.10 -8.12 0.21 0.00 0.00 1.77 3.30 1.30 -1.00 0.00 0.00 -5.88 65.20 +866.00 34259.00 12.02 2.20 2.10 33.93 -7.16 -0.66 0.00 0.00 1.65 3.40 1.50 -1.00 0.00 0.00 -5.83 31.80 +867.00 35022.60 19.51 2.20 2.10 60.28 -9.03 0.76 0.00 0.00 1.58 3.51 1.60 -1.00 0.00 0.00 -9.88 1742.60 +868.00 35132.20 10.24 2.30 2.10 32.17 -7.08 -1.12 0.00 0.00 2.08 3.57 1.90 -1.00 0.00 0.00 -3.94 162.60 +869.00 35490.30 11.26 2.10 2.10 29.65 -6.28 0.56 0.00 0.00 1.94 3.00 1.00 -1.00 0.00 0.00 -4.65 2210.30 +870.00 35188.90 11.69 1.80 2.10 32.99 -6.93 1.48 0.00 0.00 1.47 3.25 1.30 -1.00 0.00 0.00 -6.36 1908.90 +871.00 33778.70 12.56 2.90 2.10 38.00 -6.84 -0.32 0.00 0.00 2.66 3.15 2.00 -1.00 0.00 0.00 -3.77 498.70 +872.00 33189.10 12.09 3.20 2.10 34.80 -5.43 0.97 0.00 0.00 2.55 3.26 1.30 -1.00 0.00 0.00 -3.80 2469.10 +873.00 32086.00 20.64 1.70 2.10 59.87 -7.41 0.16 0.00 0.00 1.52 3.23 1.30 -1.00 0.00 0.00 -10.88 1366.00 +874.00 31961.50 18.47 2.60 2.10 55.37 -8.07 -0.56 0.00 0.00 2.23 3.33 1.70 -1.00 0.00 0.00 -6.63 1241.50 +875.00 31503.50 13.92 2.30 2.10 35.30 -7.07 1.51 0.00 0.00 2.06 3.00 1.10 -1.00 0.00 0.00 -5.41 783.50 +876.00 32520.40 16.37 1.80 2.10 41.05 -7.50 0.28 0.00 0.00 1.63 3.05 1.10 -1.00 0.00 0.00 -8.05 1800.40 +877.00 32591.60 14.53 2.70 2.10 42.12 -6.94 0.90 0.00 0.00 2.42 3.10 1.10 -1.00 0.00 0.00 -4.80 1871.60 +878.00 32967.50 13.40 2.40 2.10 40.00 -6.89 1.64 0.00 0.00 1.83 3.08 1.50 -1.00 0.00 0.00 -5.87 2247.50 +879.00 32718.40 14.28 3.90 2.10 58.35 -8.14 0.94 0.00 0.00 3.68 5.17 3.20 -1.00 0.00 0.00 -3.10 1998.40 +880.00 91451.70 24.42 3.70 2.10 99.86 -7.74 -0.07 0.00 0.00 3.16 4.88 2.90 -1.00 0.00 0.00 -6.18 520.50 +881.00 87254.30 13.39 1.60 2.10 33.52 -9.01 1.09 0.00 0.00 1.33 3.01 1.10 -1.00 0.00 0.00 -8.06 163.10 +882.00 126782.50 15.08 1.90 2.10 38.96 -7.86 0.18 0.00 0.00 1.71 3.16 1.20 -1.00 0.00 0.00 -7.04 139.30 +883.00 126269.30 18.43 1.80 2.10 51.26 -8.89 -0.36 0.00 0.00 1.27 3.31 1.40 -1.00 0.00 0.00 -11.61 778.10 +884.00 126210.90 18.87 1.90 2.10 51.76 -8.15 -0.74 0.00 0.00 1.19 3.11 1.20 -1.00 0.00 0.00 -12.66 719.70 +885.00 126974.00 25.44 1.60 2.10 68.74 -8.02 -0.34 0.00 0.00 1.38 3.03 1.10 -1.00 0.00 0.00 -14.76 330.80 +886.00 149258.10 17.07 2.30 2.10 51.97 -8.04 -0.13 0.00 0.00 2.02 3.75 1.80 -1.00 0.00 0.00 -6.76 291.70 +887.00 127051.70 11.11 2.60 2.10 36.56 -8.97 1.96 0.00 0.00 2.41 3.48 2.30 -1.00 0.00 0.00 -3.68 408.50 +888.00 148741.90 10.81 1.70 2.10 26.54 -8.12 1.43 0.00 0.00 1.50 2.42 1.20 -1.00 0.00 0.00 -5.77 1055.50 +889.00 126073.70 13.17 1.50 2.10 29.51 -7.83 -0.86 0.00 0.00 0.73 2.60 0.60 -1.00 0.00 0.00 -14.37 582.50 +890.00 125965.30 22.41 1.90 2.10 65.55 -9.27 -2.19 0.00 0.00 1.42 3.39 1.40 -1.00 0.00 0.00 -12.63 474.10 +891.00 124887.10 20.45 3.20 2.10 64.86 -7.30 -1.32 0.00 0.00 1.97 3.53 1.60 -1.00 0.00 0.00 -8.30 675.90 +892.00 124689.40 18.76 2.40 2.10 57.87 -8.12 0.34 0.00 0.00 1.41 3.61 1.70 -1.00 0.00 0.00 -10.68 478.20 +893.00 125125.00 16.63 2.80 2.10 60.01 -7.58 0.14 0.00 0.00 2.45 4.09 2.10 -1.00 0.00 0.00 -5.42 913.80 +894.00 125627.50 23.08 2.70 2.10 80.15 -8.29 -0.22 0.00 0.00 1.84 3.72 1.80 -1.00 0.00 0.00 -10.02 136.30 +895.00 125889.30 12.32 2.20 2.10 35.17 -8.72 0.28 0.00 0.00 1.68 3.16 1.40 -1.00 0.00 0.00 -5.86 398.10 +896.00 125719.30 11.97 3.10 2.10 39.92 -8.32 -1.30 0.00 0.00 2.86 3.02 2.40 -1.00 0.00 0.00 -3.35 228.10 +897.00 127253.30 19.26 2.60 2.10 62.20 -9.89 -1.55 0.00 0.00 1.65 3.89 1.90 -1.00 0.00 0.00 -9.32 610.10 +898.00 127575.40 16.61 2.10 2.10 52.63 -8.72 -1.53 0.00 0.00 1.60 3.38 1.40 -1.00 0.00 0.00 -8.29 932.20 +899.00 129077.90 10.89 3.80 2.10 40.94 -10.44 -1.06 0.00 0.00 3.41 5.00 3.10 -1.00 0.00 0.00 -2.55 591.50 +900.00 148442.90 13.07 2.70 2.10 45.82 -7.80 0.60 0.00 0.00 2.54 4.25 2.30 -1.00 0.00 0.00 -4.11 756.50 +901.00 129207.40 19.39 2.40 2.10 59.40 -13.45 0.24 0.00 0.00 2.06 3.67 1.70 -1.00 0.00 0.00 -7.52 721.00 +902.00 129365.90 24.28 2.50 2.10 84.58 -10.25 0.18 0.00 0.00 1.65 4.07 2.10 -1.00 0.00 0.00 -11.75 879.50 +903.00 129828.10 11.86 1.10 2.10 24.94 -9.55 1.51 0.00 0.00 0.66 2.33 0.40 -1.00 0.00 0.00 -14.31 1341.70 +904.00 129732.00 23.31 2.50 2.10 72.01 -8.55 -0.31 0.00 0.00 2.02 3.60 1.70 -1.00 0.00 0.00 -9.24 1245.60 +905.00 128997.80 19.55 3.00 2.10 70.45 -10.19 -0.73 0.00 0.00 1.65 3.96 2.00 -1.00 0.00 0.00 -9.51 511.40 +906.00 128921.40 17.18 2.80 2.10 58.42 -10.52 -1.45 0.00 0.00 2.07 3.99 2.00 -1.00 0.00 0.00 -6.63 435.00 +907.00 148676.50 19.81 2.60 2.10 64.66 -9.24 -0.85 0.00 0.00 2.14 3.92 2.00 -1.00 0.00 0.00 -7.40 990.10 +908.00 127761.30 10.51 1.10 2.10 22.13 -8.37 4.28 0.00 0.00 0.97 2.65 0.70 -1.00 0.00 0.00 -8.68 1118.10 +909.00 127827.80 15.64 2.10 2.10 45.92 -9.87 -2.05 0.00 0.00 1.84 3.35 1.40 -1.00 0.00 0.00 -6.82 1184.60 +910.00 128016.40 12.24 1.20 2.10 27.74 -9.56 -1.30 0.00 0.00 1.04 2.76 0.80 -1.00 0.00 0.00 -9.44 221.20 +911.00 128685.70 24.67 2.00 2.10 68.69 -9.18 -0.80 0.00 0.00 1.13 3.15 1.20 -1.00 0.00 0.00 -17.45 199.30 +912.00 128161.30 25.08 2.40 2.10 77.07 -9.87 0.06 0.00 0.00 2.12 3.73 1.80 -1.00 0.00 0.00 -9.45 366.10 +913.00 124662.70 10.54 3.80 2.10 44.85 -7.37 -0.61 0.00 0.00 3.64 4.95 3.20 -1.00 0.00 0.00 -2.32 451.50 +914.00 124353.90 10.89 5.00 2.10 58.48 -8.39 1.05 0.00 0.00 4.68 5.99 4.00 -1.00 0.00 0.00 -1.86 142.70 +915.00 120448.50 12.97 3.20 2.10 42.80 -8.04 -1.93 0.00 0.00 2.73 4.45 2.50 -1.00 0.00 0.00 -3.80 77.30 +916.00 120018.60 14.99 2.60 2.10 45.86 -8.88 -0.02 0.00 0.00 2.31 3.74 1.80 -1.00 0.00 0.00 -5.20 927.40 +917.00 120527.50 16.22 3.70 2.10 66.66 -8.71 0.38 0.00 0.00 3.43 5.00 3.10 -1.00 0.00 0.00 -3.78 156.30 +918.00 120692.40 11.35 3.90 2.10 44.26 -7.88 0.17 0.00 0.00 3.50 3.62 3.30 -1.00 0.00 0.00 -2.59 321.20 +919.00 122066.40 21.79 2.40 2.10 68.15 -8.15 0.45 0.00 0.00 2.01 3.74 1.80 -1.00 0.00 0.00 -8.66 415.20 +920.00 121703.10 14.58 2.80 2.10 48.97 -8.40 0.42 0.00 0.00 2.53 4.06 2.10 -1.00 0.00 0.00 -4.61 51.90 +921.00 119879.20 10.17 1.30 2.10 25.49 -7.82 -0.92 0.00 0.00 1.10 2.71 0.80 -1.00 0.00 0.00 -7.37 788.00 +922.00 119447.10 12.79 2.70 2.10 38.43 -7.81 -0.90 0.00 0.00 2.40 3.33 2.00 -1.00 0.00 0.00 -4.25 355.90 +923.00 118007.30 16.88 2.10 2.10 53.76 -7.91 0.93 0.00 0.00 1.74 3.75 1.80 -1.00 0.00 0.00 -7.76 196.10 +924.00 117790.80 28.36 3.40 2.10 100.30 -7.21 0.28 0.00 0.00 2.09 3.82 1.90 -1.00 0.00 0.00 -10.85 1259.60 +925.00 118945.90 17.29 2.30 2.10 54.33 -7.27 1.45 0.00 0.00 2.09 3.51 1.60 -1.00 0.00 0.00 -6.61 1134.70 +926.00 118984.10 12.73 1.60 2.10 31.63 -9.04 -0.71 0.00 0.00 0.96 3.03 1.10 -1.00 0.00 0.00 -10.66 1172.90 +927.00 150792.80 12.02 1.80 2.10 31.80 -8.44 0.78 0.00 0.00 1.52 3.29 1.50 -1.00 0.00 0.00 -6.31 546.40 +928.00 151038.10 14.28 2.70 2.10 40.84 -7.00 1.26 0.00 0.00 1.79 3.74 1.80 -1.00 0.00 0.00 -6.37 791.70 +929.00 150594.60 10.50 2.70 2.10 32.65 -9.58 -0.60 0.00 0.00 2.57 3.49 2.10 -1.00 0.00 0.00 -3.27 348.20 +930.00 122240.50 49.50 4.70 2.10 198.17 -8.21 2.99 0.00 0.00 2.78 4.31 2.40 -1.00 0.00 0.00 -14.24 589.30 +931.00 123833.60 14.49 2.10 2.10 39.66 -9.30 0.68 0.00 0.00 1.82 3.49 1.50 -1.00 0.00 0.00 -6.37 902.40 +932.00 123817.70 15.98 1.90 2.10 41.38 -7.26 -1.24 0.00 0.00 1.03 2.72 0.80 -1.00 0.00 0.00 -12.37 886.50 +933.00 91846.40 12.13 1.90 2.10 32.95 -6.76 0.65 0.00 0.00 1.66 3.30 1.40 -1.00 0.00 0.00 -5.84 915.20 +934.00 123946.10 10.10 4.30 2.10 35.89 -8.36 1.39 0.00 0.00 3.30 2.32 1.60 -1.00 0.00 0.00 -2.45 1014.90 +935.00 149987.80 37.97 2.40 2.10 123.99 -8.58 -0.39 0.00 0.00 1.61 3.69 1.70 -1.00 0.00 0.00 -18.81 1021.40 +936.00 124137.00 15.29 2.40 2.10 45.81 -7.37 1.58 0.00 0.00 1.44 3.47 1.50 -1.00 0.00 0.00 -8.47 1205.80 +937.00 123707.30 21.23 3.50 2.10 79.79 -6.86 -1.37 0.00 0.00 2.95 3.89 2.60 -1.00 0.00 0.00 -5.76 776.10 +938.00 123386.00 14.10 1.70 2.10 33.11 -8.73 0.50 0.00 0.00 1.23 2.61 0.70 -1.00 0.00 0.00 -9.16 454.80 +939.00 122885.50 11.38 2.60 2.10 37.51 -9.46 0.13 0.00 0.00 2.44 4.01 2.10 -1.00 0.00 0.00 -3.72 1234.30 +940.00 122696.40 10.50 2.30 2.10 25.35 -8.24 0.01 0.00 0.00 1.66 1.78 0.90 -1.00 0.00 0.00 -5.06 1045.20 +941.00 122975.80 10.67 1.60 2.10 25.11 -10.05 1.21 0.00 0.00 1.22 3.11 1.20 -1.00 0.00 0.00 -7.00 44.60 +942.00 150423.70 14.62 2.30 2.10 44.43 -6.76 -1.68 0.00 0.00 2.06 3.78 1.80 -1.00 0.00 0.00 -5.67 177.30 +943.00 150045.10 27.10 2.50 2.10 78.32 -8.20 0.10 0.00 0.00 1.80 3.28 1.30 -1.00 0.00 0.00 -12.01 1078.70 +944.00 123084.60 22.66 2.20 2.10 71.99 -9.38 0.85 0.00 0.00 1.23 3.58 1.60 -1.00 0.00 0.00 -14.73 153.40 +945.00 129926.90 21.25 2.20 2.10 60.04 -9.03 -1.30 0.00 0.00 1.79 3.45 1.50 -1.00 0.00 0.00 -9.48 1440.50 +946.00 130093.40 10.13 1.60 2.10 22.97 -9.65 -1.24 0.00 0.00 1.42 2.81 1.20 -1.00 0.00 0.00 -5.71 1607.00 +947.00 142807.80 21.63 2.30 2.10 69.87 -7.60 -0.24 0.00 0.00 1.60 3.67 1.70 -1.00 0.00 0.00 -10.83 241.40 +948.00 134813.30 12.23 1.30 2.10 27.73 -7.63 1.27 0.00 0.00 1.00 2.83 0.90 -1.00 0.00 0.00 -9.74 1206.90 +949.00 142737.20 14.89 2.10 2.10 42.54 -7.00 -0.40 0.00 0.00 1.75 3.43 1.50 -1.00 0.00 0.00 -6.80 170.80 +950.00 135122.40 13.48 3.10 2.10 38.03 -7.45 0.23 0.00 0.00 2.57 2.34 2.10 -1.00 0.00 0.00 -4.20 236.00 +951.00 135799.80 10.67 3.30 2.10 41.49 -7.53 0.44 0.00 0.00 3.03 4.85 2.90 -1.00 0.00 0.00 -2.82 913.40 +952.00 135337.30 14.07 2.30 2.10 40.35 -8.00 3.69 0.00 0.00 2.02 3.43 1.50 -1.00 0.00 0.00 -5.57 450.90 +953.00 134517.20 10.22 2.20 2.10 25.00 -9.77 -0.53 0.00 0.00 1.88 1.90 1.40 -1.00 0.00 0.00 -4.36 910.80 +954.00 134451.00 19.08 3.00 2.10 71.01 -8.09 -0.15 0.00 0.00 2.71 4.33 2.40 -1.00 0.00 0.00 -5.64 844.60 +955.00 133659.20 10.46 1.70 2.10 24.52 -9.37 -1.66 0.00 0.00 1.08 1.97 1.00 -1.00 0.00 0.00 -7.73 52.80 +956.00 143346.90 37.23 2.60 2.10 116.98 -6.25 1.47 0.00 0.00 1.32 3.30 1.30 -1.00 0.00 0.00 -22.52 780.50 +957.00 134030.80 42.22 3.80 2.10 164.56 -8.01 0.16 0.00 0.00 2.57 4.42 2.50 -1.00 0.00 0.00 -13.16 424.40 +958.00 134169.30 14.44 3.30 2.10 46.52 -10.17 0.46 0.00 0.00 2.81 4.04 2.10 -1.00 0.00 0.00 -4.11 562.90 +959.00 142934.70 14.01 1.20 2.10 33.26 -7.22 -1.00 0.00 0.00 0.99 2.67 0.70 -1.00 0.00 0.00 -11.29 368.30 +960.00 134272.70 16.42 2.80 2.10 54.73 -9.05 -0.30 0.00 0.00 2.56 4.05 2.10 -1.00 0.00 0.00 -5.14 666.30 +961.00 135955.30 11.12 1.70 2.10 31.01 -8.80 -2.07 0.00 0.00 1.35 3.17 1.20 -1.00 0.00 0.00 -6.58 1068.90 +962.00 137186.80 21.33 2.30 2.10 64.79 -8.30 0.30 0.00 0.00 1.81 3.57 1.60 -1.00 0.00 0.00 -9.45 1020.40 +963.00 140257.70 17.19 2.40 2.10 57.47 -7.82 0.63 0.00 0.00 2.09 3.64 1.70 -1.00 0.00 0.00 -6.57 251.30 +964.00 140010.00 13.00 1.90 2.10 29.25 -9.16 0.17 0.00 0.00 0.95 2.50 0.60 -1.00 0.00 0.00 -10.96 3.60 +965.00 142144.70 20.70 1.90 2.10 61.94 -8.78 0.23 0.00 0.00 1.69 3.39 1.40 -1.00 0.00 0.00 -9.80 858.30 +966.00 141069.30 17.80 2.40 2.10 50.73 -8.31 -2.05 0.00 0.00 2.01 3.47 1.50 -1.00 0.00 0.00 -7.10 1062.90 +967.00 141465.20 19.06 2.80 2.10 54.26 -8.34 -0.48 0.00 0.00 1.72 3.31 1.40 -1.00 0.00 0.00 -8.89 178.80 +968.00 141414.70 20.58 2.00 2.10 60.08 -7.46 1.70 0.00 0.00 1.40 3.30 1.40 -1.00 0.00 0.00 -11.76 128.30 +969.00 142316.80 19.95 1.50 2.10 50.43 -7.96 -1.76 0.00 0.00 1.28 2.95 1.00 -1.00 0.00 0.00 -12.46 1030.40 +970.00 139988.10 14.66 4.20 2.10 37.01 -7.32 -0.60 0.00 0.00 1.12 2.65 0.70 -1.00 0.00 0.00 -10.46 1261.70 +971.00 138132.70 10.91 2.70 2.10 34.77 -8.19 -1.31 0.00 0.00 2.49 3.09 1.90 -1.00 0.00 0.00 -3.51 686.30 +972.00 138103.00 12.20 2.10 2.10 34.37 -9.22 -0.67 0.00 0.00 1.57 3.19 1.20 -1.00 0.00 0.00 -6.23 656.60 +973.00 138497.90 12.92 2.10 2.10 34.71 -8.78 -1.36 0.00 0.00 1.84 2.99 1.70 -1.00 0.00 0.00 -5.60 1051.50 +974.00 138517.20 14.72 1.30 2.10 32.00 -9.44 1.51 0.00 0.00 1.11 2.38 0.90 -1.00 0.00 0.00 -10.57 1070.80 +975.00 138866.10 28.22 1.70 2.10 76.40 -8.63 0.34 0.00 0.00 1.23 3.05 1.10 -1.00 0.00 0.00 -18.41 139.70 +976.00 138752.80 13.57 2.30 2.10 35.59 -10.03 1.02 0.00 0.00 1.55 3.44 1.50 -1.00 0.00 0.00 -7.00 26.40 +977.00 133644.10 10.45 3.40 2.10 31.84 -7.92 0.83 0.00 0.00 2.48 3.89 1.90 -1.00 0.00 0.00 -3.37 37.70 +978.00 143625.00 10.97 2.40 2.10 30.31 -6.64 1.09 0.00 0.00 2.20 3.37 1.60 -1.00 0.00 0.00 -3.99 1058.60 +979.00 130522.30 10.34 2.20 2.10 25.17 -12.15 1.14 0.00 0.00 1.88 2.65 1.20 -1.00 0.00 0.00 -4.39 2035.90 +980.00 130433.50 16.31 3.00 2.10 50.92 -10.73 -0.80 0.00 0.00 2.32 3.61 1.70 -1.00 0.00 0.00 -5.63 1947.10 +981.00 145994.70 12.26 2.40 2.10 32.72 -7.80 -1.15 0.00 0.00 1.96 3.53 1.60 -1.00 0.00 0.00 -5.01 868.30 +982.00 130695.10 14.19 2.40 2.10 45.35 -10.22 -1.30 0.00 0.00 1.90 3.79 1.80 -1.00 0.00 0.00 -5.97 2208.70 +983.00 145593.60 10.21 1.60 2.10 25.62 -7.98 -0.87 0.00 0.00 1.38 2.87 0.90 -1.00 0.00 0.00 -5.90 467.20 +984.00 145743.70 18.51 2.50 2.10 58.84 -7.61 -1.63 0.00 0.00 2.01 3.64 1.70 -1.00 0.00 0.00 -7.37 617.30 +985.00 130367.10 34.85 2.80 2.10 117.97 -11.27 -0.48 0.00 0.00 1.09 3.80 1.90 -1.00 0.00 0.00 -25.49 1880.70 +986.00 146892.30 14.51 2.50 2.10 49.21 -6.91 -0.87 0.00 0.00 2.13 3.84 1.90 -1.00 0.00 0.00 -5.46 485.90 +987.00 130217.50 15.03 2.20 2.10 42.03 -9.42 0.29 0.00 0.00 2.00 3.30 1.70 -1.00 0.00 0.00 -6.02 1731.10 +988.00 130180.80 10.08 2.30 2.10 28.80 -11.25 0.39 0.00 0.00 2.04 3.47 1.50 -1.00 0.00 0.00 -3.95 1694.40 +989.00 130255.50 16.18 3.50 2.10 54.93 -9.79 -0.88 0.00 0.00 2.47 3.66 1.70 -1.00 0.00 0.00 -5.24 1769.10 +990.00 130287.80 22.13 2.80 2.10 74.38 -10.99 -0.07 0.00 0.00 1.67 3.98 2.00 -1.00 0.00 0.00 -10.60 1801.40 +991.00 147050.30 22.46 3.20 2.10 85.08 -7.85 0.36 0.00 0.00 2.80 4.48 2.50 -1.00 0.00 0.00 -6.43 643.90 +992.00 148290.00 12.55 1.90 2.10 36.46 -8.66 1.12 0.00 0.00 1.12 3.41 1.50 -1.00 0.00 0.00 -9.00 603.60 +993.00 130817.80 33.08 3.00 2.10 107.89 -10.34 -0.22 0.00 0.00 2.25 3.67 1.70 -1.00 0.00 0.00 -11.75 2331.40 +994.00 130940.90 15.56 2.20 11.10 159.62 -9.32 0.35 0.00 0.00 1.95 3.87 1.60 -1.00 0.00 0.00 -6.38 227.30 +995.00 131776.60 11.29 3.00 2.10 38.69 -9.10 0.12 0.00 0.00 2.49 4.24 2.30 -1.00 0.00 0.00 -3.63 730.20 +996.00 131716.80 13.48 2.00 2.10 35.39 -11.17 -1.76 0.00 0.00 1.72 2.78 1.30 -1.00 0.00 0.00 -6.29 670.40 +997.00 132219.80 10.83 2.20 2.10 30.94 -9.28 0.31 0.00 0.00 1.95 3.54 1.60 -1.00 0.00 0.00 -4.45 1173.40 +998.00 132662.70 10.25 3.00 2.10 36.97 -8.95 -0.69 0.00 0.00 2.83 3.65 2.10 -1.00 0.00 0.00 -2.90 336.30 +999.00 133007.90 14.35 2.40 2.10 38.38 -11.65 -1.94 0.00 0.00 1.81 2.93 1.00 -1.00 0.00 0.00 -6.34 681.50 +1000.00 132900.90 14.58 2.10 2.10 44.23 -11.15 1.30 0.00 0.00 1.57 3.56 1.60 -1.00 0.00 0.00 -7.45 574.50 +1001.00 131703.90 11.96 1.90 2.10 32.16 -10.09 2.10 0.00 0.00 1.68 3.52 1.60 -1.00 0.00 0.00 -5.69 657.50 +1002.00 144679.70 26.71 2.50 2.10 85.01 -7.46 1.66 0.00 0.00 1.94 3.58 1.60 -1.00 0.00 0.00 -10.99 833.30 +1003.00 131031.70 23.70 3.80 2.10 86.51 -9.89 0.44 0.00 0.00 3.47 4.53 2.60 -1.00 0.00 0.00 -5.46 2545.30 +1004.00 145358.70 18.79 1.80 2.10 51.32 -8.04 -0.69 0.00 0.00 1.35 3.16 1.20 -1.00 0.00 0.00 -11.11 232.30 +1005.00 145329.90 22.80 2.10 2.10 65.26 -7.78 -1.25 0.00 0.00 1.76 3.15 1.20 -1.00 0.00 0.00 -10.35 203.50 +1006.00 145236.00 15.37 2.00 2.10 46.91 -7.99 1.65 0.00 0.00 1.57 3.25 1.30 -1.00 0.00 0.00 -7.80 109.60 +1007.00 144947.10 16.32 2.40 2.10 49.50 -7.53 -0.49 0.00 0.00 2.11 3.77 1.80 -1.00 0.00 0.00 -6.18 1100.70 +1008.00 131239.40 14.55 1.90 2.10 38.67 -9.42 2.02 0.00 0.00 1.72 2.81 1.60 -1.00 0.00 0.00 -6.78 193.00 +1009.00 142078.00 14.91 1.90 2.10 39.92 -7.99 -0.42 0.00 0.00 1.46 3.21 1.40 -1.00 0.00 0.00 -8.16 791.60 +1010.00 117658.40 26.19 2.90 2.10 96.52 -9.96 0.34 0.00 0.00 2.20 4.22 2.30 -1.00 0.00 0.00 -9.51 1127.20 +1011.00 153713.60 18.06 1.80 2.10 50.54 -9.54 1.13 0.00 0.00 1.63 3.37 1.40 -1.00 0.00 0.00 -8.87 907.20 +1012.00 103324.40 13.22 3.20 2.10 35.88 -8.41 0.46 0.00 0.00 2.77 3.05 1.10 -1.00 0.00 0.00 -3.82 873.20 +1013.00 103362.40 22.30 3.80 2.10 101.60 -10.08 -1.99 0.00 0.00 2.98 5.34 3.40 -1.00 0.00 0.00 -5.99 911.20 +1014.00 103410.00 19.93 2.30 2.10 61.80 -9.45 -0.25 0.00 0.00 1.89 3.63 1.70 -1.00 0.00 0.00 -8.41 958.80 +1015.00 104205.70 20.26 2.50 2.10 68.70 -7.80 0.34 0.00 0.00 1.80 3.58 1.60 -1.00 0.00 0.00 -9.02 474.50 +1016.00 103929.70 34.56 2.90 2.10 110.26 -7.57 -2.36 0.00 0.00 1.84 3.43 1.50 -1.00 0.00 0.00 -15.02 198.50 +1017.00 103186.60 13.24 2.00 2.10 36.74 -8.30 -0.32 0.00 0.00 1.80 3.48 1.50 -1.00 0.00 0.00 -5.89 735.40 +1018.00 102957.70 11.51 1.90 2.10 26.15 -8.12 -0.71 0.00 0.00 1.23 2.72 0.80 -1.00 0.00 0.00 -7.46 506.50 +1019.00 101804.30 18.84 2.50 2.10 61.25 -7.36 0.03 0.00 0.00 2.23 3.84 1.90 -1.00 0.00 0.00 -6.75 633.10 +1020.00 101658.10 16.58 2.90 2.10 51.39 -7.09 -0.20 0.00 0.00 2.67 4.07 2.10 -1.00 0.00 0.00 -4.97 486.90 +1021.00 102314.60 21.48 2.70 2.10 70.99 -8.00 1.25 0.00 0.00 2.14 3.79 1.80 -1.00 0.00 0.00 -8.03 1143.40 +1022.00 154037.90 13.18 2.70 2.10 43.24 -8.11 -2.03 0.00 0.00 2.53 3.17 2.10 -1.00 0.00 0.00 -4.16 1231.50 +1023.00 102874.70 22.17 1.90 2.10 62.22 -8.77 -0.04 0.00 0.00 1.61 3.42 1.50 -1.00 0.00 0.00 -11.00 423.50 +1024.00 102565.40 11.16 1.90 2.10 27.37 -8.38 0.62 0.00 0.00 1.52 2.72 1.50 -1.00 0.00 0.00 -5.88 114.20 +1025.00 104499.90 10.47 1.70 2.10 23.77 -8.22 0.18 0.00 0.00 1.48 2.66 0.90 -1.00 0.00 0.00 -5.66 768.70 +1026.00 104570.40 15.84 2.30 2.10 48.14 -8.60 -0.24 0.00 0.00 2.04 3.57 1.60 -1.00 0.00 0.00 -6.21 839.20 +1027.00 105947.10 17.92 2.00 2.10 54.71 -7.65 0.24 0.00 0.00 1.45 3.45 1.50 -1.00 0.00 0.00 -9.89 935.90 +1028.00 105857.90 13.54 4.10 2.10 51.32 -8.04 0.68 0.00 0.00 2.91 4.47 2.50 -1.00 0.00 0.00 -3.72 846.70 +1029.00 106136.30 18.12 2.40 2.10 60.79 -5.99 -0.59 0.00 0.00 2.19 3.78 1.80 -1.00 0.00 0.00 -6.63 1125.10 +1030.00 106722.90 17.25 2.10 2.10 51.82 -6.76 1.65 0.00 0.00 1.48 3.50 1.60 -1.00 0.00 0.00 -9.33 431.70 +1031.00 117590.40 23.58 4.80 2.10 92.24 -7.68 -0.39 0.00 0.00 3.04 4.53 2.60 -1.00 0.00 0.00 -6.20 1059.20 +1032.00 153096.80 11.00 3.60 2.10 34.95 -8.40 0.28 0.00 0.00 2.53 3.50 1.80 -1.00 0.00 0.00 -3.47 290.40 +1033.00 105637.80 12.91 2.90 2.10 40.68 -7.37 0.67 0.00 0.00 2.06 3.81 1.90 -1.00 0.00 0.00 -5.01 626.60 +1034.00 105551.20 16.67 2.70 2.10 52.65 -7.97 -1.25 0.00 0.00 2.14 3.69 1.70 -1.00 0.00 0.00 -6.24 540.00 +1035.00 104867.60 23.40 2.50 2.10 69.64 -8.95 0.57 0.00 0.00 1.74 3.26 1.30 -1.00 0.00 0.00 -10.79 1136.40 +1036.00 104713.20 11.68 3.70 2.10 45.15 -8.15 -0.52 0.00 0.00 3.54 3.71 3.10 -1.00 0.00 0.00 -2.64 982.00 +1037.00 105170.10 13.64 2.50 2.10 40.75 -7.57 0.73 0.00 0.00 1.82 3.24 1.30 -1.00 0.00 0.00 -6.00 158.90 +1038.00 105317.10 13.89 1.10 2.10 32.53 -7.50 -0.01 0.00 0.00 0.93 2.66 0.70 -1.00 0.00 0.00 -11.90 305.90 +1039.00 153264.40 10.12 1.40 2.10 23.95 -8.22 1.71 0.00 0.00 1.27 2.87 0.90 -1.00 0.00 0.00 -6.39 458.00 +1040.00 105377.00 17.37 2.00 2.10 46.40 -7.25 0.36 0.00 0.00 1.66 3.36 1.40 -1.00 0.00 0.00 -8.36 365.80 +1041.00 154074.60 14.56 2.70 2.10 51.42 -8.98 -2.17 0.00 0.00 1.34 3.77 1.80 -1.00 0.00 0.00 -8.72 1268.20 +1042.00 101554.80 25.53 2.90 2.10 87.26 -6.84 -0.05 0.00 0.00 2.09 3.91 2.00 -1.00 0.00 0.00 -9.78 383.60 +1043.00 95641.20 15.27 3.20 2.10 59.40 -6.78 0.34 0.00 0.00 2.59 4.27 2.30 -1.00 0.00 0.00 -4.71 870.00 +1044.00 95487.70 11.72 2.20 2.10 30.01 -7.50 -1.25 0.00 0.00 1.87 2.66 1.40 -1.00 0.00 0.00 -5.01 716.50 +1045.00 95674.30 11.14 2.00 2.10 27.86 -9.85 1.02 0.00 0.00 1.73 2.54 1.30 -1.00 0.00 0.00 -5.14 903.10 +1046.00 95990.50 16.74 2.80 2.10 59.34 -7.96 -2.57 0.00 0.00 2.59 4.45 2.50 -1.00 0.00 0.00 -5.17 1219.30 +1047.00 96326.10 14.53 2.70 2.10 37.29 -8.25 0.44 0.00 0.00 1.44 2.36 0.90 -1.00 0.00 0.00 -8.09 274.90 +1048.00 96293.00 15.55 2.50 2.10 51.08 -8.16 -0.73 0.00 0.00 1.62 4.00 2.10 -1.00 0.00 0.00 -7.68 241.80 +1049.00 155211.80 21.09 2.80 2.10 60.92 -9.24 -0.64 0.00 0.00 1.40 3.09 1.10 -1.00 0.00 0.00 -12.07 1125.40 +1050.00 95397.00 14.04 2.50 2.10 41.68 -7.21 -0.86 0.00 0.00 1.71 3.40 1.40 -1.00 0.00 0.00 -6.59 625.80 +1051.00 93137.80 17.82 2.50 2.10 60.69 -8.09 1.93 0.00 0.00 2.13 3.96 2.00 -1.00 0.00 0.00 -6.71 926.60 +1052.00 92724.70 12.82 1.70 2.10 33.09 -8.31 -3.02 0.00 0.00 0.93 2.97 1.00 -1.00 0.00 0.00 -11.02 513.50 +1053.00 155373.50 12.62 1.10 2.10 27.95 -8.84 3.01 0.00 0.00 0.68 2.29 0.30 -1.00 0.00 0.00 -14.90 7.10 +1054.00 93434.40 11.91 2.20 2.10 35.24 -7.32 -1.52 0.00 0.00 1.82 3.26 1.40 -1.00 0.00 0.00 -5.23 1223.20 +1055.00 95102.90 11.88 3.40 2.10 39.09 -7.58 -0.19 0.00 0.00 2.62 4.15 2.20 -1.00 0.00 0.00 -3.63 331.70 +1056.00 94198.30 14.99 3.00 2.10 55.07 -7.83 1.07 0.00 0.00 2.72 4.29 2.40 -1.00 0.00 0.00 -4.40 707.10 +1057.00 96723.70 16.68 2.20 2.10 48.37 -7.28 1.00 0.00 0.00 1.86 3.51 1.60 -1.00 0.00 0.00 -7.19 672.50 +1058.00 96823.20 13.55 4.20 2.10 50.18 -6.76 -0.55 0.00 0.00 3.78 2.12 0.30 -1.00 0.00 0.00 -2.87 772.00 +1059.00 99134.50 13.03 2.60 2.10 41.46 -7.57 0.39 0.00 0.00 2.12 3.45 1.80 -1.00 0.00 0.00 -4.92 523.30 +1060.00 98586.50 16.92 2.40 2.10 54.60 -8.43 -0.81 0.00 0.00 1.92 3.86 1.90 -1.00 0.00 0.00 -7.07 1255.30 +1061.00 99419.10 10.53 3.10 2.10 28.22 -6.76 -0.60 0.00 0.00 2.88 2.13 1.30 -1.00 0.00 0.00 -2.93 807.90 +1062.00 154453.30 22.03 6.50 5.00 110.24 -7.29 -0.93 0.00 0.00 2.12 5.36 1.30 -1.00 0.00 0.00 -8.30 34.10 +1063.00 101166.10 20.80 2.40 2.10 73.20 -8.28 -0.08 0.00 0.00 1.07 3.92 2.00 -1.00 0.00 0.00 -15.49 1274.90 +1064.00 100625.20 13.24 3.00 2.10 34.55 -7.56 0.61 0.00 0.00 1.60 2.78 0.80 -1.00 0.00 0.00 -6.63 734.00 +1065.00 98532.40 14.09 3.60 2.10 62.79 -7.80 -1.81 0.00 0.00 3.29 5.04 3.10 -1.00 0.00 0.00 -3.43 1201.20 +1066.00 98431.70 17.55 3.00 2.10 68.20 -6.75 1.16 0.00 0.00 2.85 4.57 2.60 -1.00 0.00 0.00 -4.93 1100.50 +1067.00 96862.90 21.14 3.90 2.10 93.07 -7.86 0.08 0.00 0.00 3.32 5.21 3.30 -1.00 0.00 0.00 -5.10 811.70 +1068.00 155176.90 21.50 2.20 2.10 57.06 -8.61 1.77 0.00 0.00 1.91 2.82 1.20 -1.00 0.00 0.00 -8.99 1090.50 +1069.00 155131.80 13.27 1.60 2.10 33.55 -8.60 0.05 0.00 0.00 1.43 3.10 1.10 -1.00 0.00 0.00 -7.45 1045.40 +1070.00 97593.80 18.90 2.30 2.10 56.75 -7.23 2.49 0.00 0.00 2.04 3.67 1.70 -1.00 0.00 0.00 -7.39 262.60 +1071.00 97788.60 23.07 3.10 2.10 72.15 -6.36 0.20 0.00 0.00 1.12 3.40 1.50 -1.00 0.00 0.00 -16.45 457.40 +1072.00 107341.00 16.93 2.30 2.10 56.77 -6.33 0.14 0.00 0.00 1.40 3.60 1.60 -1.00 0.00 0.00 -9.70 1049.80 +1073.00 107293.60 16.22 3.40 2.10 59.74 -7.71 -1.14 0.00 0.00 2.98 4.17 2.20 -1.00 0.00 0.00 -4.36 1002.40 +1074.00 112524.50 13.01 3.90 2.10 53.60 -8.04 -2.25 0.00 0.00 3.54 4.28 3.10 -1.00 0.00 0.00 -2.94 1113.30 +1075.00 151717.40 24.14 1.90 2.10 62.38 -8.08 0.70 0.00 0.00 1.20 2.96 1.10 -1.00 0.00 0.00 -16.14 191.00 +1076.00 112547.80 10.89 2.10 2.10 28.97 -11.39 -1.42 0.00 0.00 1.62 3.14 1.40 -1.00 0.00 0.00 -5.39 1136.60 +1077.00 112833.20 12.17 2.00 2.10 36.59 -8.31 -2.27 0.00 0.00 1.76 3.20 1.30 -1.00 0.00 0.00 -5.55 142.00 +1078.00 113068.80 12.62 1.60 2.10 33.86 -8.19 2.03 0.00 0.00 1.31 3.07 1.10 -1.00 0.00 0.00 -7.73 377.60 +1079.00 112986.50 20.08 2.60 2.10 63.52 -7.27 -0.38 0.00 0.00 1.48 3.62 1.70 -1.00 0.00 0.00 -10.85 295.30 +1080.00 112132.70 12.77 1.60 2.10 31.17 -8.58 0.71 0.00 0.00 1.41 2.90 0.90 -1.00 0.00 0.00 -7.24 721.50 +1081.00 112105.50 13.57 2.10 2.10 40.53 -7.07 -1.45 0.00 0.00 1.83 3.56 1.60 -1.00 0.00 0.00 -5.93 694.30 +1082.00 111536.30 10.01 2.20 2.10 26.07 -7.63 -0.82 0.00 0.00 2.00 3.52 1.60 -1.00 0.00 0.00 -4.00 125.10 +1083.00 107360.50 12.00 3.90 2.10 41.74 -8.55 0.10 0.00 0.00 3.10 3.95 2.60 -1.00 0.00 0.00 -3.09 1069.30 +1084.00 111696.60 21.30 2.60 2.10 70.86 -7.66 -0.59 0.00 0.00 2.00 3.76 1.80 -1.00 0.00 0.00 -8.54 285.40 +1085.00 111876.10 17.97 1.70 2.10 45.63 -7.87 -2.12 0.00 0.00 1.38 2.89 0.90 -1.00 0.00 0.00 -10.42 464.90 +1086.00 111963.80 12.86 2.40 2.10 37.59 -8.59 -0.60 0.00 0.00 1.75 3.47 1.50 -1.00 0.00 0.00 -5.89 552.60 +1087.00 111935.70 15.86 2.80 2.10 49.66 -8.37 1.47 0.00 0.00 2.50 3.58 1.60 -1.00 0.00 0.00 -5.07 524.50 +1088.00 113146.10 11.63 1.80 2.10 30.95 -7.53 -1.00 0.00 0.00 1.19 3.35 1.40 -1.00 0.00 0.00 -7.79 454.90 +1089.00 113558.70 11.67 2.10 2.10 31.18 -7.39 0.54 0.00 0.00 1.77 2.91 1.30 -1.00 0.00 0.00 -5.28 867.50 +1090.00 116597.60 12.25 2.50 2.10 40.56 -7.85 0.14 0.00 0.00 2.17 3.51 2.20 -1.00 0.00 0.00 -4.52 66.40 +1091.00 116348.00 12.02 3.10 2.10 36.42 -7.81 -2.06 0.00 0.00 2.15 3.58 1.60 -1.00 0.00 0.00 -4.47 1096.80 +1092.00 116686.00 14.91 2.20 2.10 45.54 -8.17 -0.49 0.00 0.00 1.92 3.55 1.60 -1.00 0.00 0.00 -6.22 154.80 +1093.00 116776.40 13.28 2.60 2.10 43.35 -8.77 2.66 0.00 0.00 2.33 4.24 2.30 -1.00 0.00 0.00 -4.56 245.20 +1094.00 117176.00 12.98 1.80 2.10 35.84 -7.89 1.68 0.00 0.00 1.56 3.09 1.10 -1.00 0.00 0.00 -6.66 644.80 +1095.00 117125.10 12.68 2.70 2.10 41.91 -7.24 -0.13 0.00 0.00 2.53 3.89 1.90 -1.00 0.00 0.00 -4.01 593.90 +1096.00 116009.10 11.96 4.10 2.10 42.62 -8.09 -1.16 0.00 0.00 2.59 3.63 2.10 -1.00 0.00 0.00 -3.70 757.90 +1097.00 115861.70 13.57 1.60 2.10 31.11 -8.42 -2.02 0.00 0.00 1.24 2.66 0.90 -1.00 0.00 0.00 -8.77 610.50 +1098.00 114065.00 22.81 2.80 2.10 77.30 -8.64 1.08 0.00 0.00 2.36 3.90 1.90 -1.00 0.00 0.00 -7.75 93.80 +1099.00 113942.20 14.19 2.30 2.10 41.46 -8.62 0.07 0.00 0.00 2.07 3.49 1.50 -1.00 0.00 0.00 -5.49 1251.00 +1100.00 114349.30 30.19 3.30 2.10 110.25 -6.65 1.11 0.00 0.00 2.80 4.05 2.10 -1.00 0.00 0.00 -8.61 378.10 +1101.00 114996.20 13.35 2.30 2.10 42.40 -7.06 -0.66 0.00 0.00 2.01 3.72 1.80 -1.00 0.00 0.00 -5.30 1025.00 +1102.00 115105.10 11.72 1.90 2.10 30.53 -6.83 -1.54 0.00 0.00 1.29 2.84 0.90 -1.00 0.00 0.00 -7.29 1133.90 +1103.00 111114.70 23.31 2.00 2.10 64.00 -9.37 0.97 0.00 0.00 1.28 3.27 1.30 -1.00 0.00 0.00 -14.58 983.50 +1104.00 152021.00 12.09 2.30 2.10 35.71 -7.51 -0.60 0.00 0.00 1.92 3.72 1.80 -1.00 0.00 0.00 -5.05 494.60 +1105.00 108926.40 16.58 2.70 2.10 59.98 -7.46 0.87 0.00 0.00 2.15 4.01 2.10 -1.00 0.00 0.00 -6.18 75.20 +1106.00 152791.30 13.61 1.70 2.10 33.06 -8.76 -1.06 0.00 0.00 1.35 3.01 1.10 -1.00 0.00 0.00 -8.09 1264.90 +1107.00 152072.10 16.30 2.80 2.10 47.85 -7.70 0.79 0.00 0.00 2.20 3.39 1.40 -1.00 0.00 0.00 -5.93 545.70 +1108.00 109143.30 13.77 3.10 2.10 46.73 -6.29 -0.72 0.00 0.00 2.43 4.06 2.10 -1.00 0.00 0.00 -4.53 292.10 +1109.00 109182.00 10.07 2.10 2.10 26.58 -7.71 -0.53 0.00 0.00 1.73 3.36 1.70 -1.00 0.00 0.00 -4.65 330.80 +1110.00 107972.40 10.43 3.10 2.10 37.65 -7.23 -2.50 0.00 0.00 2.87 4.41 2.50 -1.00 0.00 0.00 -2.90 401.20 +1111.00 108680.90 14.69 2.00 2.10 40.59 -5.92 -0.95 0.00 0.00 1.77 3.19 1.20 -1.00 0.00 0.00 -6.62 1109.70 +1112.00 108009.60 11.07 3.20 2.10 37.60 -8.04 -1.22 0.00 0.00 2.98 3.77 2.40 -1.00 0.00 0.00 -2.98 438.40 +1113.00 108110.30 10.87 2.40 2.10 27.10 -8.68 1.68 0.00 0.00 2.00 2.14 1.00 -1.00 0.00 0.00 -4.35 539.10 +1114.00 108245.40 12.82 1.70 2.10 32.14 -7.14 -1.09 0.00 0.00 1.46 3.05 1.10 -1.00 0.00 0.00 -7.04 674.20 +1115.00 108384.40 19.82 3.20 2.10 61.50 -6.39 1.49 0.00 0.00 1.98 3.54 1.60 -1.00 0.00 0.00 -8.02 813.20 +1116.00 108650.50 15.92 2.20 2.10 48.10 -7.20 1.13 0.00 0.00 1.78 3.62 1.70 -1.00 0.00 0.00 -7.15 1079.30 +1117.00 109329.50 14.70 2.90 2.10 48.78 -9.53 0.00 0.00 0.00 2.01 3.60 1.60 -1.00 0.00 0.00 -5.86 478.30 +1118.00 109652.10 14.92 2.40 2.10 46.58 -6.96 0.35 0.00 0.00 1.99 3.19 1.20 -1.00 0.00 0.00 -5.99 800.90 +1119.00 152607.80 14.79 1.30 2.10 35.90 -9.04 1.16 0.00 0.00 1.02 2.85 0.90 -1.00 0.00 0.00 -11.58 1081.40 +1120.00 107677.40 22.93 4.30 2.10 78.06 -7.28 -0.92 0.00 0.00 1.20 3.88 1.90 -1.00 0.00 0.00 -15.30 106.20 +1121.00 107406.30 16.74 2.60 2.10 57.64 -7.25 -0.92 0.00 0.00 1.97 3.94 2.00 -1.00 0.00 0.00 -6.78 1115.10 +1122.00 110588.70 16.36 3.70 2.10 50.67 -8.22 -2.27 0.00 0.00 2.01 3.49 1.50 -1.00 0.00 0.00 -6.51 457.50 +1123.00 110927.80 10.60 1.90 2.10 22.67 -8.43 -0.08 0.00 0.00 1.74 2.10 1.00 -1.00 0.00 0.00 -4.87 796.60 +1124.00 110510.70 20.83 3.00 2.10 75.76 -8.36 1.84 0.00 0.00 2.46 4.22 2.30 -1.00 0.00 0.00 -6.77 379.50 +1125.00 153039.10 15.75 2.90 2.10 58.78 -8.34 1.66 0.00 0.00 2.13 4.07 2.10 -1.00 0.00 0.00 -5.92 232.70 +1126.00 109747.90 15.60 2.70 2.10 49.49 -7.07 1.36 0.00 0.00 2.32 3.43 1.90 -1.00 0.00 0.00 -5.39 896.70 +1127.00 107909.70 17.21 3.20 2.10 68.61 -8.01 -0.87 0.00 0.00 2.94 4.72 2.80 -1.00 0.00 0.00 -4.68 338.50 +1128.00 110449.50 26.47 1.70 2.10 75.03 -9.08 -1.88 0.00 0.00 1.05 3.28 1.30 -1.00 0.00 0.00 -20.10 318.30 +1129.00 110479.40 11.25 2.30 2.10 33.63 -8.98 0.56 0.00 0.00 2.09 3.43 1.50 -1.00 0.00 0.00 -4.30 348.20 +1130.00 107863.60 18.59 3.00 2.10 62.00 -7.26 -0.19 0.00 0.00 2.20 3.95 2.00 -1.00 0.00 0.00 -6.77 292.40 +1131.00 151181.50 12.41 11.40 8.20 127.55 -7.69 1.78 255.00 0.00 2.05 5.87 1.60 -1.00 0.00 0.00 -4.85 218.30 +1132.00 160956.60 16.68 4.70 10.30 154.42 -17.95 -2.05 255.00 0.00 4.46 10.42 0.70 -1.00 0.00 0.00 -3.00 137.40 +1133.00 157444.40 20.61 10.90 8.20 209.05 -7.90 -0.41 255.00 0.00 10.70 4.15 1.20 -1.00 0.00 0.00 -1.54 81.20 +1134.00 17524.60 11.63 6.60 2.10 51.45 -7.77 0.31 255.00 0.00 6.27 1.62 0.30 -1.00 0.00 0.00 -1.48 14.20 +1135.00 17551.80 10.98 4.00 2.10 41.25 -9.19 -0.82 255.00 0.00 3.82 0.84 0.30 -1.00 0.00 0.00 -2.30 41.40 +1136.00 157456.40 10.77 1.70 2.00 27.06 -19.93 -1.32 255.00 0.00 1.60 2.65 1.30 -1.00 0.00 0.00 -5.39 93.20 +1137.00 152795.40 16.83 5.80 4.30 111.37 -8.52 -0.31 255.00 0.00 5.50 5.11 2.00 -1.00 0.00 0.00 -2.45 296.20 +1138.00 3844.80 11.80 6.50 1.70 56.02 -8.41 0.97 255.00 0.00 6.40 3.34 2.30 -1.00 0.00 0.00 -1.48 158.40 +1139.00 160961.20 23.02 9.80 6.30 227.30 -13.55 0.51 255.00 0.00 8.87 10.70 5.30 -1.00 0.00 0.00 -2.08 142.00 +1140.00 47805.30 12.68 2.50 4.80 55.06 -7.11 -0.35 255.00 0.00 1.84 3.40 1.60 -1.00 0.00 0.00 -5.50 86.90 +1141.00 227535.60 15.60 5.60 2.90 74.43 -12.95 4.77 255.00 0.00 5.06 3.27 1.10 -1.00 0.00 0.00 -2.47 105.20 +1142.00 111071.00 21.19 5.60 3.70 132.48 -9.80 -2.58 255.00 0.00 5.38 6.93 5.00 -1.00 0.00 0.00 -3.15 376.60 +1143.00 269859.50 16.14 2.00 3.50 52.65 -13.63 -0.59 255.00 0.00 1.55 3.35 1.50 -1.00 0.00 0.00 -8.31 265.90 +1144.00 108722.50 12.71 43.60 5.50 334.65 -6.24 2.14 255.00 0.00 2.56 6.05 1.80 -1.00 0.00 0.00 -3.98 332.10 +1145.00 108700.80 13.26 21.80 5.60 179.48 -7.47 -0.02 255.00 0.00 4.76 4.92 1.90 -1.00 0.00 0.00 -2.23 310.40 +1146.00 111132.20 10.96 2.90 2.10 35.95 -11.27 1.27 255.00 0.00 2.73 3.41 2.30 -1.00 0.00 0.00 -3.21 1001.00 +1147.00 112320.80 15.39 2.50 5.90 78.20 -8.55 -0.65 255.00 0.00 2.33 4.16 1.90 -1.00 0.00 0.00 -5.28 90.40 +1148.00 219657.70 37.85 7.70 5.90 296.65 -9.17 -0.84 255.00 0.00 6.37 5.55 1.90 -1.00 0.00 0.00 -4.75 35.30 +1149.00 118991.10 13.36 8.60 6.50 124.95 -9.04 -0.71 255.00 0.00 8.11 6.45 1.00 -1.00 0.00 0.00 -1.32 232.70 +1150.00 57663.40 21.97 9.00 4.40 175.88 -7.97 1.17 255.00 0.00 8.39 5.45 2.20 -1.00 0.00 0.00 -2.09 345.00 +1151.00 115782.10 19.60 6.10 6.80 138.88 -8.22 0.10 255.00 0.00 5.79 5.06 1.60 -1.00 0.00 0.00 -2.71 95.70 +1152.00 59658.30 25.23 9.60 6.20 236.49 -7.67 -1.31 255.00 0.00 8.58 5.28 2.40 -1.00 0.00 0.00 -2.35 35.90 +1153.00 232103.00 10.98 2.70 2.00 34.47 -18.53 -3.47 255.00 0.00 2.51 3.41 2.30 -1.00 0.00 0.00 -3.49 64.60 +1154.00 232998.70 12.52 2.00 2.10 32.49 -13.29 1.29 255.00 0.00 1.65 2.96 1.30 -1.00 0.00 0.00 -6.08 832.30 +1155.00 86094.50 12.97 11.30 4.70 145.89 -7.65 1.87 255.00 0.00 10.65 4.63 1.20 -1.00 0.00 0.00 -0.97 360.10 +1156.00 83097.90 11.43 4.60 2.10 44.69 -7.78 -1.73 255.00 0.00 3.72 3.73 3.10 -1.00 0.00 0.00 -2.46 1126.70 +1157.00 248554.00 17.40 14.90 8.50 264.20 -9.16 -0.87 255.00 0.00 14.58 5.29 1.10 -1.00 0.00 0.00 -0.95 80.40 +1158.00 88368.50 19.30 6.50 3.70 115.95 -9.27 1.35 255.00 0.00 6.04 4.14 1.20 -1.00 0.00 0.00 -2.56 330.10 +1159.00 243048.50 16.24 9.60 4.00 119.00 -8.94 1.67 255.00 0.00 2.02 4.00 1.50 -1.00 0.00 0.00 -6.44 258.10 +1160.00 238993.30 11.85 14.00 5.80 164.49 -8.45 0.36 255.00 0.00 12.77 6.48 3.10 -1.00 0.00 0.00 -0.74 42.90 +1161.00 80471.40 14.22 8.60 7.10 122.58 -8.89 -1.66 255.00 0.00 8.21 4.86 1.10 -1.00 0.00 0.00 -1.39 113.00 +1162.00 75068.60 20.94 7.40 5.80 149.28 -6.92 1.25 255.00 0.00 7.17 4.67 1.00 -1.00 0.00 0.00 -2.33 86.20 +1163.00 78148.30 22.31 6.90 5.50 137.43 -6.64 0.84 255.00 0.00 5.57 5.35 1.60 -1.00 0.00 0.00 -3.21 93.90 +1164.00 79148.90 13.11 3.30 2.10 43.12 -13.93 0.70 255.00 0.00 2.94 3.37 1.40 -1.00 0.00 0.00 -3.56 1017.70 +1165.00 79451.60 11.85 2.40 2.10 30.72 -11.05 -2.26 255.00 0.00 2.07 3.07 1.60 -1.00 0.00 0.00 -4.58 40.40 +1166.00 290135.10 13.46 13.70 5.80 164.81 -10.42 -1.11 255.00 0.00 1.77 3.79 0.90 -1.00 0.00 0.00 -6.08 189.50 +1167.00 122983.60 10.84 9.40 4.20 81.62 -10.31 0.11 255.00 0.00 8.93 3.35 2.00 -1.00 0.00 0.00 -0.97 129.20 +1168.00 189767.90 21.36 9.90 3.80 157.62 -7.55 0.53 255.00 0.00 9.59 3.91 2.30 -1.00 0.00 0.00 -1.78 97.50 +1169.00 186970.50 23.56 8.10 6.50 211.62 -8.19 0.64 255.00 0.00 7.26 5.81 1.80 -1.00 0.00 0.00 -2.60 372.10 +1170.00 189780.20 13.74 22.10 5.90 249.38 -7.88 1.30 255.00 0.00 21.79 4.14 1.10 -1.00 0.00 0.00 -0.50 109.80 +1171.00 31532.50 12.22 1.70 2.10 29.35 -12.16 2.13 255.00 0.00 1.21 2.83 1.00 -1.00 0.00 0.00 -8.11 326.10 +1172.00 131058.10 11.24 4.30 2.10 46.95 -13.68 1.07 255.00 0.00 4.11 0.67 0.50 -1.00 0.00 0.00 -2.19 11.70 +1173.00 27496.00 16.76 5.60 2.10 86.54 -8.96 -0.78 255.00 0.00 4.82 6.43 4.50 -1.00 0.00 0.00 -2.78 129.60 +1174.00 27429.10 11.00 10.50 2.10 78.84 -8.98 1.18 255.00 0.00 2.05 2.92 1.00 -1.00 0.00 0.00 -4.29 62.70 +1175.00 333221.50 24.46 7.10 6.60 176.61 -13.48 2.23 255.00 0.00 6.68 5.72 1.60 -1.00 0.00 0.00 -2.93 139.90 +1176.00 338520.00 19.09 11.00 4.90 198.81 -10.66 0.13 255.00 0.00 9.56 5.22 1.80 -1.00 0.00 0.00 -1.60 62.40 +1177.00 134928.10 23.93 5.40 7.20 179.63 -6.89 2.03 255.00 0.00 4.32 8.40 4.10 -1.00 0.00 0.00 -4.43 92.90 +1178.00 183287.10 14.61 13.10 6.90 223.67 -8.52 -0.90 255.00 0.00 12.93 5.43 0.60 -1.00 0.00 0.00 -0.90 144.70 +1179.00 134052.30 11.62 25.30 4.70 365.65 -9.19 0.38 255.00 0.00 1.91 2.88 1.40 -1.00 0.00 0.00 -4.87 266.70 +1180.00 130946.30 22.65 7.60 4.70 148.11 -9.69 0.43 255.00 0.00 7.22 4.38 1.70 -1.00 0.00 0.00 -2.51 232.70 +1181.00 130761.20 17.06 12.60 5.60 142.45 -9.94 -0.89 255.00 0.00 1.27 4.38 1.50 -1.00 0.00 0.00 -10.79 47.60 +1182.00 203732.30 15.59 5.30 4.00 89.56 -9.52 -0.41 255.00 0.00 4.94 4.66 1.90 -1.00 0.00 0.00 -2.52 237.90 +1183.00 306578.80 12.23 15.70 3.90 158.06 -10.98 -1.14 255.00 0.00 15.58 2.53 1.00 -1.00 0.00 0.00 -0.63 121.20 +1184.00 304258.10 14.32 5.20 5.40 88.89 -10.96 -0.82 255.00 0.00 4.76 3.47 1.20 -1.00 0.00 0.00 -2.41 104.50 +1185.00 124142.70 13.89 8.10 6.20 129.00 -7.30 0.57 255.00 0.00 7.57 3.96 0.80 -1.00 0.00 0.00 -1.47 136.30 +1186.00 48981.30 16.23 6.30 2.70 93.93 -7.44 -0.20 255.00 0.00 6.03 2.82 1.50 -1.00 0.00 0.00 -2.15 110.90 +1187.00 129006.20 12.90 11.30 3.70 155.37 -10.54 0.62 255.00 0.00 10.73 4.42 1.70 -1.00 0.00 0.00 -0.96 212.60 +1188.00 130296.90 17.21 11.50 3.90 184.60 -11.85 0.33 255.00 0.00 11.35 4.01 1.40 -1.00 0.00 0.00 -1.21 351.30 +1189.00 191347.60 18.91 2.20 2.10 52.03 -17.43 0.89 255.00 0.00 1.56 3.42 1.50 -1.00 0.00 0.00 -9.69 141.20 +1190.00 130543.80 24.03 6.00 3.80 115.65 -13.12 0.98 255.00 0.00 4.77 3.95 1.60 -1.00 0.00 0.00 -4.03 214.20 +1191.00 35028.00 12.99 7.30 3.10 101.61 -12.25 4.84 255.00 0.00 7.06 3.00 1.30 -1.00 0.00 0.00 -1.47 365.60 +1192.00 130303.80 14.04 18.80 4.70 271.23 -10.79 -0.66 255.00 0.00 18.27 4.38 2.50 -1.00 0.00 0.00 -0.61 358.20 +1193.00 174174.50 12.17 10.70 3.90 130.43 -8.34 -0.66 255.00 0.00 10.52 2.47 1.60 -1.00 0.00 0.00 -0.93 299.30 diff --git a/docs/api.rst b/docs/api.rst new file mode 100644 index 00000000..42fba27d --- /dev/null +++ b/docs/api.rst @@ -0,0 +1,18 @@ +API Reference +============= + +.. code-block:: python + + import nstat + print(nstat.__all__) + +Canonical modules include: + +- ``nstat.signal`` +- ``nstat.spikes`` +- ``nstat.trial`` +- ``nstat.analysis`` +- ``nstat.fit`` +- ``nstat.cif`` +- ``nstat.decoding`` +- ``nstat.datasets`` diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 00000000..ed1e91ea --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,6 @@ +project = "nSTAT Python" +author = "Cajigas Lab" +release = "0.1.0" +extensions = [] +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] +master_doc = "index" diff --git a/docs/help_topics.rst b/docs/help_topics.rst new file mode 100644 index 00000000..27eb8b8f --- /dev/null +++ b/docs/help_topics.rst @@ -0,0 +1,37 @@ +Help Topics +=========== + +.. toctree:: + :maxdepth: 1 + + topics/neuralspikeanalysis_top + topics/documentationsetup2025b + topics/classdefinitions + topics/signalobj + topics/fitresult + topics/examples + topics/signalobjexamples + topics/covariateexamples + topics/covcollexamples + topics/nspiketrainexamples + topics/nstcollexamples + topics/eventsexamples + topics/historyexamples + topics/trialexamples + topics/trialconfigexamples + topics/configcollexamples + topics/analysisexamples + topics/fitresultexamples + topics/fitressummaryexamples + topics/ppthinning + topics/psthestimation + topics/validationdataset + topics/mepscanalysis + topics/ppsimexample + topics/explicitstimuluswhiskerdata + topics/hippocampalplacecellexample + topics/decodingexample + topics/decodingexamplewithhist + topics/stimulusdecode2d + topics/networktutorial + topics/nstatpaperexamples diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 00000000..0f804f6f --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,12 @@ +nSTAT Python Documentation +========================== + +Standalone Python port of nSTAT with MATLAB-help topic coverage and executable notebooks. + +.. toctree:: + :maxdepth: 2 + + api + help_topics + parity_runbook + repo_split_status diff --git a/docs/parity_runbook.rst b/docs/parity_runbook.rst new file mode 100644 index 00000000..df68c9bb --- /dev/null +++ b/docs/parity_runbook.rst @@ -0,0 +1,75 @@ +Parity Runbook +============== + +Use this runbook for reproducible local/CI MATLAB parity checks on this machine. + +Validated environment +--------------------- + +- MATLAB binary: ``/Applications/MATLAB_R2025b.app/bin/matlab`` +- MATLAB args: ``-maca64 -nodisplay -noFigureWindows -softwareopengl`` +- Runner service mode: ``ACTIONS_RUNNER_SVC=1`` +- Force ``.m`` help scripts: ``NSTAT_FORCE_M_HELP_SCRIPTS=1`` +- Per-topic MATLAB retries: ``NSTAT_MATLAB_TOPIC_MAX_ATTEMPTS=2`` +- Stage C strict isolation: ``NSTAT_MATLAB_FORCE_TOPIC_ISOLATION=1`` +- Stage C hard cleanup on timeout/crash: ``NSTAT_MATLAB_HARD_CLEANUP_ON_FAILURE=1`` +- Ladder timeout-only retry: ``NSTAT_PARITY_RETRY_TIMEOUT_BLOCKS=1`` +- Ladder recoverable retry: ``NSTAT_PARITY_RETRY_RECOVERABLE_BLOCKS=1`` + +Preflight + staged parity +------------------------- + +Run Stage A + selected Stage B preflight: + +.. code-block:: bash + + ACTIONS_RUNNER_SVC=1 \ + NSTAT_FORCE_M_HELP_SCRIPTS=1 \ + NSTAT_MATLAB_EXTRA_ARGS='-maca64 -nodisplay -noFigureWindows -softwareopengl' \ + NSTAT_MATLAB_TOPIC_MAX_ATTEMPTS=2 \ + tools/run_parity_preflight.sh + +Run the staged ladder (core -> timeout -> graphics -> heavy-tail): + +.. code-block:: bash + + ACTIONS_RUNNER_SVC=1 \ + NSTAT_FORCE_M_HELP_SCRIPTS=1 \ + NSTAT_MATLAB_EXTRA_ARGS='-maca64 -nodisplay -noFigureWindows -softwareopengl' \ + NSTAT_MATLAB_TOPIC_MAX_ATTEMPTS=2 \ + NSTAT_PARITY_RETRY_TIMEOUT_BLOCKS=1 \ + NSTAT_PARITY_TIMEOUT_RETRY_BLOCKS=timeout_front \ + NSTAT_PARITY_RETRY_RECOVERABLE_BLOCKS=1 \ + NSTAT_PARITY_RECOVERABLE_RETRY_BLOCKS='graphics_mid,heavy_tail' \ + tools/run_parity_ladder.sh core_smoke timeout_front graphics_mid heavy_tail + +Full Stage C gate +----------------- + +Run full-suite parity gate report: + +.. code-block:: bash + + ACTIONS_RUNNER_SVC=1 \ + NSTAT_FORCE_M_HELP_SCRIPTS=1 \ + NSTAT_MATLAB_EXTRA_ARGS='-maca64 -nodisplay -noFigureWindows -softwareopengl' \ + NSTAT_MATLAB_TOPIC_MAX_ATTEMPTS=2 \ + NSTAT_MATLAB_FORCE_TOPIC_ISOLATION=1 \ + NSTAT_MATLAB_HARD_CLEANUP_ON_FAILURE=1 \ + python3 tools/verify_python_vs_matlab_similarity.py \ + --enforce-gate \ + --matlab-max-attempts 2 \ + --report-path reports/python_vs_matlab_similarity_report.json + +Useful outputs +-------------- + +- Full report: ``reports/python_vs_matlab_similarity_report.json`` +- Ladder retry telemetry: ``reports/parity_retry_summary.json`` +- Block reports: ``reports/parity_block_*.json`` +- Summary helper: + +.. code-block:: bash + + python3 tools/summarize_parity_report.py \ + reports/python_vs_matlab_similarity_report.json --json diff --git a/docs/python-nstat.md b/docs/python-nstat.md deleted file mode 100644 index 9a730435..00000000 --- a/docs/python-nstat.md +++ /dev/null @@ -1,81 +0,0 @@ -# Python nSTAT - -This page tracks the Python implementation of the nSTAT toolbox. - -## Scope - -The Python project aims to reproduce core nSTAT functionality while keeping API behavior consistent with the MATLAB toolbox where practical. - -Priority areas: - -- Core signal and covariate objects -- Point-process GLM fitting -- Model diagnostics and summary statistics -- Simulation workflows used by published examples -- Decoding algorithms - -## Status - -Current phase: foundation and architecture planning. - -Not yet complete: - -- Public Python package -- Full class-by-class feature parity -- End-to-end benchmark parity suite against MATLAB outputs - -## Proposed Python stack - -- `numpy`, `scipy` -- `pandas` -- `statsmodels` (where appropriate) -- `matplotlib` -- `scikit-learn` (for selected utilities) -- `pytest` for testing - -## Repository plan - -Proposed layout for Python code: - -- `python/nstat/` for package source -- `python/tests/` for unit and parity tests -- `python/examples/` for executable notebooks/scripts - -## Validation strategy - -Each major Python module should be validated against MATLAB reference outputs for: - -- Conditional intensity estimates -- Fitted coefficients and confidence intervals -- Goodness-of-fit metrics (e.g., KS diagnostics) -- Simulation output statistics - -## Contribution workflow - -1. Branch from `codex/python-nstat`. -2. Implement a focused module or feature. -3. Add tests and MATLAB parity checks. -4. Open a pull request that includes the problem statement, implementation summary, and validation evidence. - -## Short-term roadmap - -1. Create package skeleton and CI checks. -2. Implement base data structures (`SignalObj`, `Covariate`, `nspikeTrain` equivalents). -3. Implement point-process GLM fitting pipeline. -4. Port one end-to-end simulation + fit example. - -## Example uses - -Runnable examples are available in `python/examples/`. - -- `python/examples/basic_data_workflow.py` -- `python/examples/simulate_population_psth.py` -- `python/examples/fit_poisson_glm.py` - -Run from repository root: - -```bash -python3 python/examples/basic_data_workflow.py -python3 python/examples/simulate_population_psth.py -python3 python/examples/fit_poisson_glm.py -``` diff --git a/docs/repo_split_status.rst b/docs/repo_split_status.rst new file mode 100644 index 00000000..1afe51fb --- /dev/null +++ b/docs/repo_split_status.rst @@ -0,0 +1,57 @@ +Repo Split Status +================= + +Scope +----- + +This document tracks readiness for splitting the current monorepo into: + +- ``nSTAT`` (MATLAB-focused repository) +- ``nSTAT-python`` (Python-focused repository) + +Inventory Source +---------------- + +Generated via: + +.. code-block:: bash + + python3 tools/generate_repo_split_inventory.py + +Output directory: + +- ``python/reports/repo_split_inventory`` +- ``reports/repo_split_inventory`` + +Current Snapshot +---------------- + +- TOC topics: 31 +- TOC example topics: 25 +- Python docs coverage (TOC topics): 31/31 +- Python notebook coverage (TOC topics): 29/31 +- Python example script coverage (TOC examples): 25/25 +- Python example full coverage (docs + notebook + script): 25/25 +- MATLAB example topics with ``.mlx``: 18/25 + +MATLAB MLX Gaps +--------------- + +The following example topics currently do not have a matching ``helpfiles/.mlx``: + +- ``ExplicitStimulusWhiskerData`` +- ``NetworkTutorial`` +- ``PPThinning`` +- ``PSTHEstimation`` +- ``StimulusDecode2D`` +- ``ValidationDataSet`` +- ``mEPSCAnalysis`` + +Immediate Next Actions +---------------------- + +1. Keep ``nSTAT`` as source-of-truth for MATLAB ``helpfiles`` and create missing ``.mlx`` examples for the 7 topics above. +2. Keep ``nSTAT-python`` standalone and run parity/docs/notebook CI in this repository. +3. Update cross-repo README links: + - ``nSTAT`` -> points Python users to ``nSTAT-python``. + - ``nSTAT-python`` -> points MATLAB users to ``nSTAT``. diff --git a/docs/topics/analysisexamples.rst b/docs/topics/analysisexamples.rst new file mode 100644 index 00000000..606182af --- /dev/null +++ b/docs/topics/analysisexamples.rst @@ -0,0 +1,47 @@ +Using the Analysis Class +======================== + +MATLAB help target: ``AnalysisExamples.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``Analysis`` + - ``nstat.analysis.Analysis`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. + +Notebook +-------- +A generated executable notebook is available at ``notebooks/helpfiles/AnalysisExamples.ipynb``. diff --git a/docs/topics/classdefinitions.rst b/docs/topics/classdefinitions.rst new file mode 100644 index 00000000..d38cff8d --- /dev/null +++ b/docs/topics/classdefinitions.rst @@ -0,0 +1,43 @@ +Class Definitions +================= + +MATLAB help target: ``ClassDefinitions.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``ClassDefinitions`` + - ``nstat (canonical module by topic)`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. diff --git a/docs/topics/configcollexamples.rst b/docs/topics/configcollexamples.rst new file mode 100644 index 00000000..ff893c9a --- /dev/null +++ b/docs/topics/configcollexamples.rst @@ -0,0 +1,47 @@ +Using the ConfigColl Class +========================== + +MATLAB help target: ``ConfigCollExamples.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``ConfigColl`` + - ``nstat.trial.ConfigCollection`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. + +Notebook +-------- +A generated executable notebook is available at ``notebooks/helpfiles/ConfigCollExamples.ipynb``. diff --git a/docs/topics/covariateexamples.rst b/docs/topics/covariateexamples.rst new file mode 100644 index 00000000..9a3bbc54 --- /dev/null +++ b/docs/topics/covariateexamples.rst @@ -0,0 +1,47 @@ +Using the Covariate Class +========================= + +MATLAB help target: ``CovariateExamples.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``Covariate`` + - ``nstat.signal.Covariate`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. + +Notebook +-------- +A generated executable notebook is available at ``notebooks/helpfiles/CovariateExamples.ipynb``. diff --git a/docs/topics/covcollexamples.rst b/docs/topics/covcollexamples.rst new file mode 100644 index 00000000..7347a1ef --- /dev/null +++ b/docs/topics/covcollexamples.rst @@ -0,0 +1,47 @@ +Using the CovColl Class +======================= + +MATLAB help target: ``CovCollExamples.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``CovColl`` + - ``nstat.trial.CovariateCollection`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. + +Notebook +-------- +A generated executable notebook is available at ``notebooks/helpfiles/CovCollExamples.ipynb``. diff --git a/docs/topics/decodingexample.rst b/docs/topics/decodingexample.rst new file mode 100644 index 00000000..da158c9a --- /dev/null +++ b/docs/topics/decodingexample.rst @@ -0,0 +1,47 @@ +Example Data Analysis - Decoding Univariate Simulated Stimuli (No History Effect) +================================================================================= + +MATLAB help target: ``DecodingExample.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``DecodingExample`` + - ``nstat.decoding.DecoderSuite`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. + +Notebook +-------- +A generated executable notebook is available at ``notebooks/helpfiles/DecodingExample.ipynb``. diff --git a/docs/topics/decodingexamplewithhist.rst b/docs/topics/decodingexamplewithhist.rst new file mode 100644 index 00000000..06775c2c --- /dev/null +++ b/docs/topics/decodingexamplewithhist.rst @@ -0,0 +1,47 @@ +Example Data Analysis - Decoding Univariate Simulated Stimuli with and without History Effect +============================================================================================= + +MATLAB help target: ``DecodingExampleWithHist.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``DecodingExampleWithHist`` + - ``nstat.decoding.DecoderSuite`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. + +Notebook +-------- +A generated executable notebook is available at ``notebooks/helpfiles/DecodingExampleWithHist.ipynb``. diff --git a/docs/topics/documentationsetup2025b.rst b/docs/topics/documentationsetup2025b.rst new file mode 100644 index 00000000..e8506158 --- /dev/null +++ b/docs/topics/documentationsetup2025b.rst @@ -0,0 +1,43 @@ +MATLAB 2025b Help Integration +============================= + +MATLAB help target: ``DocumentationSetup2025b.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``DocumentationSetup2025b`` + - ``nstat (canonical module by topic)`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. diff --git a/docs/topics/eventsexamples.rst b/docs/topics/eventsexamples.rst new file mode 100644 index 00000000..18fff396 --- /dev/null +++ b/docs/topics/eventsexamples.rst @@ -0,0 +1,47 @@ +Using the Events Class +====================== + +MATLAB help target: ``EventsExamples.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``Events`` + - ``nstat.events.Events`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. + +Notebook +-------- +A generated executable notebook is available at ``notebooks/helpfiles/EventsExamples.ipynb``. diff --git a/docs/topics/examples.rst b/docs/topics/examples.rst new file mode 100644 index 00000000..eb0b43f5 --- /dev/null +++ b/docs/topics/examples.rst @@ -0,0 +1,47 @@ +Examples +======== + +MATLAB help target: ``Examples.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``Examples`` + - ``nstat (canonical module by topic)`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. + +Notebook +-------- +A generated executable notebook is available at ``notebooks/helpfiles/Examples.ipynb``. diff --git a/docs/topics/explicitstimuluswhiskerdata.rst b/docs/topics/explicitstimuluswhiskerdata.rst new file mode 100644 index 00000000..54d0c4b1 --- /dev/null +++ b/docs/topics/explicitstimuluswhiskerdata.rst @@ -0,0 +1,43 @@ +Example Data Analysis - Explicit Stimulus +========================================= + +MATLAB help target: ``ExplicitStimulusWhiskerData.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``ExplicitStimulusWhiskerData`` + - ``nstat (canonical module by topic)`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. diff --git a/docs/topics/fitressummaryexamples.rst b/docs/topics/fitressummaryexamples.rst new file mode 100644 index 00000000..065bd5a4 --- /dev/null +++ b/docs/topics/fitressummaryexamples.rst @@ -0,0 +1,47 @@ +Using the FitResSummary Class +============================= + +MATLAB help target: ``FitResSummaryExamples.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``FitResSummary`` + - ``nstat.fit.FitSummary`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. + +Notebook +-------- +A generated executable notebook is available at ``notebooks/helpfiles/FitResSummaryExamples.ipynb``. diff --git a/docs/topics/fitresult.rst b/docs/topics/fitresult.rst new file mode 100644 index 00000000..ee3ae712 --- /dev/null +++ b/docs/topics/fitresult.rst @@ -0,0 +1,43 @@ +FitResult Reference +=================== + +MATLAB help target: ``FitResult.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``FitResult`` + - ``nstat.fit.FitResult`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. diff --git a/docs/topics/fitresultexamples.rst b/docs/topics/fitresultexamples.rst new file mode 100644 index 00000000..60fb4669 --- /dev/null +++ b/docs/topics/fitresultexamples.rst @@ -0,0 +1,47 @@ +Using the FitResult Class +========================= + +MATLAB help target: ``FitResultExamples.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``FitResult`` + - ``nstat.fit.FitResult`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. + +Notebook +-------- +A generated executable notebook is available at ``notebooks/helpfiles/FitResultExamples.ipynb``. diff --git a/docs/topics/hippocampalplacecellexample.rst b/docs/topics/hippocampalplacecellexample.rst new file mode 100644 index 00000000..322abe88 --- /dev/null +++ b/docs/topics/hippocampalplacecellexample.rst @@ -0,0 +1,47 @@ +Example Data Analysis - Hippocampal Place Cell Receptive Field Estimation +========================================================================= + +MATLAB help target: ``HippocampalPlaceCellExample.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``HippocampalPlaceCellExample`` + - ``nstat (canonical module by topic)`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. + +Notebook +-------- +A generated executable notebook is available at ``notebooks/helpfiles/HippocampalPlaceCellExample.ipynb``. diff --git a/docs/topics/historyexamples.rst b/docs/topics/historyexamples.rst new file mode 100644 index 00000000..efd09a62 --- /dev/null +++ b/docs/topics/historyexamples.rst @@ -0,0 +1,47 @@ +Using the History Class +======================= + +MATLAB help target: ``HistoryExamples.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``History`` + - ``nstat.history.HistoryBasis`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. + +Notebook +-------- +A generated executable notebook is available at ``notebooks/helpfiles/HistoryExamples.ipynb``. diff --git a/docs/topics/mepscanalysis.rst b/docs/topics/mepscanalysis.rst new file mode 100644 index 00000000..0bbb3c37 --- /dev/null +++ b/docs/topics/mepscanalysis.rst @@ -0,0 +1,43 @@ +Example Data Analysis - Miniature Excitatory Post-Synaptic Currents (mEPSCs) +============================================================================ + +MATLAB help target: ``mEPSCAnalysis.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``mEPSCAnalysis`` + - ``nstat (canonical module by topic)`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. diff --git a/docs/topics/networktutorial.rst b/docs/topics/networktutorial.rst new file mode 100644 index 00000000..6d183fd0 --- /dev/null +++ b/docs/topics/networktutorial.rst @@ -0,0 +1,43 @@ +Example Data Analysis - Two Neuron Network Simulation and Estimation of Ensemble Effect +======================================================================================= + +MATLAB help target: ``NetworkTutorial.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``NetworkTutorial`` + - ``nstat (canonical module by topic)`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. diff --git a/docs/topics/neuralspikeanalysis_top.rst b/docs/topics/neuralspikeanalysis_top.rst new file mode 100644 index 00000000..c06a09cb --- /dev/null +++ b/docs/topics/neuralspikeanalysis_top.rst @@ -0,0 +1,43 @@ +nSTAT Neural Spike Train Analysis Toolbox +========================================= + +MATLAB help target: ``NeuralSpikeAnalysis_top.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``NeuralSpikeAnalysis_top`` + - ``nstat (canonical module by topic)`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. diff --git a/docs/topics/nspiketrainexamples.rst b/docs/topics/nspiketrainexamples.rst new file mode 100644 index 00000000..25400972 --- /dev/null +++ b/docs/topics/nspiketrainexamples.rst @@ -0,0 +1,47 @@ +Using the nSpikeTrain Class +=========================== + +MATLAB help target: ``nSpikeTrainExamples.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``nSpikeTrain`` + - ``nstat.spikes.SpikeTrain`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. + +Notebook +-------- +A generated executable notebook is available at ``notebooks/helpfiles/nSpikeTrainExamples.ipynb``. diff --git a/docs/topics/nstatpaperexamples.rst b/docs/topics/nstatpaperexamples.rst new file mode 100644 index 00000000..f166aef5 --- /dev/null +++ b/docs/topics/nstatpaperexamples.rst @@ -0,0 +1,47 @@ +nSTAT Paper Examples +==================== + +MATLAB help target: ``nSTATPaperExamples.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``nSTATPaper`` + - ``nstat (canonical module by topic)`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. + +Notebook +-------- +A generated executable notebook is available at ``notebooks/helpfiles/nSTATPaperExamples.ipynb``. diff --git a/docs/topics/nstcollexamples.rst b/docs/topics/nstcollexamples.rst new file mode 100644 index 00000000..94771cb9 --- /dev/null +++ b/docs/topics/nstcollexamples.rst @@ -0,0 +1,47 @@ +Using the nstColl Class +======================= + +MATLAB help target: ``nstCollExamples.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``nstColl`` + - ``nstat.spikes.SpikeTrainCollection`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. + +Notebook +-------- +A generated executable notebook is available at ``notebooks/helpfiles/nstCollExamples.ipynb``. diff --git a/docs/topics/ppsimexample.rst b/docs/topics/ppsimexample.rst new file mode 100644 index 00000000..157fcfa3 --- /dev/null +++ b/docs/topics/ppsimexample.rst @@ -0,0 +1,47 @@ +Example Data Analysis - Simulated Explicit Stimulus and History +=============================================================== + +MATLAB help target: ``PPSimExample.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``PPSimExample`` + - ``nstat (canonical module by topic)`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. + +Notebook +-------- +A generated executable notebook is available at ``notebooks/helpfiles/PPSimExample.ipynb``. diff --git a/docs/topics/ppthinning.rst b/docs/topics/ppthinning.rst new file mode 100644 index 00000000..ab76a964 --- /dev/null +++ b/docs/topics/ppthinning.rst @@ -0,0 +1,43 @@ +Point Process Simulation via Thinning +===================================== + +MATLAB help target: ``PPThinning.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``PPThinning`` + - ``nstat.cif.CIFModel.simulate`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. diff --git a/docs/topics/psthestimation.rst b/docs/topics/psthestimation.rst new file mode 100644 index 00000000..8aa1b28d --- /dev/null +++ b/docs/topics/psthestimation.rst @@ -0,0 +1,43 @@ +Example Data Analysis - Simulated Data - Computing a Peri-Stimulus Time Histogram (PSTH) +======================================================================================== + +MATLAB help target: ``PSTHEstimation.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``PSTHEstimation`` + - ``nstat.spikes.SpikeTrainCollection.psth`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. diff --git a/docs/topics/signalobj.rst b/docs/topics/signalobj.rst new file mode 100644 index 00000000..b8734d8b --- /dev/null +++ b/docs/topics/signalobj.rst @@ -0,0 +1,43 @@ +SignalObj Reference +=================== + +MATLAB help target: ``SignalObj.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``SignalObj`` + - ``nstat.signal.Signal`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. diff --git a/docs/topics/signalobjexamples.rst b/docs/topics/signalobjexamples.rst new file mode 100644 index 00000000..90033b59 --- /dev/null +++ b/docs/topics/signalobjexamples.rst @@ -0,0 +1,47 @@ +Using the SignalObj Class +========================= + +MATLAB help target: ``SignalObjExamples.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``SignalObj`` + - ``nstat.signal.Signal`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. + +Notebook +-------- +A generated executable notebook is available at ``notebooks/helpfiles/SignalObjExamples.ipynb``. diff --git a/docs/topics/stimulusdecode2d.rst b/docs/topics/stimulusdecode2d.rst new file mode 100644 index 00000000..d6fc5d6c --- /dev/null +++ b/docs/topics/stimulusdecode2d.rst @@ -0,0 +1,43 @@ +Example Data Analysis - Decoding Bivariate Simulated Stimuli +============================================================ + +MATLAB help target: ``StimulusDecode2D.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``StimulusDecode2D`` + - ``nstat.decoding.DecoderSuite`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. diff --git a/docs/topics/trialconfigexamples.rst b/docs/topics/trialconfigexamples.rst new file mode 100644 index 00000000..8f13d3b3 --- /dev/null +++ b/docs/topics/trialconfigexamples.rst @@ -0,0 +1,47 @@ +Using the TrialConfig Class +=========================== + +MATLAB help target: ``TrialConfigExamples.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``TrialConfig`` + - ``nstat.trial.TrialConfig`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. + +Notebook +-------- +A generated executable notebook is available at ``notebooks/helpfiles/TrialConfigExamples.ipynb``. diff --git a/docs/topics/trialexamples.rst b/docs/topics/trialexamples.rst new file mode 100644 index 00000000..3368cf4f --- /dev/null +++ b/docs/topics/trialexamples.rst @@ -0,0 +1,47 @@ +Using the Trial Class +===================== + +MATLAB help target: ``TrialExamples.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``Trial`` + - ``nstat.trial.Trial`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. + +Notebook +-------- +A generated executable notebook is available at ``notebooks/helpfiles/TrialExamples.ipynb``. diff --git a/docs/topics/validationdataset.rst b/docs/topics/validationdataset.rst new file mode 100644 index 00000000..c345aa3d --- /dev/null +++ b/docs/topics/validationdataset.rst @@ -0,0 +1,43 @@ +Example Data Analysis - Simulated Constant (Piecewise Constant) Rate Poisson +============================================================================ + +MATLAB help target: ``ValidationDataSet.html`` + +Concept +------- +This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent. + +API Mapping (MATLAB -> Python) +------------------------------ +.. list-table:: + :header-rows: 1 + + * - MATLAB API + - Python API + * - ``ValidationDataSet`` + - ``nstat (canonical module by topic)`` + +Migration Callout +----------------- +- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``. +- Prefer canonical Python modules under ``nstat`` for new code. + +Python Usage +------------ +.. code-block:: python + + import nstat + print(nstat.__all__[:5]) + +Data Requirements +----------------- +Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets. + +Expected Outputs +---------------- +This topic should execute without MATLAB and produce deterministic summary metrics where applicable. + +Known Differences +----------------- +- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity. +- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults. diff --git a/examples/README.md b/examples/README.md new file mode 100644 index 00000000..d666d030 --- /dev/null +++ b/examples/README.md @@ -0,0 +1,31 @@ +# Python nSTAT Examples + +## Run the paper examples equivalent + +```bash +python3 examples/nstat_paper_examples.py --repo-root . +``` + +This is the Python equivalent of `helpfiles/nSTATPaperExamples.m` starting from Experiment 2. +Plot PNG files are generated by default under `plots/nstat_paper_examples/`. Use `--no-plots` to disable plotting. + +## Other examples + +```bash +python3 examples/basic_data_workflow.py +python3 examples/fit_poisson_glm.py +python3 examples/simulate_population_psth.py +``` + +## MATLAB help-topic source scripts + +Executable source scripts used for notebook generation live in: + +- `python/examples/help_topics/` + - `examples/help_topics/` + +Regenerate all help-topic notebooks: + +```bash +python3 tools/generate_example_notebooks.py +``` diff --git a/python/examples/basic_data_workflow.py b/examples/basic_data_workflow.py similarity index 100% rename from python/examples/basic_data_workflow.py rename to examples/basic_data_workflow.py diff --git a/python/examples/fit_poisson_glm.py b/examples/fit_poisson_glm.py similarity index 100% rename from python/examples/fit_poisson_glm.py rename to examples/fit_poisson_glm.py diff --git a/examples/help_topics/AnalysisExamples.py b/examples/help_topics/AnalysisExamples.py new file mode 100644 index 00000000..05b8a609 --- /dev/null +++ b/examples/help_topics/AnalysisExamples.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import argparse + +from ._common import main as _main + + +def run(repo_root=None): + from ._common import run_topic + + return run_topic("AnalysisExamples", repo_root) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run AnalysisExamples Python help-topic workflow") + parser.add_argument("--repo-root", default=None) + args = parser.parse_args() + return _main("AnalysisExamples", args.repo_root) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/help_topics/ConfigCollExamples.py b/examples/help_topics/ConfigCollExamples.py new file mode 100644 index 00000000..b5094932 --- /dev/null +++ b/examples/help_topics/ConfigCollExamples.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import argparse + +from ._common import main as _main + + +def run(repo_root=None): + from ._common import run_topic + + return run_topic("ConfigCollExamples", repo_root) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run ConfigCollExamples Python help-topic workflow") + parser.add_argument("--repo-root", default=None) + args = parser.parse_args() + return _main("ConfigCollExamples", args.repo_root) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/help_topics/CovCollExamples.py b/examples/help_topics/CovCollExamples.py new file mode 100644 index 00000000..97623893 --- /dev/null +++ b/examples/help_topics/CovCollExamples.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import argparse + +from ._common import main as _main + + +def run(repo_root=None): + from ._common import run_topic + + return run_topic("CovCollExamples", repo_root) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run CovCollExamples Python help-topic workflow") + parser.add_argument("--repo-root", default=None) + args = parser.parse_args() + return _main("CovCollExamples", args.repo_root) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/help_topics/CovariateExamples.py b/examples/help_topics/CovariateExamples.py new file mode 100644 index 00000000..b74b1b03 --- /dev/null +++ b/examples/help_topics/CovariateExamples.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import argparse + +from ._common import main as _main + + +def run(repo_root=None): + from ._common import run_topic + + return run_topic("CovariateExamples", repo_root) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run CovariateExamples Python help-topic workflow") + parser.add_argument("--repo-root", default=None) + args = parser.parse_args() + return _main("CovariateExamples", args.repo_root) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/help_topics/DecodingExample.py b/examples/help_topics/DecodingExample.py new file mode 100644 index 00000000..62650f4a --- /dev/null +++ b/examples/help_topics/DecodingExample.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import argparse + +from ._common import main as _main + + +def run(repo_root=None): + from ._common import run_topic + + return run_topic("DecodingExample", repo_root) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run DecodingExample Python help-topic workflow") + parser.add_argument("--repo-root", default=None) + args = parser.parse_args() + return _main("DecodingExample", args.repo_root) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/help_topics/DecodingExampleWithHist.py b/examples/help_topics/DecodingExampleWithHist.py new file mode 100644 index 00000000..aca22945 --- /dev/null +++ b/examples/help_topics/DecodingExampleWithHist.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import argparse + +from ._common import main as _main + + +def run(repo_root=None): + from ._common import run_topic + + return run_topic("DecodingExampleWithHist", repo_root) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run DecodingExampleWithHist Python help-topic workflow") + parser.add_argument("--repo-root", default=None) + args = parser.parse_args() + return _main("DecodingExampleWithHist", args.repo_root) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/help_topics/EventsExamples.py b/examples/help_topics/EventsExamples.py new file mode 100644 index 00000000..2c2e170d --- /dev/null +++ b/examples/help_topics/EventsExamples.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import argparse + +from ._common import main as _main + + +def run(repo_root=None): + from ._common import run_topic + + return run_topic("EventsExamples", repo_root) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run EventsExamples Python help-topic workflow") + parser.add_argument("--repo-root", default=None) + args = parser.parse_args() + return _main("EventsExamples", args.repo_root) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/help_topics/ExplicitStimulusWhiskerData.py b/examples/help_topics/ExplicitStimulusWhiskerData.py new file mode 100644 index 00000000..ba37ccd8 --- /dev/null +++ b/examples/help_topics/ExplicitStimulusWhiskerData.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import argparse + +from ._common import main as _main + + +def run(repo_root=None): + from ._common import run_topic + + return run_topic("ExplicitStimulusWhiskerData", repo_root) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run ExplicitStimulusWhiskerData Python help-topic workflow") + parser.add_argument("--repo-root", default=None) + args = parser.parse_args() + return _main("ExplicitStimulusWhiskerData", args.repo_root) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/help_topics/FitResSummaryExamples.py b/examples/help_topics/FitResSummaryExamples.py new file mode 100644 index 00000000..07990aa1 --- /dev/null +++ b/examples/help_topics/FitResSummaryExamples.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import argparse + +from ._common import main as _main + + +def run(repo_root=None): + from ._common import run_topic + + return run_topic("FitResSummaryExamples", repo_root) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run FitResSummaryExamples Python help-topic workflow") + parser.add_argument("--repo-root", default=None) + args = parser.parse_args() + return _main("FitResSummaryExamples", args.repo_root) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/help_topics/FitResultExamples.py b/examples/help_topics/FitResultExamples.py new file mode 100644 index 00000000..f3dc92b7 --- /dev/null +++ b/examples/help_topics/FitResultExamples.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import argparse + +from ._common import main as _main + + +def run(repo_root=None): + from ._common import run_topic + + return run_topic("FitResultExamples", repo_root) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run FitResultExamples Python help-topic workflow") + parser.add_argument("--repo-root", default=None) + args = parser.parse_args() + return _main("FitResultExamples", args.repo_root) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/help_topics/HippocampalPlaceCellExample.py b/examples/help_topics/HippocampalPlaceCellExample.py new file mode 100644 index 00000000..0cac2e6f --- /dev/null +++ b/examples/help_topics/HippocampalPlaceCellExample.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import argparse + +from ._common import main as _main + + +def run(repo_root=None): + from ._common import run_topic + + return run_topic("HippocampalPlaceCellExample", repo_root) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run HippocampalPlaceCellExample Python help-topic workflow") + parser.add_argument("--repo-root", default=None) + args = parser.parse_args() + return _main("HippocampalPlaceCellExample", args.repo_root) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/help_topics/HistoryExamples.py b/examples/help_topics/HistoryExamples.py new file mode 100644 index 00000000..9eb7a439 --- /dev/null +++ b/examples/help_topics/HistoryExamples.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import argparse + +from ._common import main as _main + + +def run(repo_root=None): + from ._common import run_topic + + return run_topic("HistoryExamples", repo_root) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run HistoryExamples Python help-topic workflow") + parser.add_argument("--repo-root", default=None) + args = parser.parse_args() + return _main("HistoryExamples", args.repo_root) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/help_topics/NetworkTutorial.py b/examples/help_topics/NetworkTutorial.py new file mode 100644 index 00000000..119c6553 --- /dev/null +++ b/examples/help_topics/NetworkTutorial.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import argparse + +from ._common import main as _main + + +def run(repo_root=None): + from ._common import run_topic + + return run_topic("NetworkTutorial", repo_root) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run NetworkTutorial Python help-topic workflow") + parser.add_argument("--repo-root", default=None) + args = parser.parse_args() + return _main("NetworkTutorial", args.repo_root) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/help_topics/PPSimExample.py b/examples/help_topics/PPSimExample.py new file mode 100644 index 00000000..a64db7ae --- /dev/null +++ b/examples/help_topics/PPSimExample.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import argparse + +from ._common import main as _main + + +def run(repo_root=None): + from ._common import run_topic + + return run_topic("PPSimExample", repo_root) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run PPSimExample Python help-topic workflow") + parser.add_argument("--repo-root", default=None) + args = parser.parse_args() + return _main("PPSimExample", args.repo_root) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/help_topics/PPThinning.py b/examples/help_topics/PPThinning.py new file mode 100644 index 00000000..442e407e --- /dev/null +++ b/examples/help_topics/PPThinning.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import argparse + +from ._common import main as _main + + +def run(repo_root=None): + from ._common import run_topic + + return run_topic("PPThinning", repo_root) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run PPThinning Python help-topic workflow") + parser.add_argument("--repo-root", default=None) + args = parser.parse_args() + return _main("PPThinning", args.repo_root) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/help_topics/PSTHEstimation.py b/examples/help_topics/PSTHEstimation.py new file mode 100644 index 00000000..e32a9628 --- /dev/null +++ b/examples/help_topics/PSTHEstimation.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import argparse + +from ._common import main as _main + + +def run(repo_root=None): + from ._common import run_topic + + return run_topic("PSTHEstimation", repo_root) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run PSTHEstimation Python help-topic workflow") + parser.add_argument("--repo-root", default=None) + args = parser.parse_args() + return _main("PSTHEstimation", args.repo_root) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/help_topics/SignalObjExamples.py b/examples/help_topics/SignalObjExamples.py new file mode 100644 index 00000000..779017ce --- /dev/null +++ b/examples/help_topics/SignalObjExamples.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import argparse + +from ._common import main as _main + + +def run(repo_root=None): + from ._common import run_topic + + return run_topic("SignalObjExamples", repo_root) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run SignalObjExamples Python help-topic workflow") + parser.add_argument("--repo-root", default=None) + args = parser.parse_args() + return _main("SignalObjExamples", args.repo_root) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/help_topics/StimulusDecode2D.py b/examples/help_topics/StimulusDecode2D.py new file mode 100644 index 00000000..7f59b39d --- /dev/null +++ b/examples/help_topics/StimulusDecode2D.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import argparse + +from ._common import main as _main + + +def run(repo_root=None): + from ._common import run_topic + + return run_topic("StimulusDecode2D", repo_root) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run StimulusDecode2D Python help-topic workflow") + parser.add_argument("--repo-root", default=None) + args = parser.parse_args() + return _main("StimulusDecode2D", args.repo_root) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/help_topics/TrialConfigExamples.py b/examples/help_topics/TrialConfigExamples.py new file mode 100644 index 00000000..4c819421 --- /dev/null +++ b/examples/help_topics/TrialConfigExamples.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import argparse + +from ._common import main as _main + + +def run(repo_root=None): + from ._common import run_topic + + return run_topic("TrialConfigExamples", repo_root) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run TrialConfigExamples Python help-topic workflow") + parser.add_argument("--repo-root", default=None) + args = parser.parse_args() + return _main("TrialConfigExamples", args.repo_root) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/help_topics/TrialExamples.py b/examples/help_topics/TrialExamples.py new file mode 100644 index 00000000..15ab82eb --- /dev/null +++ b/examples/help_topics/TrialExamples.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import argparse + +from ._common import main as _main + + +def run(repo_root=None): + from ._common import run_topic + + return run_topic("TrialExamples", repo_root) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run TrialExamples Python help-topic workflow") + parser.add_argument("--repo-root", default=None) + args = parser.parse_args() + return _main("TrialExamples", args.repo_root) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/help_topics/ValidationDataSet.py b/examples/help_topics/ValidationDataSet.py new file mode 100644 index 00000000..91b25056 --- /dev/null +++ b/examples/help_topics/ValidationDataSet.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import argparse + +from ._common import main as _main + + +def run(repo_root=None): + from ._common import run_topic + + return run_topic("ValidationDataSet", repo_root) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run ValidationDataSet Python help-topic workflow") + parser.add_argument("--repo-root", default=None) + args = parser.parse_args() + return _main("ValidationDataSet", args.repo_root) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/help_topics/__init__.py b/examples/help_topics/__init__.py new file mode 100644 index 00000000..cf3b0227 --- /dev/null +++ b/examples/help_topics/__init__.py @@ -0,0 +1 @@ +"""Source scripts for MATLAB help-topic equivalents used to build executable notebooks.""" diff --git a/examples/help_topics/_common.py b/examples/help_topics/_common.py new file mode 100644 index 00000000..ed35fbb2 --- /dev/null +++ b/examples/help_topics/_common.py @@ -0,0 +1,296 @@ +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import numpy as np + +from nstat import ( + Analysis, + CIFModel, + ConfigCollection, + Covariate, + CovariateCollection, + DecoderSuite, + HistoryBasis, + Signal, + SpikeTrain, + SpikeTrainCollection, + Trial, + TrialConfig, + run_full_paper_examples, + simulate_two_neuron_network, +) +from nstat.paper_examples_full import ( + run_experiment1, + run_experiment2, + run_experiment3, + run_experiment4, + run_experiment5, + run_experiment5b, + run_experiment6, +) + + +def _resolve_repo_root(repo_root: Path | str | None) -> Path: + if repo_root is None: + cur = Path(__file__).resolve() + for candidate in [cur, *cur.parents]: + if (candidate / "nstat").exists() and (candidate / "data").exists(): + return candidate + raise RuntimeError(f"Unable to locate repository root from {__file__}") + return Path(repo_root).resolve() + + +def _result(topic: str, payload: dict[str, Any], parity: dict[str, float] | None = None) -> dict[str, Any]: + out = {"topic": topic, **payload} + if parity: + out["parity"] = {k: float(v) for k, v in parity.items()} + return out + + +MATLAB_FIGURE_BASELINE: dict[str, float] = { + "SignalObjExamples": 16.0, + "CovariateExamples": 2.0, + "CovCollExamples": 2.0, + "nSpikeTrainExamples": 4.0, + "nstCollExamples": 3.0, + "EventsExamples": 3.0, + "HistoryExamples": 3.0, + "TrialExamples": 6.0, + "TrialConfigExamples": 0.0, + "ConfigCollExamples": 0.0, + "AnalysisExamples": 4.0, + "FitResultExamples": 0.0, + "FitResSummaryExamples": 0.0, + "PPThinning": 3.0, + "PSTHEstimation": 2.0, + "ValidationDataSet": 8.0, + "mEPSCAnalysis": 4.0, + "PPSimExample": 3.0, + "ExplicitStimulusWhiskerData": 8.0, + "HippocampalPlaceCellExample": 9.0, + "DecodingExample": 5.0, + "DecodingExampleWithHist": 2.0, + "StimulusDecode2D": 4.0, + "NetworkTutorial": 4.0, + "nSTATPaperExamples": 1.0, +} + + +def _parity(topic: str, extra: dict[str, float] | None = None) -> dict[str, float]: + out = {"figs": float(MATLAB_FIGURE_BASELINE[topic])} + if extra: + out.update({k: float(v) for k, v in extra.items()}) + return out + + +def _toy_trial() -> tuple[Trial, ConfigCollection]: + time = np.arange(0.0, 2.0, 0.001) + stim = np.sin(2.0 * np.pi * 2.0 * time) + cov = Covariate(time, stim, "stim", "time", "s", "a.u.", ["stim"]) + + base_rate = 10.0 + 5.0 * np.maximum(stim, 0.0) + model = CIFModel(time=time, rate_hz=base_rate, name="lambda") + coll = model.simulate(num_realizations=3, seed=3) + + trial = Trial(spike_collection=coll, covariate_collection=CovariateCollection([cov])) + cfg = TrialConfig(covMask=["stim"], sampleRate=1000.0, name="stimulus_only") + cfgs = ConfigCollection([cfg]) + return trial, cfgs + + +def run_topic(topic: str, repo_root: Path | str | None = None) -> dict[str, Any]: + root = _resolve_repo_root(repo_root) + data_dir = root / "data" + + if topic == "SignalObjExamples": + sample_rate_hz = 5000.0 + dt = 1.0 / sample_rate_hz + t = np.arange(0.0, 1.0 + dt * 0.5, dt) + sig = Signal(t, np.column_stack([np.sin(2 * np.pi * t), np.cos(2 * np.pi * t)]), name="demo") + return _result( + topic, + {"dimension": sig.dimension, "sample_rate": sig.sample_rate}, + parity=_parity(topic, {"sample_rate_hz": sig.sample_rate}), + ) + + if topic == "CovariateExamples": + t = np.linspace(0.0, 1.0, 100) + cov = Covariate.from_values(t, np.sin(2 * np.pi * t), name="stim", units="a.u.") + cov_z = cov.standardize() + return _result(topic, {"mean": float(np.mean(cov_z.data)), "std": float(np.std(cov_z.data))}, parity=_parity(topic)) + + if topic == "CovCollExamples": + trial, _ = _toy_trial() + _, x, labels = trial.get_covariate_matrix() + return _result(topic, {"matrix_shape": list(x.shape), "labels": labels}, parity=_parity(topic)) + + if topic == "nSpikeTrainExamples": + st = SpikeTrain(np.array([0.1, 0.12, 0.25, 0.4]), binwidth=0.01) + return _result(topic, {"n_spikes": st.n_spikes, "rate_hz": st.firing_rate_hz}, parity=_parity(topic)) + + if topic == "nstCollExamples": + trial, _ = _toy_trial() + coll = trial.spike_collection + psth = coll.psth(0.05) + return _result(topic, {"num_trains": coll.num_spike_trains, "psth_points": int(psth.time.shape[0])}, parity=_parity(topic)) + + if topic == "EventsExamples": + from nstat.events import Events + + ev = Events([0.2, 0.9, 1.4], labels=["start", "cue", "reward"]) + return _result(topic, {"n_events": int(ev.event_times.shape[0])}, parity=_parity(topic)) + + if topic == "HistoryExamples": + basis = HistoryBasis([1, 2, 5, 10]) + y = np.random.default_rng(0).poisson(0.1, size=500) + x = basis.design_matrix(y) + return _result(topic, {"lags": basis.lags.tolist(), "design_shape": list(x.shape)}, parity=_parity(topic)) + + if topic == "TrialExamples": + trial, _ = _toy_trial() + _, x, _ = trial.get_covariate_matrix() + return _result( + topic, + {"covariate_rows": int(x.shape[0]), "neurons": trial.spike_collection.num_spike_trains}, + parity=_parity(topic), + ) + + if topic == "TrialConfigExamples": + cfg = TrialConfig(covMask=[["stim", "hist"]], sampleRate=1000.0, name="demo_cfg") + return _result(topic, {"covariates": cfg.covariate_names, "sample_rate": cfg.sampleRate}, parity=_parity(topic)) + + if topic == "ConfigCollExamples": + c1 = TrialConfig(covMask=["stim"], sampleRate=1000.0, name="cfg1") + c2 = TrialConfig(covMask=["stim", "hist"], sampleRate=1000.0, name="cfg2") + coll = ConfigCollection([c1, c2]) + return _result(topic, {"num_configs": coll.numConfigs, "names": coll.getConfigNames()}, parity=_parity(topic)) + + if topic == "AnalysisExamples": + trial, cfgs = _toy_trial() + out = Analysis.run_analysis_for_all_neurons(trial, cfgs) + return _result(topic, {"num_results": len(out), "first_aic": float(out[0].AIC[0])}, parity=_parity(topic)) + + if topic == "FitResultExamples": + trial, cfgs = _toy_trial() + fit = Analysis.run_analysis_for_neuron(trial, 0, cfgs) + return _result(topic, {"coeffs": fit.getCoeffs().tolist(), "bic": float(fit.BIC[0])}, parity=_parity(topic)) + + if topic == "FitResSummaryExamples": + trial, cfgs = _toy_trial() + fits = Analysis.run_analysis_for_all_neurons(trial, cfgs) + from nstat.fit import FitSummary + + summary = FitSummary(fits) + return _result(topic, {"mean_aic": summary.AIC.tolist(), "mean_bic": summary.BIC.tolist()}, parity=_parity(topic)) + + if topic == "PPThinning": + t = np.arange(0.0, 1.0, 0.001) + rate = 20.0 + 15.0 * np.sin(2 * np.pi * 3 * t) ** 2 + model = CIFModel(t, rate) + spikes = model.simulate(num_realizations=20, seed=1) + return _result( + topic, + {"num_realizations": spikes.num_spike_trains}, + parity=_parity(topic, {"num_realizations": spikes.num_spike_trains}), + ) + + if topic == "PSTHEstimation": + delta = 0.001 + tmax = 10.0 + time = np.arange(0.0, tmax + delta, delta) + rate_hz = 10.0 * np.sin(2.0 * np.pi * 0.2 * time) + 10.0 + coll = CIFModel(time, rate_hz, name="lambda").simulate(num_realizations=20, seed=17) + psth = coll.psth(0.5) + peak = float(np.max(psth.data[:, 0])) + return _result( + topic, + {"peak_rate": peak, "num_realizations": coll.num_spike_trains}, + parity=_parity(topic, {"num_realizations": coll.num_spike_trains}), + ) + + if topic == "ValidationDataSet": + summary = run_experiment3(seed=7) + return _result(topic, summary, parity=_parity(topic)) + + if topic == "mEPSCAnalysis": + summary = run_experiment1(data_dir) + return _result(topic, summary, parity=_parity(topic)) + + if topic == "PPSimExample": + summary = run_experiment2(data_dir) + return _result(topic, summary, parity=_parity(topic)) + + if topic == "ExplicitStimulusWhiskerData": + summary = run_experiment2(data_dir) + return _result(topic, summary, parity=_parity(topic)) + + if topic == "HippocampalPlaceCellExample": + summary = run_experiment4(data_dir) + return _result(topic, summary, parity=_parity(topic)) + + if topic == "DecodingExample": + summary = run_experiment5(seed=11) + return _result(topic, summary, parity=_parity(topic, {"num_cells": summary["num_cells"]})) + + if topic == "DecodingExampleWithHist": + summary = run_experiment5b(seed=19) + return _result(topic, summary, parity=_parity(topic, {"num_cells": summary["num_cells"]})) + + if topic == "StimulusDecode2D": + summary = run_experiment5b(seed=23, n_cells=80) + return _result( + topic, + summary, + parity=_parity( + topic, + { + "num_cells": summary["num_cells"], + "decode_rmse_x": summary["decode_rmse_x"], + "decode_rmse_y": summary["decode_rmse_y"], + }, + ), + ) + + if topic == "NetworkTutorial": + sim = simulate_two_neuron_network(duration_s=2.0, dt=0.001, seed=13) + psth = sim.spikes.psth(0.05) + return _result( + topic, + { + "samples": int(sim.time.shape[0]), + "neuron_count": sim.spikes.num_spike_trains, + "psth_peak": float(np.max(psth.data[:, 0])), + }, + parity=_parity(topic), + ) + + if topic == "nSTATPaperExamples": + # Keep this help-topic notebook fast and deterministic in CI by running + # a representative subset of paper experiments. + summary = { + "experiment2": run_experiment2(data_dir), + "experiment3": run_experiment3(seed=7), + "experiment5": run_experiment5(seed=11, n_cells=40), + } + return _result( + topic, + {"experiments": sorted(summary.keys()), "summary": summary}, + parity=_parity( + topic, + { + "num_cells": summary["experiment5"]["num_cells"], + "decode_rmse": summary["experiment5"]["decode_rmse"], + }, + ), + ) + + raise KeyError(f"Unknown help topic: {topic}") + + +def main(topic: str, repo_root: Path | str | None = None) -> int: + out = run_topic(topic, repo_root) + print(json.dumps(out, indent=2, default=str)) + return 0 diff --git a/examples/help_topics/mEPSCAnalysis.py b/examples/help_topics/mEPSCAnalysis.py new file mode 100644 index 00000000..a0e5a008 --- /dev/null +++ b/examples/help_topics/mEPSCAnalysis.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import argparse + +from ._common import main as _main + + +def run(repo_root=None): + from ._common import run_topic + + return run_topic("mEPSCAnalysis", repo_root) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run mEPSCAnalysis Python help-topic workflow") + parser.add_argument("--repo-root", default=None) + args = parser.parse_args() + return _main("mEPSCAnalysis", args.repo_root) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/help_topics/nSTATPaperExamples.py b/examples/help_topics/nSTATPaperExamples.py new file mode 100644 index 00000000..b2f21399 --- /dev/null +++ b/examples/help_topics/nSTATPaperExamples.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import argparse + +from ._common import main as _main + + +def run(repo_root=None): + from ._common import run_topic + + return run_topic("nSTATPaperExamples", repo_root) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run nSTATPaperExamples Python help-topic workflow") + parser.add_argument("--repo-root", default=None) + args = parser.parse_args() + return _main("nSTATPaperExamples", args.repo_root) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/help_topics/nSpikeTrainExamples.py b/examples/help_topics/nSpikeTrainExamples.py new file mode 100644 index 00000000..09152509 --- /dev/null +++ b/examples/help_topics/nSpikeTrainExamples.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import argparse + +from ._common import main as _main + + +def run(repo_root=None): + from ._common import run_topic + + return run_topic("nSpikeTrainExamples", repo_root) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run nSpikeTrainExamples Python help-topic workflow") + parser.add_argument("--repo-root", default=None) + args = parser.parse_args() + return _main("nSpikeTrainExamples", args.repo_root) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/help_topics/nstCollExamples.py b/examples/help_topics/nstCollExamples.py new file mode 100644 index 00000000..c75ae35a --- /dev/null +++ b/examples/help_topics/nstCollExamples.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import argparse + +from ._common import main as _main + + +def run(repo_root=None): + from ._common import run_topic + + return run_topic("nstCollExamples", repo_root) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Run nstCollExamples Python help-topic workflow") + parser.add_argument("--repo-root", default=None) + args = parser.parse_args() + return _main("nstCollExamples", args.repo_root) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/nSTATPaperExamples.py b/examples/nSTATPaperExamples.py new file mode 100644 index 00000000..f02d46b1 --- /dev/null +++ b/examples/nSTATPaperExamples.py @@ -0,0 +1,15 @@ +from __future__ import annotations + +import sys +from pathlib import Path + +THIS_DIR = Path(__file__).resolve().parent +PKG_ROOT = THIS_DIR.parent +if str(PKG_ROOT) not in sys.path: + sys.path.insert(0, str(PKG_ROOT)) + +from nstat.paper_examples_full import main + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/nstat_paper_examples.py b/examples/nstat_paper_examples.py new file mode 100644 index 00000000..12ad4713 --- /dev/null +++ b/examples/nstat_paper_examples.py @@ -0,0 +1,16 @@ +from __future__ import annotations + +import sys +from pathlib import Path + +# Ensure local package import works when run directly. +THIS_DIR = Path(__file__).resolve().parent +PKG_ROOT = THIS_DIR.parent +if str(PKG_ROOT) not in sys.path: + sys.path.insert(0, str(PKG_ROOT)) + +from nstat.paper_examples import main + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/python/examples/simulate_population_psth.py b/examples/simulate_population_psth.py similarity index 100% rename from python/examples/simulate_population_psth.py rename to examples/simulate_population_psth.py diff --git a/helpfiles/Analysis.html b/helpfiles/Analysis.html deleted file mode 100644 index 5ec61a01..00000000 --- a/helpfiles/Analysis.html +++ /dev/null @@ -1,2147 +0,0 @@ - - - - - Analysis

Contents

classdef Analysis
-% ANALYSIS Collection of functions (static methods) used for GLM analysis
-% of point process data.
-%
-% <a href="matlab:web('AnalysisExamples.html', '-helpbrowser')">Analysis Examples</a>
-%
-% see also <a href="matlab:help('Trial')">Trial</a>, <a
-% href="matlab:help('CovColl')">CovColl</a>, <a
-% href="matlab:help('nstColl')">nstColl</a>,<a
-% href="matlab:help('History')">History</a>
-%
-%
-% Reference page in Help browser
-% <a href="matlab: doc('Analysis')">doc Analysis</a>
-
-properties (Constant)
-    colors = {'b','g','r','c','m','y','k'};
-end
-
-    methods (Static)
-        function fitResults =RunAnalysisForNeuron(tObj,neuronNumber,configColl,makePlot,Algorithm)
-
            % fitResults =RunAnalysisForNeuron(tObj,neuronNumber,configColl,makePlot,Algorithm)
-            % tObj: Trial to be analyzed
-            % neuronNumber: number of the neuron to be analyzed. Can be a
-            %               vector to specify multiple neurons to be analyzed.
-            %               If more than one neuron specified, then
-            %               fitResults is a cell array of fitResult
-            %               objects. fitResults{i} will contain the
-            %               fitResults object for neuronNum(i).
-            % configColl: ConfigColl object containing the different
-            %             configurations (description of the the types of fits, eg. covariates) that correspond to each fit.
-            % makePlot: Set to 1 to show a summary plot for this neuron. If performing multiple neuron analysis (eg. via RunAnalysisForAllNeurons) set ths parameter to zero to avoid screen clutter.
-            % Algorithm: Either 'GLM' or 'BNLRCG'. Default is 'GLM'
-            %            GLM - Standard GLM regression from matlab.
-            %            BNLRCG - faster Truncated, L-2 Regularized,
-            %            Binomial Logistic Regression with Conjugate
-            %            Gradient Solver by Demba Ba (demba@mit.edu).
-            %
-            if(nargin<5)
-                Algorithm = 'GLM';
-            end
-            if(nargin<4)
-                makePlot=1;
-            end
-            numNeurons = length(neuronNumber);
-            labels=cell(numNeurons,1);
-            lambda=cell(numNeurons,1);
-            b     =cell(numNeurons,1);
-            dev   =zeros(numNeurons,1);
-            numHist=cell(numNeurons,1);
-            stats =cell(numNeurons,1);
-            histObj =cell(numNeurons,1);
-            ensHistObj=cell(numNeurons,1);
-            AIC   =zeros(numNeurons,1);
-            BIC   =zeros(numNeurons,1);
-            windowSize = .01; % 1/tObj.sampleRate;% for Residual Computation;
-            spikeTraining = cell(1,numNeurons);
-            XvalData =cell(numNeurons,1);
-            XvalTime =cell(numNeurons,1);
-            spikeValidation = cell(1,numNeurons);
-

Fit Using Training Data

            if(diff(tObj.validationWindow)~=0)
-                tObj.setTrialTimesFor('training');
-            end
-            for i=1:configColl.numConfigs
-                configColl.setConfig(tObj,i);
-                display(strcat('Analyzing Configuration #',num2str(i)));
-
-                for j=1:numNeurons
-
                    display(strcat('Analyzing Configuration #',num2str(i),': Neuron #',num2str(neuronNumber(j))));
-                    %clear tempLabels;
-                    %tObj.setCurrentNeuron(neuronNumber);
-                    otherLabels  = tObj.getLabelsFromMask(neuronNumber(j));
-%                     labels{j}{i}  = horzcat('Baseline',otherLabels); % Labels change depending on presence/absense of History or ensCovHist
-                    labels{j}{i}  = otherLabels; % Labels change depending on presence/absense of History or ensCovHist
-                    numHist{j}{i} = tObj.getNumHist;
-                    histObj{j}{i} = tObj.history;
-                    ensHistObj{j}{i} = tObj.ensCovHist;
-                    [lambdaTemp, bTemp, devTemp, statsTemp,AICTemp,BICTemp,distribTemp] = Analysis.GLMFit(tObj,neuronNumber(j),i,Algorithm);
-                    lambda{j}{i} = lambdaTemp; b{j}{i} = bTemp; stats{j}{i} = statsTemp;
-                    dev(j,i) = devTemp;  AIC(j,i)= AICTemp; BIC(j,i)= BICTemp;
-                    distrib{j}{i} =distribTemp;
-                    spikeTraining{j} = tObj.nspikeColl.getNST(neuronNumber(j)).nstCopy;
-                    spikeTraining{j}.setName(num2str(neuronNumber(j)));
-

Collect the validation Data

                    if(diff(tObj.validationWindow)~=0)
-                          tObj.setTrialTimesFor('validation');
-                          XvalData{j}{i}=tObj.getDesignMatrix(neuronNumber(j));
-                          XvalTime{j}{i}=tObj.covarColl.getCov(1).time;
-                          spikeValidation{j} = tObj.nspikeColl.getNST(neuronNumber(j)).nstCopy;
-                          spikeTraining{j}.setName(num2str(neuronNumber(j)));
-                          tObj.setTrialTimesFor('training')
-                    end
-
                end
-            end
-
-
-%             %% Collect the validation Data
-%
-%             if(diff(tObj.validationWindow)~=0)
-%                 tObj.setTrialTimesFor('validation');
-%                 for i=1:configColl.numConfigs
-%                     configColl.setConfig(tObj,i);
-%                     for j=1:numNeurons
-%                         XvalData{j,i}=tObj.getDesignMatrix(neuronNumber(j));
-%                         XvalTime{j,i}=tObj.covarColl.getCov(1).time;
-%                         spikeValidation{j} = tObj.nspikeColl.getNST(neuronNumber(j)).nstCopy;
-%                         spikeTraining{j}.setName(num2str(neuronNumber(j)));
-%                     end
-%                 end
-%
-%                 %tObj.setTrialTimesFor('training');
-%             end
-%
-

Store the results

            fitResults =cell(length(neuronNumber),1);
-            for j=1:numNeurons
-
                fitResults{j}=FitResult(spikeTraining{j},labels{j},numHist{j},histObj{j},ensHistObj{j},lambda{j},b{j}, dev(j,:), stats{j},AIC(j,:),BIC(j,:),configColl,XvalData{j},XvalTime{j},distrib{j});
-                if(diff(tObj.validationWindow)~=0)
-                    tObj.setTrialTimesFor('validation');
-                    lambdaValidation = fitResults{j}.computeValLambda;
-                    ValResults = FitResult(spikeValidation{j},labels{j},numHist{j},histObj{j},ensHistObj{j},lambdaValidation,b{j}, dev(j,:), stats{j},AIC(j,:),BIC(j,:),configColl,XvalData{j},XvalTime{j},distrib);
-                    fitResults{j}.validation = ValResults; %validation field is actually another fitResults object but with the validation data
-                end
-

Process the results and compute further parameters

                if(makePlot==1)
-                    scrsz = get(0,'ScreenSize');
-                    figure('Position',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.8 scrsz(4)*.8]);
-                    subplot(2,4,[1 2]);     Analysis.KSPlot(fitResults{j},makePlot); %make the plot
-                    hold on; text(.45, .95,strcat('Neuron:',num2str(neuronNumber(j))));
-                    subplot(2,4,3);         Analysis.plotInvGausTrans(fitResults{j},makePlot);
-                    subplot(2,4,4);         Analysis.plotSeqCorr(fitResults{j});
-                    subplot(2,4,[7 8]);     Analysis.plotFitResidual(fitResults{j},windowSize,makePlot);
-                    subplot(2,4,[5 6]);     Analysis.plotCoeffs(fitResults{j});
-                else
-                    Analysis.KSPlot(fitResults{j},makePlot);
-                    Analysis.plotInvGausTrans(fitResults{j},makePlot);
-                    Analysis.plotFitResidual(fitResults{j},windowSize,makePlot);
-                    %fitResults.computePlotParams;
-                end
-
            end
-            if(length(neuronNumber)==1)
-                fitResults = fitResults{1};
-            end
-
        end
-        function fitResults = RunAnalysisForAllNeurons(tObj,configs,makePlot,Algorithm)
-            % fitResults = RunAnalysisForAllNeurons(tObj,configs,makePlot,Algorithm)
-            % Runs the fits specifed by configs (a ConfigColl object) on
-            % all the neurons that are unmasked in the trial tObj.
-            % tObj - trial to be analyzed
-            % configs - ConfigColl object specifying the types of fits to
-            %           be performed.
-            % makePlot - Set to 1 to generate a summary plot for each
-            %            neuron.
-            % Algorithm: Either 'GLM' or 'BNLRCG'. Default is 'GLM'
-            %            GLM - Standard GLM regression from matlab.
-            %            BNLRCG - faster Truncated, L-2 Regularized,
-            %            Binomial Logistic Regression with Conjugate
-            %            Gradient Solver by Demba Ba (demba@mit.edu).
-
-            if(nargin<4)
-                Algorithm = 'GLM';
-            end
-            if(nargin<3)
-                makePlot=1; %default to plotting results
-            end
-
-            neuronIndex=tObj.getNeuronIndFromMask;
-%             numLoops = floor(length(neuronIndex)/4);
-%             loopArray = cell(1,numLoops);
-%             for k=1:numLoops
-%                 if(k==numLoops)
-%                     loopArray{k} = neuronIndex((4*(k-1)+1):end);
-%                 else
-%                     loopArray{k} = neuronIndex((4*(k-1)+1):4*k);
-%                 end
-%             end
-
-           % parfor i=1:length(neuronIndex)
-                fitResults = Analysis.RunAnalysisForNeuron(tObj,neuronIndex,configs,makePlot,Algorithm);
-            %end
-
-        end
-
-
-        function [lambda,b, dev, stats,AIC, BIC,distribution] = GLMFit(tObj,neuronNumber,lambdaIndex,Algorithm)
-            % [lambda,b, dev, stats,AIC, BIC] = GLMFit(tObj,neuronNumber,lambdaIndex,Algorithm)
-            % Given a trial, tObj, and a neuronNumber specifying a neuron
-            % from the trial, extracts the design matrix X from the current
-            % covariate masks, history, and ensemble history in the trial,
-            % and the observation vector,Y, and performs the GLM regression
-            % using the specified algorithm. lambdaIndex: is used to
-            % labeling the returned lambda with the number of the
-            % configuration that it corresponds to.
-            % Algorithm: Either 'GLM' or 'BNLRCG'. Default is 'GLM'
-            %            GLM - Standard GLM regression from matlab.
-            %            BNLRCG - faster Truncated, L-2 Regularized,
-            %            Binomial Logistic Regression with Conjugate
-            %            Gradient Solver by Demba Ba (demba@mit.edu).
-            % Returns:
-            % lambda - Covariate containing the resulting conditional
-            %          intensity function evaluated with the design matrix data.
-            % b      - the GLM regression coefficients. Constant term is
-            %          first followed by the components in X.
-            %
-            % dev    - deviance for the this regression.
-            % stats  - stats structure from the GLM regression
-            %          (p-values,std dev, etc.)
-            % AIC    - Akaike's information criteria for this regression.
-            % BIC    - Bayes Information Criteria for this regression.
-
-            if(nargin<4)
-              Algorithm='GLM';
-            end
-
-            if(strcmp(Algorithm,'BNLRCG') && ~tObj.nspikeColl.getNST(neuronNumber).isSigRepBinary)
-               error('To use BNLRCG Algorithm, spikeTrain must have a binary representation. Increase sampleRate and try again');
-            end
-                    %For a single neuron given covariates,perform the GLM fit.
-            y=tObj.getSpikeVector(neuronNumber);
-            X=tObj.getDesignMatrix(neuronNumber);
-
-
-            if(tObj.nspikeColl.getNST(neuronNumber).isSigRepBinary)
-                distribution = 'binomial';
-                linkfunction = 'logit';
-            else
-                distribution = 'poisson';
-                linkfunction = 'log';
-            end
-%             size(X)
-%             size(y)
-                if(strcmp(Algorithm,'GLM'))
-                    [b,dev,stats] = glmfit(X,y,distribution, 'link', linkfunction,'constant','off');
-                elseif(strcmp(Algorithm,'BNLRCG'))
-                    rrflag=0; %ML estimation
-                    [b,dev,stats] = bnlrCG(X,y,rrflag);
-                else
-                    error('Algorithm not supported!');
-                end
-                if(length(b)>=1)
-                    if(strcmp(distribution,'binomial'))
-                        data = exp(X*b(1:end));
-                        data = (data./(1+data)).*tObj.sampleRate;
-
-                    elseif(strcmp(distribution,'poisson'));
-                        data = exp(X*b(1:end)).*tObj.sampleRate;
-
-%
-                    end
-                end
-
-%                 size(tObj.covarColl.getCov(1).getSigRep.time)
-%                 size(data)
-
-                lambda=Covariate(tObj.getCov(1).time,data,...
-                       '\Lambda(t)',tObj.getCov(1).xlabelval,...
-                        tObj.getCov(1).xunits,'Hz',strcat('\lambda_{',num2str(lambdaIndex),'}'));
-                AIC = 2*length(b)+dev;
-                BIC = length(b)*log(length(y))+dev;
-        end
-        function handle = plotInvGausTrans(fitResults,makePlot)
-            % handle = plotInvGausTrans(fitResults,makePlot)
-            % Given the CDF of the rescaled spike times (the u'js) computes
-            % the auto-correlation function inverse gaussian tranformated
-            % u'js and the 95% confidence interval that they are distinct
-            % from zero.
-            % Idea: if gaussian RVs are uncorrelated, they are indep., then
-            %       this suggest independence of the uj's and of the zj's
-            %       from the time-rescaling theorem. If zj's are
-            %       independent and KS plot is within 95% confidence
-            %       interval suggests that candidate lambda is close to the
-            %       true lambda.
-            if(nargin<2)
-                makePlot=0;
-            end
-            [X,rhoSig,confBoundSig] = Analysis.computeInvGausTrans(fitResults.Z);
-            fitResults.setInvGausStats(X,rhoSig,confBoundSig);
-
-            if(fitResults.isValDataPresent)
-                  [X,rhoSig,confBoundSig] = Analysis.computeInvGausTrans(fitResults.validation.Z);
-                  fitResults.validation.setInvGausStats(X,rhoSig,confBoundSig);
-            end
-
-            if(makePlot==1)
-                handle=fitResults.plotInvGausTrans;
-            end
-
-        end
-        function plotFitResidual(fitResults,windowSize,makePlot)
-            % plotFitResidual(fitResults,windowSize,makePlot)
-            % computes the point process residual between the true spike
-            % train and that predicted by the candidate conditional
-            % intensity function.
-            % The result is stored in fitResult.
-            %
-            M = Analysis.computeFitResidual(fitResults.neuralSpikeTrain,fitResults.lambda,windowSize);
-            fitResults.setFitResidual(M);
-
-            if(fitResults.isValDataPresent)
-                 M = Analysis.computeFitResidual(fitResults.validation.neuralSpikeTrain,fitResults.validation.lambda,windowSize);
-                 fitResults.validation.setFitResidual(M);
-            end
-
-            if(makePlot)
-              fitResults.plotResidual;
-            end
-        end
-        function handle = KSPlot(fitResults,makePlot)
-            %handle = KSPlot(fitResults,makePlot)
-            % Computes the KS statistics and makes the plot. Stores
-            % appropriate parameters in fitResults.
-            % If validation data is also available, it does the same for
-            % the validation data.
-            if(nargin <2)
-                makePlot =1; %By default make the plot
-            end
-
-            [Z, U, xAxis, KSSorted, ks_stat] = Analysis.computeKSStats(fitResults.neuralSpikeTrain,fitResults.lambda);
-            fitResults.setKSStats(Z,U, xAxis, KSSorted, ks_stat);
-
-
-            if(fitResults.isValDataPresent)
-                 %make sure nst is in appropriate window
-                    [Z, U, xAxis, KSSorted, ks_stat] = Analysis.computeKSStats(fitResults.validation.neuralSpikeTrain,fitResults.validation.lambda);
-                    fitResults.validation.setKSStats(Z, U, xAxis, KSSorted, ks_stat);
-
-            end
-
-            if(makePlot)
-                handle = fitResults.KSPlot;
-            else
-                handle = [];
-            end
-
-        end
-        function handle = plotSeqCorr(fitResults)
-            % handle = plotSeqCorr(fitResults)
-            % Plots the sequential correlation coefficients of the rescaled
-            % ISIs. zj vs. zj-1
-            handle = fitResults.plotSeqCorr;
-
-        end
-        function handle = plotCoeffs(fitResults)
-            % handle = plotCoeffs(fitResults)
-            % Plots the regression coefficients for all the different fits.
-
-            handle = fitResults.plotCoeffs;
-
-        end
-
-
-        function [X,rhoSig,confBoundSig]   = computeInvGausTrans(Z)
-            % [U,X,rhoSig,confBoundSig]   = computeInvGausTrans(Z)
-            % Take rescaled spikeTimes, zjs, transforms them to
-            % uniform(0,1), then computes the inverse gaussian
-            % transformation of these to xj's. rhoSig is the
-            % auto-correlation funcion of these xj's and is used to test
-            % for independence of the xj's. Independence of the xj's
-            % suggests indepence of the uj's and zj's (a condition
-            % necessary for the Time Rescaling Theorem).
-
-            U=1-exp(-Z);
-            U(U>=1)=.99999; %Prevent any 1 values which lead to infinity in X
-            X = norminv(U,0,1);
-            %X=erfinv(U);
-            [~,colm] = size(X);
-            for i=1:colm
-                [c(:,i),lags] = xcov(X(:,i));
-            end
-            index=find(lags==1);
-            lags=lags(index:end);
-            rho=c(index:end,:)./repmat(c(index-1,:),length(lags),1);
-            n=length(X);
-            confBound = 1.96/sqrt(n)*ones(length(lags),1);
-%              size(lags)
-%              size(rho)
-
-            confBoundSig = SignalObj(lags,[confBound -confBound],'ACF[ \Phi^{-1}(u_i) ]','\Delta \tau','sec');
-            confBoundSig.setPlotProps({' ''r'', ''LineWidth'' ,3'},1);
-            confBoundSig.setPlotProps({' ''r'', ''LineWidth'' ,3'},2);
-
-            handle=[];
-            rhoSig = SignalObj(lags,rho, 'ACF[ \Phi^-1(u_i) ]','\Delta \tau','sec');
-            plotProps = cell(1,colm);
-            for i=1:colm
-                plotProps{i}=strcat('''', '.',Analysis.colors{mod(i-1,length(Analysis.colors))+1},'''');
-            end
-            rhoSig.setPlotProps(plotProps);
-
-
-
-        end
-        function [Z,U,xAxis,KSSorted, ks_stat] = computeKSStats(nspikeTrain,lambdaInput,dtCorrection)
-            % [Z,U,xAxis,KSSorted, ks_stat] = computeKSStats(nspikeTrain,lambdaInput)
-            % Given a neural spike train (a sequence of spike times) and a
-            % conditional intensity function, computes the rescaled ISIs
-            % according to the time-rescaling theorem in Z. The Uj are
-            % returned in U and correspond to a transformation fo the Zjs
-            % (exponential rate 1 (according to T-R theorem) to be
-            % uniform(0,1).
-            %
-            % nspikeTrain: a nspikeTrain object
-            % lambdaInput: candidate conditional intensity function (a Covariate)
-            % Z: rescaled spike times
-            % U: Zjs tranformed to be uniform(0,1)
-            % xAxis: x-axis of the KS plot
-            % KSSorted: y-axis of KS plot
-            % ks_stat: the KS statistic. Maximum deviations from the 45
-            % degree line for each conditional intensity function.
-
-            %get the relevant spike train
-            if(nargin<3)
-                dtCorrection =1;
-            end
-
-            nCopy =nspikeTrain.nstCopy;
-%             minTime = nCopy.minTime;
-%             maxTime = nCopy.maxTime;
-%             nCopy.setMinTime(minTime);
-%             nCopy.setMaxTime(maxTime);
-
-
-
-            if(dtCorrection==1 && nCopy.isSigRepBin)
-                % Use DT Correction for Time Rescaling Theorem - Haslinger, Pipa and Brown (2010)
-                pkSignal=lambdaInput.*(1/lambdaInput.sampleRate);
-                pk = pkSignal.data;
-                spikeTrain = nCopy.getSigRep.data;
-                intValues=zeros(length(nCopy.getSpikeTimes)-1,lambdaInput.dimension);
-                for i=1:lambdaInput.dimension
-                    temp = ksdiscrete(pk(:,i),spikeTrain,'spiketrain');
-%                     length(temp)
-%                     length(intValues(:,i))
-                    %sometimes ksdiscrete returns 1 less spike train than
-                    %expected ... need to debug .... for now just fix
-                    %using length(temp) to index into intValues;
-                    intValues(1:length(temp),i) = temp;
-                end
-
-
-            else % do not correct for discrete time effects
-
-                tempLambda = lambdaInput;
-%                 tempLambda = tempLambda.resample(tempLambda.sampleRate*4);
-%                 lambda=tempLambda.getSigInTimeWindow(minTime,maxTime);%.dataToMatrix;
-                lambdaPosdata = max(tempLambda.data,0);
-                lambda = Covariate(tempLambda.time,lambdaPosdata,tempLambda.name,tempLambda.xlabelval,tempLambda.xunits,tempLambda.yunits,tempLambda.dataLabels);
-
-                lambdaInt = lambda.integral;
-
-                if(nCopy.isSigRepBin)
-                    spikeTimes = nCopy.getSpikeTimes;
-
-                else
-                    nstSignal = nCopy.getSigRep;
-                    spikeTimes=nstSignal.time(nstSignal.data~=0);
-
-
-                end
-
-                   if(~isempty(spikeTimes))
-                        tempVals = lambdaInt.getValueAt(spikeTimes);
-                        intValues= tempVals(2:end,:)-tempVals(1:end-1,:);
-                    else
-                        intValues = 0;
-                   end
-
-    %                 intValues=2*intValues;
-    %             lambdaInt.plot; hold all;
-    %             vals =lambdaInt.getValueAt(spikeTimes);
-    %             plot(spikeTimes,vals,'.')
-
-            end
-            Z = intValues; % rescales spike times - exponential rate 1
-            U = 1-exp(-Z); % store the rescaled spike times - uniform(0,1)
-
-
-            KSSorted = sort( U,'ascend' );
-            N = length(KSSorted);
-            if(N~=0)
-                xAxis=(([1:N]-.5)/N)'*ones(1,lambdaInput.dimension);
-                ks_stat = max(abs(KSSorted - (([1:N]-.5)/N)'*ones(1,lambdaInput.dimension)));
-            else
-                ks_stat=1;
-                xAxis=[];
-            end
-        end
-        function M=computeFitResidual(nspikeTrain,lambda,windowSize)
-            % M=computeFitResidual(nspikeTrain,lambda,windowSize)
-            % Computes the Point Process residual defined in
-            % 'A point process framework for relating neural spiking
-            % activity to spiking history, W Truccolo, UT Eden, MR Fellows,
-            % JP Donoghue and EN. Brown. Journal of Neurophysiology 2005.
-            %
-            % nspikeTrain: nspikeTrain object
-            % lambda: candidate conditional intensity function evaluated on the time
-            %         interval of the spike train.
-            % windowSize: the size of the window over which to compute the
-            %             residual.
-            % M: the point process residual (a Covariate object).
-            %
-            if(nargin<3 || isempty(windowSize))
-                windowSize=.1;
-            end
-            windowTimes = nspikeTrain.minTime:windowSize:nspikeTrain.maxTime;
-            nCopy=nspikeTrain.nstCopy.getSigRep(windowSize);%tObj.getNeuron(fitResults.neuronNumber).nstCopy;
-            %nCopy.windowedSignal(windowTimes)
-            % this gets us the SUM over a window of length windowSize
-            % y[n] = y[n-1] + x[n] -- running sum filter
-            B=1; A=[1 -1];
-            sumSpikes = nCopy.filter(B,A);
-            %spikeTimes =nCopy.getSpikeTimes';
-            sumSpikesOverWindow= sumSpikes.getValueAt(windowTimes(2:end))-sumSpikes.getValueAt(windowTimes(1:(end-1)));
-            lambdaInt = lambda.integral;
-            lambdaIntVals = lambdaInt.getValueAt(windowTimes(2:end))-lambdaInt.getValueAt(windowTimes(1:(end-1)));
-            Mdata=repmat(sumSpikesOverWindow,[1 lambdaInt.dimension])-lambdaIntVals;
-            dataLabels = cell(1,lambdaInt.dimension);
-            for i=1:lambdaInt.dimension
-                dataLabels{i} = lambda.dataLabels{i};
-            end
-
-            M=Covariate(windowTimes(2:end),Mdata,'M(t_k)-Residual',lambdaInt.xlabelval, ...
-                        lambdaInt.xunits,lambdaInt.yunits,dataLabels);
-
-        end
-
-        function [fitResults,ensembleCovariate,tcc] = compHistEnsCoeffForAll(tObj,history,makePlot)
-            % [fitResults,ensembleCovariate,tcc] = compHistEnsCoeffForAll(tObj,history,makePlot)
-            %  runs Analysis.compHistEnsCoff for each neuron that is not masked.
-            if(nargin<3 || isempty(makePlot))
-                makePlot=1;
-            end
-            neuronIndex=tObj.getNeuronIndFromMask;
-            fitResults = cell(1,length(neuronIndex));
-            tcc = cell(1,length(neuronIndex));
-            ensembleCovariate = tObj.getEnsembleNeuronCovariates(neuronIndex(1),[],history);
-            [fitResults{1},tcc{1}] = Analysis.compHistEnsCoeff(tObj,history,neuronIndex(1),tObj.getNeuronNeighbors(1),ensembleCovariate,makePlot);
-            for i=2:length(neuronIndex)
-                ensembleCovariate.maskAwayAllExcept(tObj.getNeuronNeighbors(neuronIndex(i)));
-                [fitResults{i},tcc{i}] = Analysis.compHistEnsCoeff(tObj,history,neuronIndex(i),tObj.getNeuronNeighbors(neuronIndex(i)),ensembleCovariate,makePlot);
-            end
-        end
-        function [fitResults,ensembleCov,tcc] = compHistEnsCoeff(tObj,history,neuronNum,neighbors,ensembleCov,makePlot)
-            % [fitResults,ensembleCov,tcc] = compHistEnsCoeff(tObj,history,neuronNum,neighbors,ensembleCov,makePlot)
-            % Given a trial, a history object compute the history time
-            % series for the ensemble of neighboring neurons. This is done for all neurons and the result is returned in
-            % ensembleCov as a covariate collection. This collection is
-            % then used as the design matrix and the analysis performed for
-            % each neuron. The results are returned in fitResults.
-            %
-            %
-            if(nargin<6 || isempty(makePlot))
-                makePlot=1;
-            end
-
-            if(nargin<3 || isempty(neuronNum))
-                neuronNum=tObj.getNeuronIndFromMask;
-            end
-
-            if(nargin<4 || isempty(neighbors))
-                 neighbors=tObj.getNeuronNeighbors(neuronNum); %every other neuron
-            end
-
-            if(nargin<5 || isempty(ensembleCov))
-                ensembleCov = tObj.getEnsembleNeuronCovariates(neuronNum,neighbors,history);
-            end
-
-
-            %Create a covariate collection that consists of only the
-            %ensemble history
-            ensembTrial = Trial(tObj.nspikeColl,ensembleCov);
-            tc=TrialConfig('all',[],[]); %use all ensembleCov
-            tcc = ConfigColl(tc);
-            fitResults =Analysis.RunAnalysisForNeuron(ensembTrial,neuronNum,tcc,makePlot);
-        end
-        function [fitResults,tcc] = computeHistLag(tObj,neuronNum,windowTimes,CovLabels,sampleRate,makePlot)
-            % [fitResults,tcc] = computeHistLag(tObj,tObj,neuronNum,windowTimes,CovLabels,sampleRate,makePlot)
-            % For the neuron in neuronNum, runs an analysis with self
-            % history, and no extrinsic covariates, and no ensemble history
-            % as a covariates. The self history is specfied by a vector
-            % of windowTimes. There will be length(windowTimes) different
-            % results (configurations) corresponding to increasing number of history
-            % windows.
-            if(nargin<6)
-                makePlot=1;
-            end
-            if(nargin<5 || isempty(sampleRate))
-                sampleRate = tObj.sampleRate;
-            end
-            if(nargin<4)
-                CovLabels ={};
-            end
-            if(nargin<3)
-                error('Must specify a vector of windowTimes');
-            end
-            if(nargin<2 || isempty(neuronNum))
-                neuronNum = tObj.getNeuronIndFromMask;
-            end
-
-            % tcObj=TrialConfig(covMask,sampleRate, history,minTime,maxTime)
-            tc=cell(1,length(windowTimes)-1);
-            for i=1:length(tc)+1
-                %use no covariates
-                if(i==1)
-                    tc{i} = TrialConfig(CovLabels,sampleRate,[],[]); tc{i}.setName('Baseline');
-                else
-                    tc{i} = TrialConfig(CovLabels,sampleRate,windowTimes(1:i));
-                end
-
-            end
-            tcc = ConfigColl(tc);
-            fitResults =Analysis.RunAnalysisForNeuron(tObj,neuronNum,tcc,makePlot);
-        end
-        function fitResults = computeHistLagForAll(tObj,windowTimes,CovLabels,sampleRate,makePlot)
-            % [fitResults,tcc] = computeHistLagAll(tObj,windowTimes,CovLabels,sampleRate,makePlot)
-            % Calls computeHistLab for each neuron in the trial that is not masked.
-            if(nargin<5)
-                makePlot=1;
-            end
-            if(nargin<4 || isempty(sampleRate))
-                sampleRate = tObj.sampleRate;
-            end
-            if(nargin<3)
-                CovLabels ={};
-            end
-            if(nargin<2)
-                error('Must specify a vector of windowTimes');
-            end
-
-            neuronIndex=tObj.getNeuronIndFromMask;
-            fitResults = cell(1,length(neuronIndex));
-            for i=1:length(neuronIndex)
-               fitResults{i} = Analysis.computeHistLag(tObj,neuronIndex(i),windowTimes,CovLabels,sampleRate,makePlot);
-            end
-
-
-
-        end
-        function [fitResults,tcc]=computeNeighbors(tObj,neuronNum,sampleRate,windowTimes,makePlot)
-            % [fitResults,tcc]=computeNeighbors(tObj,neuronNum,sampleRate,windowTimes,makePlot)
-            % For the neuron in neuronNum, runs an analysis with no self
-            % history, and no extrinsic covariates, only ensemble history
-            % as a covariate. The ensemble history is specfied by a vector
-            % of windowTimes. There will be length(windowTimes) different
-            % results corresponding to increasing number of history
-            % windows.
-            if(nargin<4)
-                makePlot=1;
-            end
-            if(nargin<3 || isempty(sampleRate))
-                sampleRate = tObj.sampleRate;
-            end
-            if(nargin<2 || isempty(neuronNum))
-                neuronNum = tObj.getNeuronIndFromMask;
-            end
-            tc=cell(1,length(windowTimes)-1);
-            for i=1:length(windowTimes)
-                % For reference: tcObj=TrialConfig(covMask,sampleRate, history,covHist,covLag,name)
-                if(i==1)
-                    tc{i} = TrialConfig({},sampleRate,[],[]); tc{1}.setName('Baseline');
-                else
-                    tc{i} = TrialConfig({},sampleRate,[],windowTimes(1:i));
-                end
-            end
-               tcc = ConfigColl(tc);
-               fitResults =Analysis.RunAnalysisForNeuron(tObj,neuronNum,tcc,makePlot);
-        end
-
-        function cc=spikeTrigAvg(tObj,neuronNum,windowSize)
-            % cc=spikeTrigAvg(tObj,neuronNum,windowSize)
-            % Each covariate dimension is sampled at every spike time of
-            % the neuron specified +/- windowSize. The number of columns of
-            % each new covariate corresponds to the number of spikes in the
-            % spike train. A covariate collection is returned containing
-            % each covariate dimension as a new covariate. These can then
-            % be easily avergaged by using SignalObj method
-            % plotVariability.
-
-            nCopy=tObj.getNeuron(neuronNum).nstCopy;
-            t=-windowSize/2:1/tObj.sampleRate:windowSize/2;
-            covIndex=0;
-            for i = 1:tObj.covarColl.numCov
-                tempCov=tObj.getCov(i);
-                data=[];
-                dataIndex=0;
- %               for n=1:tObj.nspikeColl.numSpikeTrains
-%                     nCopy=tObj.getNeuron(neuronNum).nstCopy;
-                    spikeTimes = nCopy.getSpikeTimes';
-                    for j=1:length(spikeTimes)
-                      dataIndex=dataIndex+1;
-                      tc=tempCov.getSigInTimeWindow(spikeTimes(j)-windowSize/2,spikeTimes(j)+windowSize/2);
-                      tc=tc.shift(-tc.minTime-windowSize/2);
-                      tempData = tc.getValueAt(t);
-%                       if(isempty(data))
-%                         data(dataIndex,1:length(tempData),:)=tempData;
-%                       else
-%                         data(dataIndex,:,:)=zeros(size(squeeze(data(1,:,:))));
-                        data(dataIndex,:,:)=tempData;
-%                       end
-                    end
-                %end
-
-                for k=1:tempCov.dimension
-                    covIndex = covIndex+1;
-                    cov{covIndex} = Covariate(t,squeeze(data(:,:,k)),tempCov.dataLabels{k},tempCov.xlabelval,tempCov.xunits,tempCov.yunits,tempCov.dataLabels{k});
-                end
-            end
-            cc=CovColl(cov);
-
-        end
-        function plotStatHistData(index,spdata,svdata,sfdata)
-        % plotStatHistData(index,spdata,svdata,sfdata)
-        % Helpfer function to view historgrams of the position, velocity,
-        % and force data at each spike time.
-        % index is used to label the plot and should correspond to the
-        % neuron that was used to compute this data.
-        %
-        % position (x,y,z) array
-        % veloctity vx vy vz array
-        % force: fz, fzmag, fld, flf array
-
-        sfdata((sfdata==0))=nan; %
-            fig(1)=figure('visible','off'); a1=scatterhist(spdata(:,1),spdata(:,2));  set(get(gca,'YLabel'),'String','y'); set(get(gca,'XLabel'),'String','x')
-            fig(2)=figure('visible','off'); a2=scatterhist(spdata(:,1),spdata(:,3));  set(get(gca,'YLabel'),'String','z'); set(get(gca,'XLabel'),'String','x')
-            fig(3)=figure('visible','off'); a3=scatterhist(spdata(:,2),spdata(:,3));  set(get(gca,'YLabel'),'String','z'); set(get(gca,'XLabel'),'String','y')
-            fig(4)=figure('visible','off'); a4=scatterhist(svdata(:,1),svdata(:,2));  set(get(gca,'YLabel'),'String','v_y'); set(get(gca,'XLabel'),'String','v_x')
-            fig(5)=figure('visible','off'); a5=scatterhist(svdata(:,1),svdata(:,3));  set(get(gca,'YLabel'),'String','v_z'); set(get(gca,'XLabel'),'String','v_x')
-            fig(6)=figure('visible','off'); a6=scatterhist(svdata(:,2),svdata(:,3));  set(get(gca,'YLabel'),'String','v_z'); set(get(gca,'XLabel'),'String','v_y')
-            fig(7)=figure('visible','off'); a7=scatterhist(sfdata(:,1),sfdata(:,3));  set(get(gca,'YLabel'),'String','f_{ld}'); set(get(gca,'XLabel'),'String','f_z')
-            fig(8)=figure('visible','off'); a8=scatterhist(sfdata(:,1),sfdata(:,4));  set(get(gca,'YLabel'),'String','f_{lf}'); set(get(gca,'XLabel'),'String','f_z')
-            fig(9)=figure('visible','off'); a9=scatterhist(sfdata(:,3),sfdata(:,4));  set(get(gca,'YLabel'),'String','f_{lf}'); set(get(gca,'XLabel'),'String','f_{ld}')
-
-
-            h=figure(index+100);
-            scrsz = get(0,'ScreenSize');
-
-            set(h,'Name',strcat('Neuron #',num2str(index)),'Position',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.8 scrsz(4)*.8]);
-            u1 = uipanel(h,'position',[.0  .66 .33 .33]); set(a1,'parent',u1);
-            u2 = uipanel(h,'position',[.33 .66 .33 .33]); set(a2,'parent',u2);
-            u3 = uipanel(h,'position',[.66 .66 .33 .33]); set(a3,'parent',u3);
-            u4 = uipanel(h,'position',[.0  .33 .33 .33]); set(a4,'parent',u4);
-            u5 = uipanel(h,'position',[.33 .33 .33 .33]); set(a5,'parent',u5);
-            u6 = uipanel(h,'position',[.66 .33 .33 .33]); set(a6,'parent',u6);
-            u7 = uipanel(h,'position',[.0   0 .33 .33]); set(a7,'parent',u7);
-            u8 = uipanel(h,'position',[.33  0 .33 .33]); set(a8,'parent',u8);
-            u9 = uipanel(h,'position',[.66  0 .33 .33]); set(a9,'parent',u9);
-            close(fig);
-        end
-
-    end
-
-
-
-end
-
-
-
-function [flatMask, maxIndex]=flatMaskCellToMat(flatMaskCell)
-    % [flatMask, maxIndex]=flatMaskCellToMat(flatMaskCell)
-    lMask =zeros(1,length(flatMaskCell));
-    for i=1:length(flatMaskCell)
-        lMask(i) = length(flatMaskCell{i});
-    end
-    [maxSize,maxIndex] = max(lMask);
-    flatMask = zeros(maxSize,length(flatMaskCell));
-    for i=1:length(flatMaskCell)
-        flatMask(1:length(flatMaskCell{i}),i) = flatMaskCell{i};
-    end
-end
-function [beta_new,devnew,stats] = bnlrCG(X,yframe,rrflag)
-% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
-%                                                               %
-% Truncated, L-2 Regularized, Binomial Logistic Regression with %
-% Conjugate Gradient Solver                                     %
-%                                                               %
-% Author: Demba Elimane Ba                                      %
-%         MIT Department of EECS                                %
-%         Neuro Stat Research Lab (MIT Department of BCS)       %
-% Date  : August the 25th, 2008                                 %
-%                                                               %
-% Note  : Matlab implementation of Paul Komarek's TR-IRLS       %
-%                                                               %
-% % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %
-
-% Modified by Iahn Cajigas 9-23-09 to automatically add the DC term for the
-% design matrix
-
-% Arguments:
-%   X:      design matrix, including DC column of all ones (1st or last)
-%   yframe: column vector of binary observations
-%   rrflag: 1: MAP estimation with Gaussian(0,sigma^2) prior (default value
-%               1/sigma^2 = 10)
-%           0: ML estimation (1/sigma^2 = 0, i.e. sigma -> infinity)
-%
-%   N.B: The equivalent call with glmfit is:
-%
-%   [beta,dev,stats]=glmfit(X(:,2:end),[yframe ones(size(yframe))],'binomial','logit');
-%
-%   Unlike glmfit, this function assumes that the design matrix
-%   already has a column of all ones (1st or last).
-
-    %Modify the design Matrix;
-    [rows,~]=size(X);
-%     X = [ones(rows,1), X];
-    % CG parameters
-    cgmax = 30;
-    cgeps = 1e-3;
-
-    % LR parameters
-    lrmax = 100;
-    lreps = 0.05;
-    lambda = 10;
-
-    [n,d] = size(X);
-    % Perform logistic regression
-    i = 0;
-    % Initial guess for Beta = beta_old ?
-    beta_old = zeros(d,1);
-    n = X*beta_old;
-    u = exp(n)./(1+exp(n));
-    W = repmat(u'.*(1-u)',d,1);
-    z = X*beta_old + (W(1,:)'.^-1).*(yframe - u);
-
-    devold = -2*sum(yframe.*log(u) + (1-yframe).*log(1-u));
-    devnew = 0;
-    devdiff = abs(devnew - devold);
-
-
-    while (i < lrmax && devdiff > lreps)
-        % Do CG -> beta_new, i.e. solve for beta_new: XtWX*beta_new = XtWz(beta_old) using CG
-
-        A = X'.*W*X; b = X'.*W*z;
-
-        if rrflag == 1
-            A = A + lambda*eye(size(A));
-        end
-
-        beta_new = cgs(A,b,cgeps,cgmax,[],[],beta_old);
-        beta_old = beta_new;
-
-        n = X*beta_old;
-        u = exp(n)./(1+exp(n));
-        W = repmat(u'.*(1-u)',d,1);
-        z = X*beta_old + (W(1,:)'.^-1).*(yframe - u);
-
-        devnew = -2*sum(yframe.*log(u) + (1-yframe).*log(1-u));
-        devdiff = abs(devnew - devold);
-        devold = devnew;
-
-        i = i+1;
-
-
-    end
-
-    % Compute a few statistics
-    stats.dfe = 0;
-    stats.s = 0;
-    stats.sfit = 0;
-    stats.covb = inv(A);
-    stats.se = sqrt(diag(stats.covb));
-    stats.coeffcorr = stats.covb./sqrt((repmat(diag(stats.covb),1,d).*repmat(diag(stats.covb)',d,1)));
-    stats.t = 0;
-    stats.p = 0;
-    stats.resid = 0;
-    stats.residp = 0;
-    stats.residd = 0;
-    stats.resida = 0;
-end
-
-
-function [rst,varargout] = ksdiscrete(pk,st,spikeflag)
-
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-%
-% ksdiscrete.m
-% written by Rob Haslinger, December 2009
-%
-% This function performs time rescaling of ISIs based upon the discrete
-% time version of the time rescaling theorem as described in Haslinger,
-% Pipa and Brown (2010?).  This method corrects for biases in the KS plot
-% caused by the temporal discretization.
-%
-% This function can be called in two ways
-%
-% 1) input the discrete time conditional probabilities "pk"  where 0<=pk<= 1
-% and the spike train "spiketrain" which has elements either equal to 0 (no
-% spike) or 1 (spike). There is also a flag 'spiketrain' to indicate that
-% it is the full spike train.
-%
-% [rst,rstsort,xks,cb,rstoldsort] = ksdiscrete(pk,spiketrain,'spiketrain')
-%
-% 2) input the discrete time conditional probabilities "pk" and a list of
-% the indicies "spikeind" of the bin indicies that the spikes are locaed in.
-% There is also a flag 'spikeind' to indicate that the indicies are
-% being given, not the full spike train
-%
-% [rst,rstsort,xks,cb,rstoldsort] = ksdiscrete(pk,spikeind,'spikeind');
-%
-% required output:
-%
-% rst : a vector of unsorted uniformly distributed rescaled times. This is
-% the only output that is required.
-%
-% optional output, given in the order they appear in the list function
-% outputs :
-%
-% rstsort : a vector of rescaled times sorted into ascending order
-% xks : a vector of x axis values to plot the sorted rescaled times against
-% cb : the value of the 95% confidence bounds
-% rstoldsort : a vector of sorted rescaled times done without the discrete
-% time correction
-%
-% To make a KS plot one would do
-% plot(xks,rstsort,'k-');
-% hold on;
-% plot(xks,xks+cb,'k--',xks,xks-cb,'k--');
-%
-% To make a Differential KS plot one would do
-% plot(xks,rstsort-xks,'k-');
-% hold on;
-% plot(xks,zeros(length(xks))+cb,'k--',xks,zeros(length(xks))-cb);
-%
-%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-
-% Start with determining the inputs and some basic input error checking
-
-    if nargin < 3 || nargin > 3;
-        error('Number of input arguments must be equal to 3');
-    end;
-
-    % make pk into a column vector;
-
-    [m1,m2]=size(pk);
-        if (m1 ~=1 && m2 ~=1); error('pk must be a vector'); end;
-        if (m2>m1); pk=pk'; end;
-        [m1,m2]=size(pk);
-
-    % make sure pk's are within [0,1]
-    index=find(pk<0);
-    if isempty(index) ~=1;
-        error('all values for pk must be within [0,1]');
-    end;
-    index=find(pk>1);
-    if isempty(index) ~=1;
-        error('all values for pk must be within [0,1]');
-    end;
-    clear index;
-
-    % make column vector of spike indicies
-
-    if strcmp(spikeflag,'spiketrain'); % spike train input
-
-        [n1,n2]=size(st);
-          if (n1 ~=1 && n2 ~=1); error('spike train must be a vector'); end;
-        if (n2>n1); st=st'; end;
-
-        if m1 ~= n1; error('pk and spike train must be same length'); end;
-
-        spikeindicies=find(st==1);
-
-        Nspikes=length(spikeindicies);
-
-    elseif strcmp(spikeflag,'spikeind'); % spike index input
-
-        [n1,n2]=size(st);
-          if (n1 ~=1 && n2 ~=1); error('spike indicies must be a vector'); end;
-        if (n2>n1); st=st'; end;
-
-        spikeindicies=unique(st);
-        Nspikes=length(spikeindicies);
-
-    end;
-
-    % check that those indicies are in [1:length(pk)];
-
-    if spikeindicies(1)<1;
-         error('There is at least one spike with index less than 0');
-    end;
-    if spikeindicies(Nspikes)>length(pk);
-         error('There is at least one spike with a index greater than the length of pk');
-    end;
-
-    % error checking done
-
-    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-    % Now do the actual discrete time KS test
-    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-
-    % initialize random number generator
-    s = RandStream('mt19937ar','Seed', sum(100*clock));
-    RandStream.setDefaultStream(s);
-    %rand('twister',sum(100*clock));
-
-    % make the qk's
-
-    qk=-log(1-pk);
-
-    % make the rescaled times
-
-    rst=zeros(Nspikes-1,1);
-    rstold=zeros(Nspikes-1,1);
-
-    for r=1:Nspikes-1;
-
-        total = 0;
-
-        ind1=spikeindicies(r);
-        ind2=spikeindicies(r+1);
-
-        total=total+sum(qk(ind1+1:ind2-1));
-
-        delta=-(1/qk(ind2))*log(1-rand()*(1-exp(-qk(ind2))));
-
-        total=total+qk(ind2)*delta;
-
-        rst(r)=total;
-
-        rstold(r)=sum(qk(ind1+1:ind2));
-
-    end;
-
-%     rst=1-exp(-rst);
-%     rstold=1-exp(-rstold);
-
-    % optional outputs
-
-    rstsort=sort(rst);
-    varargout{1}=rstsort;
-
-    inrst=1/(Nspikes-1);
-    xrst=(0.5*inrst:inrst:1-0.5*inrst)';
-    varargout{2}=xrst;
-
-    cb=1.36*sqrt(inrst);
-    varargout{3}=cb;
-
-    varargout{4}=sort(rstold);
-end
-
\ No newline at end of file diff --git a/helpfiles/AnalysisExamples.html b/helpfiles/AnalysisExamples.html deleted file mode 100644 index 45f89676..00000000 --- a/helpfiles/AnalysisExamples.html +++ /dev/null @@ -1,250 +0,0 @@ - - - - - Analysis Examples

Analysis Examples

This is an example on the standard approach to fitting GLM models to spike train data. This data set was obtained at the Society For Neuroscience '08 Workshop on Workshop on Neural Signal Processing Compare to analysis with Neural Spike Analysis Toolbox

Contents

Example 1: Tradition Preliminary Analysis

% Script glm_part1.m
-% MATLAB code to visualize data, fit a GLM model of the relation between
-% spiking and the rat's position, and visualize this model for the
-% Neuroinformatics GLM problem set.
-% The code is initialized with an overly simple GLM model construction.
-% Please improve it!
-
-% load the rat trajectory and spiking data;
-close all;
-warning off;
-load('glm_data.mat');
-

visualize the raw data

figure;
-plot(xN,yN,x_at_spiketimes,y_at_spiketimes,'r.');
-axis tight square;
-xlabel('x position (m)'); ylabel('y position (m)');
-

fit a GLM model to the x and y positions.

[b,dev,stats] = glmfit([xN yN (xN.^2-mean(xN.^2)) (yN.^2-mean(yN.^2)) (xN.*yN-mean(xN.*yN))],spikes_binned,'poisson');
-figure;
-errorbar(1:length(b), b, stats.se,'.');
-xticks=1:length(b);
-xtickLabels= {'baseline','x','y','x^2','y^2','x*y'};
-set(gca,'xtick',xticks,'xtickLabel',xtickLabels);
-

visualize your model construct a grid of positions to plot the model against...

figure;
-[x_new,y_new]=meshgrid(-1:.1:1);
-y_new = flipud(y_new);
-x_new = fliplr(x_new);
-
-% compute lambda for each point on this grid using the GLM model
-lambda = exp(b(1) + b(2)*x_new + b(3)*y_new + b(4)*x_new.^2 + b(5)*y_new.^2 + b(6)*x_new.*y_new);
-lambda((x_new.^2+y_new.^2>1))=nan;
-
-%plot lambda as a function position over this grid
-h_mesh = mesh(x_new,y_new,lambda,'AlphaData',0);
-get(h_mesh,'AlphaData');
-set(h_mesh,'FaceAlpha',0.2,'EdgeAlpha',0.8,'EdgeColor','b');
-hold on;
-plot3(cos(-pi:1e-2:pi),sin(-pi:1e-2:pi),zeros(size(-pi:1e-2:pi))); hold on;
-plot(xN,yN,x_at_spiketimes,y_at_spiketimes,'r.');
-axis tight square;
-xlabel('x position (m)'); ylabel('y position (m)');
-

Compare a linear model versus a Gaussian GLM model.

[b_lin,dev_lin,stats_lin] = glmfit([xN yN],spikes_binned,'poisson');
-[b_quad,dev_quad,stats_quad] = glmfit([xN yN xN.^2 yN.^2 xN.*yN],spikes_binned,'poisson');
-
-lambdaEst_lin = exp( b_lin(1) + b_lin(2)*xN+b_lin(3)*yN);  % based on our GLM model with the log "link function"
-lambdaEst_quad = exp( b_quad(1) + b_quad(2)*xN+b_quad(3)*yN+b_quad(4)*xN.^2 +b_quad(5)*yN.^2 +b_quad(6)*xN.*yN);
-

Make the KS Plot

% *******  K-S Plot  *******************
-% graph the K-S plot and confidence intervals for the K-S statistic
-
-%first generate the conditional intensity at each timestep
-% ** Adjust the below line according to your choice of model.
-% remember to include a column of ones to multiply the default constant GLM parameter beta_0**
-
-% Use your parameter estimates (b) from glmfit along
-% with the covariates you used (xN, yN, ...)
-
-lambdaEst=[lambdaEst_lin, lambdaEst_quad];
-timestep = 1;
-lambdaInt = 0;
-j=0;
-KS=[];
-for t=1:length(spikes_binned),
-    lambdaInt = lambdaInt + lambdaEst(t,:)*timestep;
-    if (spikes_binned(t)),
-        j = j + 1;
-        KS(j,:) = 1-exp(-lambdaInt);
-        lambdaInt = [0 0];
-    end;
-end;
-KSSorted = sort( KS );
-N = length( KSSorted);
-figure;
-plot( ([1:N]-.5)/N, KSSorted, 0:.01:1,0:.01:1, 'g',0:.01:1, [0:.01:1]+1.36/sqrt(N), 'r', 0:.01:1,[0:.01:1]-1.36/sqrt(N), 'r' );
-axis( [0 1 0 1] );
-xlabel('Uniform CDF');
-ylabel('Empirical CDF of Rescaled ISIs');
-title('KS Plot with 95% Confidence Intervals');
-legend('Linear','Quadratic');
-
\ No newline at end of file diff --git a/helpfiles/AnalysisExamples.m b/helpfiles/AnalysisExamples.m deleted file mode 100644 index b719a482..00000000 --- a/helpfiles/AnalysisExamples.m +++ /dev/null @@ -1,103 +0,0 @@ -%% Analysis Examples -% This is an example on the standard approach to fitting GLM models to -% spike train data. This data set was obtained at the Society For -% Neuroscience '08 Workshop on -% -% Compare to analysis with -% -%% Example 1: Tradition Preliminary Analysis - -% Script glm_part1.m -% MATLAB code to visualize data, fit a GLM model of the relation between -% spiking and the rat's position, and visualize this model for the -% Neuroinformatics GLM problem set. -% The code is initialized with an overly simple GLM model construction. -% Please improve it! - -% load the rat trajectory and spiking data; -close all; -warning off; -load('glm_data.mat'); - -%% -% visualize the raw data -figure; -plot(xN,yN,x_at_spiketimes,y_at_spiketimes,'r.'); -axis tight square; -xlabel('x position (m)'); ylabel('y position (m)'); - -%% -% fit a GLM model to the x and y positions. -[b,dev,stats] = glmfit([xN yN (xN.^2-mean(xN.^2)) (yN.^2-mean(yN.^2)) (xN.*yN-mean(xN.*yN))],spikes_binned,'poisson'); -figure; -errorbar(1:length(b), b, stats.se,'.'); -xticks=1:length(b); -xtickLabels= {'baseline','x','y','x^2','y^2','x*y'}; -set(gca,'xtick',xticks,'xtickLabel',xtickLabels); - -%% -% visualize your model -% construct a grid of positions to plot the model against... -figure; -[x_new,y_new]=meshgrid(-1:.1:1); -y_new = flipud(y_new); -x_new = fliplr(x_new); - -% compute lambda for each point on this grid using the GLM model -lambda = exp(b(1) + b(2)*x_new + b(3)*y_new + b(4)*x_new.^2 + b(5)*y_new.^2 + b(6)*x_new.*y_new); -lambda((x_new.^2+y_new.^2>1))=nan; - -%plot lambda as a function position over this grid -h_mesh = mesh(x_new,y_new,lambda,'AlphaData',0); -get(h_mesh,'AlphaData'); -set(h_mesh,'FaceAlpha',0.2,'EdgeAlpha',0.8,'EdgeColor','b'); -hold on; -plot3(cos(-pi:1e-2:pi),sin(-pi:1e-2:pi),zeros(size(-pi:1e-2:pi))); hold on; -plot(xN,yN,x_at_spiketimes,y_at_spiketimes,'r.'); -axis tight square; -xlabel('x position (m)'); ylabel('y position (m)'); - - -%% -% Compare a linear model versus a Gaussian GLM model. -[b_lin,dev_lin,stats_lin] = glmfit([xN yN],spikes_binned,'poisson'); -[b_quad,dev_quad,stats_quad] = glmfit([xN yN xN.^2 yN.^2 xN.*yN],spikes_binned,'poisson'); - -lambdaEst_lin = exp( b_lin(1) + b_lin(2)*xN+b_lin(3)*yN); % based on our GLM model with the log "link function" -lambdaEst_quad = exp( b_quad(1) + b_quad(2)*xN+b_quad(3)*yN+b_quad(4)*xN.^2 +b_quad(5)*yN.^2 +b_quad(6)*xN.*yN); - -%% -% Make the KS Plot - -% ******* K-S Plot ******************* -% graph the K-S plot and confidence intervals for the K-S statistic - -%first generate the conditional intensity at each timestep -% ** Adjust the below line according to your choice of model. -% remember to include a column of ones to multiply the default constant GLM parameter beta_0** - -% Use your parameter estimates (b) from glmfit along -% with the covariates you used (xN, yN, ...) - -lambdaEst=[lambdaEst_lin, lambdaEst_quad]; -timestep = 1; -lambdaInt = 0; -j=0; -KS=[]; -for t=1:length(spikes_binned), - lambdaInt = lambdaInt + lambdaEst(t,:)*timestep; - if (spikes_binned(t)), - j = j + 1; - KS(j,:) = 1-exp(-lambdaInt); - lambdaInt = [0 0]; - end; -end; -KSSorted = sort( KS ); -N = length( KSSorted); -figure; -plot( ([1:N]-.5)/N, KSSorted, 0:.01:1,0:.01:1, 'g',0:.01:1, [0:.01:1]+1.36/sqrt(N), 'r', 0:.01:1,[0:.01:1]-1.36/sqrt(N), 'r' ); -axis( [0 1 0 1] ); -xlabel('Uniform CDF'); -ylabel('Empirical CDF of Rescaled ISIs'); -title('KS Plot with 95% Confidence Intervals'); -legend('Linear','Quadratic'); \ No newline at end of file diff --git a/helpfiles/AnalysisExamples.png b/helpfiles/AnalysisExamples.png deleted file mode 100644 index b69c76a8..00000000 Binary files a/helpfiles/AnalysisExamples.png and /dev/null differ diff --git a/helpfiles/AnalysisExamples2.html b/helpfiles/AnalysisExamples2.html deleted file mode 100644 index a92f174e..00000000 --- a/helpfiles/AnalysisExamples2.html +++ /dev/null @@ -1,267 +0,0 @@ - - - - - AnalysisExamples2

Contents

Analysis Examples 2

Compare with traditional Neural Spike Train Analysis here

% load the rat trajectory and spiking data;
-close all;
-warning off;
-load('glm_data.mat');
-
-nst = nspikeTrain(spiketimes);
-baseline = Covariate(T,ones(length(xN),1),'Baseline','time','s','',{'mu'});
-position = Covariate(T,[xN yN],'Position', 'time','s','m',{'x','y'});
-velocity = Covariate(T,[vxN,vyN],'Velocity','time','s','m/s',{'v_x','v_y'});
-radial   = Covariate(T,[xN yN xN.^2 yN.^2 xN.*yN],'Radial','time','s','m',{'x','y','x^2','y^2','x*y'});
-% could just define velocity = postion.derivative;
-
-%possibly add view as vector for covariates of dimension 3 or less
-

In the original analysis, we already had vectors of the covariates sampled at the spiketimes. This step would require interpolating the covariates and then sampling them at each of the spikeTimes. In our case this is quite simple.

[values_at_spiketimes] =position.getValueAt(spiketimes);
-

We could also upsample our data to get better estimates of the covariates at these points

[values_at_spiketimes] =position.resample(1/min(diff(spiketimes))).getValueAt(spiketimes);
-

visualize the raw data

figure;
-plot(position.getSubSignal('x').dataToMatrix,position.getSubSignal('y').dataToMatrix,...
-     values_at_spiketimes(:,1),values_at_spiketimes(:,2),'r.');
-axis tight square;
-xlabel('x position (m)'); ylabel('y position (m)');
-

Create a trial object and define the fits that we want to run

spikeColl = nstColl({nst});
-covarColl = CovColl({baseline,radial});
-trial     = Trial(spikeColl,covarColl);
-clear tc;
-sampleRate=1000;
-% tcObj=TrialConfig(covMask,sampleRate, history,minTime,maxTime)
-tc{1} = TrialConfig({{'Baseline','mu'},{'Radial','x','y'}},sampleRate,[]); tc{1}.setName('Linear');
-tc{2} = TrialConfig({{'Baseline','mu'},{'Radial','x','y','x^2','y^2','x*y'}},sampleRate,[]); tc{2}.setName('Quadratic');
-tc{3} = TrialConfig({{'Baseline','mu'},{'Radial','x','y','x^2','y^2','x*y'}},sampleRate,[0 1]./sampleRate); tc{3}.setName('Quadratic+Hist');
-

Create our collection of configurations and run the analysis;

tcc = ConfigColl(tc); makePlot=1; neuronNum=1;
-fitResults =Analysis.RunAnalysisForAllNeurons(trial,tcc,0);
-fitResults.plotResults;
-
Analyzing Configuration #1: Neuron #1
-Analyzing Configuration #2: Neuron #1
-Analyzing Configuration #3: Neuron #1
-

Visualize the firing rates as a function of the spatial covariates

figure;
-[x_new,y_new]=meshgrid(-1:.1:1); %define new x and y
-y_new = flipud(y_new);
-x_new = fliplr(x_new);
-
-%For each covariate new to place the new data in a cell array
-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;
-color = Analysis.colors;
-
-% Evaluate our fits using the new parameters
-for i=1:fitResults.numResults
-
-    lambda = fitResults.evalLambda(i,newData);
-    h_mesh = mesh(x_new,y_new,lambda,'AlphaData',0);
-    get(h_mesh,'AlphaData');
-    set(h_mesh,'FaceAlpha',0.2,'EdgeAlpha',0.8,'EdgeColor',color{i});
-    %figure;
-    hold on;
-end
-legend(fitResults.lambda.dataLabels);
-plot(position.getSubSignal('x').dataToMatrix,position.getSubSignal('y').dataToMatrix,...
-     values_at_spiketimes(:,1),values_at_spiketimes(:,2),'r.');
-axis tight square;
-xlabel('x position (m)'); ylabel('y position (m)');
-

Toolbox vs. Standard GLM comparison

Compare the results using our approach with the standard approach used in the first example previous standard regression

[b,dev,stats] = glmfit([xN yN xN.^2 yN.^2 xN.*yN],spikes_binned,'poisson');
-b-fitResults.b{2} % should be close to zero
-
-ans =
-
-    3.5041
-    0.0099
-    0.0102
-    0.0210
-    0.0215
-    0.0172
-
-

Compute the history effect

sampleRate=1000;  makePlot=1; neuronNum = 1;
-covLabels = {{'Baseline','mu'},{'Radial','x','y','x^2','y^2','x*y'}};
-Algorithm = 'GLM';
-batchMode=0;
-windowTimes =(0:1:10)./sampleRate;
-% [fitResults,tcc] = computeHistLag(tObj,neuronNum,windowTimes,CovLabels,Algorithm,batchMode,sampleRate,makePlot,histMinTimes,histMaxTimes)
-[fitResults,tcc] = Analysis.computeHistLag(trial,neuronNum,windowTimes,covLabels,Algorithm,batchMode,sampleRate,makePlot);
-
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
-
\ No newline at end of file diff --git a/helpfiles/AnalysisExamples2.m b/helpfiles/AnalysisExamples2.m deleted file mode 100644 index 3e6cce0c..00000000 --- a/helpfiles/AnalysisExamples2.m +++ /dev/null @@ -1,103 +0,0 @@ -%% Analysis Examples 2 -% Compare with traditional Neural Spike Train Analysis -% - -% load the rat trajectory and spiking data; -close all; -warning off; -load('glm_data.mat'); - -nst = nspikeTrain(spiketimes); -baseline = Covariate(T,ones(length(xN),1),'Baseline','time','s','',{'mu'}); -position = Covariate(T,[xN yN],'Position', 'time','s','m',{'x','y'}); -velocity = Covariate(T,[vxN,vyN],'Velocity','time','s','m/s',{'v_x','v_y'}); -radial = Covariate(T,[xN yN xN.^2 yN.^2 xN.*yN],'Radial','time','s','m',{'x','y','x^2','y^2','x*y'}); -% could just define velocity = postion.derivative; - -%possibly add view as vector for covariates of dimension 3 or less -%% -% In the original analysis, we already had vectors of the covariates -% sampled at the spiketimes. This step would require interpolating the -% covariates and then sampling them at each of the spikeTimes. In our case -% this is quite simple. - -[values_at_spiketimes] =position.getValueAt(spiketimes); - -%% -% We could also upsample our data to get better estimates of the covariates -% at these points - -[values_at_spiketimes] =position.resample(1/min(diff(spiketimes))).getValueAt(spiketimes); - -%% -% visualize the raw data -figure; -plot(position.getSubSignal('x').dataToMatrix,position.getSubSignal('y').dataToMatrix,... - values_at_spiketimes(:,1),values_at_spiketimes(:,2),'r.'); -axis tight square; -xlabel('x position (m)'); ylabel('y position (m)'); - -%% -% Create a trial object and define the fits that we want to run -spikeColl = nstColl({nst}); -covarColl = CovColl({baseline,radial}); -trial = Trial(spikeColl,covarColl); -clear tc; -sampleRate=1000; -% tcObj=TrialConfig(covMask,sampleRate, history,minTime,maxTime) -tc{1} = TrialConfig({{'Baseline','mu'},{'Radial','x','y'}},sampleRate,[]); tc{1}.setName('Linear'); -tc{2} = TrialConfig({{'Baseline','mu'},{'Radial','x','y','x^2','y^2','x*y'}},sampleRate,[]); tc{2}.setName('Quadratic'); -tc{3} = TrialConfig({{'Baseline','mu'},{'Radial','x','y','x^2','y^2','x*y'}},sampleRate,[0 1]./sampleRate); tc{3}.setName('Quadratic+Hist'); - -%% -% Create our collection of configurations and run the analysis; -tcc = ConfigColl(tc); makePlot=1; neuronNum=1; -fitResults =Analysis.RunAnalysisForAllNeurons(trial,tcc,0); -fitResults.plotResults; - -%% -% Visualize the firing rates as a function of the spatial covariates -figure; -[x_new,y_new]=meshgrid(-1:.1:1); %define new x and y -y_new = flipud(y_new); -x_new = fliplr(x_new); - -%For each covariate new to place the new data in a cell array -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; -color = Analysis.colors; - -% Evaluate our fits using the new parameters -for i=1:fitResults.numResults - - lambda = fitResults.evalLambda(i,newData); - h_mesh = mesh(x_new,y_new,lambda,'AlphaData',0); - get(h_mesh,'AlphaData'); - set(h_mesh,'FaceAlpha',0.2,'EdgeAlpha',0.8,'EdgeColor',color{i}); - %figure; - hold on; -end -legend(fitResults.lambda.dataLabels); -plot(position.getSubSignal('x').dataToMatrix,position.getSubSignal('y').dataToMatrix,... - values_at_spiketimes(:,1),values_at_spiketimes(:,2),'r.'); -axis tight square; -xlabel('x position (m)'); ylabel('y position (m)'); - -%% Toolbox vs. Standard GLM comparison -% Compare the results using our approach with the standard approach used in -% the first example previous standard regression -[b,dev,stats] = glmfit([xN yN xN.^2 yN.^2 xN.*yN],spikes_binned,'poisson'); -b-fitResults.b{2} % should be close to zero - - - -%% Compute the history effect -sampleRate=1000; makePlot=1; neuronNum = 1; -covLabels = {{'Baseline','mu'},{'Radial','x','y','x^2','y^2','x*y'}}; -Algorithm = 'GLM'; -batchMode=0; -windowTimes =(0:1:10)./sampleRate; -% [fitResults,tcc] = computeHistLag(tObj,neuronNum,windowTimes,CovLabels,Algorithm,batchMode,sampleRate,makePlot,histMinTimes,histMaxTimes) -[fitResults,tcc] = Analysis.computeHistLag(trial,neuronNum,windowTimes,covLabels,Algorithm,batchMode,sampleRate,makePlot); diff --git a/helpfiles/AnalysisExamples2.png b/helpfiles/AnalysisExamples2.png deleted file mode 100644 index 745b81e7..00000000 Binary files a/helpfiles/AnalysisExamples2.png and /dev/null differ diff --git a/helpfiles/AnalysisExamples2_01.png b/helpfiles/AnalysisExamples2_01.png deleted file mode 100644 index 6d62d352..00000000 Binary files a/helpfiles/AnalysisExamples2_01.png and /dev/null differ diff --git a/helpfiles/AnalysisExamples2_02.png b/helpfiles/AnalysisExamples2_02.png deleted file mode 100644 index e687798e..00000000 Binary files a/helpfiles/AnalysisExamples2_02.png and /dev/null differ diff --git a/helpfiles/AnalysisExamples2_03.png b/helpfiles/AnalysisExamples2_03.png deleted file mode 100644 index 01c46946..00000000 Binary files a/helpfiles/AnalysisExamples2_03.png and /dev/null differ diff --git a/helpfiles/AnalysisExamples2_04.png b/helpfiles/AnalysisExamples2_04.png deleted file mode 100644 index 75b64706..00000000 Binary files a/helpfiles/AnalysisExamples2_04.png and /dev/null differ diff --git a/helpfiles/AnalysisExamples_01.png b/helpfiles/AnalysisExamples_01.png deleted file mode 100644 index a00c49f0..00000000 Binary files a/helpfiles/AnalysisExamples_01.png and /dev/null differ diff --git a/helpfiles/AnalysisExamples_02.png b/helpfiles/AnalysisExamples_02.png deleted file mode 100644 index 06465b04..00000000 Binary files a/helpfiles/AnalysisExamples_02.png and /dev/null differ diff --git a/helpfiles/AnalysisExamples_03.png b/helpfiles/AnalysisExamples_03.png deleted file mode 100644 index 132e7a6e..00000000 Binary files a/helpfiles/AnalysisExamples_03.png and /dev/null differ diff --git a/helpfiles/AnalysisExamples_04.png b/helpfiles/AnalysisExamples_04.png deleted file mode 100644 index e4e81f13..00000000 Binary files a/helpfiles/AnalysisExamples_04.png and /dev/null differ diff --git a/helpfiles/ClassDefinitions.html b/helpfiles/ClassDefinitions.html deleted file mode 100644 index 9d25256d..00000000 --- a/helpfiles/ClassDefinitions.html +++ /dev/null @@ -1,96 +0,0 @@ - - - - - Class Definitions \ No newline at end of file diff --git a/helpfiles/ClassDefinitions.m b/helpfiles/ClassDefinitions.m deleted file mode 100644 index baac291a..00000000 --- a/helpfiles/ClassDefinitions.m +++ /dev/null @@ -1,24 +0,0 @@ -%% Class Definitions -% Summaries of each of the available classes along with corresponding -% source code can be accessed below: - -%% -% -% * -% * -% * -% * -% * -% * -% * -% * -% * -% * -% * -% * -% * -% * -% * -% * -% -% diff --git a/helpfiles/ConfigCollExamples.html b/helpfiles/ConfigCollExamples.html deleted file mode 100644 index 7358c519..00000000 --- a/helpfiles/ConfigCollExamples.html +++ /dev/null @@ -1,79 +0,0 @@ - - - - - ConfigColl Examples

ConfigColl Examples

tcObj=TrialConfig(covMask,sampleRate, history,minTime,maxTime)

tc1 = TrialConfig({'Force','f_x'},2000,[.1 .2],-1,2);
-tc2 = TrialConfig({'Position','x'},2000,[.1 .2],-1,2);
-tcc = ConfigColl({tc1,tc2});
-
\ No newline at end of file diff --git a/helpfiles/ConfigCollExamples.m b/helpfiles/ConfigCollExamples.m deleted file mode 100644 index c128bd13..00000000 --- a/helpfiles/ConfigCollExamples.m +++ /dev/null @@ -1,5 +0,0 @@ -%% ConfigColl Examples -% tcObj=TrialConfig(covMask,sampleRate, history,minTime,maxTime) -tc1 = TrialConfig({'Force','f_x'},2000,[.1 .2],-1,2); -tc2 = TrialConfig({'Position','x'},2000,[.1 .2],-1,2); -tcc = ConfigColl({tc1,tc2}); \ No newline at end of file diff --git a/helpfiles/CovCollExamples.asv b/helpfiles/CovCollExamples.asv deleted file mode 100644 index f33d1dad..00000000 --- a/helpfiles/CovCollExamples.asv +++ /dev/null @@ -1,17 +0,0 @@ -%% Test CovColl -close all; -load Covariates.mat; -cc=CovColl({position,force}); -figure; cc.plot; %plots all covariates and their components - -cc.getCov(1); %returns position; -cc.getCov('Position'); -cc.getCov({'Position','Force'}); -cc.resample(200); %resamples both position and force - - -cc.setMask({{'Position','x'},{'Force','f_y'}}); -figure; cc.plot; %plot only x and f_y; - -dataToMatrix -s diff --git a/helpfiles/CovCollExamples.html b/helpfiles/CovCollExamples.html deleted file mode 100644 index ed7af83a..00000000 --- a/helpfiles/CovCollExamples.html +++ /dev/null @@ -1,112 +0,0 @@ - - - - - Test CovColl

Test CovColl

close all;
-load CovariateSample.mat;
-cc=CovColl({position,force});
-figure; cc.plot; %plots all covariates and their components
-
-cc.getCov(1); %returns position;
-cc.getCov('Position');
-cc.getCov({'Position','Force'});
-cc.resample(200); %resamples both position and force
-
-
-cc.setMask({{'Position','x'},{'Force','f_y'}});
-figure; cc.plot; %plot only x and f_y;
-
-% dataToMatrix
-% setMaxTime
-% setMinTime
-% removeCovariate
-% nActCovar
-
\ No newline at end of file diff --git a/helpfiles/CovCollExamples.m b/helpfiles/CovCollExamples.m deleted file mode 100644 index 8eca85ae..00000000 --- a/helpfiles/CovCollExamples.m +++ /dev/null @@ -1,21 +0,0 @@ -%% Test CovColl -close all; -load CovariateSample.mat; -cc=CovColl({position,force}); -figure; cc.plot; %plots all covariates and their components - -cc.getCov(1); %returns position; -cc.getCov('Position'); -cc.getCov({'Position','Force'}); -cc.resample(200); %resamples both position and force - - -cc.setMask({{'Position','x'},{'Force','f_y'}}); -figure; cc.plot; %plot only x and f_y; - -% dataToMatrix -% setMaxTime -% setMinTime -% removeCovariate -% nActCovar - diff --git a/helpfiles/CovCollExamples.png b/helpfiles/CovCollExamples.png deleted file mode 100644 index ae126785..00000000 Binary files a/helpfiles/CovCollExamples.png and /dev/null differ diff --git a/helpfiles/CovCollExamples_01.png b/helpfiles/CovCollExamples_01.png deleted file mode 100644 index 7f64977c..00000000 Binary files a/helpfiles/CovCollExamples_01.png and /dev/null differ diff --git a/helpfiles/CovCollExamples_02.png b/helpfiles/CovCollExamples_02.png deleted file mode 100644 index 4cc82765..00000000 Binary files a/helpfiles/CovCollExamples_02.png and /dev/null differ diff --git a/helpfiles/CovariateExamples.asv b/helpfiles/CovariateExamples.asv deleted file mode 100644 index b02d32a0..00000000 --- a/helpfiles/CovariateExamples.asv +++ /dev/null @@ -1,39 +0,0 @@ -%% Test the Cov class -% Covariates are just like signals with a mean and a standard deviation -% They have two representations, the default (original representation) and -% a zero-mean representation - -%% Example 1: Using Covariates -% Create some Data -close all; -t=0:.01:5; t=t'; -x=exp(-t); -y=sin(2*pi*t)+.2*randn(length(t),1); -z=(-y).^3+.2*rand(length(t),1); - -fx=abs(y); -fy=abs(y)-sign(; - -%% -% Define labels and plotting properties for each Covariate -dLabels1={'f_x','f_y'}; -dLabels2={'x','y','z'}; - -plotProps = {{' ''g'', ''LineWidth'' ,.5'},... %for x - {' ''k'', ''LineWidth'' ,.5'},... %for y - {' ''b'' '}}; %for z - -force = Covariate(t, [fx fy], 'Force', 'time', 's', 'N', dLabels1); -position=Covariate(t,[x y z], 'Position','time','s','cm', dLabels2); - -%% -% Plot the covariates and change their properties -position.getSigRep.plot('all',plotProps); %same as position.plot -plotPropsForce = {{' ''g'', ''LineWidth'' ,.5'},{' ''k'', ''LineWidth'' ,.5'}}; -figure; -subplot(1,2,1); force.getSigRep.plot('all',plotPropsForce); -% can also set these properties as default by calling -% >>force.setPlotProps(plotPropsForce); -% >>force.plot; - -subplot(1,2,2); force.getSigRep('zero-mean').plot('all',plotPropsForce); diff --git a/helpfiles/CovariateExamples.html b/helpfiles/CovariateExamples.html deleted file mode 100644 index 232a0f45..00000000 --- a/helpfiles/CovariateExamples.html +++ /dev/null @@ -1,135 +0,0 @@ - - - - - Test the Cov class

Test the Cov class

Covariates are just like signals with a mean and a standard deviation They have two representations, the default (original representation) and a zero-mean representation

Contents

Example 1: Using Covariates

Create some Data

close all;
-t=0:.01:5; t=t';
-x=exp(-t);
-y=sin(2*pi*t);
-z=(-y).^3;
-
-fx=abs(y);
-fy=abs(y).^2;
-

Define labels and plotting properties for each Covariate

dLabels1={'f_x','f_y'};
-dLabels2={'x','y','z'};
-
-plotProps = {{' ''g'', ''LineWidth'' ,.5'},... %for x
-             {' ''k'', ''LineWidth'' ,.5'},...   %for y
-             {' ''b'' '}}; %for z
-
-force = Covariate(t, [fx fy], 'Force', 'time', 's', 'N', dLabels1);
-position=Covariate(t,[x y z], 'Position','time','s','cm', dLabels2);
-

Plot the covariates and change their properties

position.getSigRep.plot('all',plotProps); %same as position.plot
-plotPropsForce = {{' ''b'' '},{' ''k'' '}};
-figure;
-subplot(1,2,1); force.getSigRep.plot('all',plotPropsForce);
-% can also set these properties as default by calling
-% >>force.setPlotProps(plotPropsForce);
-% >>force.plot;
-
-subplot(1,2,2); force.getSigRep('zero-mean').plot('all',plotPropsForce);
-
\ No newline at end of file diff --git a/helpfiles/CovariateExamples.m b/helpfiles/CovariateExamples.m deleted file mode 100644 index 0f483059..00000000 --- a/helpfiles/CovariateExamples.m +++ /dev/null @@ -1,39 +0,0 @@ -%% Test the Cov class -% Covariates are just like signals with a mean and a standard deviation -% They have two representations, the default (original representation) and -% a zero-mean representation - -%% Example 1: Using Covariates -% Create some Data -close all; -t=0:.01:5; t=t'; -x=exp(-t); -y=sin(2*pi*t); -z=(-y).^3; - -fx=abs(y); -fy=abs(y).^2; - -%% -% Define labels and plotting properties for each Covariate -dLabels1={'f_x','f_y'}; -dLabels2={'x','y','z'}; - -plotProps = {{' ''g'', ''LineWidth'' ,.5'},... %for x - {' ''k'', ''LineWidth'' ,.5'},... %for y - {' ''b'' '}}; %for z - -force = Covariate(t, [fx fy], 'Force', 'time', 's', 'N', dLabels1); -position=Covariate(t,[x y z], 'Position','time','s','cm', dLabels2); - -%% -% Plot the covariates and change their properties -position.getSigRep.plot('all',plotProps); %same as position.plot -plotPropsForce = {{' ''b'' '},{' ''k'' '}}; -figure; -subplot(1,2,1); force.getSigRep.plot('all',plotPropsForce); -% can also set these properties as default by calling -% >>force.setPlotProps(plotPropsForce); -% >>force.plot; - -subplot(1,2,2); force.getSigRep('zero-mean').plot('all',plotPropsForce); diff --git a/helpfiles/CovariateExamples.png b/helpfiles/CovariateExamples.png deleted file mode 100644 index d8373eb8..00000000 Binary files a/helpfiles/CovariateExamples.png and /dev/null differ diff --git a/helpfiles/CovariateExamples_01.png b/helpfiles/CovariateExamples_01.png deleted file mode 100644 index 18cf1781..00000000 Binary files a/helpfiles/CovariateExamples_01.png and /dev/null differ diff --git a/helpfiles/CovariateExamples_02.png b/helpfiles/CovariateExamples_02.png deleted file mode 100644 index accab208..00000000 Binary files a/helpfiles/CovariateExamples_02.png and /dev/null differ diff --git a/helpfiles/CovariateSample.mat b/helpfiles/CovariateSample.mat deleted file mode 100644 index 915aadee..00000000 Binary files a/helpfiles/CovariateSample.mat and /dev/null differ diff --git a/helpfiles/DecodingExample.html b/helpfiles/DecodingExample.html deleted file mode 100644 index 2f1f35e0..00000000 --- a/helpfiles/DecodingExample.html +++ /dev/null @@ -1,241 +0,0 @@ - - - - - STIMULUS DECODING

STIMULUS DECODING

In this example we show how to decode a univariate and a bivariate stimulus based on a point process observations using nSTAT. Even though due to the simulated nature of the data, we know the exact condition intensity function, we estimate the parameters before moving on to the decoding stage.

Contents

Generate the conditional Intensity Function

    close all;
-    delta = 0.001; Tmax = 10;
-    time = 0:delta:Tmax;
-    f=.1; b1=1;b0=-3;
-    x = sin(2*pi*f*time);
-    expData = exp(b1*x+b0);
-    lambdaData = expData./(1+expData);
-
-    lambda = Covariate(time,lambdaData./delta, '\Lambda(t)','time','s','Hz',{'\lambda_{1}'},{{' ''b'', ''LineWidth'' ,2'}});
-
-    numRealizations = 10;
-    spikeColl = CIF.simulateCIFByThinningFromLambda(lambda,numRealizations);
-    figure;
-    subplot(2,1,1); spikeColl.plot;
-    subplot(2,1,2); lambda.plot;
-

Fit a model to the spikedata to obtain a model CIF

stim = Covariate(time,sin(2*pi*f*time),'Stimulus','time','s','V',{'stim'});
-baseline = Covariate(time,ones(length(time),1),'Baseline','time','s','',...
-                    {'constant'});
-figure;
-cc = CovColl({stim,baseline});
-trial = Trial(spikeColl,cc);
-trial.plot;
-
-clear c;
-selfHist = [] ; NeighborHist = []; sampleRate = 1000;
-c{1} = TrialConfig({{'Baseline','constant'}},sampleRate,selfHist,...
-    NeighborHist);
-c{1}.setName('Baseline');
-c{2} = TrialConfig({{'Baseline','constant'},{'Stimulus','stim'}},...
-    sampleRate,selfHist,NeighborHist);
-c{2}.setName('Baseline+Stimulus');
-cfgColl= ConfigColl(c);
-results = Analysis.RunAnalysisForAllNeurons(trial,cfgColl,0);
-figure;
-results{1}.plotResults;
-Summary = FitResSummary(results);
-
-paramEst = squeeze(Summary.bAct(:,2,:));
-meanParams = mean(paramEst,2);
-
Analyzing Configuration #1: Neuron #1,2,3,4,5,6,7,8,9,10
-Analyzing Configuration #2: Neuron #1,2,3,4,5,6,7,8,9,10
-

So we now have a model for lambda lambda = exp(b_0 + b_1*x(t))./(1+exp(b_0 + b_1*x(t)) * 1/delta because exp(b_0 + b_1*x(t))<<1 we can approximate this lambda by just the numerator i.e. lambda = exp(b_0 + b_1*x(t))./delta

Now suppose we wanted to decode x(t) based on only having observed lambda

clear lambdaCIF;
-b0=paramEst(1,:);
-b1=paramEst(2,:);
-for i=1:numRealizations
-    % Construct a CIF object for each realization based on our encoding
-    % results abovel
-    lambdaCIF{i} = CIF([b0(i) b1(i)],{'1','x'},{'x'},'binomial');
-end
-% close all;
-spikeColl.resample(1/delta);
-dN=spikeColl.dataToMatrix;
-% Make noise according to the dynamic range of the stimulus
-Q=2*std(stim.data(2:end)-stim.data(1:end-1));
-A=1;
-[x_p, W_p, x_u, W_u] = DecodingAlgorithms.PPDecodeFilterLinear(A, Q, dN',b0,b1,'binomial',delta);
-figure;
-zVal=3;
-ciLower = min(x_u(1:end)-zVal*squeeze(sqrt(W_u(1:end)))',x_u(1:end)+zVal*squeeze(sqrt(W_u(1:end)))');
-ciUpper = max(x_u(1:end)-zVal*squeeze(sqrt(W_u(1:end)))',x_u(1:end)+zVal*squeeze(sqrt(W_u(1:end)))');
-hEst=plot(time,x_u(1:end),'b',time,ciLower,'g',time,ciUpper,'g'); hold on;
-hold all;
-
-hStim=stim.plot([],{{' ''k'',''Linewidth'',2'}});
-legend off;
-legend([hEst(1) hEst(2) hEst(3) hStim],'x_{k|k}(t)',strcat('x_{k|k}(t)-',num2str(zVal),'\sigma_{k|k}'),...
-        strcat('x_{k|k}(t)+',num2str(zVal),'\sigma_{k|k}'),'x_{k|k}(t)','x(t)');
-title(['Decoded Stimulus +/- 99% confidence intervals using ' num2str(numRealizations) ' cells']);
-
Warning: Ignoring extra legend entries. 
-
\ No newline at end of file diff --git a/helpfiles/DecodingExample.m b/helpfiles/DecodingExample.m deleted file mode 100644 index 04352c99..00000000 --- a/helpfiles/DecodingExample.m +++ /dev/null @@ -1,100 +0,0 @@ -%% STIMULUS DECODING -% In this example we show how to decode a univariate and a bivariate -% stimulus based on a point process observations using nSTAT. Even though -% due to the simulated nature of the data, we know the exact condition -% intensity function, we estimate the parameters before moving on to the -% decoding stage. -%% Generate the conditional Intensity Function - - close all; - delta = 0.001; Tmax = 10; - time = 0:delta:Tmax; - f=.1; b1=1;b0=-3; - x = sin(2*pi*f*time); - expData = exp(b1*x+b0); - lambdaData = expData./(1+expData); - - lambda = Covariate(time,lambdaData./delta, '\Lambda(t)','time','s','Hz',{'\lambda_{1}'},{{' ''b'', ''LineWidth'' ,2'}}); - - numRealizations = 10; - spikeColl = CIF.simulateCIFByThinningFromLambda(lambda,numRealizations); - figure; - subplot(2,1,1); spikeColl.plot; - subplot(2,1,2); lambda.plot; - -%% Fit a model to the spikedata to obtain a model CIF - -stim = Covariate(time,sin(2*pi*f*time),'Stimulus','time','s','V',{'stim'}); -baseline = Covariate(time,ones(length(time),1),'Baseline','time','s','',... - {'constant'}); -figure; -cc = CovColl({stim,baseline}); -trial = Trial(spikeColl,cc); -trial.plot; - -clear c; -selfHist = [] ; NeighborHist = []; sampleRate = 1000; -c{1} = TrialConfig({{'Baseline','constant'}},sampleRate,selfHist,... - NeighborHist); -c{1}.setName('Baseline'); -c{2} = TrialConfig({{'Baseline','constant'},{'Stimulus','stim'}},... - sampleRate,selfHist,NeighborHist); -c{2}.setName('Baseline+Stimulus'); -cfgColl= ConfigColl(c); -results = Analysis.RunAnalysisForAllNeurons(trial,cfgColl,0); -figure; -results{1}.plotResults; -Summary = FitResSummary(results); - -paramEst = squeeze(Summary.bAct(:,2,:)); -meanParams = mean(paramEst,2); - -%% -% So we now have a model for lambda -% lambda = exp(b_0 + b_1*x(t))./(1+exp(b_0 + b_1*x(t)) * 1/delta -% because exp(b_0 + b_1*x(t))<<1 we can approximate this lambda by -% just the numerator i.e. -% lambda = exp(b_0 + b_1*x(t))./delta -% -% -% Now suppose we wanted to decode x(t) based on only having observed lambda -% -% -% - -clear lambdaCIF; -b0=paramEst(1,:); -b1=paramEst(2,:); -for i=1:numRealizations - % Construct a CIF object for each realization based on our encoding - % results abovel - lambdaCIF{i} = CIF([b0(i) b1(i)],{'1','x'},{'x'},'binomial'); -end -% close all; -spikeColl.resample(1/delta); -dN=spikeColl.dataToMatrix; -% Make noise according to the dynamic range of the stimulus -Q=2*std(stim.data(2:end)-stim.data(1:end-1)); -A=1; -[x_p, W_p, x_u, W_u] = DecodingAlgorithms.PPDecodeFilterLinear(A, Q, dN',b0,b1,'binomial',delta); -figure; -zVal=3; -ciLower = min(x_u(1:end)-zVal*squeeze(sqrt(W_u(1:end)))',x_u(1:end)+zVal*squeeze(sqrt(W_u(1:end)))'); -ciUpper = max(x_u(1:end)-zVal*squeeze(sqrt(W_u(1:end)))',x_u(1:end)+zVal*squeeze(sqrt(W_u(1:end)))'); -hEst=plot(time,x_u(1:end),'b',time,ciLower,'g',time,ciUpper,'g'); hold on; -hold all; - -hStim=stim.plot([],{{' ''k'',''Linewidth'',2'}}); -legend off; -legend([hEst(1) hEst(2) hEst(3) hStim],'x_{k|k}(t)',strcat('x_{k|k}(t)-',num2str(zVal),'\sigma_{k|k}'),... - strcat('x_{k|k}(t)+',num2str(zVal),'\sigma_{k|k}'),'x_{k|k}(t)','x(t)'); -title(['Decoded Stimulus +/- 99% confidence intervals using ' num2str(numRealizations) ' cells']); - - - - - - - - - diff --git a/helpfiles/DecodingExample.png b/helpfiles/DecodingExample.png deleted file mode 100644 index 0fb71d5f..00000000 Binary files a/helpfiles/DecodingExample.png and /dev/null differ diff --git a/helpfiles/DecodingExampleWithHist.html b/helpfiles/DecodingExampleWithHist.html deleted file mode 100644 index 3a72196f..00000000 --- a/helpfiles/DecodingExampleWithHist.html +++ /dev/null @@ -1,242 +0,0 @@ - - - - - 1-D Stimulus Decode with History Effect

1-D Stimulus Decode with History Effect

In the above decoding example, the simulated neurons did not have memory. That is their previous firing activity did not modulate their current probability of firing. In reality the firing history does affect the probabilty of neuronal firing (eg. refractory period, bursting, etc.). In this example, we simulate a population a neurons that exhibit this type of history dependence. We then decode the stimulus activity based on a conditional intensity function that includes the correct history terms and one that assumes no history dependence.

close all;
-% clear all;
-delta = 0.001; Tmax = 1;
-time = 0:delta:Tmax;
-f=1; b1=1;b0=-2;
-stimData = b1*sin(2*pi*f*time);
-e = zeros(length(time),1);   %No Ensemble input
-mu = b0; %baseline firing rate
-Ts=delta;
-
-histCoeffs= [-2 -2 -4];
-windowTimes=[0 .001 0.002 0.003];
-histObj = History(windowTimes);
-filts = histObj.toFilter(Ts); %Convert to transfer function matrix
-H=histCoeffs*filts; %scale each window transfer function by its coefficient
-S=tf([1],1,Ts,'Variable','z^-1'); %Feed the stimulus in directly
-E=tf([0],1,Ts,'Variable','z^-1'); %No ensemble effect
-stim=Covariate(time',stimData,'Stimulus','time','s','Voltage',{'sin'});
-ens =Covariate(time',e,'Ensemble','time','s','Spikes',{'n1'});
-numRealizations = 20;    %Number of sample paths to generate
-sC=CIF.simulateCIF(mu,H,S,E,stim,ens,numRealizations);
-
-figure;
-subplot(2,1,1); sC.plot;
-subplot(2,1,2); stim.plot;
-
-
-for i=1:numRealizations
-% Construct a CIF object for each realization based on our encoding
-% results above
-    %correct CIF w/ History
-    lambdaCIF{i} = CIF([mu b1],{'1','x'},{'x'},'binomial',histCoeffs,histObj);
-    %CIF ignoring the history effect
-    lambdaCIFNoHist{i} = CIF([mu b1],{'1','x'},{'x'},'binomial');
-end
-
-
-
-
-sC.resample(1/delta);
-dN=sC.dataToMatrix;
-% Make noise according to the dynamic range of the stimulus
-Q=2*std(stim.data(2:end)-stim.data(1:end-1));
-Px0=.1; A=1;
-% Decode with the correct and incorrect CIFs
-
-[x_p, W_p, x_u, W_u] = DecodingAlgorithms.PPDecodeFilter(A, Q, Px0, dN',lambdaCIF,delta);
-[x_pNoHist, W_pNoHist, x_uNoHist, W_uNoHist] = DecodingAlgorithms.PPDecodeFilter(A, Q, Px0, dN',lambdaCIFNoHist,delta);
-
-
-% Compare the results
-figure;
-subplot(2,1,1);
-zVal=3;
-ciLower = min(x_u(1:end)-zVal*squeeze(W_u(1:end))',x_u(1:end)+zVal*squeeze(W_u(1:end))');
-ciUpper = max(x_u(1:end)-zVal*squeeze(W_u(1:end))',x_u(1:end)+zVal*squeeze(W_u(1:end))');
-hEst=plot(time,x_u(1:end),'b',time,ciLower,'g',time,ciUpper,'r'); hold on;
-hold all;
-
-hStim=stim.plot([],{{' ''k'',''Linewidth'',2'}});
-legend off;
-legend([hEst(1) hEst(2) hEst(3) hStim],'x_{k|k}(t)',strcat('x_{k|k}(t)-',num2str(zVal),'\sigma_{k|k}'),...
-        strcat('x_{k|k}(t)+',num2str(zVal),'\sigma_{k|k}'),'x_{k|k}(t)','x(t)');
-title(['Decoded Stimulus +/- 99% confidence intervals using ' num2str(numRealizations) ' cells']);
-
-subplot(2,1,2);
-zVal=3;
-ciLower = min(x_uNoHist(1:end)-zVal*squeeze(W_uNoHist(1:end))',x_uNoHist(1:end)+zVal*squeeze(W_uNoHist(1:end))');
-ciUpper = max(x_uNoHist(1:end)-zVal*squeeze(W_uNoHist(1:end))',x_uNoHist(1:end)+zVal*squeeze(W_uNoHist(1:end))');
-hEst=plot(time,x_uNoHist(1:end),'b',time,ciLower,'g',time,ciUpper,'r'); hold on;
-hold all;
-
-hStim=stim.plot([],{{' ''k'',''Linewidth'',2'}});
-legend off;
-legend([hEst(1) hEst(2) hEst(3) hStim],'x_{k|k}(t)',strcat('x_{k|k}(t)-',num2str(zVal),'\sigma_{k|k}'),...
-        strcat('x_{k|k}(t)+',num2str(zVal),'\sigma_{k|k}'),'x_{k|k}(t)','x(t)');
-title(['Decoded Stimulus No Hist +/- 99% confidence intervals using ' num2str(numRealizations) ' cells']);
-
Warning: Ignoring extra legend entries. 
-Warning: Ignoring extra legend entries. 
-

We see that inclusion of history effect improves (as expected) the decoding of the stimulus based on the point process observations

\ No newline at end of file diff --git a/helpfiles/DecodingExampleWithHist.m b/helpfiles/DecodingExampleWithHist.m deleted file mode 100644 index 5bbd9fcc..00000000 --- a/helpfiles/DecodingExampleWithHist.m +++ /dev/null @@ -1,92 +0,0 @@ -%% 1-D Stimulus Decode with History Effect -% In the above decoding example, the simulated neurons did not have memory. -% That is their previous firing activity did not modulate their current -% probability of firing. In reality the firing history does affect the -% probabilty of neuronal firing (eg. refractory period, bursting, etc.). -% In this example, we simulate a population a neurons that exhibit this -% type of history dependence. We then decode the stimulus activity based on -% a conditional intensity function that includes the correct history terms -% and one that assumes no history dependence. - - -close all; -% clear all; -delta = 0.001; Tmax = 1; -time = 0:delta:Tmax; -f=1; b1=1;b0=-2; -stimData = b1*sin(2*pi*f*time); -e = zeros(length(time),1); %No Ensemble input -mu = b0; %baseline firing rate -Ts=delta; - -histCoeffs= [-2 -2 -4]; -windowTimes=[0 .001 0.002 0.003]; -histObj = History(windowTimes); -filts = histObj.toFilter(Ts); %Convert to transfer function matrix -H=histCoeffs*filts; %scale each window transfer function by its coefficient -S=tf([1],1,Ts,'Variable','z^-1'); %Feed the stimulus in directly -E=tf([0],1,Ts,'Variable','z^-1'); %No ensemble effect -stim=Covariate(time',stimData,'Stimulus','time','s','Voltage',{'sin'}); -ens =Covariate(time',e,'Ensemble','time','s','Spikes',{'n1'}); -numRealizations = 20; %Number of sample paths to generate -sC=CIF.simulateCIF(mu,H,S,E,stim,ens,numRealizations); - -figure; -subplot(2,1,1); sC.plot; -subplot(2,1,2); stim.plot; - - -for i=1:numRealizations -% Construct a CIF object for each realization based on our encoding -% results above - %correct CIF w/ History - lambdaCIF{i} = CIF([mu b1],{'1','x'},{'x'},'binomial',histCoeffs,histObj); - %CIF ignoring the history effect - lambdaCIFNoHist{i} = CIF([mu b1],{'1','x'},{'x'},'binomial'); -end - - - - -sC.resample(1/delta); -dN=sC.dataToMatrix; -% Make noise according to the dynamic range of the stimulus -Q=2*std(stim.data(2:end)-stim.data(1:end-1)); -Px0=.1; A=1; -% Decode with the correct and incorrect CIFs - -[x_p, W_p, x_u, W_u] = DecodingAlgorithms.PPDecodeFilter(A, Q, Px0, dN',lambdaCIF,delta); -[x_pNoHist, W_pNoHist, x_uNoHist, W_uNoHist] = DecodingAlgorithms.PPDecodeFilter(A, Q, Px0, dN',lambdaCIFNoHist,delta); - - -% Compare the results -figure; -subplot(2,1,1); -zVal=3; -ciLower = min(x_u(1:end)-zVal*squeeze(W_u(1:end))',x_u(1:end)+zVal*squeeze(W_u(1:end))'); -ciUpper = max(x_u(1:end)-zVal*squeeze(W_u(1:end))',x_u(1:end)+zVal*squeeze(W_u(1:end))'); -hEst=plot(time,x_u(1:end),'b',time,ciLower,'g',time,ciUpper,'r'); hold on; -hold all; - -hStim=stim.plot([],{{' ''k'',''Linewidth'',2'}}); -legend off; -legend([hEst(1) hEst(2) hEst(3) hStim],'x_{k|k}(t)',strcat('x_{k|k}(t)-',num2str(zVal),'\sigma_{k|k}'),... - strcat('x_{k|k}(t)+',num2str(zVal),'\sigma_{k|k}'),'x_{k|k}(t)','x(t)'); -title(['Decoded Stimulus +/- 99% confidence intervals using ' num2str(numRealizations) ' cells']); - -subplot(2,1,2); -zVal=3; -ciLower = min(x_uNoHist(1:end)-zVal*squeeze(W_uNoHist(1:end))',x_uNoHist(1:end)+zVal*squeeze(W_uNoHist(1:end))'); -ciUpper = max(x_uNoHist(1:end)-zVal*squeeze(W_uNoHist(1:end))',x_uNoHist(1:end)+zVal*squeeze(W_uNoHist(1:end))'); -hEst=plot(time,x_uNoHist(1:end),'b',time,ciLower,'g',time,ciUpper,'r'); hold on; -hold all; - -hStim=stim.plot([],{{' ''k'',''Linewidth'',2'}}); -legend off; -legend([hEst(1) hEst(2) hEst(3) hStim],'x_{k|k}(t)',strcat('x_{k|k}(t)-',num2str(zVal),'\sigma_{k|k}'),... - strcat('x_{k|k}(t)+',num2str(zVal),'\sigma_{k|k}'),'x_{k|k}(t)','x(t)'); -title(['Decoded Stimulus No Hist +/- 99% confidence intervals using ' num2str(numRealizations) ' cells']); - -%% -% We see that inclusion of history effect improves (as expected) the -% decoding of the stimulus based on the point process observations \ No newline at end of file diff --git a/helpfiles/DecodingExampleWithHist.png b/helpfiles/DecodingExampleWithHist.png deleted file mode 100644 index 7538143a..00000000 Binary files a/helpfiles/DecodingExampleWithHist.png and /dev/null differ diff --git a/helpfiles/DecodingExampleWithHist_01.png b/helpfiles/DecodingExampleWithHist_01.png deleted file mode 100644 index fbcf08bc..00000000 Binary files a/helpfiles/DecodingExampleWithHist_01.png and /dev/null differ diff --git a/helpfiles/DecodingExampleWithHist_02.png b/helpfiles/DecodingExampleWithHist_02.png deleted file mode 100644 index 43b8c34e..00000000 Binary files a/helpfiles/DecodingExampleWithHist_02.png and /dev/null differ diff --git a/helpfiles/DecodingExample_01.png b/helpfiles/DecodingExample_01.png deleted file mode 100644 index dc7a0ea8..00000000 Binary files a/helpfiles/DecodingExample_01.png and /dev/null differ diff --git a/helpfiles/DecodingExample_02.png b/helpfiles/DecodingExample_02.png deleted file mode 100644 index 58d3b218..00000000 Binary files a/helpfiles/DecodingExample_02.png and /dev/null differ diff --git a/helpfiles/DecodingExample_03.png b/helpfiles/DecodingExample_03.png deleted file mode 100644 index 25cf34ed..00000000 Binary files a/helpfiles/DecodingExample_03.png and /dev/null differ diff --git a/helpfiles/DecodingExample_04.png b/helpfiles/DecodingExample_04.png deleted file mode 100644 index c3236b77..00000000 Binary files a/helpfiles/DecodingExample_04.png and /dev/null differ diff --git a/helpfiles/DecodingExample_05.png b/helpfiles/DecodingExample_05.png deleted file mode 100644 index 7a59be90..00000000 Binary files a/helpfiles/DecodingExample_05.png and /dev/null differ diff --git a/helpfiles/EventsExamples.html b/helpfiles/EventsExamples.html deleted file mode 100644 index 6605e91a..00000000 --- a/helpfiles/EventsExamples.html +++ /dev/null @@ -1,91 +0,0 @@ - - - - - Events

Events

Events are simple object to use and are aimed to facilitate illustration of epochs in any time of data.

close all;
-eTimes = sort(rand(1,3)*1);
-eLabels={'E_1','E_2','E_3'};
-eventColor = 'b';
-e=Events(eTimes,eLabels,eventColor);
-e.plot;
-

The color of the event markers can also be specified

figure; e.plot([],'r'); %dont specify handle, use red; handel = gca;
-figure; e.plot([],'g'); %dont specify handle, use green;
-
\ No newline at end of file diff --git a/helpfiles/EventsExamples.m b/helpfiles/EventsExamples.m deleted file mode 100644 index 01026811..00000000 --- a/helpfiles/EventsExamples.m +++ /dev/null @@ -1,14 +0,0 @@ -%% Events -% Events are simple object to use and are aimed to facilitate illustration -% of epochs in any time of data. -close all; -eTimes = sort(rand(1,3)*1); -eLabels={'E_1','E_2','E_3'}; -eventColor = 'b'; -e=Events(eTimes,eLabels,eventColor); -e.plot; - -%% -% The color of the event markers can also be specified -figure; e.plot([],'r'); %dont specify handle, use red; handel = gca; -figure; e.plot([],'g'); %dont specify handle, use green; \ No newline at end of file diff --git a/helpfiles/EventsExamples.png b/helpfiles/EventsExamples.png deleted file mode 100644 index d7cd43ae..00000000 Binary files a/helpfiles/EventsExamples.png and /dev/null differ diff --git a/helpfiles/EventsExamples_01.png b/helpfiles/EventsExamples_01.png deleted file mode 100644 index 3449566d..00000000 Binary files a/helpfiles/EventsExamples_01.png and /dev/null differ diff --git a/helpfiles/EventsExamples_02.png b/helpfiles/EventsExamples_02.png deleted file mode 100644 index 86480dbd..00000000 Binary files a/helpfiles/EventsExamples_02.png and /dev/null differ diff --git a/helpfiles/EventsExamples_03.png b/helpfiles/EventsExamples_03.png deleted file mode 100644 index 7e75cf6f..00000000 Binary files a/helpfiles/EventsExamples_03.png and /dev/null differ diff --git a/helpfiles/Examples.html b/helpfiles/Examples.html deleted file mode 100644 index c70746f3..00000000 --- a/helpfiles/Examples.html +++ /dev/null @@ -1,105 +0,0 @@ - - - - - Examples \ No newline at end of file diff --git a/helpfiles/Examples.m b/helpfiles/Examples.m deleted file mode 100644 index 43726448..00000000 --- a/helpfiles/Examples.m +++ /dev/null @@ -1,33 +0,0 @@ -%% Examples -% Example files are provided for each of the classes defined in the Neural -% Spike Analysis Toolbox so that the user can understand the functionality -% of each in more detail. -% -% * -% * -% * -% * -% * -% * -% * -% * -% * -% * -% * -% * -% * -% * -% * -% * -% * -% * -% * -% * -% * -% * -% * -% * -% * - - - diff --git a/helpfiles/ExplicitStimulusWhiskerData.html b/helpfiles/ExplicitStimulusWhiskerData.html deleted file mode 100644 index 4c402a62..00000000 --- a/helpfiles/ExplicitStimulusWhiskerData.html +++ /dev/null @@ -1,403 +0,0 @@ - - - - - EXPLICIT STIMULUS EXAMPLE - WHISKER STIMULATION/THALAMIC NEURON

EXPLICIT STIMULUS EXAMPLE - WHISKER STIMULATION/THALAMIC NEURON

In the worksheet with analyze the stimulus effect and history effect on the firing of a thalamic neuron under a known stimulus consisting of whisker stimulation. Data from Demba Ba (demba@mit.edu)

Contents

Load the data

close all; currdir = pwd;
-index = strfind(currdir,'helpfiles')-1;
-rootpath = currdir(1:index);
-
-Direction=3; Neuron=1; Stim=2;
-datapath = fullfile(rootpath,'data','Explicit Stimulus',strcat('Dir', num2str(Direction)),...
-    strcat('Neuron', num2str(Neuron)), strcat('Stim', num2str(Stim)));
-data=load(fullfile(datapath,'trngdataBis.mat'));
-
-time=0:.001:(length(data.t)-1)*.001;
-stimData = data.t;
-spikeTimes = time(data.y==1);
-
-stim = Covariate(time,stimData,'Stimulus','time','s','V',{'stim'});
-baseline = Covariate(time,ones(length(time),1),'Baseline','time','s','',...
-    {'constant'});
-
-nst = nspikeTrain(spikeTimes);
-nspikeColl = nstColl(nst);
-cc = CovColl({stim,baseline});
-trial = Trial(nspikeColl,cc);
-trial.plot;
-
-figure;
-subplot(2,1,1);
-nst2 = nspikeTrain(spikeTimes);
-nst2.setMaxTime(21);nst.plot;
-subplot(2,1,2);
-stim.getSigInTimeWindow(0,21).plot;
-

Fit a constant baseline and Find Stimulus Lag

We fit a constant rate (Poisson) model to the data and use the fit residual to determine the appropriate lag for the stimulus.

clear c;
-selfHist = [] ; NeighborHist = []; sampleRate = 1000;
-c{1} = TrialConfig({{'Baseline','constant'}},sampleRate,selfHist,NeighborHist);
-c{1}.setName('Baseline');
-cfgColl= ConfigColl(c);
-results = Analysis.RunAnalysisForAllNeurons(trial,cfgColl,0);
-
-% Find Stimulus Lag (look for peaks in the cross-covariance function less
-% than 1 second
-figure;
-results.Residual.xcov(stim).windowedSignal([0,1]).plot;
-[m,ind,ShiftTime] = max(results.Residual.xcov(stim).windowedSignal([0,1]));
-%Allow for shifts of less than 1 second
-stim = Covariate(time,stimData,'Stimulus','time','s','V',{'stim'});
-stim = stim.shift(ShiftTime);
-baseline = Covariate(time,ones(length(time),1),'Baseline','time','s','',...
-    {'constant'});
-
-nst = nspikeTrain(spikeTimes);
-nspikeColl = nstColl(nst);
-cc = CovColl({stim,baseline});
-trial = Trial(nspikeColl,cc);
-
Analyzing Configuration #1: Neuron #1
-

Compare constant rate model with model including stimulus effect

Addition of the stimulus improves the fits in terms of the KS plot and the making the rescaled ISIs less correlated. The Point Process Residula also looks more "white"

clear c;
-selfHist = [] ; NeighborHist = []; sampleRate = 1000;
-c{1} = TrialConfig({{'Baseline','constant'}},sampleRate,selfHist,...
-    NeighborHist);
-c{1}.setName('Baseline');
-c{2} = TrialConfig({{'Baseline','constant'},{'Stimulus','stim'}},...
-    sampleRate,selfHist,NeighborHist);
-c{2}.setName('Baseline+Stimulus');
-cfgColl= ConfigColl(c);
-results = Analysis.RunAnalysisForAllNeurons(trial,cfgColl,0);
-results.plotResults;
-
Analyzing Configuration #1: Neuron #1
-Analyzing Configuration #2: Neuron #1
-

History Effect

Determine the best history effect model using AIC, BIC, and KS statistic

sampleRate=1000;
-delta=1/sampleRate*1;
-maxWindow=1; numWindows=30;
-windowTimes =unique(round([0 logspace(log10(delta),...
-    log10(maxWindow),numWindows)]*sampleRate)./sampleRate);
-results =Analysis.computeHistLagForAll(trial,windowTimes,...
-    {{'Baseline','constant'},{'Stimulus','stim'}},'BNLRCG',0,sampleRate,0);
-
-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)));
-BICind = find((results{1}.BIC(2:end)-results{1}.BIC(1))== ...
-               min(results{1}.BIC(2:end)-results{1}.BIC(1)));
-if(AICind==1)
-    AICind=inf;
-end
-if(BICind==1)
-    BICind=inf; %sometime BIC is non-decreasing and the index would be 1
-end
-windowIndex = min([KSind,AICind,BICind]) %use the minimum order model
-Summary = FitResSummary(results);
-Summary.plotSummary;
-
-
-clear c;
-if(windowIndex>1)
-    selfHist = windowTimes(1:windowIndex);
-else
-    selfHist = [];
-end
-NeighborHist = []; sampleRate = 1000;
-
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
-
-windowIndex =
-
-     8
-
-
figure;
-x=1:length(windowTimes);
-subplot(3,1,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',[]);
-ylabel('KS Statistic');
-dAIC = results{1}.AIC-results{1}.AIC(1);
-subplot(3,1,2); plot(x,dAIC,'.');
- set(gca,'xtick',[]);
-ylabel('\Delta AIC');axis tight; hold on;
-plot(x(windowIndex),dAIC(windowIndex),'r*');
-dBIC = results{1}.BIC-results{1}.BIC(1);
-subplot(3,1,3); plot(x,dBIC,'.');
-ylabel('\Delta BIC'); axis tight; hold on;
-plot(x(windowIndex),dBIC(windowIndex),'r*');
-
-for i=2:length(x)
-   histLabels{i} = ['[' num2str(windowTimes(i-1),3) ',' num2str(windowTimes(i),3) ,']'];
-end
-
-figure;
-plot(x,dBIC,'.');
-xticks = 1:(length(histLabels));
-set(gca,'xtick',xticks,'xtickLabel',histLabels,'FontSize',6);
-if(max(xticks)>=1)
-    xticklabel_rotate([],90,[],'Fontsize',8);
-end
-

Compare Baseline, Baseline+Stimulus Model, Baseline+History+Stimulus

Addition of the history effect yields a model that falls within the 95% CI of the KS plot.

c{1} = TrialConfig({{'Baseline','constant'}},sampleRate,[],NeighborHist);
-c{1}.setName('Baseline');
-c{2} = TrialConfig({{'Baseline','constant'},{'Stimulus','stim'}},...
-                    sampleRate,[],[]);
-c{2}.setName('Baseline+Stimulus');
-c{3} = TrialConfig({{'Baseline','constant'},{'Stimulus','stim'}},...
-                    sampleRate,windowTimes(1:windowIndex),[]);
-c{3}.setName('Baseline+Stimulus+Hist');
-cfgColl= ConfigColl(c);
-results = Analysis.RunAnalysisForAllNeurons(trial,cfgColl,0);
-results.plotResults;
-
Analyzing Configuration #1: Neuron #1
-Analyzing Configuration #2: Neuron #1
-Analyzing Configuration #3: Neuron #1
-
\ No newline at end of file diff --git a/helpfiles/ExplicitStimulusWhiskerData.m b/helpfiles/ExplicitStimulusWhiskerData.m deleted file mode 100644 index a091edcf..00000000 --- a/helpfiles/ExplicitStimulusWhiskerData.m +++ /dev/null @@ -1,160 +0,0 @@ -%% EXPLICIT STIMULUS EXAMPLE - WHISKER STIMULATION/THALAMIC NEURON -% In the worksheet with analyze the stimulus effect and history effect on -% the firing of a thalamic neuron under a known stimulus consisting of -% whisker stimulation. -% Data from Demba Ba (demba@mit.edu) - -%% Load the data -close all; currdir = pwd; -index = strfind(currdir,'helpfiles')-1; -rootpath = currdir(1:index); - -Direction=3; Neuron=1; Stim=2; -datapath = fullfile(rootpath,'data','Explicit Stimulus',strcat('Dir', num2str(Direction)),... - strcat('Neuron', num2str(Neuron)), strcat('Stim', num2str(Stim))); -data=load(fullfile(datapath,'trngdataBis.mat')); - -time=0:.001:(length(data.t)-1)*.001; -stimData = data.t; -spikeTimes = time(data.y==1); - -stim = Covariate(time,stimData,'Stimulus','time','s','V',{'stim'}); -baseline = Covariate(time,ones(length(time),1),'Baseline','time','s','',... - {'constant'}); - -nst = nspikeTrain(spikeTimes); -nspikeColl = nstColl(nst); -cc = CovColl({stim,baseline}); -trial = Trial(nspikeColl,cc); -trial.plot; - -figure; -subplot(2,1,1); -nst2 = nspikeTrain(spikeTimes); -nst2.setMaxTime(21);nst.plot; -subplot(2,1,2); -stim.getSigInTimeWindow(0,21).plot; - -%% Fit a constant baseline and Find Stimulus Lag -% We fit a constant rate (Poisson) model to the data and use the fit -% residual to determine the appropriate lag for the stimulus. -clear c; -selfHist = [] ; NeighborHist = []; sampleRate = 1000; -c{1} = TrialConfig({{'Baseline','constant'}},sampleRate,selfHist,NeighborHist); -c{1}.setName('Baseline'); -cfgColl= ConfigColl(c); -results = Analysis.RunAnalysisForAllNeurons(trial,cfgColl,0); - -% Find Stimulus Lag (look for peaks in the cross-covariance function less -% than 1 second -figure; -results.Residual.xcov(stim).windowedSignal([0,1]).plot; -[m,ind,ShiftTime] = max(results.Residual.xcov(stim).windowedSignal([0,1])); -%Allow for shifts of less than 1 second -stim = Covariate(time,stimData,'Stimulus','time','s','V',{'stim'}); -stim = stim.shift(ShiftTime); -baseline = Covariate(time,ones(length(time),1),'Baseline','time','s','',... - {'constant'}); - -nst = nspikeTrain(spikeTimes); -nspikeColl = nstColl(nst); -cc = CovColl({stim,baseline}); -trial = Trial(nspikeColl,cc); - -%% Compare constant rate model with model including stimulus effect -% Addition of the stimulus improves the fits in terms of the KS plot and -% the making the rescaled ISIs less correlated. The Point Process Residula -% also looks more "white" -clear c; -selfHist = [] ; NeighborHist = []; sampleRate = 1000; -c{1} = TrialConfig({{'Baseline','constant'}},sampleRate,selfHist,... - NeighborHist); -c{1}.setName('Baseline'); -c{2} = TrialConfig({{'Baseline','constant'},{'Stimulus','stim'}},... - sampleRate,selfHist,NeighborHist); -c{2}.setName('Baseline+Stimulus'); -cfgColl= ConfigColl(c); -results = Analysis.RunAnalysisForAllNeurons(trial,cfgColl,0); -results.plotResults; - -%% History Effect -% Determine the best history effect model using AIC, BIC, and KS statistic -sampleRate=1000; -delta=1/sampleRate*1; -maxWindow=1; numWindows=30; -windowTimes =unique(round([0 logspace(log10(delta),... - log10(maxWindow),numWindows)]*sampleRate)./sampleRate); -results =Analysis.computeHistLagForAll(trial,windowTimes,... - {{'Baseline','constant'},{'Stimulus','stim'}},'BNLRCG',0,sampleRate,0); - -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))); -BICind = find((results{1}.BIC(2:end)-results{1}.BIC(1))== ... - min(results{1}.BIC(2:end)-results{1}.BIC(1))); -if(AICind==1) - AICind=inf; -end -if(BICind==1) - BICind=inf; %sometime BIC is non-decreasing and the index would be 1 -end -windowIndex = min([KSind,AICind,BICind]) %use the minimum order model -Summary = FitResSummary(results); -Summary.plotSummary; - - -clear c; -if(windowIndex>1) - selfHist = windowTimes(1:windowIndex); -else - selfHist = []; -end -NeighborHist = []; sampleRate = 1000; -%% -figure; -x=1:length(windowTimes); -subplot(3,1,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',[]); -ylabel('KS Statistic'); -dAIC = results{1}.AIC-results{1}.AIC(1); -subplot(3,1,2); plot(x,dAIC,'.'); - set(gca,'xtick',[]); -ylabel('\Delta AIC');axis tight; hold on; -plot(x(windowIndex),dAIC(windowIndex),'r*'); -dBIC = results{1}.BIC-results{1}.BIC(1); -subplot(3,1,3); plot(x,dBIC,'.'); -ylabel('\Delta BIC'); axis tight; hold on; -plot(x(windowIndex),dBIC(windowIndex),'r*'); - -for i=2:length(x) - histLabels{i} = ['[' num2str(windowTimes(i-1),3) ',' num2str(windowTimes(i),3) ,']']; -end - -figure; -plot(x,dBIC,'.'); -xticks = 1:(length(histLabels)); -set(gca,'xtick',xticks,'xtickLabel',histLabels,'FontSize',6); -if(max(xticks)>=1) - xticklabel_rotate([],90,[],'Fontsize',8); -end - - -%% Compare Baseline, Baseline+Stimulus Model, Baseline+History+Stimulus -% Addition of the history effect yields a model that falls within the 95% -% CI of the KS plot. - -c{1} = TrialConfig({{'Baseline','constant'}},sampleRate,[],NeighborHist); -c{1}.setName('Baseline'); -c{2} = TrialConfig({{'Baseline','constant'},{'Stimulus','stim'}},... - sampleRate,[],[]); -c{2}.setName('Baseline+Stimulus'); -c{3} = TrialConfig({{'Baseline','constant'},{'Stimulus','stim'}},... - sampleRate,windowTimes(1:windowIndex),[]); -c{3}.setName('Baseline+Stimulus+Hist'); -cfgColl= ConfigColl(c); -results = Analysis.RunAnalysisForAllNeurons(trial,cfgColl,0); -results.plotResults; - - diff --git a/helpfiles/ExplicitStimulusWhiskerData.png b/helpfiles/ExplicitStimulusWhiskerData.png deleted file mode 100644 index 7857b79d..00000000 Binary files a/helpfiles/ExplicitStimulusWhiskerData.png and /dev/null differ diff --git a/helpfiles/ExplicitStimulusWhiskerData_01.png b/helpfiles/ExplicitStimulusWhiskerData_01.png deleted file mode 100644 index d4327285..00000000 Binary files a/helpfiles/ExplicitStimulusWhiskerData_01.png and /dev/null differ diff --git a/helpfiles/ExplicitStimulusWhiskerData_02.png b/helpfiles/ExplicitStimulusWhiskerData_02.png deleted file mode 100644 index 0bf1e2ca..00000000 Binary files a/helpfiles/ExplicitStimulusWhiskerData_02.png and /dev/null differ diff --git a/helpfiles/ExplicitStimulusWhiskerData_03.png b/helpfiles/ExplicitStimulusWhiskerData_03.png deleted file mode 100644 index 72f63838..00000000 Binary files a/helpfiles/ExplicitStimulusWhiskerData_03.png and /dev/null differ diff --git a/helpfiles/ExplicitStimulusWhiskerData_04.png b/helpfiles/ExplicitStimulusWhiskerData_04.png deleted file mode 100644 index 12c58f68..00000000 Binary files a/helpfiles/ExplicitStimulusWhiskerData_04.png and /dev/null differ diff --git a/helpfiles/ExplicitStimulusWhiskerData_05.png b/helpfiles/ExplicitStimulusWhiskerData_05.png deleted file mode 100644 index 2f81749e..00000000 Binary files a/helpfiles/ExplicitStimulusWhiskerData_05.png and /dev/null differ diff --git a/helpfiles/ExplicitStimulusWhiskerData_06.png b/helpfiles/ExplicitStimulusWhiskerData_06.png deleted file mode 100644 index 898d5a7f..00000000 Binary files a/helpfiles/ExplicitStimulusWhiskerData_06.png and /dev/null differ diff --git a/helpfiles/ExplicitStimulusWhiskerData_07.png b/helpfiles/ExplicitStimulusWhiskerData_07.png deleted file mode 100644 index 17870dbd..00000000 Binary files a/helpfiles/ExplicitStimulusWhiskerData_07.png and /dev/null differ diff --git a/helpfiles/ExplicitStimulusWhiskerData_08.png b/helpfiles/ExplicitStimulusWhiskerData_08.png deleted file mode 100644 index 48ab58b1..00000000 Binary files a/helpfiles/ExplicitStimulusWhiskerData_08.png and /dev/null differ diff --git a/helpfiles/FitResSummaryExamples.html b/helpfiles/FitResSummaryExamples.html deleted file mode 100644 index f604fc72..00000000 --- a/helpfiles/FitResSummaryExamples.html +++ /dev/null @@ -1,71 +0,0 @@ - - - - - FitResSummary Examples

FitResSummary Examples

\ No newline at end of file diff --git a/helpfiles/FitResSummaryExamples.m b/helpfiles/FitResSummaryExamples.m deleted file mode 100644 index dc5b84c7..00000000 --- a/helpfiles/FitResSummaryExamples.m +++ /dev/null @@ -1 +0,0 @@ -%% FitResSummary Examples diff --git a/helpfiles/FitResult.html b/helpfiles/FitResult.html deleted file mode 100644 index fc242ccd..00000000 --- a/helpfiles/FitResult.html +++ /dev/null @@ -1,2066 +0,0 @@ - - - - - FitResult
classdef FitResult < handle
-    % FITRESULT
-    % stores results of a fit using the Analysis object
-    % The results are for a single neuron over a range of configurations
-    % <a href="matlab:web('FitResultExamples.html', '-helpbrowser')">FitResult Examples</a>
-    % see also <a href="matlab:help('Analysis')">Analysis</a>
-    % Reference page in Help browser
-    % <a href="matlab:doc('FitResult')">doc FitResult</a>
-    properties
-       numResults   %Number of results in this FitResult object
-       lambda       %Lambda signal
-       numCoeffs    %Number of coefficients for each fitResult
-       fitType      %Poisson or Binomial
-
-       b            %coefficients for each fit
-       dev          %deviance for each fit
-       AIC          %Akaike's Information Criterion for each fit
-       BIC          %Baysian Information Criterion for each fit
-       stats        %Relevant statistics for each fit
-       configs      % the config collection for the different fits
-       configNames  % names of the the differen fits
-       neuronNumber % the number of the neuron the data comes from
-       neuralSpikeTrain % the spike data
-       covLabels
-       uniqueCovLabels
-       indicesToUniqueLabels
-       numHist        % Number of history terms (used for indexing into the regression coefficients) for each fit
-       histObjects    % History object for self firing
-       ensHistObjects % History object to be applied to the neuron's neigbors to compute ensemble effect
-       flatMask
-       Z    % Rescaled spike times from the Time-Rescaling theorem, exponential rate 1
-       U    % Transformed z's -> uniform in [0,1]
-       X    % Transformed u's -> gaussian in [-inf, inf]
-       Residual %fit residual
-%        xAxis
-%        KSSorted
-%        ks_stat
-       invGausStats
-       KSStats  %Kolmogorov Smirnov Statistics
-       plotParams
-       XvalData % cell array of raw data used for validation
-       XvalTime % cell array of time vectors for each element of XvalData
-       validation % a FitResult object with the validation data
-       minTime  % The minTime from the spikeTrain (not necessarily the analysis)
-       maxTime  % The maxTime for the spikeTrain (not necessarily the analysis)
-    end
-    properties (Constant,Hidden)
-        colors={'b','g','r','c','m','y','k'};
-    end
-
-
-    methods
-
-        function fitObj=FitResult(spikeObj,covLabels,numHist,histObjects,ensHistObj,lambda,b, dev, stats,AIC,BIC,configColl,XvalData,XvalTime,distribution)
-            % fitObj=FitResult(spikeObj,covLabels,numHist,histObjects,ensHistObj,lambda,b, dev, stats,AIC,BIC,configColl,XvalData,XvalTime)
-            % Stores the results of multiple regressions for a single  neuron into a accessible structure.
-            %
-            % spikeObj: The spike train for the neuron whose results are
-            %           being stored.
-            % covLabels: A 2-d cell array, the jth row has all the labels for the covariates used in the jth fit
-            % numHist: The number of history terms in each of the N fits.
-            % histObjects: The History object for each of the N fits
-            % ensHistObj: The History object for used to compute the ensemble history effect.
-            % lambda: The conditional intensity function evaluated usin the
-            % data. Each dimension of lambda corresponds to the a different
-            %       GLM Fit.
-            % b: N-component cell array containing the GLM regression
-            %    coefficient of each of the fits. The jth component has all
-            %    the regression coefficients for the jth trial.
-            % dev: vector of Deviances for each the GLM fits.
-            % stats: Cell array of the stats parameters for each GLM fit;
-            % AIC: vector of Akaike's information criteria for each the GLM fits.
-            % BIC: vector of Bayes Information criteria for each the GLM fits.
-            % configColl: configCollection object used to generate this
-            %             results
-            % XvalData: Data to be used for validation.
-            % XvalTime: Time vector for the data.
-
-            if(nargin< 14)
-                XvalTime =[];
-            end
-            if(nargin<13)
-                XvalData =[];
-            end
-
-            if(isnumeric(spikeObj.name))
-                nNumber =spikeObj.name;
-            else
-                nNumber = str2double(spikeObj.name(~isletter(spikeObj.name)));
-            end
-            fitObj.neuronNumber = nNumber; %str2num(spikeObj.name);
-            fitObj.neuralSpikeTrain = spikeObj;
-            fitObj.minTime = spikeObj.minTime;
-            fitObj.maxTime = spikeObj.maxTime;
-            fitObj.numResults = 0;
-            fitObj.configs = configColl;
-            fitObj.configNames = configColl.getConfigNames;
-            fitObj.covLabels=covLabels;
-            fitObj.uniqueCovLabels= getUniqueLabels(covLabels);
-
-            fitObj.mapCovLabelsToUniqueLabels;
-            fitObj.numHist=numHist;
-            fitObj.histObjects = histObjects;
-            fitObj.ensHistObjects = ensHistObj;
-            fitObj.addParamsToFit(fitObj.neuronNumber,lambda,b, dev, stats,AIC,BIC,configColl);
-            fitObj.Z        =[]; %rescaled spikes times - exponentially dist.
-            fitObj.U        =[]; %rescaled spike times - uniformly dist.
-            fitObj.X        =[]; %rescaled spike times - gaussian dist.
-            fitObj.Residual =[]; %fit residual for PP
-            fitObj.KSStats.xAxis    =[];
-            fitObj.KSStats.KSSorted =[];
-            fitObj.KSStats.ks_stat  =[];
-            fitObj.invGausStats.rhoSig=[];
-            fitObj.invGausStats.confBoundSig=[];
-            fitObj.plotParams = [];
-            fitObj.XvalData = XvalData;
-            fitObj.XvalTime = XvalTime;
-
-            fitObj.fitType = distribution;
-
-        end
-        function mFitRes = mergeResults(fitObj,newFitObj)
-            if(isa(newFitObj,'FitResult'))
-                if(fitObj.neuronNumber ==newFitObj.neuronNumber)
-                    spikeObj = fitObj.neuralSpikeTrain;
-                    covLabels = fitObj.covLabels(1:fitObj.numResults);
-                    covLabels((fitObj.numResults+1):(fitObj.numResults+newFitObj.numResults)) = newFitObj.covLabels(1:newFitObj.numResults);
-                    numHist = fitObj.numHist(1:fitObj.numResults);
-                    numHist((fitObj.numResults+1):(fitObj.numResults+newFitObj.numResults)) = newFitObj.numHist(1:newFitObj.numResults);
-                    histObjects=fitObj.histObjects(1:fitObj.numResults);
-                    histObjects((fitObj.numResults+1):(fitObj.numResults+newFitObj.numResults)) = newFitObj.histObjects(1:newFitObj.numResults);
-                    ensHistObjects=fitObj.ensHistObjects(1:fitObj.numResults);
-                    ensHistObjects((fitObj.numResults+1):(fitObj.numResults+newFitObj.numResults)) = newFitObj.ensHistObjects(1:newFitObj.numResults);
-                    b=fitObj.b(1:fitObj.numResults);
-                    b((fitObj.numResults+1):(fitObj.numResults+newFitObj.numResults)) = newFitObj.b(1:newFitObj.numResults);
-                    dev = [fitObj.dev newFitObj.dev];
-                    AIC = [fitObj.AIC newFitObj.AIC];
-                    BIC = [fitObj.BIC newFitObj.BIC];
-                    stats=fitObj.stats(1:fitObj.numResults);
-                    stats((fitObj.numResults+1):(fitObj.numResults+newFitObj.numResults)) = newFitObj.stats(1:newFitObj.numResults);
-                    lambda = fitObj.lambda.merge(newFitObj.lambda);
-
-                    for i=1:fitObj.numResults
-                        config{i}=fitObj.configs.getConfig(i);
-                    end
-                    offset=fitObj.numResults;
-                    for i=1:newFitObj.numResults
-                        config{i+offset}=newFitObj.configs.getConfig(i);
-                    end
-                    configColl= ConfigColl(config);
-
-                    XvalData = [fitObj.XvalData newFitObj.XvalData];
-                    XvalTime = [fitObj.XvalTime newFitObj.XvalTime];
-                    distribution=fitObj.fitType(1:fitObj.numResults);
-                    distribution((fitObj.numResults+1):(fitObj.numResults+newFitObj.numResults)) = newFitObj.fitType(1:newFitObj.numResults);
-                    Z=[fitObj.Z newFitObj.Z];
-                    U=[fitObj.U newFitObj.U];
-                    [X,rhoSig,confBoundSig] = Analysis.computeInvGausTrans(Z);
-
-                    M=fitObj.Residual.merge(newFitObj.Residual);
-                    xAxis    = [fitObj.KSStats.xAxis newFitObj.KSStats.xAxis];
-                    KSSorted = [fitObj.KSStats.KSSorted newFitObj.KSStats.KSSorted];
-                    ks_stat  = [fitObj.KSStats.ks_stat newFitObj.KSStats.ks_stat];
-                    mFitRes=FitResult(spikeObj,covLabels,numHist,histObjects,ensHistObjects,lambda,b, dev, stats,AIC,BIC,configColl,XvalData,XvalTime,distribution);
-                    mFitRes.setKSStats(Z,U, xAxis, KSSorted, ks_stat);
-                    mFitRes.setInvGausStats(X,rhoSig,confBoundSig);
-                    mFitRes.setFitResidual(M);
-
-
-                elseif(isa(newFitObj,'cell'))
-                    if(isa(newFitObj{1},'FitResult'))
-                        for i=1:length(newFitObj)
-                            if(i==1)
-                                mFitRes = fitObj.mergeResults(newFitObj{i});
-                            else
-                                mFitRes = mFitRes.mergeResults(newFitObj{i});
-                            end
-                        end
-                    end
-                end
-            end
-
-        end
-        function addParamsToFit(fitObj,neuronNum,lambda,b, dev, stats,AIC,BIC,configColl)
-            % addParamsToFit(fitObj,neuronNum,lambda,b, dev, stats,AIC,BIC,configColl)
-            % Add the specified parameters to the current FitResult object
-            % only if the neuronNum matches the neuronNum of this object
-            if(fitObj.neuronNumber==neuronNum)
-              if(isa(lambda,'cell'))
-                  newLambda=lambda{1};
-                  for i=2:length(lambda)
-                      newLambda = newLambda.merge(lambda{i});
-                  end
-              elseif(isa(lambda,'Covariate')||isa(lambda,'SignalObj'))
-                  newLambda = lambda;
-              end
-
-              numNewResults = newLambda.dimension;%number of new elements
-              if(nargin<8)
-                  configColl = cell(1,numNewResults);
-              end
-
-              if(numNewResults==1)
-                      fitObj.b{fitObj.numResults+1}    = b{1};
-                      fitObj.dev(fitObj.numResults+1)  = dev;
-                      fitObj.stats{fitObj.numResults+1}= stats{1};
-                      if(nargin<7)
-                          fitObj.AIC(fitObj.numResults+1)  = 2*length(b)+dev;
-                          fitObj.BIC(fitObj.numResults+1)  = length(b)*log(length(newLambda.time))+dev;
-                      else
-                          fitObj.AIC(fitObj.numResults+1)  = AIC;
-                          fitObj.BIC(fitObj.numResults+1)  = BIC;
-                      end
-
-                      fitObj.numCoeffs(fitObj.numResults+1) = length(b);
-              else
-                  for i=1:numNewResults
-                      fitObj.b{fitObj.numResults+i}    = b{i};
-                      fitObj.dev(fitObj.numResults+i)  = dev(i);
-                      fitObj.stats{fitObj.numResults+i}= stats{i};
-                      if(nargin<7)
-                          fitObj.AIC(fitObj.numResults+i)  = 2*length(b{i})+dev(i);
-                          fitObj.BIC(fitObj.numResults+i)  = length(b{i})*log(length(newLambda.time))+dev(i);
-                      else
-                          fitObj.AIC(fitObj.numResults+i)  = AIC(i);
-                          fitObj.BIC(fitObj.numResults+i)  = BIC(i);
-                      end
-                      fitObj.numCoeffs(fitObj.numResults+i) = length(b{i});
-                  end
-              end
-              if(fitObj.numResults ==0)
-                  fitObj.lambda = newLambda;
-              else
-                fitObj.lambda = fitObj.lambda.merge(newLambda); %new lambda
-              end
-
-              fitObj.numResults = fitObj.numResults+numNewResults;
-              dataLabels = cell(1,fitObj.numResults);
-              for i=1:fitObj.numResults
-                 dataLabels{i} = strcat('\lambda_',num2str(i));
-              end
-              fitObj.lambda.setDataLabels(dataLabels);
-
-              fitObj.configs.addConfig(configColl);
-              fitObj.configNames = fitObj.configs.getConfigNames;
-          else
-              error('Neuron number does not match');
-          end
-        end
-        function lambda = computeValLambda(fitObj)
-            % lambda = computeValLambda(fitObj)
-            % Returns a Covariate object lambda. This is the Conditional
-            % intensity function evaluated using the validation data
-            lambdaData = zeros(length(fitObj.XvalTime{1}),fitObj.numResults);
-            for i=1:fitObj.numResults
-                lambdaData(:,i) = fitObj.evalLambda(i,fitObj.XvalData{i});
-            end
-            lambda=Covariate(fitObj.XvalTime{1},lambdaData,...
-                  '\Lambda(t)',fitObj.lambda.xlabelval,...
-                  fitObj.lambda.xunits,'Hz',fitObj.lambda.dataLabels);
-        end
-
-        function mapCovLabelsToUniqueLabels(fitObj)
-            flatMask = zeros(length(fitObj.uniqueCovLabels),length(fitObj.covLabels));
-            for j=1:length(fitObj.covLabels)
-                currLabels = fitObj.covLabels{j};
-                index=zeros(1,length(currLabels));
-                for i=1:length(currLabels)
-                    index(i)=strmatch(currLabels{i}, fitObj.uniqueCovLabels, 'exact');
-                end
-
-                fitObj.indicesToUniqueLabels{j} = index;
-                flatMask(index,j) = 1;
-            end
-            fitObj.flatMask = flatMask;
-        end
-        function p=getPlotParams(fitObj)
-            % p=getPlotParams(fitObj)
-            if(isempty(fitObj.plotParams))
-                fitObj.computePlotParams;
-            end
-                p=fitObj.plotParams;
-        end
-        function plotValidation(fitObj)
-            % plotValidation(fitObj)
-            % calls plotResults on the validation FitResult object if
-            % validation data is present. Note that the GLM coefficients
-            % are not recomputed and therefore the same as those obtained
-            % from the training data.
-            if(~isempty(fitObj.validation))
-                fitObj.validation.plotResults;
-            else
-                display('Validation Data not available to plot');
-            end
-        end
-        function answer = isValDataPresent(fitObj)
-            % answer = isValDataPresent(fitObj)
-            % returns 1 if validation data is present. This method is used
-            % to determine if validation data is available to compute the
-            % validation results.
-            answer = 0;
-            if(~isempty(fitObj.XvalTime) && ~isempty(fitObj.XvalData))
-                for i=1:length(fitObj.XvalTime)
-                    currTime = fitObj.XvalTime{i};
-                    if(~isempty(currTime))
-                        if(currTime(end)-currTime(1)>0)
-                            answer =1;
-                            break;
-                        end
-                    end
-                end
-
-            end
-
-        end
-        function lambdaData = evalLambda(fitObj,lambdaIndex,newData)
-            % lambdaData = evalLambda(fitObj,lambdaIndex,newData)
-            % lambdaIndex: the index of the corresponding lambda to be
-            %              evaluated with the new data.
-            % newData:     matrix of covariates in same order as fits without
-            %              constant term in first column
-%             if(isa(newData,'double'))
-%                 [~,columns] = size(newData);
-%                 tempData = cell(1,columns);
-%                 for i=1:columns
-%                    tempData{i} = newData(:,i);
-%                 end
-%                 newData = tempData;
-%             end
-
-            if(lambdaIndex>0 && lambdaIndex <= fitObj.numResults)
-                b=fitObj.b{lambdaIndex}; %coefficient matrix
-                if(isempty(newData))
-                    [rows,~] = size(newData);
-                    baseline=ones(rows,1);
-                    lambdaData =  exp(b(1)*baseline);
-                else
-                    if(isa(newData,'double')) %matrix, 1 column per coefficient
-                        baseline=ones(length(newData),1);
-                        [~,columns] = size(newData);
-
-                        if(length(b)>=1)
-                            lambdaData = exp(newData*b(1:end));
-                            if(strcmp(fitObj.fitType{lambdaIndex},'poisson'))
-%                                 lambdaData = exp(newData*b(1:end));
-%                                 lambdaData = exp(b(1) + newData*b(2:end));
-                            else
-%                                 lambdaData = exp(b(1) + newData*b(2:end));
-                                lambdaData = lambdaData./(1+lambdaData);
-                            end
-%                         else
-%                             if(strcmp(fitObj.fitType{lambdaIndex},'poisson'))
-%                                 lambdaData = exp(b(1)*baseline);
-%
-%                             else
-%                                 lambdaData = exp(b(1)*baseline);
-%                                 lambdaData = lambdaData./(1+lambdaData);
-%                             end
-                        end
-                        lambdaData = lambdaData*fitObj.neuralSpikeTrain.sampleRate;
-                    elseif(isa(newData,'cell')) % a cell array, each element is matrix of values for each coeff
-%                         baseline=ones(size(newData{1})); %design matrix
-                            runSum=0;
-                        for i=1:(length(newData)) %-fitObj.numHist(lambdaIndex))
-%                             if(i==1)
-%                                 runSum = b(1)*baseline;
-%                             else
-                                runSum = runSum+b(i)*newData{i-1};
-%                             end
-                        end
-                        if(strcmp(fitObj.fitType{lambdaIndex},'poisson'))
-                            lambdaData = exp(runSum);
-                            lambdaData = lambdaData*fitObj.neuralSpikeTrain.sampleRate;
-                        else
-                            lambdaData = exp(runSum);
-                            lambdaData = lambdaData./(1+lambdaData);
-                            lambdaData = lambdaData*fitObj.neuralSpikeTrain.sampleRate;
-                        end
-                    else
-                        error('New data must be cell or a matrix');
-                    end
-
-                end
-            else
-                error('Index into fit params is incorrect');
-            end
-
-        end
-%         function handle = plotHist(fitObj,fitNum)
-%            % handle = plotHist(fitObj,fitNum)
-%            % plots the history terms used in this FitResult object
-%            % if fitNum is not specified then fitNum=1:numResults
-%            if(nargin<2 || isempty(fitNum))
-%                fitNum = 1:fitObj.numResults;
-%            end
-%
-%            for j=fitNum
-%                if(j>0 && j <= fitObj.numResults)
-%                     b=fitObj.b{j}; %coefficient matrix
-%                     startHistIndex = length(b)-fitObj.numHist(j)+1;
-%                     if(startHistIndex<length(b))
-%                         bHist = b(startHistIndex:end);
-%                         if(~isempty(fitObj.histObjects{j}))
-%                             windowTimes = fitObj.histObjects{j}.windowTimes;
-%                             t=linspace(windowTimes(1),windowTimes(end),100)';
-%                             histEffect = zeros(length(t),1);
-%                             for i=1:length(windowTimes)-1
-%                                 index = and(t>=windowTimes(i),t<=windowTimes(i+1));
-%                                 histEffect(index)=exp(-bHist(i))-1; %To offset zero coeffs
-%                             end
-%                         end
-%                     else
-%                         t=[0; 0.00001];
-%                         histEffect =[0;0];
-%                     end
-%                     if(j==fitNum(1))
-%                         hSig = SignalObj(t,histEffect,'History','time','s','',fitObj.lambda.dataLabels{j});
-%                     else
-%                         hSig = hSig.merge(SignalObj(t,histEffect,'History Effect','time','s','',fitObj.lambda.dataLabels{j}));
-%                     end
-%                end
-%            end
-%            N=floor(length(hSig.time)./70); B=ones(1,N)/N; A=1;
-%            handle=hSig.filtfilt(B,A).plot;
-%         end
-        function computePlotParams(fitObj,fitNum)
-             if(nargin<2)
-               fitNum = 1:fitObj.numResults;
-             end
-           index=find(sum(fitObj.flatMask,2)>0);%1:length(fitObj.flatMask(:,1));
-           %Only use the labels that appear in at least one fit
-           %Otherwise that parameter was not present for any of the
-           %regressions and just takes up plot real-estate
-
-           sigIndex=zeros(length(index),length(fitNum));
-           bAct = nan(length(index),length(fitNum));
-           seAct= nan(length(index),length(fitNum));
-
-           for i=fitNum
-               %this indexing is to avoid extremely large se's from
-               %affecting plots
-               criteria = find(fitObj.stats{i}.se'<100);
-               %indicesForFit = find(fitObj.flatMask(index,i)==1);
-               indicesForFit = fitObj.indicesToUniqueLabels{i};
-               bVals = fitObj.b{i}(criteria);
-               bAct(indicesForFit(criteria),i) = bVals; %sorted according to uniqueLabels
-               seVals = fitObj.stats{i}.se(criteria)';
-               seAct(indicesForFit(criteria),i)= seVals; %sorted according to uniqueLabels;
-               temp = sign([bAct(:,i)-seAct(:,i) bAct(:,i)+seAct(:,i)]);
-               productOfSigns = temp(:,1).*temp(:,2); %should be positive
-               sIndex=and(productOfSigns>0,seAct(:,i)~=0);
-               sigIndex(:,i)=sIndex;
-           end
-           fitObj.plotParams.bAct = bAct;
-           fitObj.plotParams.seAct= seAct;
-           fitObj.plotParams.sigIndex = sigIndex;
-           fitObj.plotParams.xLabels  = cell(length(index),1);
-           fitObj.plotParams.xLabels = fitObj.uniqueCovLabels;
-
-%            for i=1:(length(index))
-%                if(i==1)
-%                    fitObj.plotParams.xLabels{i} = 'baseline';
-%                    %text(i, 0,'baseline','interpreter','latex');
-%                else
-%                    fitObj.plotParams.xLabels{i} = fitObj.covLabels{index(i)-1};
-%                    %text(i, 0,fitObj.covLabels{index(i)-1},'interpreter','latex');
-%                end
-%            end
-           tempVal =sum(fitObj.flatMask,2);
-           fitObj.plotParams.numResultsCoeffPresent =tempVal(index);
-        end
-        function h=plotCoeffs(fitObj,handle,fitNum,plotProps,plotSignificance)
-           % h=plotCoeffs(fitObj,handle,fitNum,plotProps,plotSignificance)
-           % plots the GLM coefficients for each fit along with the
-           % confidence intervals.
-           % fitNum: number of the fit to plot. If not specified, all are
-           %         plotted.
-           % plotProps: properties to use for the making the plot
-           % plotSignificance: If 1 then an asterix (*) is place above
-           %                   parameters that are statistically different
-           %                   from zero with alpha=5%.
-
-           if(nargin<5)
-               plotSignificance = 1;
-           end
-
-           if(nargin<4 || isempty(plotProps))
-               plotProps = [];
-           end
-
-           if(nargin<3 || isempty(fitNum))
-               fitNum = 1:fitObj.numResults;
-           end
-
-           if(nargin<2 || isempty(handle))
-               handle=gca;
-           end
-
-           if(isempty(fitObj.plotParams))
-               fitObj.computePlotParams(fitNum);
-           end
-
-           bAct = fitObj.getPlotParams.bAct;
-           seAct= fitObj.getPlotParams.seAct;
-           sigIndex=fitObj.getPlotParams.sigIndex;
-
-           if(~isempty(plotProps))
-               for i=1:length(fitNum)
-                    h=errorbar(handle,1:length(index),bAct,seAct,plotProps{i}); hold on;
-               end
-           else
-               Xaxis=repmat(1:length(bAct(:,1)),[length(bAct(1,:)) 1]);
-               h=errorbar(handle,Xaxis',bAct,seAct,'.');%strcat('.',FitResult.colors{mod(i-1,length(FitResult.colors))+1}));
-           end
-
-            hold on;
-
-
-            if(plotSignificance==1)
-               v=axis;
-               vdiff = .8*v(4);
-
-               for i=fitNum
-                  plot(handle,find(sigIndex(:,i)==1),vdiff*ones(length(find(sigIndex(:,i)==1)),1)-i*.1,strcat('.',FitResult.colors{mod(i-1,length(FitResult.colors))+1})); hold on;
-               end
-            end
-           ylabel('Fit Coefficients','Interpreter','latex');
-           xtickLabels = fitObj.getPlotParams.xLabels;
-           xticks = 1:(length(xtickLabels));
-
-           set(handle,'xtick',xticks,'xtickLabel',xtickLabels,'FontSize',6);
-           if(max(fitObj.numCoeffs)>1)
-            xticklabel_rotate([],90,[],'Fontsize',6);
-           end
-%            hT=rotateticklabel(gca,-90);
-           legend(handle,fitObj.lambda.dataLabels,'Location','Best');
-           %axis tight;
-
-        end
-        function plotResults(fitObj)
-            % plotResults(fitObj)
-            % Generates KS plot, auto-correlation function of the inverse
-            % gaussian transformed rescaled ISIs, the sequential
-            % correlation coefficient between neigboring pairs of the
-            % rescaled ISIs (zj vs. zj-1), the GLM regression coefficients,
-            % and the Point Process Residual.
-                scrsz = get(0,'ScreenSize');
-                figure('Position',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.8 scrsz(4)*.8]);
-
-                subplot(2,4,[1 2]); fitObj.KSPlot; %make the plot
-                text(.45, .95,strcat('Neuron:',num2str(fitObj.neuronNumber)));
-                subplot(2,4,3); fitObj.plotInvGausTrans;
-                subplot(2,4,4); fitObj.plotSeqCorr;
-                subplot(2,4,[7 8]); fitObj.plotResidual;
-                subplot(2,4,[5 6]); fitObj.plotCoeffs;
-        end
-        function handle = KSPlot(fitObj)
-            % handle = KSPlot(fitObj)
-            % computes the K-S plot for each of the the candidate rate
-            % functions in this FitResult object. These candidate rate
-            % functions are numbered according to the order in which they
-            % were added to the FitResult.
-            h=gcf;
-            %h=[];
-            figure(h);
-        %     size(xAxis)
-        %     size(KSSorted)
-            N = length(fitObj.KSStats.KSSorted);
-            xaxis = fitObj.KSStats.xAxis(:,1);
-            handle=plot(fitObj.KSStats.xAxis,fitObj.KSStats.KSSorted, xaxis,xaxis, 'k-.',xaxis, xaxis+1.36/sqrt(N), 'r', xaxis,xaxis-1.36/sqrt(N), 'r' );
-
-            %set(gca,'xtick',[],'ytick',[],'ztick', [])
-            axis( [0 1 0 1] );
-            dataLabels = cell(1,fitObj.lambda.dimension);
-            for i=1:fitObj.lambda.dimension
-                dataLabels{i} = fitObj.lambda.dataLabels{i};
-            end
-            legend(dataLabels,'Location','Best');
-            xlabel('Uniform CDF');
-            ylabel('Empirical CDF of Rescaled ISIs');
-            title('KS Plot with 95% Confidence Intervals');
-
-
-        end
-
-        function structure = toStructure(fitObj)
-            %
-            fnames = fieldnames(fitObj);
-
-            for i=1:length(fnames)
-
-                currObj = fitObj.(fnames{i});
-                if(strcmp(fnames{i},'histObjects')||strcmp(fnames{i},'ensHistObjects'))
-                    for j=1:fitObj.numResults
-                        tempObj = fitObj.(fnames{i}){j};
-                        if(~isempty(tempObj))
-                            structure.(fnames{i}){j} = tempObj.toStructure;
-                        else
-                            structure.(fnames{i}){j} = tempObj;
-                        end
-                    end
-                elseif(strcmp(fnames{i},'invGausStats'))
-                    tempNames = fieldnames(fitObj.(fnames{i}));
-                    for j=1:length(tempNames)
-                       tempObj = currObj.(tempNames{j});
-                       if(~isempty(tempObj))
-                        structure.(fnames{i}).(tempNames{j})=  tempObj.dataToStructure;
-                       else
-                         structure.(fnames{i}).(tempNames{j})=  tempObj;
-                       end
-
-                    end
-
-                else
-
-                    if(isa(currObj,'double')||isa(currObj,'cell'))
-                        structure.(fnames{i}) = currObj;
-                    elseif(isa(currObj,'Covariate') ||isa(currObj,'ConfigColl')||isa(currObj,'nspikeTrain'))
-                        structure.(fnames{i}) = currObj.toStructure;
-                    elseif(isa(currObj,'SignalObj'))
-                        structure.(fnames{i})  = currObj.dataToStructure;
-                    elseif(isa(currObj,'struct'))
-                        structure.(fnames{i}) = currObj;
-                    end
-                end
-            end
-
-        end
-
-
-        function handle = plotSeqCorr(fitObj)
-            % handle = plotSeqCorr(fitObj)
-            % plot zj+1 against zj
-
-            %colors = {'.b','.g','.r','.c','.m','.y','.k'};
-            rho=zeros(1,fitObj.numResults);
-            pval=zeros(1,fitObj.numResults);
-            dataLabels = fitObj.lambda.dataLabels;
-            for i=1:fitObj.numResults
-               handle = plot(fitObj.Z(1:end-1,i),fitObj.Z(2:end,i),strcat('.',Analysis.colors{mod(i-1,length(Analysis.colors))+1})); hold on;
-               [rhoTemp,p]= corrcoef(fitObj.Z(1:end-1,i),fitObj.Z(2:end,i));%handle=scatterhist(fitResults.Z(1:end-1,i),fitResults.Z(2:end,i))
-
-               [~,columns]=size(rhoTemp);
-                if(columns>1)
-                    rho(i) = rhoTemp(1,2);
-                    pval(i)= p(1,2);
-                else
-                    rho(i) = rhoTemp;
-                    pval(i)= p;
-                end
-               dataLabels{i} = strcat(dataLabels{i},', \rho=',num2str(rho(i),'%0.2g'),' (p=',num2str(pval(i),'%0.2g'),')');
-                %get(h,'AlphaData');
-                %set(h,'FaceAlpha',0.2,'EdgeAlpha',0.8,'EdgeColor',color{i});
-            end
-
-
-            legend(dataLabels,'Location','Best');
-            ylabel('z_{j+1}'); xlabel('z_j');
-            axis tight;
-        end
-        function handle = plotInvGausTrans(fitObj)
-            %[rows,colm] = size(fitObj.X);
-            %index=find(fitObj.invGausStats.lags==1);
-            %lags=fitObj.invGausStats.lags;
-            rhoSig=fitObj.invGausStats.rhoSig;
-            n=length(fitObj.X);
-            confBoundSig = fitObj.invGausStats.confBoundSig;
-            handle=[];
-%              for i=1:colm
-%                     %i
-%                     htemp=plot(lags',rho(:,i),strcat('.',FitResults.colors{mod(i-1,length(Analysis.colors))+1}));
-%                     handle=[handle,htemp];
-%                     hold on;
-%                     %labelArray{i} = ['Fit ' num2str(i)];
-%              end
-
-            rhoSig.plot;
-            legend(fitObj.lambda.dataLabels,'Location','Best');
-            %legend(h,labelArray);
-            hold on; confBoundSig.plot;
-
-        end
-        function handle = plotResidual(fitObj)
-            % handle = plotResidual(fitObj)
-            % Plots the Point Process Residual
-            handle=fitObj.Residual.plot;
-            legend off;
-            legend(fitObj.Residual.dataLabels,'Location','Best');
-        end
-
-
-        function setKSStats(fitObj, Z, U, xAxis, KSSorted, ks_stat)
-            % setKSStats(fitObj, Z, xAxis, KSSorted, ks_stat)
-            % Allows KS statistics to be set after object creation
-            % Z: Rescaled ISIs from the Time Rescaling Theorem
-            % xAxis: xAxis of the KS plot
-            % KSSorted: the sorted values of Uj=1-exp(-zj)
-            % ks_stat: the maximum deviation from the 45 degree line for
-            % all of the fits.
-            %
-            fitObj.Z        =Z;
-            fitObj.U        =U;
-            fitObj.KSStats.xAxis    =xAxis;
-            fitObj.KSStats.KSSorted =KSSorted;
-            fitObj.KSStats.ks_stat  =ks_stat;
-            N = length(fitObj.KSStats.KSSorted);
-            fitObj.KSStats.withinConfInt = ks_stat<1.36/sqrt(N);
-        end
-        function setInvGausStats(fitObj, X,rhoSig,confBoundSig)
-            % setInvGausStats(fitObj,X,rhoSig,confBoundSig)
-            % Sets the inverse gaussian transformed rescaled ISIs and the
-            % confidence bounds after the object has been created.
-            %fitObj.U=U;
-            fitObj.X=X;
-            fitObj.invGausStats.rhoSig=rhoSig;
-            fitObj.invGausStats.confBoundSig=confBoundSig;
-        end
-        function setFitResidual(fitObj,M)
-           % setFitResidual(fitObj,M).
-           % Adds the point process residual to the FitResult object
-           fitObj.Residual = M;
-        end
-
-
-
-    end
-
-    methods (Static)
-
-        function fitObj = fromStructure(structure)
-            if(isa(structure,'struct'))
-                spikeObj=nspikeTrain.fromStructure(structure.neuralSpikeTrain);
-                lambda=Covariate.fromStructure(structure.lambda);
-                rhoSig=SignalObj.signalFromStruct(structure.invGausStats.rhoSig);
-                confBoundSig = SignalObj.signalFromStruct(structure.invGausStats.confBoundSig);
-                M = Covariate.fromStructure(structure.Residual);
-                for i=1:structure.numResults
-                    histObjects{i} = History.fromStructure(structure.histObjects{i});
-                    ensHistObject{i} = History.fromStructure(structure.ensHistObjects{i});
-                end
-                configColl = ConfigColl.fromStructure(structure.configs);
-                fitObj=FitResult(spikeObj,structure.covLabels,structure.numHist,histObjects,ensHistObject,lambda,structure.b, structure.dev, structure.stats,structure.AIC,structure.BIC,configColl,structure.XvalData,structure.XvalTime,structure.fitType);
-                fitObj.setKSStats(structure.Z,structure.U, structure.KSStats.xAxis, structure.KSStats.KSSorted, structure.KSStats.ks_stat);
-                fitObj.setInvGausStats(structure.X,rhoSig,confBoundSig);
-                fitObj.setFitResidual(M);
-            elseif(isa(structure,'cell')) %cell array of FitResult objects
-                fitObj = cell(size(structure));
-               for i=1:length(structure)
-                  fitObj{i} = FitResult.fromStructure(structure{i});
-               end
-            end
-
-        end
-
-        function structCell = CellArrayToStructure(fitResObjCell)
-           if(isa(fitResObjCell,'FitResult'))
-               structCell = fitResObjCell.toStructure;
-           elseif(isa(fitResObjCell,'cell'))
-               if(isa(fitResObjCell{1},'FitResult'))
-                   structCell = cell(size(fitResObjCell));
-                  for i=1:length(fitResObjCell)
-                     structCell{i} = fitResObjCell{i}.toStructure;
-                  end
-               end
-           end
-
-        end
-
-    end
-
-end
-
-%Helper functions
-function hText = xticklabel_rotate(XTick,rot,varargin)
-    %hText = xticklabel_rotate(XTick,rot,XTickLabel,varargin)     Rotate XTickLabel
-    %
-    % Syntax: xticklabel_rotate
-    %
-    % Input:
-    % {opt}     XTick       - vector array of XTick positions & values (numeric)
-    %                           uses current XTick values or XTickLabel cell array by
-    %                           default (if empty)
-    % {opt}     rot         - angle of rotation in degrees, 90° by default
-    % {opt}     XTickLabel  - cell array of label strings
-    % {opt}     [var]       - "Property-value" pairs passed to text generator
-    %                           ex: 'interpreter','none'
-    %                               'Color','m','Fontweight','bold'
-    %
-    % Output:   hText       - handle vector to text labels
-    %
-    % Example 1:  Rotate existing XTickLabels at their current position by 90°
-    %    xticklabel_rotate
-    %
-    % Example 2:  Rotate existing XTickLabels at their current position by 45° and change
-    % font size
-    %    xticklabel_rotate([],45,[],'Fontsize',14)
-    %
-    % Example 3:  Set the positions of the XTicks and rotate them 90°
-    %    figure;  plot([1960:2004],randn(45,1)); xlim([1960 2004]);
-    %    xticklabel_rotate([1960:2:2004]);
-    %
-    % Example 4:  Use text labels at XTick positions rotated 45° without tex interpreter
-    %    xticklabel_rotate(XTick,45,NameFields,'interpreter','none');
-    %
-    % Example 5:  Use text labels rotated 90° at current positions
-    %    xticklabel_rotate([],90,NameFields);
-    %
-    % Note : you can not re-run xticklabel_rotate on the same graph.
-    %
-    %
-
-
-    % This is a modified version of xticklabel_rotate90 by Denis Gilbert
-    % Modifications include Text labels (in the form of cell array)
-    %                       Arbitrary angle rotation
-    %                       Output of text handles
-    %                       Resizing of axes and title/xlabel/ylabel positions to maintain same overall size
-    %                           and keep text on plot
-    %                           (handles small window resizing after, but not well due to proportional placement with
-    %                           fixed font size. To fix this would require a serious resize function)
-    %                       Uses current XTick by default
-    %                       Uses current XTickLabel is different from XTick values (meaning has been already defined)
-
-    % Brian FG Katz
-    % bfgkatz@hotmail.com
-    % 23-05-03
-    % Modified 03-11-06 after user comment
-    %	Allow for exisiting XTickLabel cell array
-
-    % Other m-files required: cell2mat
-    % Subfunctions: none
-    % MAT-files required: none
-    %
-    % See also: xticklabel_rotate90, TEXT,  SET
-
-    % Based on xticklabel_rotate90
-    %   Author: Denis Gilbert, Ph.D., physical oceanography
-    %   Maurice Lamontagne Institute, Dept. of Fisheries and Oceans Canada
-    %   email: gilbertd@dfo-mpo.gc.ca  Web: http://www.qc.dfo-mpo.gc.ca/iml/
-    %   February 1998; Last revision: 24-Mar-2003
-
-    % check to see if xticklabel_rotate has already been here (no other reason for this to happen)
-    if isempty(get(gca,'XTickLabel')),
-        error('xticklabel_rotate : can not process, either xticklabel_rotate has already been run or XTickLabel field has been erased')  ;
-    end
-
-    % if no XTickLabel AND no XTick are defined use the current XTickLabel
-    %if nargin < 3 & (~exist('XTick') | isempty(XTick)),
-    if (nargin < 3 || isempty(varargin{1})) & (~exist('XTick') | isempty(XTick)),
-        xTickLabels = get(gca,'XTickLabel')  ; % use current XTickLabel
-        if ~iscell(xTickLabels)
-            % remove trailing spaces if exist (typical with auto generated XTickLabel)
-            temp1 = num2cell(xTickLabels,2)         ;
-            for loop = 1:length(temp1),
-                temp1{loop} = deblank(temp1{loop})  ;
-            end
-            xTickLabels = temp1                     ;
-        end
-    varargin = varargin(2:length(varargin));
-    end
-
-    % if no XTick is defined use the current XTick
-    if (~exist('XTick') | isempty(XTick)),
-        XTick = get(gca,'XTick')        ; % use current XTick
-    end
-
-    %Make XTick a column vector
-    XTick = XTick(:);
-
-    if ~exist('xTickLabels'),
-        % Define the xtickLabels
-        % If XtickLabel is passed as a cell array then use the text
-        if (length(varargin)>0) & (iscell(varargin{1})),
-            xTickLabels = varargin{1};
-            varargin = varargin(2:length(varargin));
-        else
-            xTickLabels = num2str(XTick);
-        end
-    end
-
-    if length(XTick) ~= length(xTickLabels),
-        error('xticklabel_rotate : must have same number of elements in "XTick" and "XTickLabel"')  ;
-    end
-
-    %Set the Xtick locations and set XTicklabel to an empty string
-    set(gca,'XTick',XTick,'XTickLabel','')
-
-    if nargin < 2,
-        rot = 90 ;
-    end
-
-    % Determine the location of the labels based on the position
-    % of the xlabel
-    hxLabel = get(gca,'XLabel');  % Handle to xlabel
-    xLabelString = get(hxLabel,'String');
-
-    % if ~isempty(xLabelString)
-    %    warning('You may need to manually reset the XLABEL vertical position')
-    % end
-
-    set(hxLabel,'Units','data');
-    xLabelPosition = get(hxLabel,'Position');
-    y = xLabelPosition(2);
-
-    %CODE below was modified following suggestions from Urs Schwarz
-    y=repmat(y,size(XTick,1),1);
-    % retrieve current axis' fontsize
-    fs = get(gca,'fontsize');
-
-    % Place the new xTickLabels by creating TEXT objects
-    hText = text(XTick, y, xTickLabels,'fontsize',fs);
-
-    % Rotate the text objects by ROT degrees
-    set(hText,'Rotation',rot,'HorizontalAlignment','right',varargin{:})
-
-    % Adjust the size of the axis to accomodate for longest label (like if they are text ones)
-    % This approach keeps the top of the graph at the same place and tries to keep xlabel at the same place
-    % This approach keeps the right side of the graph at the same place
-
-    set(get(gca,'xlabel'),'units','data')           ;
-        labxorigpos_data = get(get(gca,'xlabel'),'position')  ;
-    set(get(gca,'ylabel'),'units','data')           ;
-        labyorigpos_data = get(get(gca,'ylabel'),'position')  ;
-    set(get(gca,'title'),'units','data')           ;
-        labtorigpos_data = get(get(gca,'title'),'position')  ;
-
-    set(gca,'units','pixel')                        ;
-    set(hText,'units','pixel')                      ;
-    set(get(gca,'xlabel'),'units','pixel')          ;
-    set(get(gca,'ylabel'),'units','pixel')          ;
-
-    origpos = get(gca,'position')                   ;
-    textsizes = cell2mat(get(hText,'extent'))       ;
-    longest =  max(textsizes(:,4))                  ;
-
-    laborigext = get(get(gca,'xlabel'),'extent')    ;
-    laborigpos = get(get(gca,'xlabel'),'position')  ;
-
-
-    labyorigext = get(get(gca,'ylabel'),'extent')   ;
-    labyorigpos = get(get(gca,'ylabel'),'position') ;
-    leftlabdist = labyorigpos(1) + labyorigext(1)   ;
-
-    % assume first entry is the farthest left
-    leftpos = get(hText(1),'position')              ;
-    leftext = get(hText(1),'extent')                ;
-    leftdist = leftpos(1) + leftext(1)              ;
-    if leftdist > 0,    leftdist = 0 ; end          % only correct for off screen problems
-
-    botdist = origpos(2) + laborigpos(2)            ;
-    newpos = [origpos(1)-leftdist longest+botdist origpos(3)+leftdist origpos(4)-longest+origpos(2)-botdist]  ;
-    set(gca,'position',newpos)                      ;
-
-    % readjust position of nex labels after resize of plot
-    set(hText,'units','data')                       ;
-    for loop= 1:length(hText),
-        set(hText(loop),'position',[XTick(loop), y(loop)])  ;
-    end
-
-
-    % adjust position of xlabel and ylabel
-    laborigpos = get(get(gca,'xlabel'),'position')  ;
-    set(get(gca,'xlabel'),'position',[laborigpos(1) laborigpos(2)-longest 0])   ;
-
-    % switch to data coord and fix it all
-    set(get(gca,'ylabel'),'units','data')                   ;
-    set(get(gca,'ylabel'),'position',labyorigpos_data)      ;
-    set(get(gca,'title'),'position',labtorigpos_data)       ;
-
-    set(get(gca,'xlabel'),'units','data')                   ;
-        labxorigpos_data_new = get(get(gca,'xlabel'),'position')  ;
-    set(get(gca,'xlabel'),'position',[labxorigpos_data(1) labxorigpos_data_new(2)])   ;
-
-
-    % Reset all units to normalized to allow future resizing
-    set(get(gca,'xlabel'),'units','normalized')          ;
-    set(get(gca,'ylabel'),'units','normalized')          ;
-    set(get(gca,'title'),'units','normalized')          ;
-    set(hText,'units','normalized')                      ;
-    set(gca,'units','normalized')                        ;
-
-    if nargout < 1,
-        clear hText
-    end
-
-end
-function [uniqueLabels, indexIntoOriginal, restoreIndex] = getUniqueLabels(covLabels)
-            offset = 0;
-            for i=1:length(covLabels)
-                currLabels = covLabels{i};
-                allLabels((1:length(currLabels))+offset) = currLabels;
-                offset=length(allLabels);
-            end
-            [uniqueLabels, indexIntoOriginal, restoreIndex] = unique(allLabels);
-end
-
Input argument "spikeObj" is undefined.
-
-Error in ==> FitResult>FitResult.FitResult at 86
-            if(isnumeric(spikeObj.name))
-
\ No newline at end of file diff --git a/helpfiles/FitResult.m b/helpfiles/FitResult.m deleted file mode 100644 index 6b1aa4b6..00000000 --- a/helpfiles/FitResult.m +++ /dev/null @@ -1,1741 +0,0 @@ -classdef FitResult < handle -% FITRESULT -% stores results of a fit using the Analysis object -% The results are for a single neuron over a range of configurations -% -% methods -% FitResult Examples -% -% see also Analysis -% -% Reference page in Help browser -% doc FitResult - - -% -% nSTAT v1 Copyright (C) 2012 Masschusetts Institute of Technology -% Cajigas, I, Malik, WQ, Brown, EN -% This program is free software; you can redistribute it and/or -% modify it under the terms of the GNU General Public License as published -% by the Free Software Foundation; either version 2 of the License, or -% (at your option) any later version. -% -% This program is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -% See the GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with this program; if not, write to the Free Software Foundation, -% Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - properties - numResults %Number of results in this FitResult object - lambda %Lambda signal - numCoeffs %Number of coefficients for each fitResult - fitType %Poisson or Binomial - - b %coefficients for each fit - - dev %deviance for each fit - AIC %Akaike's Information Criterion for each fit - BIC %Baysian Information Criterion for each fit - logLL %Log Likelihood - stats %Relevant statistics for each fit - configs % the config collection for the different fits - configNames % names of the the differen fits - neuronNumber % the number of the neuron the data comes from - neuralSpikeTrain % the spike data - covLabels - uniqueCovLabels - indicesToUniqueLabels - numHist % Number of history terms (used for indexing into the regression coefficients) for each fit - histObjects % History object for self firing - ensHistObjects % History object to be applied to the neuron's neigbors to compute ensemble effect - flatMask - Z % Rescaled spike times from the Time-Rescaling theorem, exponential rate 1 - U % Transformed z's -> uniform in [0,1] - X % Transformed u's -> gaussian in [-inf, inf] - Residual %fit residual -% xAxis -% KSSorted -% ks_stat - invGausStats - KSStats %Kolmogorov Smirnov Statistics - plotParams - XvalData % cell array of raw data used for validation - XvalTime % cell array of time vectors for each element of XvalData - validation % a FitResult object with the validation data - minTime % The minTime from the spikeTrain (not necessarily the analysis) - maxTime % The maxTime for the spikeTrain (not necessarily the analysis) - end - properties (Constant,Hidden) - colors={'b','g','r','c','m','y','k'}; - end - - - methods - - function fitObj=FitResult(spikeObj,covLabels,numHist,histObjects,ensHistObj,lambda,b, dev, stats,AIC,BIC,logLL, configColl,XvalData,XvalTime,distribution) - % fitObj=FitResult(spikeObj,covLabels,numHist,histObjects,ensHistObj,lambda,b, dev, stats,AIC,BIC,configColl,XvalData,XvalTime) - % Stores the results of multiple regressions for a single neuron into a accessible structure. - % - % spikeObj: The spike train for the neuron whose results are - % being stored. - % covLabels: A 2-d cell array, the jth row has all the labels for the covariates used in the jth fit - % numHist: The number of history terms in each of the N fits. - % histObjects: The History object for each of the N fits - % ensHistObj: The History object for used to compute the ensemble history effect. - % lambda: The conditional intensity function evaluated usin the - % data. Each dimension of lambda corresponds to the a different - % GLM Fit. - % b: N-component cell array containing the GLM regression - % coefficient of each of the fits. The jth component has all - % the regression coefficients for the jth trial. - % dev: vector of Deviances for each the GLM fits. - % stats: Cell array of the stats parameters for each GLM fit; - % AIC: vector of Akaike's information criteria for each the GLM fits. - % BIC: vector of Bayes Information criteria for each the GLM fits. - % configColl: configCollection object used to generate this - % results - % XvalData: Data to be used for validation. - % XvalTime: Time vector for the data. - - if(nargin< 14) - XvalTime =[]; - end - if(nargin<13) - XvalData =[]; - end - - if(isa(spikeObj,'cell')) - for i=1:length(spikeObj) - if(isnumeric(spikeObj{i}.name)) - nNumber(i) =spikeObj{i}.name; - else - nNumber(i) = str2double(spikeObj{i}.name(~isletter(spikeObj{i}.name))); - end - minTime(i)=spikeObj{i}.minTime; - maxTime(i)=spikeObj{i}.maxTime; - end - nNumber = unique(nNumber); - minTime = unique(minTime); - maxTime = unique(maxTime); - if(length(nNumber)>1) - error('Can only have a FitResults with spike trains from a single neuron'); - end - if(length(minTime)>1 || length(maxTime)>1) - error('Spike Trains are of different lengths'); - end - - elseif(isa(spikeObj,'nspikeTrain')) - if(isnumeric(spikeObj.name)) - nNumber =spikeObj.name; - else - nNumber = str2double(spikeObj.name(~isletter(spikeObj.name))); - end - minTime=spikeObj.minTime; - maxTime=spikeObj.maxTime; - - end - - fitObj.neuronNumber = nNumber; %str2num(spikeObj.name); - fitObj.neuralSpikeTrain = spikeObj; - fitObj.minTime = minTime; - fitObj.maxTime = maxTime; - - fitObj.numResults = 0; - fitObj.configs = configColl; - fitObj.configNames = configColl.getConfigNames; - fitObj.covLabels=covLabels; - fitObj.uniqueCovLabels= getUniqueLabels(covLabels); - - fitObj.mapCovLabelsToUniqueLabels; - fitObj.numHist=numHist; - fitObj.histObjects = histObjects; - fitObj.ensHistObjects = ensHistObj; - fitObj.addParamsToFit(fitObj.neuronNumber,lambda,b, dev, stats,AIC,BIC,logLL,configColl); - fitObj.Z =[]; %rescaled spikes times - exponentially dist. - fitObj.U =[]; %rescaled spike times - uniformly dist. - fitObj.X =[]; %rescaled spike times - gaussian dist. - fitObj.Residual =[]; %fit residual for PP - fitObj.KSStats.xAxis =[]; - fitObj.KSStats.KSSorted =[]; - fitObj.KSStats.ks_stat =[]; - fitObj.invGausStats.rhoSig=[]; - fitObj.invGausStats.confBoundSig=[]; - fitObj.plotParams = []; - fitObj.XvalData = XvalData; - fitObj.XvalTime = XvalTime; - - fitObj.fitType = distribution; - - end - function fitObj = setNeuronName(fitObj,name) - fitObj.neuronNumber = name; - end - function mFitRes = mergeResults(fitObj,newFitObj) - % mFitRes = mergeResults(fitObj,newFitObj) - % mFitRes contains the results from fitObj followed by the - % results of newFitObj in a single new FitResult object - % - % newFitObj can be of class 'FitResult' or a cell array of - % 'FitResult' objects. In the latter case, the results are - % apppended in the order that they appear in each cell array. - if(isa(newFitObj,'FitResult')) -% newFitObj.neuronNumber - if(fitObj.neuronNumber ==newFitObj.neuronNumber) - spikeObj = fitObj.neuralSpikeTrain; - covLabels = fitObj.covLabels(1:fitObj.numResults); - covLabels((fitObj.numResults+1):(fitObj.numResults+newFitObj.numResults)) = newFitObj.covLabels(1:newFitObj.numResults); - numHist = fitObj.numHist(1:fitObj.numResults); - numHist((fitObj.numResults+1):(fitObj.numResults+newFitObj.numResults)) = newFitObj.numHist(1:newFitObj.numResults); - histObjects=fitObj.histObjects(1:fitObj.numResults); - histObjects((fitObj.numResults+1):(fitObj.numResults+newFitObj.numResults)) = newFitObj.histObjects(1:newFitObj.numResults); - ensHistObjects=fitObj.ensHistObjects(1:fitObj.numResults); - ensHistObjects((fitObj.numResults+1):(fitObj.numResults+newFitObj.numResults)) = newFitObj.ensHistObjects(1:newFitObj.numResults); - b=fitObj.b(1:fitObj.numResults); - b((fitObj.numResults+1):(fitObj.numResults+newFitObj.numResults)) = newFitObj.b(1:newFitObj.numResults); - dev = [fitObj.dev newFitObj.dev]; - AIC = [fitObj.AIC newFitObj.AIC]; - BIC = [fitObj.BIC newFitObj.BIC]; - logLL = [fitObj.logLL newFit.logLL]; - stats=fitObj.stats(1:fitObj.numResults); - stats((fitObj.numResults+1):(fitObj.numResults+newFitObj.numResults)) = newFitObj.stats(1:newFitObj.numResults); - lambda = fitObj.lambda.merge(newFitObj.lambda); - - for i=1:fitObj.numResults - config{i}=fitObj.configs.getConfig(i); - end - offset=fitObj.numResults; - for i=1:newFitObj.numResults - config{i+offset}=newFitObj.configs.getConfig(i); - end - configColl= ConfigColl(config); - - XvalData = [fitObj.XvalData newFitObj.XvalData]; - XvalTime = [fitObj.XvalTime newFitObj.XvalTime]; - distribution=fitObj.fitType(1:fitObj.numResults); - distribution((fitObj.numResults+1):(fitObj.numResults+newFitObj.numResults)) = newFitObj.fitType(1:newFitObj.numResults); - tempZ = zeros(length(fitObj.Z),size(newFitObj.Z,2)); - tempU = zeros(length(fitObj.U),size(newFitObj.U,2)); - tempZ(1:length(newFitObj.Z),:) = newFitObj.Z; - tempU(1:length(newFitObj.U),:) = newFitObj.U; - Z=[fitObj.Z tempZ]; - U=[fitObj.U tempU]; - [X,rhoSig,confBoundSig] = Analysis.computeInvGausTrans(Z); - - M=fitObj.Residual.merge(newFitObj.Residual); - - origLength = size(fitObj.KSStats.xAxis,1); - currLength = size(newFitObj.KSStats.xAxis,1); - - if(currLength~=origLength) - %we use this because some times the time scales - %dont match up. In particular when spikeTrain is - %segmented by steps or windows and the window sizes - %are normalized to 1. - newX = fitObj.KSStats.xAxis; - oldX = newFitObj.KSStats.xAxis; - oldY = newFitObj.KSStats.KSSorted; - y = interp1(oldX,oldY,newX(:,1),'spline','extrap'); - xAxis = [fitObj.KSStats.xAxis newX(:,1)]; - KSSorted = [fitObj.KSStats.KSSorted y]; - else - - xAxis = [fitObj.KSStats.xAxis newFitObj.KSStats.xAxis]; - KSSorted = [fitObj.KSStats.KSSorted newFitObj.KSStats.KSSorted]; - - end - ks_stat = [fitObj.KSStats.ks_stat newFitObj.KSStats.ks_stat]; - mFitRes=FitResult(spikeObj,covLabels,numHist,histObjects,ensHistObjects,lambda,b, dev, stats,AIC,BIC,logLL,configColl,XvalData,XvalTime,distribution); - mFitRes.setKSStats(Z,U, xAxis, KSSorted, ks_stat); - mFitRes.setInvGausStats(X,rhoSig,confBoundSig); - mFitRes.setFitResidual(M); - - - elseif(isa(newFitObj,'cell')) - if(isa(newFitObj{1},'FitResult')) - for i=1:length(newFitObj) - if(i==1) - mFitRes = fitObj.mergeResults(newFitObj{i}); - else - mFitRes = mFitRes.mergeResults(newFitObj{i}); - end - end - end - end - end - - end - function subsetFit = getSubsetFitResult(fitObj,subfits) - %subfits is a row vector with numbers corresponding to the - %subfits - if(and(min(subfits)>0,max(subfits)<=fitObj.numResults)) - spikeObj = fitObj.neuralSpikeTrain; - covLabels = fitObj.covLabels(subfits); - numHist = fitObj.numHist(subfits); - histObjects = fitObj.histObjects(subfits); - ensHistObj = fitObj.ensHistObjects(subfits); - lambda = fitObj.lambda.getSubSignal(subfits); - b = fitObj.b(subfits); - dev = fitObj.dev(subfits); - stats = fitObj.stats(subfits); - AIC = fitObj.AIC(subfits); - BIC = fitObj.BIC(subfits); - logLL = fitObj.logLL(subfits); - configColl = fitObj.configs.getSubsetConfigs(subfits); - XvalData = fitObj.XvalData; - XvalTime = fitObj.XvalTime; - distribution = fitObj.fitType; - - subsetFit=FitResult(spikeObj,covLabels,numHist,histObjects,ensHistObj,lambda,b, dev, stats,AIC,BIC,logLL,configColl,XvalData,XvalTime,distribution); - Z = fitObj.Z(:,subfits); - U = fitObj.U(:,subfits); - X = fitObj.X(:,subfits); - xAxis= fitObj.KSStats.xAxis(:,subfits); - KSSorted=fitObj.KSStats.KSSorted(:,subfits); - ks_stat=fitObj.KSStats.ks_stat(subfits); - rhoSig=fitObj.invGausStats.rhoSig.getSubSignal(subfits); - confBoundSig=fitObj.invGausStats.confBoundSig; - M = fitObj.Residual.getSubSignal(subfits); - - subsetFit.setKSStats(Z,U, xAxis, KSSorted, ks_stat); - subsetFit.setInvGausStats(X,rhoSig,confBoundSig); - subsetFit.setFitResidual(M); - end - end - function addParamsToFit(fitObj,neuronNum,lambda,b, dev, stats,AIC,BIC,logLL,configColl) - % addParamsToFit(fitObj,neuronNum,lambda,b, dev, stats,AIC,BIC,configColl) - % Add the specified parameters to the current FitResult object - % only if the neuronNum matches the neuronNum of this object - if(fitObj.neuronNumber==neuronNum) - if(isa(lambda,'cell')) - newLambda=lambda{1}; - for i=2:length(lambda) - newLambda = newLambda.merge(lambda{i}); - end - elseif(isa(lambda,'Covariate')||isa(lambda,'SignalObj')) - newLambda = lambda; - end - - numNewResults = newLambda.dimension;%number of new elements - if(nargin<8) - configColl = cell(1,numNewResults); - end - - if(numNewResults==1) - fitObj.b{fitObj.numResults+1} = b{1}; - - fitObj.dev(fitObj.numResults+1) = dev; - fitObj.stats{fitObj.numResults+1}= stats{1}; - if(nargin<7) - fitObj.AIC(fitObj.numResults+1) = 2*length(b)+dev; - fitObj.BIC(fitObj.numResults+1) = length(b)*log(length(newLambda.time))+dev; - delta = 1/newLambda.sampleRate; - fitObj.logLL(fitObj.numResults+1) = sum(y.*log(data*delta)+(1-y).*(1-newLambda.data*delta)); - else - fitObj.AIC(fitObj.numResults+1) = AIC; - fitObj.BIC(fitObj.numResults+1) = BIC; - fitObj.logLL(fitObj.numResults+1) = logLL; - end - - fitObj.numCoeffs(fitObj.numResults+1) = length(b); - else - for i=1:numNewResults - fitObj.b{fitObj.numResults+i} = b{i}; - - fitObj.dev(fitObj.numResults+i) = dev(i); - fitObj.stats{fitObj.numResults+i}= stats{i}; - if(nargin<7) - fitObj.AIC(fitObj.numResults+i) = 2*length(b{i})+dev(i); - fitObj.BIC(fitObj.numResults+i) = length(b{i})*log(length(newLambda.time))+dev(i); - delta=fitObj.neuralSpikeTrain.sampleRate; - y=fitObj.neuralSpikeTrain.getSigRep.dataToMatrix; - - fitObj.logLL(fitObj.numResults+i)= sum(y.*log(newLambda.data*delta)+(1-y).*(1-newLambda.data*delta)); - else - fitObj.AIC(fitObj.numResults+i) = AIC(i); - fitObj.BIC(fitObj.numResults+i) = BIC(i); - fitObj.logLL(fitObj.numResults+i)= logLL(i); - end - fitObj.numCoeffs(fitObj.numResults+i) = length(b{i}); - end - end - if(fitObj.numResults ==0) - fitObj.lambda = newLambda; - else - fitObj.lambda = fitObj.lambda.merge(newLambda); %new lambda - end - - fitObj.numResults = fitObj.numResults+numNewResults; - dataLabels = cell(1,fitObj.numResults); - for i=1:fitObj.numResults - dataLabels{i} = strcat('\lambda_{',num2str(i),'}'); - end - fitObj.lambda.setDataLabels(dataLabels); - - fitObj.configs.addConfig(configColl); - fitObj.configNames = fitObj.configs.getConfigNames; - else - error('Neuron number does not match'); - end - end - function [lambda, logLL] = computeValLambda(fitObj) - % lambda = computeValLambda(fitObj) - % Returns a Covariate object lambda. This is the Conditional - % intensity function evaluated using the validation data - lambdaData = zeros(length(fitObj.XvalTime{1}),fitObj.numResults); - for i=1:fitObj.numResults - lambdaData(:,i) = fitObj.evalLambda(i,fitObj.XvalData{i}); - end - lambda=Covariate(fitObj.XvalTime{1},lambdaData,... - '\lambda(t)',fitObj.lambda.xlabelval,... - fitObj.lambda.xunits,'Hz',fitObj.lambda.dataLabels); - delta = 1/lambda.sampleRate; - y=fitObj.neuralSpikeTrain.getSigRep.dataToMatrix; - logLL =sum(y.*log(lambda.data*delta)+(1-y).*(1-lambda.data*delta)); - end - - function mapCovLabelsToUniqueLabels(fitObj) - % mapCovLabelsToUniqueLabels(fitObj) - % Used internally by the FitResult class generate a matrix that - % maps how covariate labels of the fit object map to unique - % covariate labels. For example, multiple fits that have a - % constant baseline term will be assumed to refer to the same - % "baseline" term and not two separate ones - flatMask = zeros(length(fitObj.uniqueCovLabels),length(fitObj.covLabels)); - for j=1:length(fitObj.covLabels) - currLabels = fitObj.covLabels{j}; - index=zeros(1,length(currLabels)); - for i=1:length(currLabels) - index(i)=strmatch(currLabels{i}, fitObj.uniqueCovLabels, 'exact'); - end - - fitObj.indicesToUniqueLabels{j} = index; - flatMask(index,j) = 1; - end - fitObj.flatMask = flatMask; - end - function p=getPlotParams(fitObj) - % p=getPlotParams(fitObj) - if(isempty(fitObj.plotParams)) - fitObj.computePlotParams; - end - p=fitObj.plotParams; - end - function plotValidation(fitObj) - % plotValidation(fitObj) - % calls plotResults on the validation FitResult object if - % validation data is present. Note that the GLM coefficients - % are not recomputed and therefore the same as those obtained - % from the training data. - if(~isempty(fitObj.validation)) - fitObj.validation.plotResults; - else - display('Validation Data not available to plot'); - end - end - function answer = isValDataPresent(fitObj) - % answer = isValDataPresent(fitObj) - % returns 1 if validation data is present. This method is used - % to determine if validation data is available to compute the - % validation results. - answer = 0; - if(~isempty(fitObj.XvalTime) && ~isempty(fitObj.XvalData)) - for i=1:length(fitObj.XvalTime) - currTime = fitObj.XvalTime{i}; - if(~isempty(currTime)) - if(currTime(end)-currTime(1)>0) - answer =1; - break; - end - end - end - - end - - end - function lambdaData = evalLambda(fitObj,lambdaIndex,newData) - % lambdaData = evalLambda(fitObj,lambdaIndex,newData) - % lambdaIndex: the index of the corresponding lambda to be - % evaluated with the new data. - % newData: matrix of covariates in same order as fits without - % constant term in first column -% if(isa(newData,'double')) -% [~,columns] = size(newData); -% tempData = cell(1,columns); -% for i=1:columns -% tempData{i} = newData(:,i); -% end -% newData = tempData; -% end - - if(lambdaIndex>0 && lambdaIndex <= fitObj.numResults) - b=fitObj.b{lambdaIndex}; %coefficient matrix - if(isempty(newData)) - [rows,~] = size(newData); - baseline=ones(rows,1); - lambdaData = exp(b(1)*baseline); - else - if(isa(newData,'double')) %matrix, 1 column per coefficient - baseline=ones(length(newData),1); - [~,columns] = size(newData); - - if(length(b)>=1) - lambdaData = exp(newData*b(1:end)); - if(strcmp(fitObj.fitType{lambdaIndex},'poisson')) -% lambdaData = exp(newData*b(1:end)); -% lambdaData = exp(b(1) + newData*b(2:end)); - else -% lambdaData = exp(b(1) + newData*b(2:end)); - lambdaData = lambdaData./(1+lambdaData); - end -% else -% if(strcmp(fitObj.fitType{lambdaIndex},'poisson')) -% lambdaData = exp(b(1)*baseline); -% -% else -% lambdaData = exp(b(1)*baseline); -% lambdaData = lambdaData./(1+lambdaData); -% end - end - lambdaData = lambdaData*fitObj.neuralSpikeTrain.sampleRate; - elseif(isa(newData,'cell')) % a cell array, each element is matrix of values for each coeff -% baseline=ones(size(newData{1})); %design matrix - runSum=0; - for i=1:(length(newData)) %-fitObj.numHist(lambdaIndex)) -% if(i==1) -% runSum = b(1)*baseline; -% else - if(i<=length(b)) - runSum = runSum+b(i)*newData{i}; - end -% end - end - if(strcmp(fitObj.fitType{lambdaIndex},'poisson')) - lambdaData = exp(runSum); - lambdaData = lambdaData*fitObj.neuralSpikeTrain.sampleRate; - else - lambdaData = exp(runSum); - lambdaData = lambdaData./(1+lambdaData); - lambdaData = lambdaData*fitObj.neuralSpikeTrain.sampleRate; - end - else - error('New data must be cell or a matrix'); - end - - end - else - error('Index into fit params is incorrect'); - end - - end -% function handle = plotHist(fitObj,fitNum) -% % handle = plotHist(fitObj,fitNum) -% % plots the history terms used in this FitResult object -% % if fitNum is not specified then fitNum=1:numResults -% if(nargin<2 || isempty(fitNum)) -% fitNum = 1:fitObj.numResults; -% end -% -% for j=fitNum -% if(j>0 && j <= fitObj.numResults) -% b=fitObj.b{j}; %coefficient matrix -% startHistIndex = length(b)-fitObj.numHist(j)+1; -% if(startHistIndex=windowTimes(i),t<=windowTimes(i+1)); -% histEffect(index)=exp(-bHist(i))-1; %To offset zero coeffs -% end -% end -% else -% t=[0; 0.00001]; -% histEffect =[0;0]; -% end -% if(j==fitNum(1)) -% hSig = SignalObj(t,histEffect,'History','time','s','',fitObj.lambda.dataLabels{j}); -% else -% hSig = hSig.merge(SignalObj(t,histEffect,'History Effect','time','s','',fitObj.lambda.dataLabels{j})); -% end -% end -% end -% N=floor(length(hSig.time)./70); B=ones(1,N)/N; A=1; -% handle=hSig.filtfilt(B,A).plot; -% end - function computePlotParams(fitObj,fitNum) - if(nargin<2) - fitNum = 1:fitObj.numResults; - end - index=find(sum(fitObj.flatMask,2)>0);%1:length(fitObj.flatMask(:,1)); - %Only use the labels that appear in at least one fit - %Otherwise that parameter was not present for any of the - %regressions and just takes up plot real-estate - - sigIndex=zeros(length(index),length(fitNum)); - bAct = nan(length(index),length(fitNum)); - seAct= nan(length(index),length(fitNum)); - - for i=fitNum - %this indexing is to avoid extremely large se's from - %affecting plots - criteria = find(fitObj.stats{i}.se'<100); - %indicesForFit = find(fitObj.flatMask(index,i)==1); - indicesForFit = fitObj.indicesToUniqueLabels{i}; - bVals = fitObj.b{i}(criteria); - bAct(indicesForFit(criteria),i) = bVals; %sorted according to uniqueLabels - seVals = fitObj.stats{i}.se(criteria)'; - seAct(indicesForFit(criteria),i)= seVals; %sorted according to uniqueLabels; - temp = sign([bAct(:,i)-seAct(:,i) bAct(:,i)+seAct(:,i)]); - productOfSigns = temp(:,1).*temp(:,2); %should be positive - sIndex=and(productOfSigns>0,seAct(:,i)~=0); - sigIndex(:,i)=sIndex; - end - fitObj.plotParams.bAct = bAct; - fitObj.plotParams.seAct= seAct; - fitObj.plotParams.sigIndex = sigIndex; - fitObj.plotParams.xLabels = cell(length(index),1); - fitObj.plotParams.xLabels = fitObj.uniqueCovLabels; - -% for i=1:(length(index)) -% if(i==1) -% fitObj.plotParams.xLabels{i} = 'baseline'; -% %text(i, 0,'baseline','interpreter','latex'); -% else -% fitObj.plotParams.xLabels{i} = fitObj.covLabels{index(i)-1}; -% %text(i, 0,fitObj.covLabels{index(i)-1},'interpreter','latex'); -% end -% end - tempVal =sum(fitObj.flatMask,2); - fitObj.plotParams.numResultsCoeffPresent =tempVal(index); - end - - function [coeffIndex, epochId,numEpochs] = getCoeffIndex(fitObj,fitNum,sortByEpoch) - if(nargin<3 || isempty(sortByEpoch)) - sortByEpoch=0; - end - if(nargin<2 || isempty(fitNum)) - fitNum = 1:fitObj.numResults; - end - if(isempty(fitObj.plotParams)) - fitObj.computePlotParams; - end - [histIndex, epochId] = fitObj.getHistIndex(fitNum,sortByEpoch); - allIndex = 1:length(fitObj.uniqueCovLabels); - - nonHistIndex = setdiff(allIndex,histIndex); -% nonNANIndex = find(sum(~isnan(fitObj.plotParams.bAct(:,fitNum)),2)>=1); - nonNANIndex= allIndex; - actCoeffIndex = nonHistIndex(ismember(nonHistIndex, nonNANIndex)); - allCoeffTerms = fitObj.uniqueCovLabels(actCoeffIndex); -% coeffName = cell(size(allCoeffTerms)); - epochStartInd=regexp(allCoeffTerms,'_\{\d*\}','start'); - epochEndInd=regexp(allCoeffTerms,'_\{\d*\}','end'); - - allCoeffIndex = []; - nonEpochIndex=[]; -% nonEmptyCoeffNameInd = []; - epochsExist =0; - for i=1:length(allCoeffTerms) - if(~isempty(allCoeffTerms{i})) - allCoeffIndex = [allCoeffIndex i]; - - if(~isempty(epochStartInd{i})) -% nonEmptyCoeffNameInd = [nonEmptyCoeffNameInd i]; - epochsExist=1; - actStart = epochStartInd{i}+2; - actEnd = epochEndInd{i}-1; - numEpoch(i) = str2num(allCoeffTerms{i}(actStart:actEnd)); -% coeffName{i} = allCoeffTerms{i}(1:actStart-3); - - - else - nonEpochIndex = [nonEpochIndex i]; - numEpoch(i) = 0; % make terms that only appear once part of epoch 0. - - end - end - - end - -% coeffName = coeffName(nonEmptyCoeffNameInd); - if(epochsExist && ~sortByEpoch) - totalEpochs = unique(numEpoch); - coeffIndex = nonEpochIndex; - if(nargout>1) - epochId=zeros(size(nonEpochIndex)); - end - for i=1:length(totalEpochs) - if(totalEpochs(i)~=0) - coeffIndex = [coeffIndex, find(numEpoch==totalEpochs(i))]; - - if(nargout>1) - epochId = [epochId, totalEpochs(i)*ones(size(find(numEpoch==totalEpochs(i))))]; - end - end - end - coeffIndex = actCoeffIndex(coeffIndex); - elseif(epochsExist && sortByEpoch) - coeffIndex = actCoeffIndex(allCoeffIndex); - if(nargout>1) - epochId = numEpoch; - end - else - coeffIndex = actCoeffIndex(allCoeffIndex); - if(nargout>1) - epochId = zeros(size(allCoeffIndex)); %no epochs exist so just create same index for all; - end - end - - -% nonNANIndex = find(sum(~isnan(fitObj.plotParams.bAct(:,fitNum)),2)>=1); - nonNANIndex = allIndex; - coeffIndex = coeffIndex(ismember(coeffIndex, nonNANIndex)); - - if(nargout>2) - numEpochs = length(unique(epochId)); - end - - end - - function h=plotCoeffsWithoutHistory(fitObj,fitNum,sortByEpoch,plotSignificance) - if(nargin<4 || isempty(plotSignificance)) - plotSignificance=1; - end - if(nargin<3 || isempty(sortByEpoch)) - sortByEpoch = 0; - end - if(nargin<2 || isempty(fitNum)) - fitNum = 1:fitObj.numResults; - end - if(isempty(fitObj.plotParams)) - fitObj.computePlotParams; - end - - - coeffIndex = fitObj.getCoeffIndex(fitNum,sortByEpoch); - h=fitObj.plotCoeffs([],fitNum,[],plotSignificance,coeffIndex); - - - - end - - function [histIndex, epochId,numEpochs] = getHistIndex(fitObj,fitNum,sortByEpoch) - %if sortByEpoch==1 then we group all regression terms with the - %same name one next to each other by epoch (time interval). - %Otherwise, we show all epoch one terms, followed by all epoch - %2 terms, etc. - if(nargin<3 || isempty(sortByEpoch)) - sortByEpoch = 0; - end - if(nargin<2 || isempty(fitNum)) - fitNum = 1:fitObj.numResults; - end - if(isempty(fitObj.plotParams)) - fitObj.computePlotParams; - end - - - allHistTerms = regexp(fitObj.uniqueCovLabels,'^[\w*'); - epochStartInd=regexp(fitObj.uniqueCovLabels,'\]_\{\d*\}','start'); - epochEndInd=regexp(fitObj.uniqueCovLabels,'\]_\{\d*\}','end'); - allHistIndex = []; - epochsExist =0; - for i=1:length(allHistTerms) - if(~isempty(allHistTerms{i})) - allHistIndex = [allHistIndex i]; - if(~isempty(epochStartInd{i})) - epochsExist=1; - actStart = epochStartInd{i}+3; - actEnd = epochEndInd{i}-1; - numEpoch(i) = str2num(fitObj.uniqueCovLabels{i}(actStart:actEnd)); - end - end - - end - - if(epochsExist && ~sortByEpoch) - totalEpochs = unique(numEpoch); - histIndex = []; - if(nargout>1) - epochId=[]; - end - for i=1:length(totalEpochs) - histIndex = [histIndex, find(numEpoch==totalEpochs(i))]; - if(nargout>1) - epochId = [epochId, totalEpochs(i)*ones(size(find(numEpoch==totalEpochs(i))))]; - end - end - elseif(epochsExist && sortByEpoch) - histIndex = allHistIndex; - if(nargout>1) - epochId = numEpoch; - end - else - histIndex = allHistIndex; - if(nargout>1) - epochId = zeros(size(allHistIndex)); %no epochs exist so just create same index for all; - end - end - - -% nonNANIndex = find(sum(~isnan(fitObj.plotParams.bAct(:,fitNum)),2)>=1); -% histIndex = histIndex(ismember(histIndex, nonNANIndex)); - - if(nargout>2) - numEpochs = length(unique(epochId)); - end - - end - - function [coeffMat, labels, SEMat] = getCoeffs(fitObj, fitNum) - if(nargin<2 || isempty(fitNum)) - fitNum =1:fitObj.numResults; - end - sortByEpoch = 0; % Make sure we have different time series if the history is divided into epochs; - [coeffIndex, epochId, numEpochs] = fitObj.getCoeffIndex(fitNum,sortByEpoch); - epochNums = unique(epochId); - - - coeffStrings = fitObj.uniqueCovLabels(coeffIndex); - baseStringEndIndex =regexp(coeffStrings,'_\{\d*\}','start'); - - for i=1:length(baseStringEndIndex) - if(~isempty(baseStringEndIndex{i})) - baseStrings{i} = coeffStrings{i}(1:baseStringEndIndex{i}-1); - else - baseStrings{i} = coeffStrings{i}; - end - end - uniqueCoeffs = unique(baseStrings); - - for i=1:length(uniqueCoeffs) - coeffStrIndex{i} = coeffIndex(strcmp(baseStrings,uniqueCoeffs{i})); - if(min(epochId)==0) - epochIndices{i} = epochId(strcmp(baseStrings,uniqueCoeffs{i}))+1; - else - epochIndices{i} = epochId(strcmp(baseStrings,uniqueCoeffs{i})); - end - end - -% -% for i=1:numEpochs -% epochIndices{i} = find(epochId==epochNums(i)); -% epochLength(i) = length(epochIndices{i}); -% end - - - - coeffIndMat= nan(length(uniqueCoeffs),numEpochs); - - labels = cell(size(coeffIndMat)); - for i=1:length(uniqueCoeffs) - coeffIndMat(i,epochIndices{i}) = coeffStrIndex{i}; - labels(i,epochIndices{i}) = fitObj.uniqueCovLabels(coeffStrIndex{i}); - end - - -% for i=1:numEpochs -% coeffIndMat(1:epochLength(i),i) = coeffIndex(epochIndices{i}); -% labels(1:epochLength(i),i) = fitObj.uniqueCovLabels(coeffIndMat(1:epochLength(i),i)); -% end - - - - if(length(fitNum)>1) - coeffMat = nan(size(coeffIndMat,1),size(coeffIndMat,2), length(fitNum)); - SEMat = nan(size(coeffIndMat,1),size(coeffIndMat,2), length(fitNum)); - for i=1:length(fitNum) - for j=1:length(uniqueCoeffs) - bTemp=fitObj.plotParams.bAct(coeffStrIndex{j},i); - seTemp=fitObj.plotParams.seAct(coeffStrIndex{j},i); - coeffMat(j,epochIndices{j},i) = bTemp'; - SEMat(j,epochIndices{j},i) = seTemp'; - end - end - else - coeffMat = nan(size(coeffIndMat,1),size(coeffIndMat,2)); - SEMat = nan(size(coeffIndMat,1),size(coeffIndMat,2)); - for j=1:length(uniqueCoeffs) - bTemp=fitObj.plotParams.bAct(coeffStrIndex{j},fitNum); - seTemp = fitObj.plotParams.seAct(coeffStrIndex{j},fitNum); - coeffMat(j,epochIndices{j}) = bTemp'; - SEMat(j,epochIndices{j}) = seTemp'; - end - - end - - end - - function [histMat, labels, SEMat] = getHistCoeffs(fitObj,fitNum) - if(nargin<2 || isempty(fitNum)) - fitNum =1:fitObj.numResults; - end - sortByEpoch = 0; % Make sure we have different time series if the history is divided into epochs; - [histIndex, epochId, numEpochs] = fitObj.getHistIndex(fitNum,sortByEpoch); - epochNums = unique(epochId); - - - histcoeffStrings = fitObj.uniqueCovLabels(histIndex); - baseStringEndIndex =regexp(histcoeffStrings,'_\{\d*\}','start'); - baseStrings = cell(length(baseStringEndIndex),1); - for i=1:length(baseStringEndIndex) - if(~isempty(baseStringEndIndex{i})) - baseStrings{i} = histcoeffStrings{i}(1:baseStringEndIndex{i}-1); - else - baseStrings{i} = histcoeffStrings{i}; - end - end - uniqueCoeffs = unique(baseStrings); - - for i=1:length(uniqueCoeffs) - histcoeffStrIndex{i} = histIndex(strcmp(baseStrings,uniqueCoeffs{i})); - if(min(epochId)==0) - epochIndices{i} = epochId(strcmp(baseStrings,uniqueCoeffs{i}))+1; - else - epochIndices{i} = epochId(strcmp(baseStrings,uniqueCoeffs{i})); - end - end - -% -% for i=1:numEpochs -% epochIndices{i} = find(epochId==epochNums(i)); -% epochLength(i) = length(epochIndices{i}); -% end - - - - histcoeffIndMat= nan(length(uniqueCoeffs),numEpochs); - labels = cell(size(histcoeffIndMat)); -% SEMat = nan(length(uniqueCoeffs),numEpochs); - for i=1:length(uniqueCoeffs) - histcoeffIndMat(i,epochIndices{i}) = histcoeffStrIndex{i}; - labels(i,epochIndices{i}) = fitObj.uniqueCovLabels(histcoeffStrIndex{i}); -% SEMat(i,epochIndices{i}) = fitObj.se; - end - - -% for i=1:numEpochs -% coeffIndMat(1:epochLength(i),i) = coeffIndex(epochIndices{i}); -% labels(1:epochLength(i),i) = fitObj.uniqueCovLabels(coeffIndMat(1:epochLength(i),i)); -% end - - - - if(length(fitNum)>1) - histMat = nan(size(histcoeffIndMat,1),size(histcoeffIndMat,2), length(fitNum)); - SEMat = nan(size(histcoeffIndMat,1),size(histcoeffIndMat,2), length(fitNum)); - for i=fitNum - for j=1:length(uniqueCoeffs) - bTemp=fitObj.plotParams.bAct(histcoeffStrIndex{j},i); - seTemp = fitObj.plotParams.seAct(histcoeffStrIndex{j},i); - histMat(j,epochIndices{j},i) = bTemp'; - SEMat(j,epochIndices{j},i) = seTemp'; - end - end - else - histMat = nan(size(histcoeffIndMat,1),size(histcoeffIndMat,2)); - SEMat = nan(size(histcoeffIndMat,1),size(histcoeffIndMat,2)); - for j=1:length(uniqueCoeffs) - bTemp=fitObj.plotParams.bAct(histcoeffStrIndex{j},fitNum); - seTemp=fitObj.plotParams.seAct(histcoeffStrIndex{j},fitNum); - histMat(j,epochIndices{j}) = bTemp'; - SEMat(j,epochIndices{j}) = seTemp'; - end - - end - - -% -% if(nargin<2 || isempty(fitNum)) -% fitNum =1:fitObj.numResults; -% end -% sortByEpoch = 0; % Make sure we have different time series if the history is divided into epochs; -% [histIndex, epochId, numEpochs] = fitObj.getHistIndex(fitNum,sortByEpoch); -% epochNums = unique(epochId); -% for i=1:numEpochs -% epochIndices{i} = find(epochId==epochNums(i)); -% epochLength(i) = length(epochIndices{i}); -% end -% -% histIndMat= nan(max(epochLength),numEpochs); -% labels = cell(size(histIndMat)); -% for i=1:numEpochs -% histIndMat(1:epochLength(i),i) = histIndex(epochIndices{i}); -% labels(1:epochLength(i),i) = fitObj.uniqueCovLabels(histIndMat(1:epochLength(i),i)); -% end -% -% -% -% if(length(fitNum)>1) -% histMat = nan(size(histIndMat,1),size(histIndMat,2), length(fitNum)); -% for i=1:length(fitNum) -% for j=1:numEpochs -% bTemp=fitObj.plotParams.bAct(epochIndices{j},i); -% histMat(1:epochLength(j),j,i) = bTemp; -% end -% end -% else -% histMat = nan(size(histIndMat,1),size(histIndMat,2)); -% -% for j=1:numEpochs -% bTemp=fitObj.plotParams.bAct(epochIndices{j},fitNum); -% histMat(1:epochLength(j),j) = bTemp; -% end -% -% end - - end - function h=plotHistCoeffs(fitObj,fitNum,sortByEpoch,plotSignificance) - if(nargin<4 || isempty(plotSignificance)) - plotSignificance=1; - end - if(nargin<3 || isempty(sortByEpoch)) - sortByEpoch=0; - end - if(nargin<2 || isempty(fitNum)) - fitNum = 1:fitObj.numResults; - end - if(isempty(fitObj.plotParams)) - fitObj.computePlotParams; - end - histIndex = fitObj.getHistIndex(fitNum,sortByEpoch); - h=fitObj.plotCoeffs([],fitNum,[],plotSignificance,histIndex); - end - - - function h=plotCoeffs(fitObj,handle,fitNum,plotProps,plotSignificance,subIndex) - % h=plotCoeffs(fitObj,handle,fitNum,plotProps,plotSignificance) - % plots the GLM coefficients for each fit along with the - % confidence intervals. - % fitNum: number of the fit to plot. If not specified, all are - % plotted. - % plotProps: properties to use for the making the plot - % plotSignificance: If 1 then an asterix (*) is place above - % parameters that are statistically different - % from zero with alpha=5%. - - - if(nargin<5 || isempty(plotSignificance)) - plotSignificance = 1; - end - - if(nargin<4 || isempty(plotProps)) - plotProps = []; - end - - if(nargin<3 || isempty(fitNum)) - fitNum = 1:fitObj.numResults; - end - - if(nargin<2 || isempty(handle)) - handle=gca; - end - - if(isempty(fitObj.plotParams)) - fitObj.computePlotParams; - end - - if(nargin<6 || isempty(subIndex)) - subIndex = [fitObj.getHistIndex, fitObj.getCoeffIndex]; - end - - bAct = fitObj.getPlotParams.bAct(subIndex,fitNum); - seAct= fitObj.getPlotParams.seAct(subIndex,fitNum); - sigIndex=fitObj.getPlotParams.sigIndex(subIndex,fitNum); - - if(~isempty(plotProps)) - for i=1:length(fitNum) - h(i)=errorbar(handle,1:length(subIndex),bAct(:,i),seAct(:,i),plotProps{i}); hold on; - set(h(i), 'LineStyle', 'none', 'Marker', '.');%,... -% 'Linewidth',1,'Marker','o','MarkerSize',6); - currColor = get(h(i),'Color'); - set(h(i),'MarkerEdgeColor',currColor,'MarkerFaceColor',currColor); -% hE= get(h(i),'Children'); -% errorbarXData = get(hE(2),'XData'); -% errorbarXData(4:9:end) = errorbarXData(1:9:end) - 0.2; -% errorbarXData(7:9:end) = errorbarXData(1:9:end) - 0.2; -% errorbarXData(5:9:end) = errorbarXData(1:9:end) + 0.2; -% errorbarXData(8:9:end) = errorbarXData(1:9:end) + 0.2; -% set(hE(2), 'XData', errorbarXData); - end - else - Xaxis=repmat(1:length(bAct(:,1)),[length(bAct(1,:)) 1]); - h=errorbar(handle,Xaxis',bAct,seAct,'.');%strcat('.',FitResult.colors{mod(i-1,length(FitResult.colors))+1})); - set(h, 'LineStyle', 'none', 'Marker', '.');%,... - - for n=1:length(h) - currColor = get(h(n),'Color'); - set(h(n),'MarkerEdgeColor',currColor,'MarkerFaceColor',currColor); - - end - end - - hold on; - - - if(plotSignificance==1) - v=axis; - vdiff = .8*v(4); - - for i=1:length(fitNum) - plot(handle,find(sigIndex(:,i)==1),vdiff*ones(length(find(sigIndex(:,i)==1)),1)-i*.1,strcat('*',FitResult.colors{mod(i-1,length(FitResult.colors))+1})); hold on; - end - end - ylabel('GLM Fit Coefficients','Interpreter','none'); - xtickLabels = fitObj.getPlotParams.xLabels(subIndex); - xticks = 1:(length(xtickLabels)); - - set(handle,'xtick',xticks,'xtickLabel',xtickLabels,'FontSize',6); -% axis tight; - if(max(fitObj.numCoeffs)>=1) - xticklabel_rotate([],90,[],'Fontsize',10); - end -% hT=rotateticklabel(gca,-90); - h_legend=legend(handle,fitObj.lambda.dataLabels(fitNum),'Location','NorthEast'); - set(h_legend,'FontSize',14) - pos = get(h_legend,'position'); - set(h_legend, 'position',[pos(1)+.05 pos(2) pos(3:4)]); - -% axis tight; - title({'GLM Coefficients with 95% CIs (* p<0.05)'},'FontWeight','bold',... - 'FontSize',11,... - 'FontName','Arial'); - set(gca,'FontName', 'Arial' ); - set(gca, ... - 'TickLength' , [.02 .02] , ... - 'YGrid' , 'on' , ... - 'LineWidth' , 1 ); - hx=get(gca,'XLabel'); hy=get(gca,'YLabel'); - set([hx hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - - - end - function h=plotResults(fitObj) - % plotResults(fitObj) - % Generates KS plot, auto-correlation function of the inverse - % gaussian transformed rescaled ISIs, the sequential - % correlation coefficient between neigboring pairs of the - % rescaled ISIs (zj vs. zj-1), the GLM regression coefficients, - % and the Point Process Residual. - scrsz = get(0,'ScreenSize'); - h=figure('OuterPosition',[scrsz(3)*.01 scrsz(4)*.04 scrsz(3)*.98 scrsz(4)*.95]); - - subplot(2,4,[1 2]); fitObj.KSPlot; %make the plot - ht=text(.45, .95,strcat('Neuron:',num2str(fitObj.neuronNumber))); - set(ht,'FontName', 'Arial','FontWeight','bold','FontSize',10); - - subplot(2,4,3); fitObj.plotInvGausTrans; - subplot(2,4,4); fitObj.plotSeqCorr; - subplot(2,4,[7 8]); fitObj.plotResidual; - subplot(2,4,[5 6]); fitObj.plotCoeffs; - end - function handle = KSPlot(fitObj,fitNum) - % handle = KSPlot(fitObj) - % computes the K-S plot for each of the the candidate rate - % functions in this FitResult object. These candidate rate - % functions are numbered according to the order in which they - % were added to the FitResult. - if(nargin<2) - fitNum=1:fitObj.numResults; - end - h=gcf; - %h=[]; - figure(h); - % size(xAxis) - % size(KSSorted) - N = length(fitObj.KSStats.KSSorted); - if(~isempty(fitObj.KSStats.xAxis)) - xaxis = fitObj.KSStats.xAxis(:,1); - % Plot the CIs - plot(xaxis,xaxis, 'k-.'); hold on; - plot(xaxis, xaxis+1.36/sqrt(N), 'r','Linewidth',1); - plot(xaxis,xaxis-1.36/sqrt(N), 'r','Linewidth',1 ); - handle=plot(fitObj.KSStats.xAxis(:,fitNum),fitObj.KSStats.KSSorted(:,fitNum),'Linewidth',2); - - %set(gca,'xtick',[],'ytick',[],'ztick', []) - axis( [0 1 0 1] ); -% dataLabels = cell(1,fitObj.lambda.dimension); -% for i=1:fitObj.lambda.dimension - dataLabels = fitObj.lambda.dataLabels(fitNum); -% end - h_legend=legend(handle,dataLabels,'Location','SouthEast'); - set(h_legend,'FontSize',14) - end - hx=xlabel('Ideal Uniform CDF'); - hy=ylabel('Empirical CDF'); - title({'KS Plot of Rescaled ISIs'; 'with 95% Confidence Intervals'},'FontWeight','bold','FontSize',11,'FontName','Arial'); - set([hx, hy],'FontName', 'Arial','FontWeight','bold','FontSize',12); - - set(gca, ... - 'TickLength' , [.02 .02] , ... - 'YTick' , 0:.2:1, ... - 'XTick' , 0:.2:1, ... - 'LineWidth' , 1 ); - end - - function structure = toStructure(fitObj) - % structure = toStructure(fitObj) - % Converts FitResult object to a matlab structure than can then - % be saved. The structure is compatible with the FitResult - % static method FitResult.fromStructure(structure) that returns - % the object corresponding structure passed in. - fnames = fieldnames(fitObj); - - for i=1:length(fnames) - - currObj = fitObj.(fnames{i}); - if(strcmp(fnames{i},'histObjects')||strcmp(fnames{i},'ensHistObjects')) - for j=1:fitObj.numResults - tempObj = fitObj.(fnames{i}){j}; - if(~isempty(tempObj)) - structure.(fnames{i}){j} = tempObj.toStructure; - else - structure.(fnames{i}){j} = tempObj; - end - end - elseif(strcmp(fnames{i},'invGausStats')) - tempNames = fieldnames(fitObj.(fnames{i})); - for j=1:length(tempNames) - tempObj = currObj.(tempNames{j}); - if(~isempty(tempObj)) - structure.(fnames{i}).(tempNames{j})= tempObj.dataToStructure; - else - structure.(fnames{i}).(tempNames{j})= tempObj; - end - - end - - else - - if(isa(currObj,'double')||isa(currObj,'cell')) - structure.(fnames{i}) = currObj; - elseif(isa(currObj,'Covariate') ||isa(currObj,'ConfigColl')||isa(currObj,'nspikeTrain')) - structure.(fnames{i}) = currObj.toStructure; - elseif(isa(currObj,'SignalObj')) - structure.(fnames{i}) = currObj.dataToStructure; - elseif(isa(currObj,'struct')) - structure.(fnames{i}) = currObj; - end - end - end - - end - - - function handle = plotSeqCorr(fitObj) - % handle = plotSeqCorr(fitObj) - % plot zj+1 against zj - - %colors = {'.b','.g','.r','.c','.m','.y','.k'}; - rho=zeros(1,fitObj.numResults); - pval=zeros(1,fitObj.numResults); - dataLabels = fitObj.lambda.dataLabels; - for i=1:fitObj.numResults - handle = plot(fitObj.U(1:end-1,i),fitObj.U(2:end,i),strcat('.',Analysis.colors{mod(i-1,length(Analysis.colors))+1})); hold on; - [rhoTemp,p]= corrcoef(fitObj.U(1:end-1,i),fitObj.U(2:end,i));%handle=scatterhist(fitResults.Z(1:end-1,i),fitResults.Z(2:end,i)) - - [~,columns]=size(rhoTemp); - if(columns>1) - rho(i) = rhoTemp(1,2); - pval(i)= p(1,2); - else - rho(i) = rhoTemp; - pval(i)= p; - end - dataLabels{i} = strcat(dataLabels{i},', \rho=',num2str(rho(i),'%0.2g'),' (p=',num2str(pval(i),'%0.2g'),')'); - %get(h,'AlphaData'); - %set(h,'FaceAlpha',0.2,'EdgeAlpha',0.8,'EdgeColor',color{i}); - end - - - h_legend=legend(dataLabels,'Location','NorthEast'); - set(h_legend,'FontSize',14) - pos = get(h_legend,'position'); - if(~isempty(pos)) - set(h_legend, 'position',[pos(1)+.05 pos(2) pos(3:4)]); - end - - hy=ylabel('u_{j+1}'); hx=xlabel('u_j'); - set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - - axis([0 1 0 1]); - title({'Sequential Correlation of'; 'Rescaled ISIs'},'FontWeight','bold',... - 'FontSize',11,... - 'FontName','Arial'); - - - set(gca, ... - 'TickLength' , [.02 .02] , ... - 'YTick' , 0:.25:1, ... - 'XTick' , 0:.25:1, ... - 'LineWidth' , 1 ); - - - - end - function handle = plotInvGausTrans(fitObj) - % handle = plotInvGausTrans(fitObj) - % Plots the Auto-correlation function of the X_j's where: - % Z_j: rescaled ISI from the Time Rescaling Theorem. - % Exponential Rate 1 under true conditional intensity - % function. - % U_j: 1-exp(-Z_j). Uniform on the interval [0,1) if Z_j's - % are exponential rate 1. - % - % X_j: norminv(U_j,0,1). Gaussian mean 0, stdev 1 if U_j's are - % U([0,1)) - % - - %[rows,colm] = size(fitObj.X); - %index=find(fitObj.invGausStats.lags==1); - %lags=fitObj.invGausStats.lags; - [fitObj.X,rhoSig,confBoundSig] = Analysis.computeInvGausTrans(fitObj.Z); -% rhoSig=fitObj.invGausStats.rhoSig; - n=length(fitObj.X); -% confBoundSig = fitObj.invGausStats.confBoundSig; - handle=[]; -% for i=1:colm -% %i -% htemp=plot(lags',rho(:,i),strcat('.',FitResults.colors{mod(i-1,length(Analysis.colors))+1})); -% handle=[handle,htemp]; -% hold on; -% %labelArray{i} = ['Fit ' num2str(i)]; -% end - if(~isempty(rhoSig)) - rhoSig.plot; - end - h_legend=legend(fitObj.lambda.dataLabels,'Location','NorthEast'); - set(h_legend,'FontSize',14) - pos = get(h_legend,'position'); - if(~isempty(pos)) - set(h_legend, 'position',[pos(1)+.05 pos(2) pos(3:4)]); - end - %legend(h,labelArray); - hold on; - if(~isempty(confBoundSig)) - confBoundSig.plot; - end - title({'Autocorrelation Function';'of Rescaled ISIs'; 'with 95% CIs'},'FontWeight','bold',... - 'FontSize',11,... - 'FontName','Arial'); - hx=get(gca,'XLabel'); hy=get(gca,'YLabel'); - set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - set(gca, ... - 'TickLength' , [.02 .02] , ... - 'LineWidth' , 1 ); - v=axis; - maxY = max(abs(v(3:4)))*(1.1); %add 10% - axis([v(1:2) -maxY maxY]); - end - function handle = plotResidual(fitObj) - % handle = plotResidual(fitObj) - % Plots the Point Process Residual - handle=fitObj.Residual.plot; - legend off; - h_legend=legend(fitObj.lambda.dataLabels,'Location','NorthEast'); - set(h_legend,'FontSize',14) - pos = get(h_legend,'position'); -% set(h_legend, 'position',[.91 .41 pos(3:4)]); - set(h_legend, 'position',[pos(1)+.05 pos(2) pos(3:4)]); - title('Point Process Residual','FontWeight','bold',... - 'FontSize',11,... - 'FontName','Arial'); - xlabel('time [s]','Interpreter','none'); - hx=get(gca,'XLabel'); hy=get(gca,'YLabel'); - set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - v=axis; - maxY = max(abs(v(3:4)))*(1.1); %add 10% - axis([v(1:2) -maxY maxY]); - end - - - function setKSStats(fitObj, Z, U, xAxis, KSSorted, ks_stat) - % setKSStats(fitObj, Z, xAxis, KSSorted, ks_stat) - % Allows KS statistics to be set after object creation - % Z: Rescaled ISIs from the Time Rescaling Theorem - % xAxis: xAxis of the KS plot - % KSSorted: the sorted values of Uj=1-exp(-zj) - % ks_stat: the maximum deviation from the 45 degree line for - % all of the fits. - % - fitObj.Z =Z; - fitObj.U =U; - fitObj.KSStats.xAxis =xAxis; - fitObj.KSStats.KSSorted =KSSorted; - - - for i=1:size(xAxis,2); - [differentDists(i),pVal(i),ks_stat(i)]=kstest2(fitObj.KSStats.xAxis(:,i) ,fitObj.KSStats.KSSorted(:,i)); - end - if(~exist('differentDists')) - differentDists=1; - end - if(~exist('pVal')) - pVal=1; - end - - fitObj.KSStats.ks_stat =ks_stat; -% N = length(fitObj.KSStats.KSSorted); -% fitObj.KSStats.withinConfInt = ks_stat<1.36/sqrt(N); - fitObj.KSStats.withinConfInt = ~differentDists; - fitObj.KSStats.pValue = pVal; - end - function setInvGausStats(fitObj, X,rhoSig,confBoundSig) - % setInvGausStats(fitObj,X,rhoSig,confBoundSig) - % Sets the inverse gaussian transformed rescaled ISIs and the - % confidence bounds after the object has been created. - %fitObj.U=U; - fitObj.X=X; - fitObj.invGausStats.rhoSig=rhoSig; - fitObj.invGausStats.confBoundSig=confBoundSig; - end - function setFitResidual(fitObj,M) - % setFitResidual(fitObj,M). - % Adds the point process residual to the FitResult object - fitObj.Residual = M; - end - - function [paramVals, paramSE, paramSigIndex] = getParam(fitObj,paramNames,fitNum) - % output is a matrix of length equal to the total number of - % paramNames - % and one column for each fit - - if(nargin<3) - fitNum = 1:fitObj.numResults; - end - if(isempty(fitObj.plotParams)) - fitObj.computePlotParams; - end - paramVals = zeros(length(paramNames),length(fitNum)); - - if(nargout>1) - paramSE = zeros(length(paramNames),length(fitNum)); - end - - if(nargout>2) - paramSigIndex = zeros(length(paramNames),length(fitNum)); - end - - for i=1:length(paramNames) - paramIndex=find(strcmp(paramNames(i),fitObj.uniqueCovLabels)); - paramVals(i,:) = fitObj.plotParams.bAct(paramIndex,fitNum); - if(nargout>1) - paramSE(i,:) = fitObj.plotParams.seAct(paramIndex,fitNum); - end - if(nargout>2) - paramSigIndex(i,:) = fitObj.plotParams.sigIndex(paramIndex,fitNum); - end - end - - end - - - end - - methods (Static) - - function fitObj = fromStructure(structure) - % fitObj = fromStructure(structure) - % Returns a FitResult object from the input structure. - % This is used to be able to save and restore FitResult - if(isa(structure,'struct')) - if(isa(structure.neuralSpikeTrain,'cell')) - spikeObj = cell(1,length(structure.neuralSpikeTrain)); - for k=1:length(structure.neuralSpikeTrain) - spikeObj{k} = nspikeTrain.fromStructure(structure.neuralSpikeTrain{k}); - - end - else - spikeObj=nspikeTrain.fromStructure(structure.neuralSpikeTrain); - end - lambda=Covariate.fromStructure(structure.lambda); - rhoSig=SignalObj.signalFromStruct(structure.invGausStats.rhoSig); - confBoundSig = SignalObj.signalFromStruct(structure.invGausStats.confBoundSig); - M = Covariate.fromStructure(structure.Residual); - for i=1:structure.numResults - histObjects{i} = History.fromStructure(structure.histObjects{i}); - ensHistObject{i} = History.fromStructure(structure.ensHistObjects{i}); - end - configColl = ConfigColl.fromStructure(structure.configs); - fitObj=FitResult(spikeObj,structure.covLabels,structure.numHist,histObjects,ensHistObject,lambda,structure.b, structure.dev, structure.stats,structure.AIC,structure.BIC,configColl,structure.XvalData,structure.XvalTime,structure.fitType); - fitObj.setKSStats(structure.Z,structure.U, structure.KSStats.xAxis, structure.KSStats.KSSorted, structure.KSStats.ks_stat); - fitObj.setInvGausStats(structure.X,rhoSig,confBoundSig); - fitObj.setFitResidual(M); - fitObj.setNeuronName(structure.neuronNumber); - - elseif(isa(structure,'cell')) %cell array of FitResult objects - fitObj = cell(size(structure)); - for i=1:length(structure) - fitObj{i} = FitResult.fromStructure(structure{i}); - end - end - - end - - function structCell = CellArrayToStructure(fitResObjCell) - % structCell = CellArrayToStructure(fitResObjCell) - % For every FitResult structure in the a cell array, it calls - % FitResults.fromStructure - - if(isa(fitResObjCell,'FitResult')) - structCell = fitResObjCell.toStructure; - elseif(isa(fitResObjCell,'cell')&&~isempty(fitResObjCell)) - if(isa(fitResObjCell{1},'FitResult')) - structCell = cell(size(fitResObjCell)); - for i=1:length(fitResObjCell) - structCell{i} = fitResObjCell{i}.toStructure; - end - end - else - structCell={}; - end - - end - - end - -end - -%Helper functions -function hText = xticklabel_rotate(XTick,rot,varargin) - %hText = xticklabel_rotate(XTick,rot,XTickLabel,varargin) Rotate XTickLabel - % - % Syntax: xticklabel_rotate - % - % Input: - % {opt} XTick - vector array of XTick positions & values (numeric) - % uses current XTick values or XTickLabel cell array by - % default (if empty) - % {opt} rot - angle of rotation in degrees, 90° by default - % {opt} XTickLabel - cell array of label strings - % {opt} [var] - "Property-value" pairs passed to text generator - % ex: 'interpreter','none' - % 'Color','m','Fontweight','bold' - % - % Output: hText - handle vector to text labels - % - % Example 1: Rotate existing XTickLabels at their current position by 90° - % xticklabel_rotate - % - % Example 2: Rotate existing XTickLabels at their current position by 45° and change - % font size - % xticklabel_rotate([],45,[],'Fontsize',14) - % - % Example 3: Set the positions of the XTicks and rotate them 90° - % figure; plot([1960:2004],randn(45,1)); xlim([1960 2004]); - % xticklabel_rotate([1960:2:2004]); - % - % Example 4: Use text labels at XTick positions rotated 45° without tex interpreter - % xticklabel_rotate(XTick,45,NameFields,'interpreter','none'); - % - % Example 5: Use text labels rotated 90° at current positions - % xticklabel_rotate([],90,NameFields); - % - % Note : you can not re-run xticklabel_rotate on the same graph. - % - % - - - % This is a modified version of xticklabel_rotate90 by Denis Gilbert - % Modifications include Text labels (in the form of cell array) - % Arbitrary angle rotation - % Output of text handles - % Resizing of axes and title/xlabel/ylabel positions to maintain same overall size - % and keep text on plot - % (handles small window resizing after, but not well due to proportional placement with - % fixed font size. To fix this would require a serious resize function) - % Uses current XTick by default - % Uses current XTickLabel is different from XTick values (meaning has been already defined) - - % Brian FG Katz - % bfgkatz@hotmail.com - % 23-05-03 - % Modified 03-11-06 after user comment - % Allow for exisiting XTickLabel cell array - - % Other m-files required: cell2mat - % Subfunctions: none - % MAT-files required: none - % - % See also: xticklabel_rotate90, TEXT, SET - - % Based on xticklabel_rotate90 - % Author: Denis Gilbert, Ph.D., physical oceanography - % Maurice Lamontagne Institute, Dept. of Fisheries and Oceans Canada - % email: gilbertd@dfo-mpo.gc.ca Web: http://www.qc.dfo-mpo.gc.ca/iml/ - % February 1998; Last revision: 24-Mar-2003 - - % check to see if xticklabel_rotate has already been here (no other reason for this to happen) - if isempty(get(gca,'XTickLabel')), - error('xticklabel_rotate : can not process, either xticklabel_rotate has already been run or XTickLabel field has been erased') ; - end - - % if no XTickLabel AND no XTick are defined use the current XTickLabel - %if nargin < 3 & (~exist('XTick') | isempty(XTick)), - if (nargin < 3 || isempty(varargin{1})) && (~exist('XTick') || isempty(XTick)), - xTickLabels = get(gca,'XTickLabel') ; % use current XTickLabel - if ~iscell(xTickLabels) - % remove trailing spaces if exist (typical with auto generated XTickLabel) - temp1 = num2cell(xTickLabels,2) ; - for loop = 1:length(temp1), - temp1{loop} = deblank(temp1{loop}) ; - end - xTickLabels = temp1 ; - end - varargin = varargin(2:length(varargin)); - end - - % if no XTick is defined use the current XTick - if (~exist('XTick') | isempty(XTick)), - XTick = get(gca,'XTick') ; % use current XTick - end - - %Make XTick a column vector - XTick = XTick(:); - - if ~exist('xTickLabels'), - % Define the xtickLabels - % If XtickLabel is passed as a cell array then use the text - if (length(varargin)>0) & (iscell(varargin{1})), - xTickLabels = varargin{1}; - varargin = varargin(2:length(varargin)); - else - xTickLabels = num2str(XTick); - end - end - - if length(XTick) ~= length(xTickLabels), - error('xticklabel_rotate : must have same number of elements in "XTick" and "XTickLabel"') ; - end - - %Set the Xtick locations and set XTicklabel to an empty string - set(gca,'XTick',XTick,'XTickLabel','') - - if nargin < 2, - rot = 90 ; - end - - % Determine the location of the labels based on the position - % of the xlabel - hxLabel = get(gca,'XLabel'); % Handle to xlabel - xLabelString = get(hxLabel,'String'); - - % if ~isempty(xLabelString) - % warning('You may need to manually reset the XLABEL vertical position') - % end - - set(hxLabel,'Units','data'); - xLabelPosition = get(hxLabel,'Position'); - y = xLabelPosition(2); - - %CODE below was modified following suggestions from Urs Schwarz - y=repmat(y,size(XTick,1),1); - % retrieve current axis' fontsize - fs = get(gca,'fontsize'); - - % Place the new xTickLabels by creating TEXT objects - hText = text(XTick, y, xTickLabels,'fontsize',fs); - - % Rotate the text objects by ROT degrees - set(hText,'Rotation',rot,'HorizontalAlignment','right',varargin{:}) - - % Adjust the size of the axis to accomodate for longest label (like if they are text ones) - % This approach keeps the top of the graph at the same place and tries to keep xlabel at the same place - % This approach keeps the right side of the graph at the same place - - set(get(gca,'xlabel'),'units','data') ; - labxorigpos_data = get(get(gca,'xlabel'),'position') ; - set(get(gca,'ylabel'),'units','data') ; - labyorigpos_data = get(get(gca,'ylabel'),'position') ; - set(get(gca,'title'),'units','data') ; - labtorigpos_data = get(get(gca,'title'),'position') ; - - set(gca,'units','pixel') ; - set(hText,'units','pixel') ; - set(get(gca,'xlabel'),'units','pixel') ; - set(get(gca,'ylabel'),'units','pixel') ; - - origpos = get(gca,'position') ; - - % Modified by Iahn Cajigas - % 3/4/2011 to allow for a single - % xTickLabel to work properly - temphText = get(hText,'extent'); - if(isa(temphText,'cell')) - textsizes = cell2mat(temphText) ; - else - textsizes = temphText; - end - - longest = max(textsizes(:,4)) ; - - laborigext = get(get(gca,'xlabel'),'extent') ; - laborigpos = get(get(gca,'xlabel'),'position') ; - - - labyorigext = get(get(gca,'ylabel'),'extent') ; - labyorigpos = get(get(gca,'ylabel'),'position') ; - leftlabdist = labyorigpos(1) + labyorigext(1) ; - - % assume first entry is the farthest left - leftpos = get(hText(1),'position') ; - leftext = get(hText(1),'extent') ; - leftdist = leftpos(1) + leftext(1) ; - if leftdist > 0, leftdist = 0 ; end % only correct for off screen problems - - botdist = origpos(2) + laborigpos(2) ; - newpos = [origpos(1)-leftdist longest+botdist origpos(3)+leftdist origpos(4)-longest+origpos(2)-botdist] ; - set(gca,'position',newpos) ; - - % readjust position of nex labels after resize of plot - set(hText,'units','data') ; - for loop= 1:length(hText), - set(hText(loop),'position',[XTick(loop), y(loop)]) ; - end - - - % adjust position of xlabel and ylabel - laborigpos = get(get(gca,'xlabel'),'position') ; - set(get(gca,'xlabel'),'position',[laborigpos(1) laborigpos(2)-longest 0]) ; - - % switch to data coord and fix it all - set(get(gca,'ylabel'),'units','data') ; - set(get(gca,'ylabel'),'position',labyorigpos_data) ; - set(get(gca,'title'),'position',labtorigpos_data) ; - - set(get(gca,'xlabel'),'units','data') ; - labxorigpos_data_new = get(get(gca,'xlabel'),'position') ; - set(get(gca,'xlabel'),'position',[labxorigpos_data(1) labxorigpos_data_new(2)]) ; - - - % Reset all units to normalized to allow future resizing - set(get(gca,'xlabel'),'units','normalized') ; - set(get(gca,'ylabel'),'units','normalized') ; - set(get(gca,'title'),'units','normalized') ; - set(hText,'units','normalized') ; - set(gca,'units','normalized') ; - - if nargout < 1, - clear hText - end - -end -function [uniqueLabels, indexIntoOriginal, restoreIndex] = getUniqueLabels(covLabels) -% Given a set of covLabels, returns a subset of labels that are unique - offset = 0; - for i=1:length(covLabels) - currLabels = covLabels{i}; - allLabels((1:length(currLabels))+offset) = currLabels; - offset=length(allLabels); - end - [uniqueLabels, indexIntoOriginal, restoreIndex] = unique(allLabels); -end - - - \ No newline at end of file diff --git a/helpfiles/FitResultExamples.html b/helpfiles/FitResultExamples.html deleted file mode 100644 index 4b9728b9..00000000 --- a/helpfiles/FitResultExamples.html +++ /dev/null @@ -1,85 +0,0 @@ - - - - - - - - FitResult Examples - - - - -
-

FitResult Examples

- -
- - - \ No newline at end of file diff --git a/helpfiles/FitResultExamples.m b/helpfiles/FitResultExamples.m deleted file mode 100644 index 5b4ca64c..00000000 --- a/helpfiles/FitResultExamples.m +++ /dev/null @@ -1 +0,0 @@ -%% FitResult Examples diff --git a/helpfiles/HippocampalPlaceCellExample.asv b/helpfiles/HippocampalPlaceCellExample.asv deleted file mode 100644 index b8bae1d4..00000000 --- a/helpfiles/HippocampalPlaceCellExample.asv +++ /dev/null @@ -1,293 +0,0 @@ -%% HIPPOCAMPAL PLACE CELL - RECEPTIVE FIELD ESTIMATION -% Estimation of receptive fields of neurons is a very common data analysis problem in neuroscience. -% Here we use the nSTAT software to perform an estimation of the receptive fields of hippocampal -% place cells using a bivariate Gaussian model and Zernike polynomials. The number of zernike polynomials -% is based on "An Analysis of Hippocampal Spatio-Temporal Representations Using a Bayesian Algorithm for Neural -% Spike Train Decoding" Barbieri et. al 2005. The data used herein in was -% provided by Dr. Ricardo Barbieri on 2/28/2011. -% -% *Author*: Iahn Cajigas -% -% *Date*: 3/1/2011 -%% -close all - -%% Example Data -% The x and y coordinates of a freely foraging rat in a circular environment (70cm in diameter and 30cm high walls) and a fixed visual cue. -% The x and y coordinates at the time when a spike was observed are marked -% in red. The position coordinates have been normalized to be between -1 -% and 1 to allow to simplify the analysis. - load(strcat('PlaceCellDataAnimal1.mat')); - exampleCell = 25; - figure(1); - plot(x,y,'b',neuron{exampleCell}.xN,neuron{exampleCell}.yN,'r.'); - xlabel('x'); ylabel('y'); - title(['Animal#1, Cell#' num2str(exampleCell)]); - - %% Analyze All Cells - numAnimals =2; -for n=1:numAnimals - % load the data - clear x y neuron time nst tc tcc z; - load(strcat('PlaceCellDataAnimal',num2str(n),'.mat')); - - % Create the spikeTrains for each cell - for i=1:length(neuron) - nst{i} = nspikeTrain(neuron{i}.spikeTimes); - end - - - % 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 - cnt=0; - for l=0:3 - for m=-l:l - if(~any(mod(l-m,2))) % otherwise the polynomial = 0 - cnt = cnt+1; - z(:,cnt) = zernfun(l,m,r,theta,'norm'); - % zernfun by Paul Fricker - % http://www.mathworks.com/matlabcentral/fileexchange/7687 - end - end - end - - % Data sampled at 30 Hz but just to be sure - delta=min(diff(time)); - sampleRate = round(1/delta); - - % Define Covariates for the analysis - baseline = Covariate(time,ones(length(x),1),'Baseline','time','s','',... - {'mu'}); - 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'); - tcc = ConfigColl(tc); - - % Perform Analysis (Commented to since data already saved) -% results =Analysis.RunAnalysisForAllNeurons(trial,tcc,0); - - % Save results -% resStruct =FitResult.CellArrayToStructure(results); -% filename = ['PlaceCellAnimal' num2str(n) 'Results']; -% save(filename,'resStruct'); -end - -%% View Summary Statistics -% Note the Zernike Polynomials yield better fits in terms of decreased KS -% Statistics (less deviation from the 45 degree line), reduced AIC and -% reduced BIC across the majority of cells and for both animals -for n=1:numAnimals - resData=load(strcat('PlaceCellAnimal',num2str(n),'Results.mat')); - results = FitResult.fromStructure(resData.resStruct); - Summary = FitResSummary(results); - Summary.plotSummary; -end - -%% Visualize the results - -% Define a grid -[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 -idx = r_new<=1; -zpoly = cell(1,10); -cnt=0; -for l=0:3 - for m=-l:l - if(~any(mod(l-m,2))) - cnt = cnt+1; - temp = nan(size(x_new)); - temp(idx) = zernfun(l,m,r_new(idx),theta_new(idx),'norm'); - zpoly{cnt} = temp; - end - end -end - - - -for n=1:numAnimals - - clear lambdaGaussian lambdaZernike; - load(strcat('PlaceCellDataAnimal',num2str(n),'.mat')); - resData=load(strcat('PlaceCellAnimal',num2str(n),'Results.mat')); - results = FitResult.fromStructure(resData.resStruct); - - for i=1:length(neuron) - % 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); - end - - - - - % Plot the receptive fields - for i=1:length(neuron) - % 3d plot of an example place field - - - % 2d plot of all the cell's fields - if(n==1) - h4=figure(4); - if(i==1) - annotation(h4,'textbox',... - [0.343261904761904 0.928571428571418 ... - 0.392857142857143 0.0595238095238095],... - 'String',{['Gaussian Place Fields - Animal#' ... - num2str(n)]},'FitBoxToText','on'); hold on; - end - subplot(7,7,i); - elseif(n==2) - h6=figure(6); - if(i==1) - annotation(h6,'textbox',... - [0.343261904761904 0.928571428571418 ... - 0.392857142857143 0.0595238095238095],... - 'String',{['Gaussian Place Fields - Animal#' ... - num2str(n)]},'FitBoxToText','on'); hold on; - end - subplot(6,7,i); - end - pcolor(x_new,y_new,lambdaGaussian{i}), shading interp - axis square; set(gca,'xtick',[],'ytick',[]); - - - if(n==1) - h5=figure(5); - if(i==1) - annotation(h5,'textbox',... - [0.343261904761904 0.928571428571418 ... - 0.392857142857143 0.0595238095238095],... - 'String',{['Zernike Place Fields - Animal#' ... - num2str(n)]},'FitBoxToText','on'); hold on; - - end - subplot(7,7,i); - elseif(n==2) - h7=figure(7); - if(i==1) - annotation(h7,'textbox',... - [0.343261904761904 0.928571428571418 ... - 0.392857142857143 0.0595238095238095],... - 'String',{['Zernike Place Fields - Animal#' ... - num2str(n)]},'FitBoxToText','on'); hold on; - end - subplot(6,7,i); - end - pcolor(x_new,y_new,lambdaZernike{i}), shading interp - axis square; - set(gca,'xtick',[],'ytick',[]); - end - - - - -end - - - - clear lambdaGaussian lambdaZernike; - load(strcat('PlaceCellDataAnimal1.mat')); - resData=load(strcat('PlaceCellAnimal1Results.mat')); - results = FitResult.fromStructure(resData.resStruct); - - for i=1:length(neuron) - % 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); - end - - - - exampleCell = 25; - figure(8); - plot(x,y,'b',neuron{exampleCell}.xN,neuron{exampleCell}.yN,'r.'); - xlabel('x'); ylabel('y'); - title(['Animal#1, Cell#' num2str(exampleCell)]); - - figure(9); - h_mesh = mesh(x_new,y_new,lambdaGaussian{exampleCell},'AlphaData',0); - get(h_mesh,'AlphaData'); - set(h_mesh,'FaceAlpha',0.2,'EdgeAlpha',0.2,'EdgeColor','b'); - hold on; - h_mesh = mesh(x_new,y_new,lambdaZernike{exampleCell},'AlphaData',0); - get(h_mesh,'AlphaData'); - set(h_mesh,'FaceAlpha',0.2,'EdgeAlpha',0.2,'EdgeColor','g'); - - legend(results{exampleCell}.lambda.dataLabels); - plot(x,y,neuron{exampleCell}.xN,neuron{exampleCell}.yN,'r.'); - axis tight square; - xlabel('x position'); ylabel('y position'); - title(['Animal#1, Cell#' num2str(exampleCell)]); - %% - - - -% clear x y neuron time nst tc tcc z lambdaCIF; -% n=1; -% load(strcat('PlaceCellDataAnimal',num2str(n),'.mat')); -% -% % Create the spikeTrains for each cell -% for i=1:length(neuron) -% nst{i} = nspikeTrain(neuron{i}.spikeTimes); -% end -% -% -% spikeColl = nstColl(nst); -% spikeColl.resample(1/delta); -% dN = spikeColl.dataToMatrix; -% -% for i=1:length(results) -% -% lambdaCIF{i} = CIF(results{i}.b{1}',{'1','x','y','x^2','y^2','x*y'},{'x','y'},'binomial'); -% -% end -% -% figure; -% % for i=1:length(lambda) -% % lambda{i}.plot; -% % end -% -% -% index1=1000; -% dN2 = dN(1:index1,:); -% vx=var(x(2:index1)-x(1:index1-1)); -% vy=var(y(2:index1)-y(1:index1-1)); -% Q=[vx 0;0 vy]*10; -% Px0=.1*eye(2,2); A=1*eye(2,2); -% [x_p, Pe_p, x_u, Pe_u] = CIF.PPDecodeFilter(A, Q, Px0, dN2',lambdaCIF); -% figure; -% plot(x_p(1,1:end-1),x_p(2,1:end-1),'b',x(1:index1),y(1:index1),'k') - - - diff --git a/helpfiles/HippocampalPlaceCellExample.html b/helpfiles/HippocampalPlaceCellExample.html deleted file mode 100644 index ab1f4ff7..00000000 --- a/helpfiles/HippocampalPlaceCellExample.html +++ /dev/null @@ -1,550 +0,0 @@ - - - - - HIPPOCAMPAL PLACE CELL - RECEPTIVE FIELD ESTIMATION

HIPPOCAMPAL PLACE CELL - RECEPTIVE FIELD ESTIMATION

Estimation of receptive fields of neurons is a very common data analysis problem in neuroscience. Here we use the nSTAT software to perform an estimation of the receptive fields of hippocampal place cells using a bivariate Gaussian model and Zernike polynomials. The number of zernike polynomials is based on "An Analysis of Hippocampal Spatio-Temporal Representations Using a Bayesian Algorithm for Neural Spike Train Decoding" Barbieri et. al 2005. The data used herein in was provided by Dr. Ricardo Barbieri on 2/28/2011.

Author: Iahn Cajigas

Date: 3/1/2011

Contents

close all
-

Example Data

The x and y coordinates of a freely foraging rat in a circular environment (70cm in diameter and 30cm high walls) and a fixed visual cue. The x and y coordinates at the time when a spike was observed are marked in red. The position coordinates have been normalized to be between -1 and 1 to allow to simplify the analysis.

    load(strcat('PlaceCellDataAnimal1.mat'));
-    exampleCell = 25;
-    figure(1);
-    plot(x,y,'b',neuron{exampleCell}.xN,neuron{exampleCell}.yN,'r.');
-    xlabel('x'); ylabel('y');
-    title(['Animal#1, Cell#' num2str(exampleCell)]);
-

Analyze All Cells

 numAnimals =2;
-for n=1:numAnimals
-    % load the data
-    clear x y neuron time nst tc tcc z;
-    load(strcat('PlaceCellDataAnimal',num2str(n),'.mat'));
-
-    % Create the spikeTrains for each cell
-    for i=1:length(neuron)
-        nst{i} = nspikeTrain(neuron{i}.spikeTimes);
-    end
-
-
-    % 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
-    cnt=0;
-    for l=0:3
-       for m=-l:l
-           if(~any(mod(l-m,2))) % otherwise the polynomial = 0
-            cnt = cnt+1;
-            z(:,cnt) = zernfun(l,m,r,theta,'norm');
-            % zernfun by Paul Fricker
-            % http://www.mathworks.com/matlabcentral/fileexchange/7687
-           end
-       end
-    end
-
-    % Data sampled at 30 Hz but just to be sure
-    delta=min(diff(time));
-    sampleRate = round(1/delta);
-
-    % Define Covariates for the analysis
-    baseline = Covariate(time,ones(length(x),1),'Baseline','time','s','',...
-                        {'mu'});
-    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');
-    tcc = ConfigColl(tc);
-
-    % Perform Analysis (Commented to since data already saved)
-%     results =Analysis.RunAnalysisForAllNeurons(trial,tcc,0);
-
-    % Save results
-%     resStruct =FitResult.CellArrayToStructure(results);
-%     filename = ['PlaceCellAnimal' num2str(n) 'Results'];
-%     save(filename,'resStruct');
-end
-

View Summary Statistics

Note the Zernike Polynomials yield better fits in terms of decreased KS Statistics (less deviation from the 45 degree line), reduced AIC and reduced BIC across the majority of cells and for both animals

for n=1:numAnimals
-    resData=load(strcat('PlaceCellAnimal',num2str(n),'Results.mat'));
-    results = FitResult.fromStructure(resData.resStruct);
-    Summary = FitResSummary(results);
-    Summary.plotSummary;
-end
-

Visualize the results

% Define a grid
-[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
-idx = r_new<=1;
-zpoly = cell(1,10);
-cnt=0;
-for l=0:3
-   for m=-l:l
-       if(~any(mod(l-m,2)))
-        cnt = cnt+1;
-        temp = nan(size(x_new));
-        temp(idx) = zernfun(l,m,r_new(idx),theta_new(idx),'norm');
-        zpoly{cnt} = temp;
-       end
-   end
-end
-
-
-
-for n=1:numAnimals
-
-    clear lambdaGaussian lambdaZernike;
-    load(strcat('PlaceCellDataAnimal',num2str(n),'.mat'));
-    resData=load(strcat('PlaceCellAnimal',num2str(n),'Results.mat'));
-    results = FitResult.fromStructure(resData.resStruct);
-
-    for i=1:length(neuron)
-        % 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);
-    end
-
-
-
-
-    % Plot the receptive fields
-    for i=1:length(neuron)
-        % 3d plot of an example place field
-
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            if(i==1)
-                annotation(h4,'textbox',...
-                    [0.343261904761904 0.928571428571418 ...
-                    0.392857142857143 0.0595238095238095],...
-                    'String',{['Gaussian Place Fields - Animal#' ...
-                    num2str(n)]},'FitBoxToText','on'); hold on;
-            end
-            subplot(7,7,i);
-        elseif(n==2)
-            h6=figure(6);
-            if(i==1)
-                annotation(h6,'textbox',...
-                    [0.343261904761904 0.928571428571418 ...
-                    0.392857142857143 0.0595238095238095],...
-                    'String',{['Gaussian Place Fields - Animal#' ...
-                    num2str(n)]},'FitBoxToText','on'); hold on;
-            end
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-
-
-        if(n==1)
-            h5=figure(5);
-            if(i==1)
-                annotation(h5,'textbox',...
-                    [0.343261904761904 0.928571428571418 ...
-                    0.392857142857143 0.0595238095238095],...
-                    'String',{['Zernike Place Fields - Animal#' ...
-                    num2str(n)]},'FitBoxToText','on'); hold on;
-
-            end
-            subplot(7,7,i);
-        elseif(n==2)
-            h7=figure(7);
-            if(i==1)
-               annotation(h7,'textbox',...
-                    [0.343261904761904 0.928571428571418 ...
-                    0.392857142857143 0.0595238095238095],...
-                    'String',{['Zernike Place Fields - Animal#' ...
-                    num2str(n)]},'FitBoxToText','on'); hold on;
-            end
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square;
-        set(gca,'xtick',[],'ytick',[]);
-    end
-
-
-
-
-end
-
-
-
-    clear lambdaGaussian lambdaZernike;
-    load(strcat('PlaceCellDataAnimal1.mat'));
-    resData=load(strcat('PlaceCellAnimal1Results.mat'));
-    results = FitResult.fromStructure(resData.resStruct);
-
-    for i=1:length(neuron)
-        % 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);
-    end
-
-
-
-    exampleCell = 25;
-    figure(8);
-    plot(x,y,'b',neuron{exampleCell}.xN,neuron{exampleCell}.yN,'r.');
-    xlabel('x'); ylabel('y');
-    title(['Animal#1, Cell#' num2str(exampleCell)]);
-
-    figure(9);
-    h_mesh = mesh(x_new,y_new,lambdaGaussian{exampleCell},'AlphaData',0);
-    get(h_mesh,'AlphaData');
-    set(h_mesh,'FaceAlpha',0.2,'EdgeAlpha',0.2,'EdgeColor','b');
-    hold on;
-    h_mesh = mesh(x_new,y_new,lambdaZernike{exampleCell},'AlphaData',0);
-    get(h_mesh,'AlphaData');
-    set(h_mesh,'FaceAlpha',0.2,'EdgeAlpha',0.2,'EdgeColor','g');
-
-    legend(results{exampleCell}.lambda.dataLabels);
-    plot(x,y,neuron{exampleCell}.xN,neuron{exampleCell}.yN,'r.');
-    axis tight square;
-    xlabel('x position'); ylabel('y position');
-    title(['Animal#1, Cell#' num2str(exampleCell)]);
-
\ No newline at end of file diff --git a/helpfiles/HippocampalPlaceCellExample.m b/helpfiles/HippocampalPlaceCellExample.m deleted file mode 100644 index 91fd04a9..00000000 --- a/helpfiles/HippocampalPlaceCellExample.m +++ /dev/null @@ -1,255 +0,0 @@ -%% HIPPOCAMPAL PLACE CELL - RECEPTIVE FIELD ESTIMATION -% Estimation of receptive fields of neurons is a very common data analysis problem in neuroscience. -% Here we use the nSTAT software to perform an estimation of the receptive fields of hippocampal -% place cells using a bivariate Gaussian model and Zernike polynomials. The number of zernike polynomials -% is based on "An Analysis of Hippocampal Spatio-Temporal Representations Using a Bayesian Algorithm for Neural -% Spike Train Decoding" Barbieri et. al 2005. The data used herein in was -% provided by Dr. Ricardo Barbieri on 2/28/2011. -% -% *Author*: Iahn Cajigas -% -% *Date*: 3/1/2011 -%% -close all - -%% Example Data -% The x and y coordinates of a freely foraging rat in a circular environment (70cm in diameter and 30cm high walls) and a fixed visual cue. -% The x and y coordinates at the time when a spike was observed are marked -% in red. The position coordinates have been normalized to be between -1 -% and 1 to allow to simplify the analysis. - load(strcat('PlaceCellDataAnimal1.mat')); - exampleCell = 25; - figure(1); - plot(x,y,'b',neuron{exampleCell}.xN,neuron{exampleCell}.yN,'r.'); - xlabel('x'); ylabel('y'); - title(['Animal#1, Cell#' num2str(exampleCell)]); - - %% Analyze All Cells - numAnimals =2; -for n=1:numAnimals - % load the data - clear x y neuron time nst tc tcc z; - load(strcat('PlaceCellDataAnimal',num2str(n),'.mat')); - - % Create the spikeTrains for each cell - for i=1:length(neuron) - nst{i} = nspikeTrain(neuron{i}.spikeTimes); - end - - - % 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 - cnt=0; - for l=0:3 - for m=-l:l - if(~any(mod(l-m,2))) % otherwise the polynomial = 0 - cnt = cnt+1; - z(:,cnt) = zernfun(l,m,r,theta,'norm'); - % zernfun by Paul Fricker - % http://www.mathworks.com/matlabcentral/fileexchange/7687 - end - end - end - - % Data sampled at 30 Hz but just to be sure - delta=min(diff(time)); - sampleRate = round(1/delta); - - % Define Covariates for the analysis - baseline = Covariate(time,ones(length(x),1),'Baseline','time','s','',... - {'mu'}); - 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'); - tcc = ConfigColl(tc); - - % Perform Analysis (Commented to since data already saved) -% results =Analysis.RunAnalysisForAllNeurons(trial,tcc,0); - - % Save results -% resStruct =FitResult.CellArrayToStructure(results); -% filename = ['PlaceCellAnimal' num2str(n) 'Results']; -% save(filename,'resStruct'); -end - -%% View Summary Statistics -% Note the Zernike Polynomials yield better fits in terms of decreased KS -% Statistics (less deviation from the 45 degree line), reduced AIC and -% reduced BIC across the majority of cells and for both animals -for n=1:numAnimals - resData=load(strcat('PlaceCellAnimal',num2str(n),'Results.mat')); - results = FitResult.fromStructure(resData.resStruct); - Summary = FitResSummary(results); - Summary.plotSummary; -end - -%% Visualize the results - -% Define a grid -[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 -idx = r_new<=1; -zpoly = cell(1,10); -cnt=0; -for l=0:3 - for m=-l:l - if(~any(mod(l-m,2))) - cnt = cnt+1; - temp = nan(size(x_new)); - temp(idx) = zernfun(l,m,r_new(idx),theta_new(idx),'norm'); - zpoly{cnt} = temp; - end - end -end - - - -for n=1:numAnimals - - clear lambdaGaussian lambdaZernike; - load(strcat('PlaceCellDataAnimal',num2str(n),'.mat')); - resData=load(strcat('PlaceCellAnimal',num2str(n),'Results.mat')); - results = FitResult.fromStructure(resData.resStruct); - - for i=1:length(neuron) - % 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); - end - - - - - % Plot the receptive fields - for i=1:length(neuron) - % 3d plot of an example place field - - - % 2d plot of all the cell's fields - if(n==1) - h4=figure(4); - if(i==1) - annotation(h4,'textbox',... - [0.343261904761904 0.928571428571418 ... - 0.392857142857143 0.0595238095238095],... - 'String',{['Gaussian Place Fields - Animal#' ... - num2str(n)]},'FitBoxToText','on'); hold on; - end - subplot(7,7,i); - elseif(n==2) - h6=figure(6); - if(i==1) - annotation(h6,'textbox',... - [0.343261904761904 0.928571428571418 ... - 0.392857142857143 0.0595238095238095],... - 'String',{['Gaussian Place Fields - Animal#' ... - num2str(n)]},'FitBoxToText','on'); hold on; - end - subplot(6,7,i); - end - pcolor(x_new,y_new,lambdaGaussian{i}), shading interp - axis square; set(gca,'xtick',[],'ytick',[]); - - - if(n==1) - h5=figure(5); - if(i==1) - annotation(h5,'textbox',... - [0.343261904761904 0.928571428571418 ... - 0.392857142857143 0.0595238095238095],... - 'String',{['Zernike Place Fields - Animal#' ... - num2str(n)]},'FitBoxToText','on'); hold on; - - end - subplot(7,7,i); - elseif(n==2) - h7=figure(7); - if(i==1) - annotation(h7,'textbox',... - [0.343261904761904 0.928571428571418 ... - 0.392857142857143 0.0595238095238095],... - 'String',{['Zernike Place Fields - Animal#' ... - num2str(n)]},'FitBoxToText','on'); hold on; - end - subplot(6,7,i); - end - pcolor(x_new,y_new,lambdaZernike{i}), shading interp - axis square; - set(gca,'xtick',[],'ytick',[]); - end - - - - -end - - - - clear lambdaGaussian lambdaZernike; - load(strcat('PlaceCellDataAnimal1.mat')); - resData=load(strcat('PlaceCellAnimal1Results.mat')); - results = FitResult.fromStructure(resData.resStruct); - - for i=1:length(neuron) - % 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); - end - - - - exampleCell = 25; - figure(8); - plot(x,y,'b',neuron{exampleCell}.xN,neuron{exampleCell}.yN,'r.'); - xlabel('x'); ylabel('y'); - title(['Animal#1, Cell#' num2str(exampleCell)]); - - figure(9); - h_mesh = mesh(x_new,y_new,lambdaGaussian{exampleCell},'AlphaData',0); - get(h_mesh,'AlphaData'); - set(h_mesh,'FaceAlpha',0.2,'EdgeAlpha',0.2,'EdgeColor','b'); - hold on; - h_mesh = mesh(x_new,y_new,lambdaZernike{exampleCell},'AlphaData',0); - get(h_mesh,'AlphaData'); - set(h_mesh,'FaceAlpha',0.2,'EdgeAlpha',0.2,'EdgeColor','g'); - - legend(results{exampleCell}.lambda.dataLabels); - plot(x,y,neuron{exampleCell}.xN,neuron{exampleCell}.yN,'r.'); - axis tight square; - xlabel('x position'); ylabel('y position'); - title(['Animal#1, Cell#' num2str(exampleCell)]); - - - - diff --git a/helpfiles/HippocampalPlaceCellExample.png b/helpfiles/HippocampalPlaceCellExample.png deleted file mode 100644 index 9294edd6..00000000 Binary files a/helpfiles/HippocampalPlaceCellExample.png and /dev/null differ diff --git a/helpfiles/HippocampalPlaceCellExample_01.png b/helpfiles/HippocampalPlaceCellExample_01.png deleted file mode 100644 index 0039f3c7..00000000 Binary files a/helpfiles/HippocampalPlaceCellExample_01.png and /dev/null differ diff --git a/helpfiles/HippocampalPlaceCellExample_02.png b/helpfiles/HippocampalPlaceCellExample_02.png deleted file mode 100644 index c487eeb2..00000000 Binary files a/helpfiles/HippocampalPlaceCellExample_02.png and /dev/null differ diff --git a/helpfiles/HippocampalPlaceCellExample_03.png b/helpfiles/HippocampalPlaceCellExample_03.png deleted file mode 100644 index 85946da4..00000000 Binary files a/helpfiles/HippocampalPlaceCellExample_03.png and /dev/null differ diff --git a/helpfiles/HippocampalPlaceCellExample_04.png b/helpfiles/HippocampalPlaceCellExample_04.png deleted file mode 100644 index 85409dbc..00000000 Binary files a/helpfiles/HippocampalPlaceCellExample_04.png and /dev/null differ diff --git a/helpfiles/HippocampalPlaceCellExample_05.png b/helpfiles/HippocampalPlaceCellExample_05.png deleted file mode 100644 index cd48a6e8..00000000 Binary files a/helpfiles/HippocampalPlaceCellExample_05.png and /dev/null differ diff --git a/helpfiles/HippocampalPlaceCellExample_06.png b/helpfiles/HippocampalPlaceCellExample_06.png deleted file mode 100644 index 8aff8d24..00000000 Binary files a/helpfiles/HippocampalPlaceCellExample_06.png and /dev/null differ diff --git a/helpfiles/HippocampalPlaceCellExample_07.png b/helpfiles/HippocampalPlaceCellExample_07.png deleted file mode 100644 index e21f25aa..00000000 Binary files a/helpfiles/HippocampalPlaceCellExample_07.png and /dev/null differ diff --git a/helpfiles/HippocampalPlaceCellExample_08.png b/helpfiles/HippocampalPlaceCellExample_08.png deleted file mode 100644 index b9d7a7a1..00000000 Binary files a/helpfiles/HippocampalPlaceCellExample_08.png and /dev/null differ diff --git a/helpfiles/HippocampalPlaceCellExample_09.png b/helpfiles/HippocampalPlaceCellExample_09.png deleted file mode 100644 index 7a8f0756..00000000 Binary files a/helpfiles/HippocampalPlaceCellExample_09.png and /dev/null differ diff --git a/helpfiles/HistoryExamples.asv b/helpfiles/HistoryExamples.asv deleted file mode 100644 index 502e368d..00000000 --- a/helpfiles/HistoryExamples.asv +++ /dev/null @@ -1,41 +0,0 @@ -%% Test History -% Generete a nspikeTrain and define a set of history windows of interest. -% We desire windows from 1-2ms, 2-3ms, 3-5ms, and 5ms-10ms. -% The history object with this windows in created below and then the -% - -spikeTimes = sort(rand(1,100))*1; -nst = nspikeTrain(spikeTimes,'n1',.001); -windowTimes = [.001 .002 .003 .005 .01]; -h=History(windowTimes); - -%% -% The firing activity within each window is computed by calling the -% computeHistory method on a nspikeTrain, nstColl, or a cell array of -% nspikeTrains - -histn1=h.computeHistory(nst); -figure; subplot(3,1,1); h.plot; ylabel('History Windows'); -subplot(3,1,2); histn1.plot; ylabel('History Covariate for nst'); -figure; nst.plot; ylabel('Neural Spike Train'); - - -%% Example 2: History covariates for a collection of Neural Spikes (nstColl) -% It is possible to compute history covariates for all the nspikeTrains in -% a nstColl simultaneously. - -%% -% Generate data and create a nstColl -clear nst; -for i=1:7 - spikeTimes = sort(rand(1,100))*1; - nst{i}=nspikeTrain(spikeTimes,'',.001); - %nst{i}.setName(strcat('Neuron',num2str(i))); -end -spikeColl=nstColl(nst); -%% -% generate a CovColl (collection of covariates) by applying the computing -% the history of the entire nstColl - -histColl = h.computeHistory(spikeColl); -figure; histColl.plot; diff --git a/helpfiles/HistoryExamples.html b/helpfiles/HistoryExamples.html deleted file mode 100644 index c765d875..00000000 --- a/helpfiles/HistoryExamples.html +++ /dev/null @@ -1,136 +0,0 @@ - - - - - HistoryExamples

Contents

Test History

Generete a nspikeTrain and define a set of history windows of interest. We desire windows from 1-2ms, 2-3ms, 3-5ms, and 5ms-10ms. The history object with this windows in created below and then the

spikeTimes = sort(rand(1,100))*1;
-nst        = nspikeTrain(spikeTimes,'n1',.001);
-windowTimes = [.001 .002 .004];
-h=History(windowTimes);
-

/

The firing activity within each window is computed by calling the computeHistory method on a nspikeTrain, nstColl, or a cell array of nspikeTrains

histn1=h.computeHistory(nst);
-figure; subplot(3,1,1); h.plot; ylabel('History Windows');
-subplot(3,1,2); histn1.plot;    ylabel('History Covariate for nst');
-figure; nst.plot;               ylabel('Neural Spike Train');
-

Example 2: History covariates for a collection of Neural Spikes (nstColl)

It is possible to compute history covariates for all the nspikeTrains in a nstColl simultaneously.

Generate data and create a nstColl

clear nst;
-for i=1:1
-    spikeTimes = sort(rand(1,100))*1;
-    nst{i}=nspikeTrain(spikeTimes,'',.001);
-    %nst{i}.setName(strcat('Neuron',num2str(i)));
-end
-spikeColl=nstColl(nst);
-
-windowTimes = [.001 .002 .01];
-h=History(windowTimes);
-

generate a CovColl (collection of covariates) by applying the computing the history of the entire nstColl

histColl = h.computeHistory(spikeColl);
-figure; histColl.plot;
-
\ No newline at end of file diff --git a/helpfiles/HistoryExamples.m b/helpfiles/HistoryExamples.m deleted file mode 100644 index 1426c797..00000000 --- a/helpfiles/HistoryExamples.m +++ /dev/null @@ -1,44 +0,0 @@ -%% Test History -% Generete a nspikeTrain and define a set of history windows of interest. -% We desire windows from 1-2ms, 2-3ms, 3-5ms, and 5ms-10ms. -% The history object with this windows in created below and then the -% - -spikeTimes = sort(rand(1,100))*1; -nst = nspikeTrain(spikeTimes,'n1',.001); -windowTimes = [.001 .002 .004]; -h=History(windowTimes); - -%% / -% The firing activity within each window is computed by calling the -% computeHistory method on a nspikeTrain, nstColl, or a cell array of -% nspikeTrains - -histn1=h.computeHistory(nst); -figure; subplot(3,1,1); h.plot; ylabel('History Windows'); -subplot(3,1,2); histn1.plot; ylabel('History Covariate for nst'); -figure; nst.plot; ylabel('Neural Spike Train'); - - -%% Example 2: History covariates for a collection of Neural Spikes (nstColl) -% It is possible to compute history covariates for all the nspikeTrains in -% a nstColl simultaneously. - -%% -% Generate data and create a nstColl -clear nst; -for i=1:1 - spikeTimes = sort(rand(1,100))*1; - nst{i}=nspikeTrain(spikeTimes,'',.001); - %nst{i}.setName(strcat('Neuron',num2str(i))); -end -spikeColl=nstColl(nst); - -windowTimes = [.001 .002 .01]; -h=History(windowTimes); -%% -% generate a CovColl (collection of covariates) by applying the computing -% the history of the entire nstColl - -histColl = h.computeHistory(spikeColl); -figure; histColl.plot; diff --git a/helpfiles/HistoryExamples.png b/helpfiles/HistoryExamples.png deleted file mode 100644 index 0b01958e..00000000 Binary files a/helpfiles/HistoryExamples.png and /dev/null differ diff --git a/helpfiles/HistoryExamples_01.png b/helpfiles/HistoryExamples_01.png deleted file mode 100644 index bcd3d8fc..00000000 Binary files a/helpfiles/HistoryExamples_01.png and /dev/null differ diff --git a/helpfiles/HistoryExamples_02.png b/helpfiles/HistoryExamples_02.png deleted file mode 100644 index 5b185b7e..00000000 Binary files a/helpfiles/HistoryExamples_02.png and /dev/null differ diff --git a/helpfiles/HistoryExamples_03.png b/helpfiles/HistoryExamples_03.png deleted file mode 100644 index 1d19ebfc..00000000 Binary files a/helpfiles/HistoryExamples_03.png and /dev/null differ diff --git a/helpfiles/HybridFilterExample.asv b/helpfiles/HybridFilterExample.asv deleted file mode 100644 index de24b66e..00000000 --- a/helpfiles/HybridFilterExample.asv +++ /dev/null @@ -1,186 +0,0 @@ -%% Hybrid Point Process Filter Example -% This example is based on an implementation of the Hybrid Point Process -% filter described in _General-purpose filter design for neural prosthetic devices_ -% by Srinivasan L, Eden UT, Mitter SK, Brown EN in J Neurophysiol. 2007 Oct, 98(4):2456-75. -% - -%% Problem Statement -% Suppose that a process of interest can be modeled as consisting of -% several discrete states where the evolution of the system under each -% state can be modeled as a linear state space model. The observations of -% both the state and the continuous dynamics are not direct, but rather -% observed through how the continuous and discrete states affect the firing -% of a population of neurons. The goal of the hybrid filter is to estimate -% both the continuous dynamics and the underlying system state from only -% the neural population firing (point process observations). -% -% To illustrate the use of this filter, we consider a reaching task. We -% assume two underlying system states s=1="Not Moving"=NM and s=2="Moving"=M. -% Under the "Not Moving" the position of the arm remain constant, -% whereas in the "Moving" state, the position and velocities evolved based -% on the arm acceleration that is modeled as a gaussian white noise -% process. -% -% Under both the "Moving" and "Not Moving" states, the arm evolution state -% vector is -%% -% -% $${\bf{x}} = {[x,y,{v_x},{v_y},{a_x},{a_y}]^T}$$ -% - -%% Generated Simulated Arm Reach - -clear all; -close all; -delta=0.001; -Tmax=2; -time=0:delta:Tmax; -A{2} = [1 0 delta 0 delta^2/2 0; - 0 1 0 delta 0 delta^2/2; - 0 0 1 0 delta 0; - 0 0 0 1 0 delta; - 0 0 0 0 1 0; - 0 0 0 0 0 1]; - -A{1} = [1 0 0 0 0 0; - 0 1 0 0 0 0; - 0 0 0 0 0 0; - 0 0 0 0 0 0; - 0 0 0 0 0 0; - 0 0 0 0 0 0]; -Px0{2} =.1*eye(6,6); -Px0{1} =.1*eye(6,6); -minCovVal = 1e-7; -Q{2}=[minCovVal 0 0 0 0 0; - 0 minCovVal 0 0 0 0; - 0 0 minCovVal 0 0 0; - 0 0 0 minCovVal 0 0; - 0 0 0 0 1 0; - 0 0 0 0 0 1]; -Q{1}=minCovVal*eye(6,6); - - - -mstate = zeros(1,length(time)); -ind{1}=1:6; -ind{2}=1:6; - -% Acceleration model -X=zeros(size(A{1},1),length(time)); -p_ij = [.998 .002; .002 .998]; -for i = 1:length(time) - - if(i==1) - mstate(i) = 1+(rand(1,1)>.5); - else - if(rand(1,1)1)=1; %Avoid more than 1 spike per bin. - -% Starting states are equally probable -Mu0=.5*ones(size(p_ij,1),1); - -% Run the Hybrid Point Process Filter -[S_est, X_est, W_est, MU_est, X_s, W_s,pNGivenS]=CIF.PPHybridFilter(A, Q, p_ij,Mu0,Px0, dN',lambdaCIF,delta); - -%% Plot the results -% close all; -figure; subplot(2,2,1);plot(time,mstate,'k',time,S_est,'r-.'); axis tight; v=axis; axis([v(1) v(2) 0 3]); - set(gca,'xtick',[],'YTick',[1 2],'YTickLabel',{'NM','M'}); - ylabel('state'); l=legend('$s(t)$','$\hat{s}(t)$','Location','Best'); - set(l, 'Interpreter', 'latex'); - - subplot(2,2,3);plot(time,X_est(1:2,:)','-.'); hold on;plot(time,X(1:2,1:end-1)'); axis tight; - xlabel('time [s]'); ylabel('[m]');l=legend('$\hat{x}(t)$','$\hat{y}(t)$','x(t)','y(t)','Location','Best'); - set(l, 'Interpreter', 'latex') - - subplot(2,2,[2 4]); h1=plot(X_est(1,:)',X_est(2,:)','r-.',X(1,1:end-1)',X(2,1:end-1)','k'); hold on; - xlabel('X [m]'); ylabel('Y [m]'); plot(X(1,1),X(2,1),'ro','MarkerSize',10); plot(X(1,end),X(2,end),'bo','MarkerSize',10); - legend(h1,'Estimate','Actual','Location','Best'); - - -figure; -subplot(2,1,1);plot(time,mstate,'k',time,S_est,'r-.'); -title('Estimated vs. Actual State and State Probabilities'); -axis tight; v=axis; axis([v(1) v(2) 0 3]); -set(gca,'xtick',[],'YTick',[1 2],'YTickLabel',{'NM','M'}); -ylabel('state'); -l=legend('$s(t)$','$\hat{s}(t)$','Location','Best'); -set(l, 'Interpreter', 'latex'); - - -subplot(2,1,2); plot(time,MU_est); axis tight; -xlabel('time'); ylabel('P(s(t)=i | data)'); -legend('P(s(t)=1 | data)','P(s(t)=2 | data)','Location','Best'); - diff --git a/helpfiles/HybridFilterExample.html b/helpfiles/HybridFilterExample.html deleted file mode 100644 index 53d0e9cb..00000000 --- a/helpfiles/HybridFilterExample.html +++ /dev/null @@ -1,871 +0,0 @@ - - - - - Hybrid Point Process Filter Example

Hybrid Point Process Filter Example

This example is based on an implementation of the Hybrid Point Process filter described in General-purpose filter design for neural prosthetic devices by Srinivasan L, Eden UT, Mitter SK, Brown EN in J Neurophysiol. 2007 Oct, 98(4):2456-75.

Contents

Problem Statement

Suppose that a process of interest can be modeled as consisting of several discrete states where the evolution of the system under each state can be modeled as a linear state space model. The observations of both the state and the continuous dynamics are not direct, but rather observed through how the continuous and discrete states affect the firing of a population of neurons. The goal of the hybrid filter is to estimate both the continuous dynamics and the underlying system state from only the neural population firing (point process observations).

To illustrate the use of this filter, we consider a reaching task. We assume two underlying system states s=1="Not Moving"=NM and s=2="Moving"=M. Under the "Not Moving" the position of the arm remain constant, whereas in the "Moving" state, the position and velocities evolved based on the arm acceleration that is modeled as a gaussian white noise process.

Under both the "Moving" and "Not Moving" states, the arm evolution state vector is

$${\bf{x}} = {[x,y,{v_x},{v_y},{a_x},{a_y}]^T}$$

Generated Simulated Arm Reach

clear all;
-close all;
-delta=0.001;
-Tmax=2;
-time=0:delta:Tmax;
-A{2} = [1 0 delta 0     delta^2/2   0;
-        0 1 0     delta 0           delta^2/2;
-        0 0 1     0     delta       0;
-        0 0 0     1     0           delta;
-        0 0 0     0     1           0;
-        0 0 0     0     0           1];
-
-A{1} = [1 0 0 0 0 0;
-        0 1 0 0 0 0;
-        0 0 0 0 0 0;
-        0 0 0 0 0 0;
-        0 0 0 0 0 0;
-        0 0 0 0 0 0];
-A{1} = [1 0;
-        0 1];
-
-Px0{2} =1e-6*eye(6,6);
-Px0{1} =1e-6*eye(2,2);
-
-minCovVal = 1e-12;
-covVal = 1e-3;
-
-
-
-Q{2}=[minCovVal     0   0     0   0       0;
-      0       minCovVal 0     0   0       0;
-      0       0   minCovVal   0   0       0;
-      0       0   0     minCovVal 0       0;
-      0       0   0     0   covVal      0;
-      0       0   0     0   0       covVal];
-
-Q{1}=minCovVal*eye(2,2);
-
-mstate = zeros(1,length(time));
-ind{1}=1:2;
-ind{2}=1:6;
-
-% Acceleration model
-X=zeros(max([size(A{1},1),size(A{2},1)]),length(time));
-p_ij = [.998 .002;
-        .001 .999];
-
-for i = 1:length(time)
-
-    if(i==1)
-        mstate(i) = 1;
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       else
-           if(mstate(i-1)==1)
-               mstate(i) = 2;
-           else
-               mstate(i) = 1;
-           end
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-
%save paperHybridFilterExample time Tmax delta mstate X p_ij ind A Q Px0
-load paperHybridFilterExample;
-Q{1}=minCovVal*eye(2,2);
-numCells=40;
-close all;
-scrsz = get(0,'ScreenSize');
-fig1=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 ...
-    scrsz(3)*.8 scrsz(4)*.9]);
-subplot(4,2,[1 3]);
-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');
-hold on;
-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');
-
-
-
-subplot(4,2,[6 8]);
-plot(time,mstate,'k','Linewidth',2); axis tight; v=axis;
-axis([v(1) v(2) 0 3]);
-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,...
-    'FontName','Arial');
-
-subplot(4,2,5);
-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)]);
-
-
-subplot(4,2,7);
-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) ...
-    0*randn(numCells,2)];
-%Add realization by thinning with history
-dataMat = [ones(size(X,2),1),X(:,1:end)'];
-% Generate M1 cells
-clear lambda tempSpikeColl lambdaCIF n;
-fitType ='binomial';
-% matlabpool open;
- for i=1:numCells
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     else
-        lambdaData = tempData;
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));
- end
- spikeColl = nstColl(n);
- subplot(4,2,[2 4]);
-spikeColl.plot;
-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');
-
-% close all;
-

Simulate Neural Firing

We simulate a population of neurons that fire in response to the movement velocity (x and y coorinates)

%Use the data to estimate the process noise for the moving case and
-%non-moving case
-
-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));
-Q{2}(1:4,1:4)=0;
-varNV=diag(var(diff(X(:,nonMovingInd),[],2),[],2));
-Q{1} = varNV(1:2,1:2);
-close all; clear S_est X_est MU_est S_estNT X_estNT MU_estNT;
-numExamples = 20;
-numCells=40;
-scrsz = get(0,'ScreenSize');
-fig1=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 ...
-    scrsz(3)*.9 scrsz(4)*.9]);
-
-for n=1:numExamples
-    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) ...
-        0*randn(numCells,2)];
-
-
-
-    %Add realization by thinning with history
-    dataMat = [ones(size(X,2),1),X(:,1:end)'];
-    % Generate M1 cells
-    clear lambda tempSpikeColl lambdaCIF nst;
-    fitType ='binomial';
-    % matlabpool open;
-     for i=1:numCells
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'));
-            lambdaData = tempData./(1+tempData);
-         else
-            lambdaData = tempData;
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));
-     end
-
-    % 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;
-    x0{1} = X(ind{1},1);
-    yT{1} = X(ind{1},end);
-    Pi0    = Px0;
-    PiT{1} = 1e-9*eye(size(x0{1},1),size(x0{1},1));
-
-    x0{2} = X(ind{2},1);
-    yT{2} = X(ind{2},end);
-    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);
-
-    %Store the results for computing relevant statistics later
-    X_estAll(:,:,n) = X_est;
-    X_estNTAll(:,:,n) = X_estNT;
-    S_estAll(n,:)=S_est;
-    S_estNTAll(n,:)=S_estNT;
-    MU_estAll(:,:,n)=MU_est;
-    MU_estNTAll(:,:,n) = MU_estNT;
-
-
-    %State Estimate
-    subplot(4,3,[1 4]);
-    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))
-    subplot(4,3,[7 10]);
-    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]);
-
-    %The movement path
-    subplot(4,3,[2 3 5 6]);
-    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-.');
-
-    %X-Position
-    subplot(4,3,8);
-    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-.');
-
-    %Y-Position
-    subplot(4,3,9);
-    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-.');
-
-    %X-Velocity
-    subplot(4,3,11);
-    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-.');
-
-    subplot(4,3,12);
-    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-.');
-
-
-
-
-end
-
-%
-%     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
-    subplot(4,3,[1 4]);
-    hold all;
-    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',...
-        'Interpreter','none');
-    title('Estimated vs. Actual State','FontWeight','bold','Fontsize',...
-        12,'FontName','Arial');
-
-
-
-
-   % Mean State Movement State Probability
-    subplot(4,3,[7 10]);
-    plot(time, mean(squeeze(MU_estAll(2,:,:)),2),'b','LineWidth',3);
-    hold on;
-    plot(time,mean(squeeze(MU_estNTAll(2,:,:)),2),'g','LineWidth',3);
-    hold on;
-    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,...
-        'FontName','Arial');
-
-    % Mean movement path
-    subplot(4,3,[2 3 5 6]);
-    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');
-
-
-    % Mean X-Positon
-    subplot(4,3,8);
-    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');
-
-    % Mean Y-Position
-    subplot(4,3,9);
-    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)]);
-
-    % Mean X-Velocity
-    subplot(4,3,11);
-    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');
-
-    % Mean Y-Velocity
-    subplot(4,3,12);
-    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');
-
\ No newline at end of file diff --git a/helpfiles/HybridFilterExample.m b/helpfiles/HybridFilterExample.m deleted file mode 100644 index 720b1785..00000000 --- a/helpfiles/HybridFilterExample.m +++ /dev/null @@ -1,419 +0,0 @@ -%% Hybrid Point Process Filter Example -% This example is based on an implementation of the Hybrid Point Process -% filter described in _General-purpose filter design for neural prosthetic -% devices_ by Srinivasan L, Eden UT, Mitter SK, Brown EN in J Neurophysiol. -% 2007 Oct, 98(4):2456-75. -% - -%% Problem Statement -% Suppose that a process of interest can be modeled as consisting of -% several discrete states where the evolution of the system under each -% state can be modeled as a linear state space model. The observations of -% both the state and the continuous dynamics are not direct, but rather -% observed through how the continuous and discrete states affect the firing -% of a population of neurons. The goal of the hybrid filter is to estimate -% both the continuous dynamics and the underlying system state from only -% the neural population firing (point process observations). -% -% To illustrate the use of this filter, we consider a reaching task. We -% assume two underlying system states s=1="Not Moving"=NM and s=2="Moving"=M. -% Under the "Not Moving" the position of the arm remain constant, -% whereas in the "Moving" state, the position and velocities evolved based -% on the arm acceleration that is modeled as a gaussian white noise -% process. -% -% Under both the "Moving" and "Not Moving" states, the arm evolution state -% vector is -%% -% -% $${\bf{x}} = {[x,y,{v_x},{v_y},{a_x},{a_y}]^T}$$ -% - -%% Generated Simulated Arm Reach - -clear all; -close all; -delta=0.001; -Tmax=2; -time=0:delta:Tmax; -A{2} = [1 0 delta 0 delta^2/2 0; - 0 1 0 delta 0 delta^2/2; - 0 0 1 0 delta 0; - 0 0 0 1 0 delta; - 0 0 0 0 1 0; - 0 0 0 0 0 1]; - -A{1} = [1 0 0 0 0 0; - 0 1 0 0 0 0; - 0 0 0 0 0 0; - 0 0 0 0 0 0; - 0 0 0 0 0 0; - 0 0 0 0 0 0]; -A{1} = [1 0; - 0 1]; - -Px0{2} =1e-6*eye(6,6); -Px0{1} =1e-6*eye(2,2); - -minCovVal = 1e-12; -covVal = 1e-3; - - - -Q{2}=[minCovVal 0 0 0 0 0; - 0 minCovVal 0 0 0 0; - 0 0 minCovVal 0 0 0; - 0 0 0 minCovVal 0 0; - 0 0 0 0 covVal 0; - 0 0 0 0 0 covVal]; - -Q{1}=minCovVal*eye(2,2); - -mstate = zeros(1,length(time)); -ind{1}=1:2; -ind{2}=1:6; - -% Acceleration model -X=zeros(max([size(A{1},1),size(A{2},1)]),length(time)); -p_ij = [.998 .002; - .001 .999]; - -for i = 1:length(time) - - if(i==1) - mstate(i) = 1; - else - if(rand(1,1)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; - x0{1} = X(ind{1},1); - yT{1} = X(ind{1},end); - Pi0 = Px0; - PiT{1} = 1e-9*eye(size(x0{1},1),size(x0{1},1)); - - x0{2} = X(ind{2},1); - yT{2} = X(ind{2},end); - 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); - - %Store the results for computing relevant statistics later - X_estAll(:,:,n) = X_est; - X_estNTAll(:,:,n) = X_estNT; - S_estAll(n,:)=S_est; - S_estNTAll(n,:)=S_estNT; - MU_estAll(:,:,n)=MU_est; - MU_estNTAll(:,:,n) = MU_estNT; - - - %State Estimate - subplot(4,3,[1 4]); - 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)) - subplot(4,3,[7 10]); - 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]); - - %The movement path - subplot(4,3,[2 3 5 6]); - 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-.'); - - %X-Position - subplot(4,3,8); - 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-.'); - - %Y-Position - subplot(4,3,9); - 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-.'); - - %X-Velocity - subplot(4,3,11); - 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-.'); - - subplot(4,3,12); - 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-.'); - - - - -end - -% -% 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 - subplot(4,3,[1 4]); - hold all; - 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',... - 'Interpreter','none'); - title('Estimated vs. Actual State','FontWeight','bold','Fontsize',... - 12,'FontName','Arial'); - - - - - % Mean State Movement State Probability - subplot(4,3,[7 10]); - plot(time, mean(squeeze(MU_estAll(2,:,:)),2),'b','LineWidth',3); - hold on; - plot(time,mean(squeeze(MU_estNTAll(2,:,:)),2),'g','LineWidth',3); - hold on; - 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,... - 'FontName','Arial'); - - % Mean movement path - subplot(4,3,[2 3 5 6]); - 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'); - - - % Mean X-Positon - subplot(4,3,8); - 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'); - - % Mean Y-Position - subplot(4,3,9); - 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)]); - - % Mean X-Velocity - subplot(4,3,11); - 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'); - - % Mean Y-Velocity - subplot(4,3,12); - 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'); diff --git a/helpfiles/HybridFilterExample.png b/helpfiles/HybridFilterExample.png deleted file mode 100644 index b536aaf6..00000000 Binary files a/helpfiles/HybridFilterExample.png and /dev/null differ diff --git a/helpfiles/HybridFilterExample_01.png b/helpfiles/HybridFilterExample_01.png deleted file mode 100644 index c4301cae..00000000 Binary files a/helpfiles/HybridFilterExample_01.png and /dev/null differ diff --git a/helpfiles/HybridFilterExample_02.png b/helpfiles/HybridFilterExample_02.png deleted file mode 100644 index 3e1faab9..00000000 Binary files a/helpfiles/HybridFilterExample_02.png and /dev/null differ diff --git a/helpfiles/HybridFilterExample_eq06211.png b/helpfiles/HybridFilterExample_eq06211.png deleted file mode 100644 index e33450a1..00000000 Binary files a/helpfiles/HybridFilterExample_eq06211.png and /dev/null differ diff --git a/helpfiles/Logo.png b/helpfiles/Logo.png deleted file mode 100644 index a828e7c4..00000000 Binary files a/helpfiles/Logo.png and /dev/null differ diff --git a/helpfiles/LogoSmall.png b/helpfiles/LogoSmall.png deleted file mode 100644 index 95aeeadc..00000000 Binary files a/helpfiles/LogoSmall.png and /dev/null differ diff --git a/helpfiles/NetworkTutorial.html b/helpfiles/NetworkTutorial.html deleted file mode 100644 index 519893b2..00000000 --- a/helpfiles/NetworkTutorial.html +++ /dev/null @@ -1,437 +0,0 @@ - - - - - NetworkTutorial

Contents

% Author: Iahn Cajigas
-% Date: 2/10/2014
-

Point Process Network Simulation

In order to understand how the point process GLM framework can be used to estimate the network connectivity within a population of neurons, we simulate a network of 2 neurons.

This block diagram specifies a conditional intensity function of the form

$$lambda_{i} \cdot \Delta = logistic(\mu_{i} + H*\Delta N_{i}[n] +
S*u_{stim}[n] + E*\Delta N_{k}[n]$$

where, $\hbox{\fontsize{14}{16}\selectfont\(logistic(x)=e^{x}/{1+e^{x}}\)}$. Note that * is the convolution opertator.

2 Neuron Network

clear all;
-close all;
-Ts=.001;            %Sample Time
-tMin=0; tMax=50;    %Simulation duration
-t=tMin:Ts:tMax;
-numNeurons=2;
-

Baseline firing rate of the neurons being modeled

mu{1}=-3;
-mu{2}=-3;
-

History Effect

Captures how the firing of a neuron at modulates its probability of firing. Captures effects such as the refractory period and bursting. We use the same firing history for both neurons in this example. Note that the firing activity at time n leads to strong inhibition at time n+1 (refractory period) and that this effect becomes smaller over the next two time periods.

$$1*h[n]=-4*\Delta N[n-1]-2*\Delta N[n-2] -1*\Delta N[n-3]$$

Note that the one sample delay in same cell firing is included in the simulink model.

H{1}=tf([-4 -2 -1],[1],Ts,'Variable','z^-1');
-H{2}=tf([-4 -2 -1],[1],Ts,'Variable','z^-1');
-

Stimulus Effect

$$1*s_{1}[n]=1*u_{stim}[n]$$

$$1*s_{2}[n]=-1*u_{stim}[n]$$

Neuron 1 is positively modulated by the stimulus

S{1}=tf([1],1,Ts,'Variable','z^-1');
-% Neuron 1 is negatively modulated by the stimulus
-S{2}=tf([-1],1,Ts,'Variable','z^-1');
-

Ensemble Effect

Captures the effect of how neighboring neuron firing modulates the firing of a given neuron.

$$1*e_{1}[n]=1*\Delta N_{2}[n-1]$$

$$1*e_{2}[n]=-4*\Delta N_{1}[n-1]$$

Note that the one sample delay in firing of the neighbor cell is included in the simulink model.

%Neuron 2 firing positively modulates Neuron 1
-E{1}=tf([1],1,Ts,'Variable','z^-1');
-%Neuron 1 firing has strong inhibitory effect on neuron 2.
-E{2}=tf([-4],1,Ts,'Variable','z^-1');
-

Stimulus

We use a simple sine wave here but we may want to explore other types of inputs to see if they affect the recovery of the network parameters.

f=1;                      %Stimulus frequency [Hz]
-u = sin(2*pi*f*t)';       %Make this neuron modulated by a sine wave
-stim=Covariate(t',u,'Stimulus','time','s','Voltage',{'sin'});
-
-
-% Map the variables to the Simulink model
-assignin('base','S1',S{1});
-assignin('base','H1',H{1});
-assignin('base','E1',E{1});
-assignin('base','mu1',mu{1});
-assignin('base','S2',S{2});
-assignin('base','H2',H{2});
-assignin('base','E2',E{2});
-assignin('base','mu2',mu{2});
-options = simget;
-

Simulate the Network

Uses a binomial model for the conditional intensity function nSTAT supports poisson model too but this simulink model simulates the firing using a binomial model

fitType = 'binomial';
-if(strcmp(fitType,'binomial'))
-    Algorithm = 'BNLRCG';
-else
-    Algorithm ='GLM';
-end
-[tout,~,yout] = sim('SimulatedNetwork2',[stim.minTime stim.maxTime], ...
-    options,stim.dataToStructure);
-clear nst;
-
-  for i=1:numNeurons
-    spikeTimes = tout(yout(:,i)>.5); %find the spike times
-    nst{i} = nspikeTrain(spikeTimes);
-  end
-
-
-sC=nstColl(nst);
-sC.setMinTime(stim.minTime);
-sC.setMaxTime(stim.maxTime);
-
-
-
-figure;
-subplot(2,1,1); sC.plot;    v=axis; axis([0 tMax/10 v(3) v(4)]);
-subplot(2,1,2); stim.plot;  v=axis; axis([0 tMax/10 v(3) v(4)]);
-
Warning: The model 'SimulatedNetwork2' has the 'Configuration Parameters' >
-'Data Import/Export' > 'Signal logging format' parameter set to 'ModelDataLogs'.
-The signal logging save format 'ModelDataLogs' will be removed in a future
-release.  To take advantage of new functionality, update models that use
-'ModelDataLogs' signal logging format to use the 'Dataset' format.  For help
-with resolving this and other upgrade issues, use the Simulink Upgrade Advisor. 
-

GLM Model Fitting Setup

In this section, we create the appropriate structures to fit several GLM models to the data generated above.

% Create a constant covariate representing the mean firing rate $$\mu_{i}$
-baseline=Covariate(t',ones(length(t),1),'Baseline','time','s','',{'mu'});
-
-spikeColl = sC; %Use the generated data as our collection of spikes
-%Use stimulation and baseline as possible covariates
-cc=CovColl({stim,baseline});
-trial = Trial(spikeColl,cc); sampleRate = 1/Ts; %Create trial
-% trial.setTrialPartition([0 tMax/2 tMax]);
-

GLM Model Fitting and Results

clear c;
-% We know the history effect goes back 3 lag orders
-selfHist = [0:1:3]*Ts;
-% only have an effect at the 1ms lag. This captures the effect of the
-% firing of neuron 1 on neuron 2 and vice versa.
-ensHist  = [0 1]*Ts;
-
-
-
-sampleRate = 1/Ts;
-%Lets compare three models of increasing complexity for each neuron
-
-% When results are shown, ]ambda_1 corresponds to the CIF obtained from the
-% c{1}, lambda_2 to c{2} etc.
-% Fit only a mean firing rate
-c{1} = TrialConfig({{'Baseline','mu'}},sampleRate,[],[]);
-c{1}.setName('Baseline');
-
-% Fit a constant rate and ensemble model
-c{2} = TrialConfig({{'Baseline','mu'}},sampleRate,[],ensHist);
-c{2}.setName('Baseline+EnsHist');
-
-% Fit the correct/exact model
-c{3} = TrialConfig({{'Baseline','mu'},{'Stimulus','sin'}},sampleRate,...
-    selfHist,ensHist);
-c{3}.setName('Stim+Hist+EnsHist');
-
-% Place all configurations together and run analysis for each neuron
-
-cfgColl= ConfigColl(c);
-results = Analysis.RunAnalysisForAllNeurons(trial,cfgColl,0,Algorithm);
-
-% Visualize the Results
-results{1}.plotResults;
-results{2}.plotResults;
-Summary = FitResSummary(results);
-% Summary.plotSummary;
-
-% Construct an image of the Actual vs. Estimated Network
-actNetwork = zeros(numNeurons,numNeurons);
-network1ms = zeros(numNeurons,numNeurons);
-for i=1:numNeurons
-    index = 1:numNeurons;
-    neighbors = setdiff(index,i);
-    [num,den] = tfdata(E{i});
-    actNetwork(i,neighbors) = cell2mat(num);
-    % Coefficients in the 2rd Analysis correspond to the estimated
-    % connection weights.
-    % See labels after running command: [coeffs,labels]=results{i}.getCoeffs;
-    [coeffs,labels]=results{i}.getCoeffs;
-    network1ms(i,neighbors)=coeffs(1:(length(neighbors)),3);
-end
-
-maxVal=max(max(abs(actNetwork)));
-minVal=-maxVal;%min(min(actNetwork));
-CLIM = [minVal maxVal];
-figure;
-colormap(jet);
-subplot(1,2,1);
-imagesc(actNetwork,CLIM);
-set(gca,'XTick',index,'YTick',index);
-title('Actual');
-subplot(1,2,2);
-imagesc(network1ms,CLIM);
-set(gca,'XTick',index,'YTick',index);
-title('Estimated 1ms');
-
Analyzing Configuration #1: Neuron #1,2
-Analyzing Configuration #2: Neuron #1,2
-Analyzing Configuration #3: Neuron #1,2
-

Note: by default all neurons are considered to be potential neighbors. If this is not the case, you can call trial.setNeighbors(neighborArray) where neighborArray is a matrix that in the ith row has ones in the columns of those neurons considered to be potential neighbors and zeros otherwise. By default neighborArray has 0 only on the diagonal, so that the ith neuron cannot be its own neighbor, and 1 ones elsewhere.

\ No newline at end of file diff --git a/helpfiles/NetworkTutorial.m b/helpfiles/NetworkTutorial.m deleted file mode 100644 index beed6799..00000000 --- a/helpfiles/NetworkTutorial.m +++ /dev/null @@ -1,223 +0,0 @@ -% Author: Iahn Cajigas -% Date: 2/10/2014 -%% Point Process Network Simulation -% In order to understand how the point process GLM framework can be used to -% estimate the network connectivity within a population of neurons, we -% simulate a network of 2 neurons. -%% -% -% <> -% - -%% -% -% <> -% -%% -% This block diagram specifies a conditional intensity function of the form - - -%% -% $$lambda_{i} \cdot \Delta = logistic(\mu_{i} + H*\Delta N_{i}[n] + -% S*u_{stim}[n] + E*\Delta N_{k}[n]$$ -% -%% -% where, -% $\hbox{\fontsize{14}{16}\selectfont\(logistic(x)=e^{x}/{1+e^{x}}\)}$. Note that * is the convolution opertator. -%% 2 Neuron Network - -clear all; -close all; -Ts=.001; %Sample Time -tMin=0; tMax=50; %Simulation duration -t=tMin:Ts:tMax; -numNeurons=2; - -%% Baseline firing rate of the neurons being modeled -mu{1}=-3; -mu{2}=-3; - -%% History Effect -% Captures how the firing of a neuron at modulates its probability of -% firing. Captures effects such as the refractory period and bursting. We -% use the same firing history for both neurons in this example. Note that -% the firing activity at time n leads to strong inhibition at time n+1 -% (refractory period) and that this effect becomes smaller over the next -% two time periods. -%% -% $$1*h[n]=-4*\Delta N[n-1]-2*\Delta N[n-2] -1*\Delta N[n-3]$$ -% -% Note that the one sample delay in same cell firing is included -% in the simulink model. -H{1}=tf([-4 -2 -1],[1],Ts,'Variable','z^-1'); -H{2}=tf([-4 -2 -1],[1],Ts,'Variable','z^-1'); - -%% Stimulus Effect - -%% -% $$1*s_{1}[n]=1*u_{stim}[n]$$ -% -%% -% $$1*s_{2}[n]=-1*u_{stim}[n]$$ -% -% Neuron 1 is positively modulated by the stimulus -S{1}=tf([1],1,Ts,'Variable','z^-1'); -% Neuron 1 is negatively modulated by the stimulus -S{2}=tf([-1],1,Ts,'Variable','z^-1'); - - -%% Ensemble Effect -% Captures the effect of how neighboring neuron firing modulates the firing -% of a given neuron. -%% -% $$1*e_{1}[n]=1*\Delta N_{2}[n-1]$$ -% -%% -% $$1*e_{2}[n]=-4*\Delta N_{1}[n-1]$$ -% -% Note that the one sample delay in firing of the neighbor cell is included -% in the simulink model. -%Neuron 2 firing positively modulates Neuron 1 -E{1}=tf([1],1,Ts,'Variable','z^-1'); -%Neuron 1 firing has strong inhibitory effect on neuron 2. -E{2}=tf([-4],1,Ts,'Variable','z^-1'); - -%% Stimulus -% We use a simple sine wave here but we may want to explore other types of -% inputs to see if they affect the recovery of the network parameters. - -f=1; %Stimulus frequency [Hz] -u = sin(2*pi*f*t)'; %Make this neuron modulated by a sine wave -stim=Covariate(t',u,'Stimulus','time','s','Voltage',{'sin'}); - - -% Map the variables to the Simulink model -assignin('base','S1',S{1}); -assignin('base','H1',H{1}); -assignin('base','E1',E{1}); -assignin('base','mu1',mu{1}); -assignin('base','S2',S{2}); -assignin('base','H2',H{2}); -assignin('base','E2',E{2}); -assignin('base','mu2',mu{2}); -options = simget; - -%% Simulate the Network -% Uses a binomial model for the conditional intensity function -% nSTAT supports poisson model too but this simulink model simulates the -% firing using a binomial model -fitType = 'binomial'; -if(strcmp(fitType,'binomial')) - Algorithm = 'BNLRCG'; -else - Algorithm ='GLM'; -end -[tout,~,yout] = sim('SimulatedNetwork2',[stim.minTime stim.maxTime], ... - options,stim.dataToStructure); -clear nst; - - for i=1:numNeurons - spikeTimes = tout(yout(:,i)>.5); %find the spike times - nst{i} = nspikeTrain(spikeTimes); - end - - -sC=nstColl(nst); -sC.setMinTime(stim.minTime); -sC.setMaxTime(stim.maxTime); - - - -figure; -subplot(2,1,1); sC.plot; v=axis; axis([0 tMax/10 v(3) v(4)]); -subplot(2,1,2); stim.plot; v=axis; axis([0 tMax/10 v(3) v(4)]); - -%% GLM Model Fitting Setup -% In this section, we create the appropriate structures to fit several GLM -% models to the data generated above. - -% Create a constant covariate representing the mean firing rate $$\mu_{i}$ -baseline=Covariate(t',ones(length(t),1),'Baseline','time','s','',{'mu'}); - -spikeColl = sC; %Use the generated data as our collection of spikes -%Use stimulation and baseline as possible covariates -cc=CovColl({stim,baseline}); -trial = Trial(spikeColl,cc); sampleRate = 1/Ts; %Create trial -% trial.setTrialPartition([0 tMax/2 tMax]); - -%% GLM Model Fitting and Results -clear c; -% We know the history effect goes back 3 lag orders -selfHist = [0:1:3]*Ts; -% only have an effect at the 1ms lag. This captures the effect of the -% firing of neuron 1 on neuron 2 and vice versa. -ensHist = [0 1]*Ts; - - - -sampleRate = 1/Ts; -%Lets compare three models of increasing complexity for each neuron - -% When results are shown, ]ambda_1 corresponds to the CIF obtained from the -% c{1}, lambda_2 to c{2} etc. -% Fit only a mean firing rate -c{1} = TrialConfig({{'Baseline','mu'}},sampleRate,[],[]); -c{1}.setName('Baseline'); - -% Fit a constant rate and ensemble model -c{2} = TrialConfig({{'Baseline','mu'}},sampleRate,[],ensHist); -c{2}.setName('Baseline+EnsHist'); - -% Fit the correct/exact model -c{3} = TrialConfig({{'Baseline','mu'},{'Stimulus','sin'}},sampleRate,... - selfHist,ensHist); -c{3}.setName('Stim+Hist+EnsHist'); - -% Place all configurations together and run analysis for each neuron - -cfgColl= ConfigColl(c); -results = Analysis.RunAnalysisForAllNeurons(trial,cfgColl,0,Algorithm); - -% Visualize the Results -results{1}.plotResults; -results{2}.plotResults; -Summary = FitResSummary(results); -% Summary.plotSummary; - -% Construct an image of the Actual vs. Estimated Network -actNetwork = zeros(numNeurons,numNeurons); -network1ms = zeros(numNeurons,numNeurons); -for i=1:numNeurons - index = 1:numNeurons; - neighbors = setdiff(index,i); - [num,den] = tfdata(E{i}); - actNetwork(i,neighbors) = cell2mat(num); - % Coefficients in the 2rd Analysis correspond to the estimated - % connection weights. - % See labels after running command: [coeffs,labels]=results{i}.getCoeffs; - [coeffs,labels]=results{i}.getCoeffs; - network1ms(i,neighbors)=coeffs(1:(length(neighbors)),3); -end - -maxVal=max(max(abs(actNetwork))); -minVal=-maxVal;%min(min(actNetwork)); -CLIM = [minVal maxVal]; -figure; -colormap(jet); -subplot(1,2,1); -imagesc(actNetwork,CLIM); -set(gca,'XTick',index,'YTick',index); -title('Actual'); -subplot(1,2,2); -imagesc(network1ms,CLIM); -set(gca,'XTick',index,'YTick',index); -title('Estimated 1ms'); - -%% -% Note: by default all neurons are considered to be potential neighbors. If -% this is not the case, you can call trial.setNeighbors(neighborArray) -% where neighborArray is a matrix that in the ith row has ones in the -% columns of those neurons considered to be potential neighbors and zeros -% otherwise. By default neighborArray has 0 only on the diagonal, so that -% the ith neuron cannot be its own neighbor, and 1 ones elsewhere. - diff --git a/helpfiles/NetworkTutorial.png b/helpfiles/NetworkTutorial.png deleted file mode 100644 index 3e7d12c7..00000000 Binary files a/helpfiles/NetworkTutorial.png and /dev/null differ diff --git a/helpfiles/NetworkTutorial_01.png b/helpfiles/NetworkTutorial_01.png deleted file mode 100644 index 7338c72d..00000000 Binary files a/helpfiles/NetworkTutorial_01.png and /dev/null differ diff --git a/helpfiles/NetworkTutorial_02.png b/helpfiles/NetworkTutorial_02.png deleted file mode 100644 index 3e7b6ba5..00000000 Binary files a/helpfiles/NetworkTutorial_02.png and /dev/null differ diff --git a/helpfiles/NetworkTutorial_03.png b/helpfiles/NetworkTutorial_03.png deleted file mode 100644 index 39440759..00000000 Binary files a/helpfiles/NetworkTutorial_03.png and /dev/null differ diff --git a/helpfiles/NetworkTutorial_04.png b/helpfiles/NetworkTutorial_04.png deleted file mode 100644 index de888417..00000000 Binary files a/helpfiles/NetworkTutorial_04.png and /dev/null differ diff --git a/helpfiles/NetworkTutorial_eq01608.png b/helpfiles/NetworkTutorial_eq01608.png deleted file mode 100644 index 2adf9a8d..00000000 Binary files a/helpfiles/NetworkTutorial_eq01608.png and /dev/null differ diff --git a/helpfiles/NetworkTutorial_eq05678.png b/helpfiles/NetworkTutorial_eq05678.png deleted file mode 100644 index ae4a76a3..00000000 Binary files a/helpfiles/NetworkTutorial_eq05678.png and /dev/null differ diff --git a/helpfiles/NetworkTutorial_eq10976.png b/helpfiles/NetworkTutorial_eq10976.png deleted file mode 100644 index 70a2356d..00000000 Binary files a/helpfiles/NetworkTutorial_eq10976.png and /dev/null differ diff --git a/helpfiles/NetworkTutorial_eq80304.png b/helpfiles/NetworkTutorial_eq80304.png deleted file mode 100644 index abaeb7b9..00000000 Binary files a/helpfiles/NetworkTutorial_eq80304.png and /dev/null differ diff --git a/helpfiles/NetworkTutorial_eq83377.png b/helpfiles/NetworkTutorial_eq83377.png deleted file mode 100644 index 2321054d..00000000 Binary files a/helpfiles/NetworkTutorial_eq83377.png and /dev/null differ diff --git a/helpfiles/NetworkTutorial_eq91481.png b/helpfiles/NetworkTutorial_eq91481.png deleted file mode 100644 index c8863c99..00000000 Binary files a/helpfiles/NetworkTutorial_eq91481.png and /dev/null differ diff --git a/helpfiles/NetworkTutorial_eq96233.png b/helpfiles/NetworkTutorial_eq96233.png deleted file mode 100644 index ca221168..00000000 Binary files a/helpfiles/NetworkTutorial_eq96233.png and /dev/null differ diff --git a/helpfiles/NeuralSpikeAnalysis_top.html b/helpfiles/NeuralSpikeAnalysis_top.html deleted file mode 100644 index e8a41cad..00000000 --- a/helpfiles/NeuralSpikeAnalysis_top.html +++ /dev/null @@ -1,92 +0,0 @@ - - - - - Neural Spike Train Analysis Toolbox (nSTAT)

Neural Spike Train Analysis Toolbox (nSTAT)

Author: Iahn Cajigas (iahn@mit.edu)

Original Release Date: 9/10/2009

Current Release Date: 4/10/2014

Purpose: The Neural Spike Analysis Toolbox is an effort to consolidate many of the data analysis methods of the Point Process/Generalized Linear Model Framework into a coherent and simple to use package.

\ No newline at end of file diff --git a/helpfiles/NeuralSpikeAnalysis_top.m b/helpfiles/NeuralSpikeAnalysis_top.m deleted file mode 100644 index 306132ed..00000000 --- a/helpfiles/NeuralSpikeAnalysis_top.m +++ /dev/null @@ -1,20 +0,0 @@ -%% Neural Spike Train Analysis Toolbox (nSTAT) -% -% -% <> -% -% *Author*: Iahn Cajigas (iahn@mit.edu) -% -% *Original Release Date*: 9/10/2009 -% -% *Current Release Date*: 4/10/2014 -% -% *Purpose:* -% The Neural Spike Analysis Toolbox is an effort to consolidate many of the -% data analysis methods of the Point Process/Generalized Linear Model -% Framework into a coherent and simple to use package. -% -% - - - diff --git a/helpfiles/PPSimExample-BlockDiagram.png b/helpfiles/PPSimExample-BlockDiagram.png deleted file mode 100644 index 5e29e610..00000000 Binary files a/helpfiles/PPSimExample-BlockDiagram.png and /dev/null differ diff --git a/helpfiles/PPSimExample.html b/helpfiles/PPSimExample.html deleted file mode 100644 index 76012b56..00000000 --- a/helpfiles/PPSimExample.html +++ /dev/null @@ -1,242 +0,0 @@ - - - - - General Point Process Simulation

General Point Process Simulation

In this demo, we show how sample-paths of a point process (PP) can be generated from specification of its conditional intensity function (CIF). We then use the generated PP data to validate the outputs of the Neural Spike Analysis Toolbox.

Contents

Point Process Sample Path Generation

That both the stimulus effect and ensemble effects can be made into multi-input/multi-output transfer functions to account for more than 1 stimulus effect or multiple neighboring neuron effects. To do this, simply define $$E$ or $$S$ to be a row vector of LTI transfer functions. Make sure than the number of dimensions of the input matches the number of transfer functions specified in the row vector.

This block diagram specifies a conditional intensity function of the form

$$\lambda_{i} \cdot \Delta = exp(\mu_{i} + H*\Delta N_{i}[n] + S*u_{stim}[n] + E*\Delta N_{k}[n])/(1+exp(\mu_{i} + H*\Delta N_{i}[n] + S*u_{stim}[n] + E*\Delta N_{k}[n]))$$

close all;
-Ts=.001;            %Sample Time
-tMin=0; tMax=50;    %Simulation duration
-t=tMin:Ts:tMax;
-
-mu=-3;              %Baseline firing rate of the neurons being modeled
-

History Effect

$$1*h[n]=-1*\Delta N[n-1]-2*\Delta N[n-2] -4*\Delta N[n-3]$$

H=tf([-1 -2 -4],[1],Ts,'Variable','z^-1');
-

Stimulus Effect

$$1*s[n]=1*u_{stim}[n]$$

S=tf([1],1,Ts,'Variable','z^-1');
-

Ensemble Effect

$$1*e[n]=0*\Delta N_{k}[n]$$

E=tf([0],1,Ts,'Variable','z^-1');
-
f=1;                    %Stimulus frequency
-u = sin(2*pi*f*t)';       %Make this neuron modulated by a sine wave
-e = zeros(length(t),1);   %No Ensemble input
-
-stim=Covariate(t',u,'Stimulus','time','s','Voltage',{'sin'});
-ens =Covariate(t',e,'Ensemble','time','s','Spikes',{'n1'});
-numRealizations = 5;    %Number of sample paths to generate
-fitType = 'binomial';
-sC=CIF.simulateCIF(mu,H,S,E,stim,ens,numRealizations,fitType);
-figure;
-subplot(2,1,1); sC.plot;    v=axis; axis([0 tMax/10 v(3) v(4)]);
-subplot(2,1,2); stim.plot;  v=axis; axis([0 tMax/10 v(3) v(4)]);
-

GLM Model Fitting Setup

In this section, we create the appropriate structures to fit several GLM models to the data generated above.

% Create a constant covariate representing the mean firing rate $$\mu_{i}$
-baseline=Covariate(t',ones(length(t),1),'Baseline','time','s','',{'mu'});
-
-
-spikeColl = sC;               %Use the generated data as our collection of spikes
-cc=CovColl({stim,baseline});  %Use stimulation and baseline as possible covariates
-trial = Trial(spikeColl,cc); sampleRate = 1/Ts; %Create trial
-

GLM Model Fitting and Results

clear c;
-selfHist = [0:0.001:0.003]; %We know the history effect goes back 3 lag orders
-

Fit only a mean firing rate

c{1} = TrialConfig({{'Baseline','mu'}},sampleRate,[],[]);
-c{1}.setName('Baseline');
-

Fit a mean firing rate + the stimulus term

c{2} = TrialConfig({{'Baseline','mu'},{'Stimulus','sin'}},sampleRate,[],[]);
-c{2}.setName('Stim');
-

Fit a mean firing rate, self-history, and stimulus --- Same as true model

c{3} = TrialConfig({{'Baseline','mu'},{'Stimulus','sin'}},sampleRate,selfHist,[]);
-c{3}.setName('Stim+Hist');
-

Place all configurations together and run analysis for each neuron

cfgColl= ConfigColl(c);
-if(strcmp(fitType,'binomial'))
-    Algorithm = 'BNLRCG';   % BNLRCG - faster Truncated, L-2 Regularized,
-                            % Binomial Logistic Regression with Conjugate
-                            % Gradient Solver by Demba Ba (demba@mit.edu).
-else
-    Algorithm = 'GLM';      % Standard Matlab GLM (Can be used for binomial or
-                            % or Poisson CIFs
-end
-results = Analysis.RunAnalysisForAllNeurons(trial,cfgColl,0,Algorithm);
-
Analyzing Configuration #1: Neuron #1,2,3,4,5
-Analyzing Configuration #2: Neuron #1,2,3,4,5
-Analyzing Configuration #3: Neuron #1,2,3,4,5
-

Results for sample neuron

results{1}.plotResults;
-

Results for across all sample paths

Summary = FitResSummary(results);
-Summary.plotSummary;
-
\ No newline at end of file diff --git a/helpfiles/PPSimExample.m b/helpfiles/PPSimExample.m deleted file mode 100644 index 04d3527f..00000000 --- a/helpfiles/PPSimExample.m +++ /dev/null @@ -1,121 +0,0 @@ -%% General Point Process Simulation -% In this demo, we show how sample-paths of a point process (PP) can be -% generated from specification of its conditional intensity function (CIF). -% We then use the generated PP data to validate the outputs of the Neural -% Spike Analysis Toolbox. -%% Point Process Sample Path Generation -% That both the stimulus effect and ensemble effects can be made into -% multi-input/multi-output transfer functions to account for more than 1 -% stimulus effect or multiple neighboring neuron effects. To do this, -% simply define $$E$ or $$S$ to be a row vector of LTI transfer functions. -% Make sure than the number of dimensions of the input matches the number -% of transfer functions specified in the row vector. - -%% -% -% <> -% - -%% -% This block diagram specifies a conditional intensity function of the form - -%% -% -% $$\lambda_{i} \cdot \Delta = exp(\mu_{i} + H*\Delta N_{i}[n] + S*u_{stim}[n] + E*\Delta N_{k}[n])/(1+exp(\mu_{i} + H*\Delta N_{i}[n] + S*u_{stim}[n] + E*\Delta N_{k}[n]))$$ -% - - - -close all; -Ts=.001; %Sample Time -tMin=0; tMax=50; %Simulation duration -t=tMin:Ts:tMax; - -mu=-3; %Baseline firing rate of the neurons being modeled - -%% History Effect -% -% $$1*h[n]=-1*\Delta N[n-1]-2*\Delta N[n-2] -4*\Delta N[n-3]$$ -% -H=tf([-1 -2 -4],[1],Ts,'Variable','z^-1'); - - -%% Stimulus Effect -% -% $$1*s[n]=1*u_{stim}[n]$$ -% -S=tf([1],1,Ts,'Variable','z^-1'); - - -%% Ensemble Effect -% -% $$1*e[n]=0*\Delta N_{k}[n]$$ -% -E=tf([0],1,Ts,'Variable','z^-1'); - -%% -f=1; %Stimulus frequency -u = sin(2*pi*f*t)'; %Make this neuron modulated by a sine wave -e = zeros(length(t),1); %No Ensemble input - -stim=Covariate(t',u,'Stimulus','time','s','Voltage',{'sin'}); -ens =Covariate(t',e,'Ensemble','time','s','Spikes',{'n1'}); -numRealizations = 5; %Number of sample paths to generate -fitType = 'binomial'; -sC=CIF.simulateCIF(mu,H,S,E,stim,ens,numRealizations,fitType); -figure; -subplot(2,1,1); sC.plot; v=axis; axis([0 tMax/10 v(3) v(4)]); -subplot(2,1,2); stim.plot; v=axis; axis([0 tMax/10 v(3) v(4)]); - -%% GLM Model Fitting Setup -% In this section, we create the appropriate structures to fit several GLM -% models to the data generated above. - -% Create a constant covariate representing the mean firing rate $$\mu_{i}$ -baseline=Covariate(t',ones(length(t),1),'Baseline','time','s','',{'mu'}); - - -spikeColl = sC; %Use the generated data as our collection of spikes -cc=CovColl({stim,baseline}); %Use stimulation and baseline as possible covariates -trial = Trial(spikeColl,cc); sampleRate = 1/Ts; %Create trial - - -%% GLM Model Fitting and Results -clear c; -selfHist = [0:0.001:0.003]; %We know the history effect goes back 3 lag orders - -%% -% Fit only a mean firing rate -c{1} = TrialConfig({{'Baseline','mu'}},sampleRate,[],[]); -c{1}.setName('Baseline'); - -%% -% Fit a mean firing rate + the stimulus term -c{2} = TrialConfig({{'Baseline','mu'},{'Stimulus','sin'}},sampleRate,[],[]); -c{2}.setName('Stim'); - -%% -% Fit a mean firing rate, self-history, and stimulus --- Same as true model -c{3} = TrialConfig({{'Baseline','mu'},{'Stimulus','sin'}},sampleRate,selfHist,[]); -c{3}.setName('Stim+Hist'); - -%% -% Place all configurations together and run analysis for each neuron -cfgColl= ConfigColl(c); -if(strcmp(fitType,'binomial')) - Algorithm = 'BNLRCG'; % BNLRCG - faster Truncated, L-2 Regularized, - % Binomial Logistic Regression with Conjugate - % Gradient Solver by Demba Ba (demba@mit.edu). -else - Algorithm = 'GLM'; % Standard Matlab GLM (Can be used for binomial or - % or Poisson CIFs -end -results = Analysis.RunAnalysisForAllNeurons(trial,cfgColl,0,Algorithm); - -%% Results for sample neuron -results{1}.plotResults; - -%% Results for across all sample paths - -Summary = FitResSummary(results); -Summary.plotSummary; \ No newline at end of file diff --git a/helpfiles/PPSimExample.png b/helpfiles/PPSimExample.png deleted file mode 100644 index ba45854a..00000000 Binary files a/helpfiles/PPSimExample.png and /dev/null differ diff --git a/helpfiles/PPSimExample_01.png b/helpfiles/PPSimExample_01.png deleted file mode 100644 index 0979ba4e..00000000 Binary files a/helpfiles/PPSimExample_01.png and /dev/null differ diff --git a/helpfiles/PPSimExample_02.png b/helpfiles/PPSimExample_02.png deleted file mode 100644 index c98eaf59..00000000 Binary files a/helpfiles/PPSimExample_02.png and /dev/null differ diff --git a/helpfiles/PPSimExample_03.png b/helpfiles/PPSimExample_03.png deleted file mode 100644 index 60b7801e..00000000 Binary files a/helpfiles/PPSimExample_03.png and /dev/null differ diff --git a/helpfiles/PPSimExample_eq05913.png b/helpfiles/PPSimExample_eq05913.png deleted file mode 100644 index b519c034..00000000 Binary files a/helpfiles/PPSimExample_eq05913.png and /dev/null differ diff --git a/helpfiles/PPSimExample_eq12837.png b/helpfiles/PPSimExample_eq12837.png deleted file mode 100644 index 6ab5ec4b..00000000 Binary files a/helpfiles/PPSimExample_eq12837.png and /dev/null differ diff --git a/helpfiles/PPSimExample_eq43772.png b/helpfiles/PPSimExample_eq43772.png deleted file mode 100644 index 78ca1196..00000000 Binary files a/helpfiles/PPSimExample_eq43772.png and /dev/null differ diff --git a/helpfiles/PPSimExample_eq52469.png b/helpfiles/PPSimExample_eq52469.png deleted file mode 100644 index de1575d5..00000000 Binary files a/helpfiles/PPSimExample_eq52469.png and /dev/null differ diff --git a/helpfiles/PPSimExample_eq58538.png b/helpfiles/PPSimExample_eq58538.png deleted file mode 100644 index f6801185..00000000 Binary files a/helpfiles/PPSimExample_eq58538.png and /dev/null differ diff --git a/helpfiles/PPSimExample_eq62582.png b/helpfiles/PPSimExample_eq62582.png deleted file mode 100644 index be759863..00000000 Binary files a/helpfiles/PPSimExample_eq62582.png and /dev/null differ diff --git a/helpfiles/PPSimExample_eq76278.png b/helpfiles/PPSimExample_eq76278.png deleted file mode 100644 index d517ad06..00000000 Binary files a/helpfiles/PPSimExample_eq76278.png and /dev/null differ diff --git a/helpfiles/PPSimExample_eq82580.png b/helpfiles/PPSimExample_eq82580.png deleted file mode 100644 index 0a433d32..00000000 Binary files a/helpfiles/PPSimExample_eq82580.png and /dev/null differ diff --git a/helpfiles/PPSimExample_eq93975.png b/helpfiles/PPSimExample_eq93975.png deleted file mode 100644 index ed59b9c3..00000000 Binary files a/helpfiles/PPSimExample_eq93975.png and /dev/null differ diff --git a/helpfiles/PPThinning.html b/helpfiles/PPThinning.html deleted file mode 100644 index 5a15c1ce..00000000 --- a/helpfiles/PPThinning.html +++ /dev/null @@ -1,184 +0,0 @@ - - - - - Simulate PP via thinning

Simulate PP via thinning

Given a conditional intensity function, we generate a point process consistent with this CIF.

Contents

Basic Example

close all;
-delta = 0.001;
-Tmax = 100;
-time = 0:delta:Tmax;
-f=.1;
-lambdaData = 10*sin(2*pi*f*time)+10; %lambda >=0
-lambda = Covariate(time,lambdaData, '\Lambda(t)','time','s','Hz',{'\lambda_{1}'},{{' ''b'', ''LineWidth'' ,2'}});
-
-lambdaBound = max(lambda);
-N=lambdaBound*(1.5*Tmax);   %Expected number of arrivals in interval 1.5*Tmax
-u = rand(1,N);              %N samples uniform(0,1)
-w = -log(u)./(lambdaBound); %N samples exponential rate lambdaBound (ISIs)
-
-tSpikes = cumsum(w);        %Spiketimes;
-tSpikes = tSpikes(tSpikes<=Tmax);%Spiketimes within Tmax
-
-% Thinning
-
-lambdaRatio = lambda.getValueAt(tSpikes)./lambdaBound;
-% lambdaRatio <=1
-
-% draw uniform random number in 0,1
-u2 = rand(length(lambdaRatio),1);
-
-% keep spike if lambda ratio is greater than random number
-tSpikesThin  = tSpikes(lambdaRatio>=u2);
-

Compare Constant rate process vs. thinned process

figure(1);
-n1 = nspikeTrain(tSpikes);
-n2 = nspikeTrain(tSpikesThin);
-subplot(2,2,1); n1.plot; plot(tSpikes,ones(size(tSpikes)),'.');
-v=axis; axis([0 Tmax/4 v(3) v(4)]);
-subplot(2,2,2); n1.plotISIHistogram;
-subplot(2,2,3); n2.plot; plot(tSpikes,ones(size(tSpikes)),'.');
-v=axis; axis([0 Tmax/4 v(3) v(4)]);
-subplot(2,2,4); n2.plotISIHistogram;
-
-figure(2);
-n2.plot;
-scaledProb = lambda*(1./lambdaBound);
-scaledProb.plot;
-v=axis;
-axis([0 Tmax/4 v(3) v(4)]);
-

Simulate multiple realizations of a point process via thinning

The CIF class can generated realizations of a point process given a conditional intensity function (defined as a Covariate or SignalObj)

numRealizations = 20;
-spikeColl = CIF.simulateCIFByThinningFromLambda(lambda,numRealizations);
-figure(3);
-spikeColl.plot;
-lambda.plot;
-v=axis;
-axis([0 Tmax/4 v(3) v(4)]);
-
\ No newline at end of file diff --git a/helpfiles/PPThinning.m b/helpfiles/PPThinning.m deleted file mode 100644 index 15ab9653..00000000 --- a/helpfiles/PPThinning.m +++ /dev/null @@ -1,63 +0,0 @@ -%% Simulate PP via thinning -% Given a conditional intensity function, we generate a point process -% consistent with this CIF. - -%% Basic Example -close all; -delta = 0.001; -Tmax = 100; -time = 0:delta:Tmax; -f=.1; -lambdaData = 10*sin(2*pi*f*time)+10; %lambda >=0 -lambda = Covariate(time,lambdaData, '\Lambda(t)','time','s','Hz',{'\lambda_{1}'},{{' ''b'', ''LineWidth'' ,2'}}); - -lambdaBound = max(lambda); -N=lambdaBound*(1.5*Tmax); %Expected number of arrivals in interval 1.5*Tmax -u = rand(1,N); %N samples uniform(0,1) -w = -log(u)./(lambdaBound); %N samples exponential rate lambdaBound (ISIs) - -tSpikes = cumsum(w); %Spiketimes; -tSpikes = tSpikes(tSpikes<=Tmax);%Spiketimes within Tmax - -% Thinning - -lambdaRatio = lambda.getValueAt(tSpikes)./lambdaBound; -% lambdaRatio <=1 - -% draw uniform random number in 0,1 -u2 = rand(length(lambdaRatio),1); - -% keep spike if lambda ratio is greater than random number -tSpikesThin = tSpikes(lambdaRatio>=u2); - -%% Compare Constant rate process vs. thinned process -figure(1); -n1 = nspikeTrain(tSpikes); -n2 = nspikeTrain(tSpikesThin); -subplot(2,2,1); n1.plot; plot(tSpikes,ones(size(tSpikes)),'.'); -v=axis; axis([0 Tmax/4 v(3) v(4)]); -subplot(2,2,2); n1.plotISIHistogram; -subplot(2,2,3); n2.plot; plot(tSpikes,ones(size(tSpikes)),'.'); -v=axis; axis([0 Tmax/4 v(3) v(4)]); -subplot(2,2,4); n2.plotISIHistogram; - -figure(2); -n2.plot; -scaledProb = lambda*(1./lambdaBound); -scaledProb.plot; -v=axis; -axis([0 Tmax/4 v(3) v(4)]); - -%% Simulate multiple realizations of a point process via thinning -% The CIF class can generated realizations of a point process given -% a conditional intensity function (defined as a Covariate or SignalObj) - -numRealizations = 20; -spikeColl = CIF.simulateCIFByThinningFromLambda(lambda,numRealizations); -figure(3); -spikeColl.plot; -lambda.plot; -v=axis; -axis([0 Tmax/4 v(3) v(4)]); - - diff --git a/helpfiles/PPThinning.png b/helpfiles/PPThinning.png deleted file mode 100644 index 611d13ff..00000000 Binary files a/helpfiles/PPThinning.png and /dev/null differ diff --git a/helpfiles/PPThinning_01.png b/helpfiles/PPThinning_01.png deleted file mode 100644 index 5ae1cf5b..00000000 Binary files a/helpfiles/PPThinning_01.png and /dev/null differ diff --git a/helpfiles/PPThinning_02.png b/helpfiles/PPThinning_02.png deleted file mode 100644 index 65d50ec5..00000000 Binary files a/helpfiles/PPThinning_02.png and /dev/null differ diff --git a/helpfiles/PPThinning_03.png b/helpfiles/PPThinning_03.png deleted file mode 100644 index 7e593267..00000000 Binary files a/helpfiles/PPThinning_03.png and /dev/null differ diff --git a/helpfiles/PSTHEstimation.bak b/helpfiles/PSTHEstimation.bak deleted file mode 100644 index ae66d0b7..00000000 --- a/helpfiles/PSTHEstimation.bak +++ /dev/null @@ -1,60 +0,0 @@ -%% PSTH Estimation -% We illustrate two ways to estimate a peristimulus time histogram using -% the nSTAT toolbox. One technique is the standard binning in time, -% averaging across trials, and dividing by the binwidth to estimate the -% spike rate and the other is based on the method presented in "Analysis of -% Between-Trial and Within-Trial Neural Spiking Dynamics" by Czanner et al -% in J Neurophysiology 2008. -% -% -%% 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. - -close all; -delta = 0.001; -Tmax = 35; -time = 0:delta:Tmax; -f=.1; -lambdaData = 10*sin(2*pi*f*time)+10; %lambda >=0 -lambda = Covariate(time,lambdaData, '\Lambda(t)','time','s','Hz',{'\lambda_{1}'},{{' ''b'', ''LineWidth'' ,2'}}); -numRealizations = 20; % Use 20 realization so that lamba and raster plot are the same size -spikeColl = CIF.simulateCIFByThinning(lambda,numRealizations); -spikeColl.plot; -lambda.plot; - -%% Estimate the PSTH with 200ms windows -% - -figure; -binsize = .5; %500ms window -psth = spikeColl.psth(binsize); -psthGLM = spikeColl.psthGLM(binsize); -true = lambda*binsize; %rate*delta = expected number of arrivals per bin -h1=true.plot; -h2=psth.plot([],{{' ''rx'',''Linewidth'',4'}}); -h3=psthGLM.plotAllVariability('g',2,1/sqrt(psth.dimension)); -legend off; -legend([h1(1) h2(1) h3(1)],'true','PSTH','PSTH_{glm}'); - -% Because currently the psthGLM estimated the psth coefficients in each bin -% for each realization, we want the show the mean and standard error of the -% cofficient in each bin. We make the upper and lower confidence bounds -% equal to 1/sqrt(numRealization)=1/sqrt(psth.dimension) to view the -% standard error instead of the standard deviation - - -%% -% Note the mean of the PSTH estimated via the GLM model and the PSTH -% computed via standard methods agree precisely. The benefit of the GLM -% estimated PSTH is the presence of confidence bounds on the estimate. Both -% the standard and GLM PSTH are in close agreement with the "true" -% underlying rate function (conditional intensity function) used in this -% simulated example. Both the PSTH and PSTHGLM code could be updated in the -% future to allow for variable bin sizes (e.g. in the vein of Baysian Adaptive Regression -% Splines by Wallstrom, Leibner and Kass). Alternatively, porting of BARS -% to Matlab may allow for it to be easily integrated into the nSTAT -% toolbox. - - diff --git a/helpfiles/PSTHEstimation.html b/helpfiles/PSTHEstimation.html deleted file mode 100644 index 871e4155..00000000 --- a/helpfiles/PSTHEstimation.html +++ /dev/null @@ -1,159 +0,0 @@ - - - - - PSTH Estimation

PSTH Estimation

We illustrate two ways to estimate a peristimulus time histogram using the nSTAT toolbox. One technique is the standard binning in time, averaging across trials, and dividing by the binwidth to estimate the spike rate and the other is based on the method presented in "Analysis of Between-Trial and Within-Trial Neural Spiking Dynamics" by Czanner et al in J Neurophysiology 2008.

Contents

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.

close all;
-delta = 0.001;
-Tmax = 10;
-time = 0:delta:Tmax;
-f=.2;
-lambdaData = 10*sin(2*pi*f*time)+10; %lambda >=0
-lambda = Covariate(time,lambdaData, '\Lambda(t)','time','s','Hz',{'\lambda_{1}'},{{' ''b'', ''LineWidth'' ,2'}});
-numRealizations = 20; % Use 20 realization so that lamba and raster plot are the same size
-spikeColl = CIF.simulateCIFByThinningFromLambda(lambda,numRealizations);
-spikeColl.plot; set(gca,'ytickLabel',[]);
-lambda.plot;
-

Estimate the PSTH with 500ms windows

figure;
-binsize = .5; %500ms window
-psth    = spikeColl.psth(binsize);
-psthGLM = spikeColl.psthGLM(binsize);
-true = lambda; %rate*delta = expected number of arrivals per bin
-h1=true.plot;
-h3=psthGLM.plot([],{{' ''k'',''Linewidth'',4'}});
-h2=psth.plot([],{{' ''rx'',''Linewidth'',4'}});
-legend off;
-legend([h1(1) h2(1)  h3(1)],'true','PSTH','PSTH_{glm}');
-
-% Because currently the psthGLM estimated the psth coefficients in each bin
-% for each realization, we want the show the mean and standard error of the
-% cofficient in each bin. We make the upper and lower confidence bounds
-% equal to 1/sqrt(numRealization)=1/sqrt(psth.dimension) to view the
-% standard error instead of the standard deviation
-
Running in batch mode: neurons with same name are fit simultaneously
-Analyzing Configuration #1: Neuron #1
-

Note the mean of the PSTH estimated via the GLM model and the PSTH computed via standard methods agree precisely. The benefit of the GLM estimated PSTH is the presence of confidence bounds on the estimate. Both the standard and GLM PSTH are in close agreement with the "true" underlying rate function (conditional intensity function) used in this simulated example. Both the PSTH and PSTHGLM code could be updated in the future to allow for variable bin sizes (e.g. in the vein of Baysian Adaptive Regression Splines by Wallstrom, Leibner and Kass). Alternatively, porting of BARS to Matlab may allow for it to be easily integrated into the nSTAT toolbox.

\ No newline at end of file diff --git a/helpfiles/PSTHEstimation.m b/helpfiles/PSTHEstimation.m deleted file mode 100644 index f9947f11..00000000 --- a/helpfiles/PSTHEstimation.m +++ /dev/null @@ -1,60 +0,0 @@ -%% PSTH Estimation -% We illustrate two ways to estimate a peristimulus time histogram using -% the nSTAT toolbox. One technique is the standard binning in time, -% averaging across trials, and dividing by the binwidth to estimate the -% spike rate and the other is based on the method presented in "Analysis of -% Between-Trial and Within-Trial Neural Spiking Dynamics" by Czanner et al -% in J Neurophysiology 2008. -% -% -%% 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. - -close all; -delta = 0.001; -Tmax = 10; -time = 0:delta:Tmax; -f=.2; -lambdaData = 10*sin(2*pi*f*time)+10; %lambda >=0 -lambda = Covariate(time,lambdaData, '\Lambda(t)','time','s','Hz',{'\lambda_{1}'},{{' ''b'', ''LineWidth'' ,2'}}); -numRealizations = 20; % Use 20 realization so that lamba and raster plot are the same size -spikeColl = CIF.simulateCIFByThinningFromLambda(lambda,numRealizations); -spikeColl.plot; set(gca,'ytickLabel',[]); -lambda.plot; - -%% Estimate the PSTH with 500ms windows -% - -figure; -binsize = .5; %500ms window -psth = spikeColl.psth(binsize); -psthGLM = spikeColl.psthGLM(binsize); -true = lambda; %rate*delta = expected number of arrivals per bin -h1=true.plot; -h3=psthGLM.plot([],{{' ''k'',''Linewidth'',4'}}); -h2=psth.plot([],{{' ''rx'',''Linewidth'',4'}}); -legend off; -legend([h1(1) h2(1) h3(1)],'true','PSTH','PSTH_{glm}'); - -% Because currently the psthGLM estimated the psth coefficients in each bin -% for each realization, we want the show the mean and standard error of the -% cofficient in each bin. We make the upper and lower confidence bounds -% equal to 1/sqrt(numRealization)=1/sqrt(psth.dimension) to view the -% standard error instead of the standard deviation - - -%% -% Note the mean of the PSTH estimated via the GLM model and the PSTH -% computed via standard methods agree precisely. The benefit of the GLM -% estimated PSTH is the presence of confidence bounds on the estimate. Both -% the standard and GLM PSTH are in close agreement with the "true" -% underlying rate function (conditional intensity function) used in this -% simulated example. Both the PSTH and PSTHGLM code could be updated in the -% future to allow for variable bin sizes (e.g. in the vein of Baysian Adaptive Regression -% Splines by Wallstrom, Leibner and Kass). Alternatively, porting of BARS -% to Matlab may allow for it to be easily integrated into the nSTAT -% toolbox. - - diff --git a/helpfiles/PSTHEstimation.png b/helpfiles/PSTHEstimation.png deleted file mode 100644 index 5c0d5757..00000000 Binary files a/helpfiles/PSTHEstimation.png and /dev/null differ diff --git a/helpfiles/PSTHEstimation_01.png b/helpfiles/PSTHEstimation_01.png deleted file mode 100644 index 0c4cff50..00000000 Binary files a/helpfiles/PSTHEstimation_01.png and /dev/null differ diff --git a/helpfiles/PSTHEstimation_02.png b/helpfiles/PSTHEstimation_02.png deleted file mode 100644 index e9acde65..00000000 Binary files a/helpfiles/PSTHEstimation_02.png and /dev/null differ diff --git a/helpfiles/SignalObj.html b/helpfiles/SignalObj.html deleted file mode 100644 index b78e6fc3..00000000 --- a/helpfiles/SignalObj.html +++ /dev/null @@ -1,2797 +0,0 @@ - - - - - - - - SignalObj - - - - -
classdef SignalObj < handle
-    %SignalObj Class representing a signal abstraction
-    %   SignalObj consist of data that is indexed by time (as a default). The
-    %   indexing variable can be any other type of data and the x-axis labels
-    %   modified to represent this change.
-    %
-    %   A SignalObj can be multivariate in that the data can have more than one component. The
-    %   sample rate of the SignalObj is determined by the time increment used
-    %   in the time sequence used when the SingalObj is created
-    %
-    %   Usage:
-    %   >> s=SignalObj(time, data, name, xlabelval, xunits, yunits, dataLabels, plotProps)
-    %
-    %   Only time and data need to be specified. Other arguments are optional.
-    %
-    %
-    %  time: indexing variable for the data. n x 1 or 1 x n array. The sample
-    %        rate is determined by the time increment between samples of this vector. Units of
-    %        [sec] are assumed, but need not be used. If the time vector is
-    %        in units of [sec], the sampleRate is in units of [Hz]. If the
-    %        time vector is in units of [msec] then the sampleRate is in
-    %        units of [1/msec] or 10^3 [Hz].
-    %
-    %  data: n x m or m x n array reprenting the signal at each index of the time vector.
-    %        The dimension that is compatible with the time vector will be automatically detected.
-    %        Thus a SignalObj can be created by either passing the data matrix or its transpose. The remaining
-    %        dimension will determine the dimensionality of the SignalObj.
-    %
-    %  name: string that determines the name of the signal. This is used to
-    %        label the y-axis of the SignalObj.
-    %
-    %  xlabelval: A string specifying the name of the indexing variable. If
-    %        this value is not specified, 'time' is used.
-    %
-    %  xunits: A string specifying the name of the units of the indexing
-    %          variable. In not specified, 'sec' is used.
-    %
-    %  yunits: A string specifying the units of the SignalObj. Used when plotting the SignalObj.
-    %
-    %  dataLabels: If data is multivariate, the names of the components of the SignalObj can be specified.
-    %              These can be used to reference specific data within the
-    %              signal (e.g. the x-component of a 3-d vector) and are
-    %              also used for plotting. SignalObj's will be created for
-    %              each component of the orignal SignalObj under the
-    %              vars field. Can be specified all at once or by a cell of
-    %              strings.
-    %
-    %  plotProps:  Can be specified for each component of the SignalObj
-    %              individually or by a cell of string of same dimension as the
-    %              number of components in the data.
-    %
-    %
-    %
-    % <a href="matlab:web(fullfile(strread(userpath,'%s','delimiter',';'),'Code Development','Signal','trunk','html','SignalObjExamples.html'))">SignalObj Examples</a>
-
-
-    properties (SetAccess = private)
-        name       % name of the SignalObj
-        time       % time vector
-        data       % actual SignalObj data
-        dimension  % number of different components of the SignalObj
-        minTime    % minimum Time value of the SignalObj
-        maxTime    % maximum Time value of the SignalObj
-        xlabelval  % label to use for the x-axis
-        xunits     % units for x-axis
-        yunits     % units for y-axis data
-        dataLabels % labels for each dimension of the data;
-        dataMask   % vector same length as SignalObj dimension. a 1 indicates this SignalObj should be output a 0 otherwie
-        sampleRate % Hz if time is in seconds
-        plotProps  % Plotting properties
-    end
-    properties (Hidden)
-        origSampleRate
-        originalTime %original timeVector
-        originalData %original Data
-    end
-    properties (Dependent = true)
-        vars %Contains subfields of the same names as the dataLabels that contain Signals with only the data corresponding to that label.
-    end
-    methods
-        %Constructor
-        function s=SignalObj(time, data, name, xlabelval, xunits, yunits, dataLabels, plotProps)
-
-            if(nargin<6)
-                yunits='';
-            end
-            if(nargin<5)
-                xunits='s';
-            end
-            if(nargin<4)
-                xlabelval='time';
-            end
-            if(nargin<3)
-                name='';
-            end
-            [l,w]=size(time);
-            if(l>=w);
-                if(w>1)
-                    error('Time vector can only have one dimension');
-                else
-                    s.time=time;
-
-                end
-            elseif(l<=w)
-                if(l>1)
-                    error('Time vector can only have one dimension');
-                else
-                    s.time=time';
-                end
-            end
-            s.originalTime=s.time;
-            [l,w]=size(data);
-           if(l==length(s.time));
-                s.data=data;
-                s.dimension =w;
-            elseif(w==length(s.time));
-                s.data=data';
-                s.dimension=l;
-           else
-               error('Data dimensions do not match the time vector specified');
-           end
-           s.originalData = s.data;
-            if(nargin <7)
-                for i=1:s.dimension
-                    dataLabels{i} = '';
-                end
-            end
-            s.dataMask  = ones(1,s.dimension);
-            if(nargin<8)
-                plotProps = cell(s.dimension,1);
-            end
-            s.sampleRate = 1/mean(diff(s.time));
-            s.origSampleRate = s.sampleRate;
-            s.name=name;
-            s.xlabelval=xlabelval;
-            s.xunits=xunits;
-            s.yunits=yunits;
-            s.minTime=min(s.time);
-            s.maxTime=max(s.time);
-            s.setPlotProps(plotProps);
-            s.setDataLabels(dataLabels);
-        end
-
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        %Set functions
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        function setName(sObj,name) %set the name after construction
-            if(isa(name,'char'))
-                sObj.name = name;
-            else
-                error('Name must be a string!');
-            end
-        end
-        function setXlabel(sObj,name)
-            sObj.xlabelval = name;
-        end
-        function setYLabel(sObj,name)
-            sObj.setName(name);
-        end
-        function setUnits(sObj, xUnits, yUnits)
-            if(nargin==3)
-                if(isa(yUnits,'char'))
-                    sObj.setYunits(yUnits);
-                end
-            end
-            if(nargin>=2)
-                if(isa(xUnits,'char'))
-                    sObj.setXunits(xUnits);
-                end
-            end
-        end
-        function setXUnits(sObj, units)
-            if(isa(units, 'char'))
-                sObj.xunits = units;
-            end
-        end
-        function setYUnits(sObj, units)
-            if(isa(units,'char'))
-                sObj.yunits = units;
-            end
-        end
-        function setSampleRate(sObj, sampleRate)
-%             sampleRate
-%             sObj.sampleRate
-%             ~(sampleRate==sObj.sampleRate)
-            if(~(floor(sampleRate*100)/100==floor(sObj.sampleRate*100)/100)) %Compare to 2 decimal places (finite precision has caused errors 500.000001 ~= 500.00000x
-                if(sampleRate>sObj.sampleRate)
-                    %fprintf(strcat('SignalObj,',sObj.name',', upsampled to:',num2str(sampleRate)));
-                else
-                    %fprintf(strcat('SignalObj,',sObj.name',', downsampled to:',num2str(sampleRate)));
-                end
-                sObj.resampleMe(sampleRate);
-            end
-        end
-        function setDataLabels(sObj,dataLabels)
-            if(isa(dataLabels,'char'))
-                if(sObj.dimension==1)
-                    sObj.dataLabels{1}=dataLabels;
-                else
-                    error('Adding single dataLabel to a SignalObj with more that 1 dimension');
-                end
-
-            elseif(isa(dataLabels,'cell'))
-                if(length(dataLabels)==sObj.dimension)
-                    ind=sObj.findIndFromDataMask;
-                    for i=ind
-                        sObj.dataLabels{i} = dataLabels{i};
-                    end
-                else
-                    error('Need the number of labels to match the number of dimensions of the SignalObj');
-                end
-            end
-        end
-        function setMinTime(sObj,minTime,holdVals)
-            if(nargin<3)
-                holdVals=0;
-            end
-
-            if(nargin<2)
-                minTime=sObj.time(1);
-            end
-            timeVec=sObj.getTime;
-            if(minTime<min(timeVec))
-                maxTime=max(timeVec);
-                newTime=minTime:1/sObj.sampleRate:maxTime;
-                numSamples = length(newTime)-length(timeVec);
-                if(holdVals==1)
-                    newData=[ones(numSamples,1)*sObj.data(1,:);sObj.data];
-                else
-                    newData=[zeros(numSamples,sObj.dimension);sObj.data];
-                end
-                sObj.data=newData;
-                sObj.time=newTime;
-                sObj.minTime=min(sObj.time);
-            elseif(min(timeVec)==minTime)
-                    %do nothing
-            else
-                startIndex = sObj.findNearestTimeIndex(minTime);
-                sObj.time=sObj.time(startIndex:end);
-                sObj.data=sObj.data(startIndex:end,:);
-            end
-            sObj.minTime=min(sObj.time);
-        end
-        function setMaxTime(sObj,maxTime, holdVals)
-            if(nargin<3)
-                holdVals=0;
-            end
-
-            if(nargin<2)
-                maxTime=sObj.time(end);
-            end
-            timeVec=sObj.getTime;
-            if(max(timeVec)<maxTime)
-                minTime=min(timeVec);
-                newTime=minTime:1/sObj.sampleRate:maxTime;
-                numSamples = length(newTime)-length(timeVec);
-                if(holdVals==1)
-                    newData=[sObj.data;ones(numSamples,1)*sObj.data(end,:)];
-                else
-                    newData=[sObj.data;zeros(numSamples,sObj.dimension)];
-                end
-
-                sObj.data=newData;
-                sObj.time=newTime;
-                sPnj.maxTime=max(sObj.time);
-            elseif(max(timeVec)==maxTime)
-                    %do nothing
-
-            else
-                endIndex = sObj.findNearestTimeIndex(maxTime);
-                sObj.time=sObj.time(1:endIndex);
-                sObj.data=sObj.data(1:endIndex,:);
-            end
-            sObj.maxTime=max(sObj.time);
-        end
-        function setPlotProps(sObj, plotProps,index)
-            if(nargin<=2)
-                if(isa(plotProps,'cell'))
-                    if(length(plotProps) == sObj.dimension)
-                        for i=1:sObj.dimension
-                            sObj.plotProps{i} = cell2str(plotProps{i});
-                        end
-                    elseif(length(plotProps)==1)
-                        for i=1:sObj.dimension
-                            sObj.plotProps{i} = cell2str(plotProps);
-                            display('Index not specified. All dimensions set to have same plotting properties');
-                        end
-                    else
-                        error('Index not specified and more than 1 plotProp specified. Need to number of plotProps same as sObj.dimension or length 1');
-                    end
-                elseif(isa(plotProps,'char'))
-                     for i=1:sObj.dimension
-                        sObj.plotProps{i} = cell2str(plotProps);
-                     end
-                     display('All dimensions set to have same plotting properties')
-                end
-
-            else
-                if(isa(plotProps,'cell') && length(plotProps)==1)
-                    if(index>0 && index<=sObj.dimension)
-                        sObj.plotProps{index} = plotProps{:};
-                    else
-                        error('Index out of bounds during setPlotProps');
-                    end
-                elseif(isa(plotProps,'char'))
-                     if(index>0 && index<=sObj.dimension)
-                        sObj.plotProps{index} = plotProps;
-                    else
-                        error('Index out of bounds during setPlotProps');
-                    end
-
-                end
-            end
-        end
-        function setMask(sObj, mask)
-            if(nargin<2)
-                mask=zeros(1,sObj.dimension);
-                sObj.setDataMask(mask);
-                return;
-            end
-            %mask is either a set of indices or names;
-            if(isa(mask,'cell'))
-                if(isa(mask{1},'char'))
-                    sObj.setMaskByLabels(mask);
-                else
-                    error('Mask cells must contains strings!');
-                end
-            elseif(isa(mask,'double'))
-                sObj.setMaskByInd(mask);
-            else
-                error('Can only set datamask with strings or indices')
-            end
-        end
-        function setDataMask(sObj, dataMask)
-        %DataMasks affect how the SignalObj is visualized and converted to
-        %other representations. It doesnt change the dimensions of the
-        %object, nor does it delete data.
-            if(length(dataMask)==sObj.dimension)
-                  sObj.dataMask = dataMask;
-            end
-
-        end
-        function setMaskByInd(sObj,index)
-            if(length(index)==sObj.dimension)
-                sObj.setDataMask(index);
-            else
-                mask=zeros(1,sObj.dimension);
-                mask(index)=1;
-                sObj.setDataMask(mask);
-            end
-        end
-        function setMaskByLabels(sObj,labels)
-            ind=sObj.getIndicesFromLabels(labels);
-            mask=zeros(1,sObj.dimension);
-            mask(ind)=1;
-            sObj.setDataMask(mask);
-        end
-
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        function tVec       = getTime(sObj)
-            tVec=sObj.time;
-        end
-        function data       = getData(sObj)
-            data=sObj.dataToMatrix;
-        end
-        function [t,d]      = getOriginalData(sObj)
-            t=sObj.originalTime;
-            d=sObj.originalData;
-        end
-        function s          = getOrigDataSig(sObj)
-                [time,data]=sObj.getOriginalData;
-                name=sObj.name;
-                xlabelval=sObj.xlabelval;
-                xunits=sObj.xunits;
-                yunits=sObj.yunits;
-                dataLabels=sObj.dataLabels;
-                plotProps=sObj.plotProps;
-                s = SignalObj(time, data,name, xlabelval, xunits, yunits,dataLabels,plotProps);
-        end
-        function index      = getIndexFromLabel(sObj,label)
-            index=[];
-            for i=1:length(sObj.dataLabels)
-                if(strcmp(label, sObj.dataLabels{i}))
-                    index = [index i];
-                end
-            end
-        end
-        function indices    = getIndicesFromLabels(sObj,label)
-            %Returns a cell array if the label appears for various point
-            %int the SignalObj
-            %Returns an array if the SignalObj label appears only once in the
-            %SignalObj
-            if(isa(label,'cell'))
-                indices =cell(1,length(label));
-                numInd  =zeros(1,length(label));
-                for i=1:length(label)
-                    tempInd = sObj.getIndexFromLabel(label{i});
-                    if(~isempty(tempInd))
-                        numInd(i) = length(tempInd);
-                        indices{i}=tempInd;
-                    else
-                        error('Label does not exist!');
-                    end
-
-                end
-            elseif(isa(label,'char'))
-                indices = getIndexFromLabel(label);
-                numInd = length(indices);
-            end
-            if(max(numInd)==1)      %For backwards compatibility if assuming only on index per label
-                for i=1:length(label)
-                    tempInd(i) = indices{i};
-                end
-                indices = tempInd;
-            end
-        end
-        function val        = getValueAt(sObj,x)
-            ind=sObj.findNearestTimeIndex(x);
-            val=sObj.data(ind,:);
-        end
-        function PropsStr   = getPlotProps(sObj,index)
-            if(index>0 && index<=sObj.dimension)
-                PropsStr = cell2str(sObj.plotProps{index});
-            else
-                error('index is out of bounds!');
-            end
-        end
-
-
-
-
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        % Operand Definitions and other mathematical operations
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        function s3 = plus(s1,s2)
-            if(isa(s1,'SignalObj') && isa(s2,'SignalObj'))
-                % What is s2 is a constant or double?
-                if(s1.dimension == s2.dimension)
-                    [s1c,s2c] = makeCompatible(s1,s2);
-                    s3=s1c.copySignal;
-                    s3.data = s1c.data+s2c.data;
-
-                    for i=1:length(s3.dataLabels)
-                        if(strcmp(s2c.dataLabels{i}(1),'-'))
-                            s3.dataLabels{i} = [s1c.dataLabels{i} '-' s2c.dataLabels{i}(2:end)];
-                        else
-                            s3.dataLabels{i} = [s1c.dataLabels{i} '+' s2c.dataLabels{i}];
-                        end
-                    end
-                else
-                    error('Can only add signals if they have the same dimension');
-                end
-            elseif(isa(s1,'double') || isa(s2,'double'))
-                if(isa(s1,'double'))
-                  s3=s2.copySignal;
-                  [l,w] = size(s1);
-                  if(w==s3.dimension && l==1)
-                      s3.data = s3.data+ones(length(s3.data),1)*s1;
-                      for i=1:length(s3.dataLabels)
-                            if(sign(s1(i))==-1)
-                                s3.dataLabels{i} = [s2.dataLabels{i} '-' num2str(abs(s1(i)))];
-                            else
-                                s3.dataLabels{i} = [s2.dataLabels{i} '+' num2str(abs(s1(i)))];
-                            end
-                      end
-                  else
-                      s3.data = s3.data+s1;
-                      %dont modify dataLabels since s1 is a matrix;
-
-                      %for i=1:length(s3.dataLabels)
-                      %      s3.dataLabels{i} = [s2.dataLabels{i} '+' num2str(s1(i))];
-                      %end
-                  end
-                else
-                  s3=s1.copySignal;
-                  [l,w] = size(s2);
-                  %size(s3.data)
-                  if(w==s3.dimension && l==1)
-                      s3.data = s3.data+ones(length(s3.data),1)*s2;
-                      for i=1:length(s3.dataLabels)
-                            if(sign(s2(i))==-1)
-                                s3.dataLabels{i} = [s1.dataLabels{i} '-' num2str(abs(s2(i)))];
-                            else
-                                s3.dataLabels{i} = [s1.dataLabels{i} '+' num2str(abs(s2(i)))];
-                            end
-                      end
-                  else
-
-                      s3.data = s3.data+s2;
-                      %dont modify dataLabels since s2 is a matrix;
-                      %for i=1:length(s3.dataLabels)
-                      %      s3.dataLabels{i} = [s1.dataLabels{i} '+' num2str(s2)];
-                      %end
-                  end
-                end
-            else
-                error('only Signals or doubles are currently supported');
-            end
-        end
-        function s3 = minus(s1,s2)
-            s3=plus(s1,-s2);
-        end
-        function s3 = uplus(s1) %+s1
-            s3=s1.copySignal;
-        end
-        function s3 = uminus(s1) %-s1
-
-            s3=s1.copySignal;
-            s3.data=-s3.data;
-            for i=1:length(s3.dataLabels)
-                s3.dataLabels{i} = strcat('-',s1.dataLabels{i});
-            end
-        end
-        function s3 = times(s1,s2) %s1.*s2
-            if(isa(s1,'SignalObj') && isa(s2,'SignalObj'))
-               if(s1.dimension == s2.dimension)
-                   [s1c,s2c] = makeCompatible(s1,s2);
-                   s3 = s1c;
-                   s3.data = s1c.data.*s2c.data;
-                   %can multiply units
-               else
-                   error('can only multiply signals with same dimension');
-               end
-            elseif(isa(s1,'double') || isa(s2,'double'))
-                if(isa(s1,'double'))
-                  s3=s2.copySignal;
-                  [l,w] = size(s1);
-                  if(w==s3.dimension && l==1)
-                      s3.data = s3.data.*(ones(length(s3.data),1)*s1);
-                  else
-                      s3.data = s3.data.*s1;
-                  end
-                else
-                  s3=s1.copySignal;
-                  [l,w] = size(s2);
-                  if(w==s3.dimension && l==1)
-                      s3.data = s3.data.*(ones(length(s3.data),1)*s2);
-                  else
-                      s3.data = s3.data.*s2;
-                  end
-                end
-            end
-        end
-        function s3 = mtimes(s1,s2) %s1*s2
-            if(isa(s1,'SignalObj') && isa(s2,'SignalObj'))
-                   %[s1c,s2c] = makeCompatible(s1,s2);
-                   s3 = s1.copySignal;
-                   s3.data = s1.data.*s2.data;
-                   %can multiply units
-           elseif(isa(s1,'double') || isa(s2,'double'))
-                if(isa(s1,'double'))
-                  s3=s2.copySignal;
-                  s3.data = (s1*s3.data')';
-                else
-                  s3=s1.copySignal;
-                  s3.data = (s3.data'*s2)';
-                end
-            end
-        end
-        function s3 = rdivide(s1,s2)
-            if(isa(s1,'SignalObj') && isa(s2,'SignalObj'))
-               if(s1.dimension == s2.dimension)
-                   [s1c,s2c] = makeCompatible(s1,s2);
-                   s3 = s1c;
-                   s3.data = s1c.data./s2c.data;
-                   %can multiply units
-               else
-                   error('can only multiply signals with same dimension');
-               end
-            elseif(isa(s1,'double') || isa(s2,'double'))
-                if(isa(s1,'double'))
-                  s3=s2.copySignal;
-                  s3.data = s1./s3.data;
-                else
-                  s3=s1.copySignal;
-                  s3.data = s3.data./s2;
-                end
-            end
-        end
-        function s3 = ldivide(s1,s2)
-            if(isa(s1,'SignalObj') && isa(s2,'SignalObj'))
-               if(s1.dimension == s2.dimension)
-                   [s1c,s2c] = makeCompatible(s1,s2);
-                   s3 = s1c;
-                   s3.data = s1c.data.\s2c.data;
-                   %can multiply units
-               else
-                   error('can only multiply signals with same dimension');
-               end
-            elseif(isa(s1,'double') || isa(s2,'double'))
-                if(isa(s1,'double'))
-                  s3=s2.copySignal;
-                  s3.data = s1.\s3.data;
-                else
-                  s3=s1.copySignal;
-                  s3.data = s3.data.\s2;
-                end
-            end
-        end
-        function s3 = ctranspose(s1)
-            s3=s1.copySignal;
-            s3.data=s3.data.';
-            [l,w]=size(s3.data);
-            s3.dimension=w;
-        end
-        function s3 = transpose(s1)
-            s3=s1.copySignal;
-            s3.data=s3.data.';
-            [l,w]=size(s3.data);
-            s3.dimension=w;
-        end
-        function s3 = derivative(sObj)
-%             B=[1 -1]*sObj.sampleRate;
-%             A=1;
-%             s3=sObj.filter(B,A);
-            s3=sObj.copySignal;
-            tData=diff(s3.data)*s3.sampleRate;
-            tData=[zeros(1,s3.dimension); tData];
-            s3.data=tData;
-
-            s3.setYUnits(strcat('\frac{',s3.yunits,'}{',s3.xunits,'}'));
-            denomstr = strcat('d', s3.xlabelval(1));
-
-            s3.setName(strcat('\frac{d}{',denomstr,'}',s3.name));
-            for i=1:s3.dimension
-                if(~strcmp(sObj.dataLabels{i},''))
-                    s3.dataLabels{i}= strcat('\frac{d}{',denomstr,'}',s3.dataLabels{i});
-                end
-            end
-        end
-        function val = derivativeAt(sObj,x0)
-            sTemp = sObj.derivative;
-            val = sTemp.getValueAt(x0);
-        end
-        function s3 = integral(sObj,t0,tf)
-            if(nargin<3)
-                tf=sObj.maxTime;
-            end
-            if(nargin<2)
-                t0=sObj.minTime;
-            end
-
-            %y[n] = y[n-1] + x[n]*deltaT
-            B=1*1/sObj.sampleRate;
-            A=[1 -1];
-            s3=sObj.getSigInTimeWindow(t0,tf);
-            s3=s3.filter(B,A);
-            s3.setYUnits(strcat(s3.yunits,'*',s3.xunits));
-            dtstr = strcat(' d','\tau');
-            s3.setName(['\int_',num2str(s3.minTime),'^',s3.xlabelval(1),'\!\!{',[s3.name dtstr],'}']);
-            for i=1:s3.dimension
-                if(~strcmp(sObj.dataLabels{i},''))
-                    s3.dataLabels{i}= ['\int_',num2str(s3.minTime),'^',s3.xlabelval(1),'\!\!{',[s3.dataLabels{i} dtstr],'}'];
-                end
-            end
-        end
-        function s3 = filter(sObj, B,A)
-            s3=sObj.copySignal;
-            s3.data = filter(B,A,s3.data);
-        end
-        function s3 = filtfilt(sObj,B,A)
-            s3=sObj.copySignal;
-            s3.data = filtfilt(B,A,s3.data);
-        end
-        function [s1c,s2c] = makeCompatible(s1,s2,holdVals)
-            if(nargin<3)
-                holdVals=0;
-            end
-            s1c = s1.copySignal; s2c = s2.copySignal;
-            minTime=min(s1c.minTime,s2c.minTime);
-            maxTime=max(s1c.maxTime,s2c.maxTime);
-            sampleRate=max(s1c.sampleRate,s2c.sampleRate);
-            s1c.setSampleRate(sampleRate); s2c.setSampleRate(sampleRate);
-            s1c.setMinTime(minTime,holdVals);       s2c.setMinTime(minTime,holdVals);
-            s1c.setMaxTime(maxTime,holdVals);       s2c.setMaxTime(maxTime,holdVals);
-
-            %pause
-%             for i=1:s2c.dimension
-             data = spline(s2c.time,s2c.data',s1c.time);
-%             end
-             s2c.time = s1c.time;
-             [nrows,ncolumns] = size(data);
-             if(nrows>ncolumns)
-                s2c.data = data;
-             else
-                s2c.data = data';
-             end
-        end
-        function m=mean(sObj,varargin)
-            mdata=mean(sObj.data,varargin{:});
-            [nrows,ncolumns]=size(mdata);
-            if( (nrows==length(sObj.time)) && (ncolumns==1) ) %mean across dimensions
-                m=SignalObj(sObj.time, mdata, ['Mean of ' sObj.name],sObj.xlabelval, sObj.xunits,sObj.yunits);
-            elseif( (nrows==1) && (ncolumns == sObj.dimension) )  %mean of each dimension
-                if(~sObj.areDataLabelsEmpty)
-                    dataLabels = cell(size(sObj.dataLabels));
-                    for i=1:sObj.dimension
-                        dataLabels{i} = strcat('\mu(',sObj.dataLabels{i},')');
-                    end
-                     m=SignalObj([sObj.time(1); sObj.time(end)], [mdata;mdata], ['Mean of ' sObj.name],sObj.xlabelval, sObj.xunits,sObj.yunits,dataLabels);
-                else
-                    m=SignalObj([sObj.time(1); sObj.time(end)], [mdata;mdata],  ['Mean of ' sObj.name],sObj.xlabelval, sObj.xunits,sObj.yunits);
-                end
-            end
-        end
-        function m=max(sObj,varargin)
-            m=max(sObj.data,varargin{:});
-        end
-        function m=min(sObj,varargin)
-            m=min(sObj.data,varargin{:});
-        end
-        function periodogram = periodogram(sObj)
-            fs = sObj.sampleRate;  % Sampling frequency
-            periodogram = cell(1,sObj.dimension);
-            for i=1:sObj.dimension
-                xn = sObj.data(:,i);
-                Hs = spectrum.periodogram('rectangular');
-                switch sObj.dimension
-                    case 2
-                        subplot(1,2,i)
-                    case 3
-                        subplot(1,3,i)
-                    case 4
-                        subplot(2,2,i)
-                    case 5
-                        subplot(3,2,i)
-                    case 6
-                        subplot(3,2,i)
-                    otherwise
-                         h=gcf;figure(h);
-                end
-                periodogram{i}=psd(Hs,xn,'Fs',fs,'NFFT',1024);
-                h=periodogram{i}.plot;legend(h, sObj.dataLabels{i});
-            end
-        end
-        function mtmSpec = MTMspectrum(sObj,NW,NFFT,Pval)
-            if(nargin<4)
-                Pval=.95;
-            end
-            if(nargin<3)
-                NFFT=[];
-            end
-            if(nargin<2)
-                NW=4;
-            end
-
-            Fs=sObj.sampleRate;
-            mtmSpec = cell(1,sObj.dimension);
-            for i=1:sObj.dimension
-                xn=sObj.data(:,i);
-                [Pxx,Pxxc,f] = pmtm(xn,NW,NFFT,Fs,Pval);
-                hpsd = dspdata.psd([Pxx Pxxc],'Fs',Fs);
-                mtmSpec{i} = hpsd;
-                switch sObj.dimension
-                    case 2
-                        subplot(1,2,i)
-                    case 3
-                        subplot(1,3,i)
-                    case 4
-                        subplot(2,2,i)
-                    case 5
-                        subplot(3,2,i)
-                    case 6
-                        subplot(3,2,i)
-                    otherwise
-                         h=gcf;figure(h);
-                end
-                str1=strcat(num2str(Pval*100), '% Conf. Int.');
-                h=plot(hpsd); legend(h, sObj.dataLabels{i},strcat('-',str1),strcat('+',str1));
-            end
-        end
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        %Utility Functions
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        function mergedSig = merge(sObj,varargin)
-            numToMerge=0;
-            holdVals=0;
-            for i=1:length(varargin)
-                if(isa(varargin{i},'SignalObj'))
-                    numToMerge = numToMerge+1;
-                end
-                if(isa(varargin{i},'double')&&i==length(varargin)) %expect only one double at the end
-                    holdVals = varargin{i};
-                end
-            end
-
-            if(numToMerge == 1)
-                [s1c, s2c] = sObj.makeCompatible(varargin{1},holdVals);
-                 data=[s1c.dataToMatrix, s2c.dataToMatrix];
-                 dataLabels = cell(s1c.dimension+s2c.dimension,1);
-                 for i=1:s1c.dimension
-                        dataLabels{i} = s1c.dataLabels{i};
-                 end
-                 for i=1:s2c.dimension
-                        dataLabels{s1c.dimension+i}=s2c.dataLabels{i};
-                 end
-                 name = [s1c.name, ',', s2c.name];
-                 mergedSig = SignalObj(s1c.time, data, name, s1c.xlabelval,s1c.xunits, s1c.yunits, dataLabels);
-            else
-                  mergedSig = sObj.merge(varargin{1},holdVals);
-                  for i=2:numToMerge
-                        mergedSig = mergedSig.merge(varargin{i},holdVals);
-                  end
-            end
-        end
-        function sigOut=copySignal(sigIn)
-                time=sigIn.time;
-                data=sigIn.data;
-                name=sigIn.name;
-                xlabelval=sigIn.xlabelval;
-                xunits=sigIn.xunits;
-                yunits=sigIn.yunits;
-                dataLabels=sigIn.dataLabels;
-                plotProps=sigIn.plotProps;
-                sigOut = SignalObj(time, data,name, xlabelval, xunits, yunits,dataLabels,plotProps);
-                sigOut.dataMask = sigIn.dataMask;
-        end
-        function sObjOut=resample(sObj, newSampleRate)
-            sObjOut = sObj.copySignal;
-            sObjOut.resampleMe(newSampleRate);
-        end
-        function resampleMe(sObj, newSampleRate)
-            sObj.restoreToOriginal; %use default data for changing samplerate
-            %Change the sampling rate of this object
-            minTime=sObj.minTime;
-            maxTime=sObj.maxTime;
-            newTime=minTime:1/newSampleRate:maxTime;
-            newData=zeros(length(newTime),sObj.dimension);
-            for i=1:sObj.dimension
-                newData(:,i)= spline(sObj.time,sObj.data(:,i),newTime);
-            end
-                sObj.time=newTime;
-                sObj.data=newData;
-                sObj.sampleRate=newSampleRate;
-        end
-        function restoreToOriginal(sObj,rMask)
-            if(nargin<2)
-              rMask = 0; %keep mask even when data reset
-            end
-             [time,data]=sObj.getOriginalData;
-             sObj.time=time;
-             sObj.data=data;
-             sObj.minTime=min(time);
-             sObj.maxTime=max(time);
-             sObj.sampleRate = 1/mean(diff(time));
-             if(rMask==1)
-                 sObj.resetMask;
-             end
-        end
-        function resetMask(sObj)
-            sObj.dataMask = ones(1,sObj.dimension);
-        end
-        function ind = findIndFromDataMask(sObj)
-            ind = find(sObj.dataMask ==1);
-%             if(isempty(ind))
-%                 error('All data masked out of SignalObj');
-%             end
-        end
-        function ind=findNearestTimeIndex(sObj, time)
-            if(time<sObj.minTime)
-                ind=1;
-            elseif(time>sObj.maxTime)
-                ind=length(sObj.time);
-            else
-                ind1=find(sObj.time>=time,1,'first');
-                ind2=find(sObj.time<=time,1,'last');
-                if(abs(sObj.time(ind1)-time)<=abs(sObj.time(ind2)-time))
-                    ind=ind1;
-                else
-                    ind=ind2;
-                end
-%                 if(time-sObj.minTime < sObj.maxTime-time) %Time is close to beginning
-%                     ind=min([ind1, ind2]);
-%                 else
-%                     ind=max([ind1, ind2]);
-%                 end
-            end
-        end
-        function sOut = shift(sObj, deltaT)
-
-            %returns s shift by deltaT. If deltaT is positive
-            %the SignalObj is moved deltaT time steps forward
-            %if deltaT is negative, the SignalObj is moved deltaT units
-            %backwards.
-            %compute number of samples delayed
-            sOut=sObj.copySignal;
-            newMinTime = sOut.minTime+deltaT;
-            newMaxTime = sOut.maxTime+deltaT;
-            newTime=newMinTime:1/sOut.sampleRate:newMaxTime;
-            sOut.time = newTime;
-            sOut.minTime = newMinTime;
-            sOut.maxTime = newMaxTime;
-        end
-        function shiftMe(sObj,deltaT)
-            sTemp = sObj.shift(deltaT);
-            sObj.data=sTemp.data;
-            sObj.time=sTemp.time;
-        end
-        function alignTime(sObj, timeMarker,newTime)
-            if(sObj.minTime<=timeMarker && sObj.maxTime>=timeMarker)
-                deltaT=newTime-timeMarker;
-                sObj.shiftMe(deltaT);
-            end
-        end
-        function answer = plotPropsSet(sObj)
-            answer =0;
-            for i=1:sObj.dimension
-                if(~strcmp(sObj.getPlotProps(i),''))
-                    answer=1;
-                    break;
-                end
-            end
-        end
-        function answer = areDataLabelsEmpty(sObj)
-            answer = 1;
-            for i=1:length(sObj.dataLabels);
-                if(~strcmp(sObj.dataLabels{i},''))
-                    answer = 0;
-                    break;
-                end
-            end
-        end
-        function answer = isLabelPresent(sObj, label)
-            if(isa(label,'char'))
-                if(strcmp(label,'all')||~isempty(sObj.getIndexFromLabel(label)))
-                    answer=1;
-                else
-                    answer=0;
-                end
-            else
-                error('Labels must be a char');
-            end
-        end
-        function answer = isMaskSet(sObj)
-            answer=~isempty(sObj.dataMask==0);
-        end
-        function sArray = convertNamesToIndices(sObj, selectorArray)
-            if(sObj.areDataLabelsEmpty)
-                sArray = 1:sObj.dimension; % Return all the data;
-                fprintf('tried to find data by labels but data doesnot have labels assigned');
-            else
-                if(isa(selectorArray, 'char'))
-                    if(strcmp(selectorArray,'all'))
-                        sArray=1:sObj.dimension;
-                    elseif(sObj.isLabelPresent(selectorArray))
-                        sArray=sObj.getIndexFromLabel(selectorArray);
-                    else
-                        error('Specified label does not match data label');
-                    end
-
-                elseif(isa(selectorArray, 'double'))
-                    sArray=selectorArray;
-                elseif(isa(selectorArray, 'cell'))
-                    sArray = zeros(1, length(selectorArray));
-                    for i=1:length(sArray)
-                        if(sObj.isLabelPresent(selectorArray{i}))
-                            sArray(i) = sObj.getIndexFromLabel(selectorArray{i});
-                        end
-                    end
-                else
-                    error('selectorArray cells must contain text');
-                end
-            end
-        end
-        function [indices, values] = findPeaks(sObj,type)
-            if(nargin<2)
-                type='maxima';
-            end
-            values=cell(1,sObj.dimension);
-            indices=cell(1,sObj.dimension);
-            if(strcmp(type,'maxima'))
-                for i=1:w
-                    [values{i},indices{i}] = findPeaks(sObj.data(:,i));
-                end
-            elseif(strcmp(type,'minima'))
-                for i=1:w
-                    [values{i},indices{i}] = findPeaks(sObj.data(:,i));
-                end
-            end
-        end
-        function [indices, values] = findMaxima(sObj)
-            [indices,values]=sObj.findPeaks('maxima');
-        end
-        function [indices, values] = findMinima(sObj)
-            [indices,times,values]= sObj.findPeaks('minima');
-        end
-        function clearPlotProps(sObj,index)
-            if(nargin<2)
-                index=1:sObj.dimension;
-            end
-            tempCell = cell(length(index),1);
-            for i=index
-                sObj.plotProps{i} = cell2str(tempCell{i});
-            end
-
-        end
-        function v=get.vars(sObj)
-            if(~sObj.areDataLabelsEmpty)
-                UniqueSigLabels = unique(sObj.dataLabels);
-
-                for i=1:length(UniqueSigLabels)
-                    eval(strcat('v.(''',UniqueSigLabels{i},''')=sObj.getSubSignal(''',UniqueSigLabels{i},''');'));
-                end
-            %sObj.vars=v;
-            else
-                for i=1:sObj.dimension
-
-                    eval(strcat('v.(''',sObj.dataLabels{i},''')=sObj.getSubSignal(i);'))
-                end
-            end
-        end
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        %Change of Representation Functions
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        function structure=dataToStructure(sObj,selectorArray)
-            if(nargin<2)
-                if(sObj.isMaskSet)
-                    selectorArray=sObj.findIndFromDataMask;
-                else
-                    selectorArray=1:sObj.dimension;
-                end
-            end
-            %Convert to a standard matlab structure
-            structure.time=sObj.time;
-            structure.signals.values=sObj.dataToMatrix(selectorArray);
-        end
-        function dataMat=dataToMatrix(sObj,selectorArray)
-            if(nargin<2)
-                if(sObj.isMaskSet)
-                    selectorArray=sObj.findIndFromDataMask;
-                else
-                    selectorArray=1:sObj.dimension;
-                end
-            end
-            % Convert data to a standard matrix.
-            % The matrix is length(times)x dimension
-            dataMat=sObj.data(:,selectorArray);
-        end
-        function sOut = getSubSignal(sObj,identifier)
-            if(isa(identifier,'cell'))
-                if(isa(identifier{1},'char'))
-                    sOut = sObj.getSubSignalFromNames(identifier);
-                elseif(isa(identifier{1},'double'))
-                    sOut = sObj.getSubSignalFromInd(identifier);
-                else
-                    error('Cells must contain strings!');
-                end
-            elseif(isa(identifier,'double'))
-                sOut = sObj.getSubSignalFromInd(identifier);
-            end
-        end
-        function wSignal = getSigInTimeWindow(sObj,wMin,wMax)
-            wSignal = sObj.copySignal;
-            if(wMin<wSignal.minTime)
-                %if the window starts before the SignalObj pad with zeros
-                %and set as new starttime
-                wSignal.setMinTime(wMin);
-            end
-            if(wMax>wSignal.maxTime)
-                %if wMax is too big, pad with zeros at end and set as new
-                %end
-                wSignal.setMaxTime(wMax);
-            end
-
-            startIndex= wSignal.findNearestTimeIndex(wMin);
-            endIndex  = wSignal.findNearestTimeIndex(wMax);
-            wSignal.time=wSignal.time(startIndex:endIndex); wSignal.data=wSignal.data(startIndex:endIndex,:);
-            wSignal.setMinTime;
-            wSignal.setMaxTime;
-        end
-        function sOut = getSubSignalFromInd(sObj, selectorArray)
-            if(nargin<2)
-                if(sObj.isDataMaskSet)
-                    selectorArray=sObj.findIndFromDataMask;
-                else
-                    selectorArray=1:sObj.dimension;
-                end
-            end
-            s3   = sObj.copySignal;
-            time = s3.time;
-            if(isa(selectorArray,'cell'))
-                data=[];
-               for i=1:length(selectorArray)
-                   offset=0;
-                   data = [data s3.data(:,selectorArray{i})];
-                   for j=1:length(selectorArray{i})
-                        dataLabels{offset + j} = s3.dataLabels{selectorArray{i}(j)};
-                        if(~isempty(s3.plotProps))
-                            plotProps{offset+ j} = s3.plotProps{selectorArray{i}(j)};
-                        end
-                   end
-                   offset = offset + length(selectorArray{i});
-               end
-            else
-                data = s3.data(:,selectorArray);
-                dataLabels = cell(1,length(selectorArray));
-                plotProps  = [];
-                for i=1:length(selectorArray)
-                    dataLabels{i}= s3.dataLabels{selectorArray(i)};
-                    if(~isempty(s3.plotProps))
-                        plotProps{i} = s3.plotProps{selectorArray(i)};
-                    end
-                end
-            end
-
-
-
-
-            name = s3.name;
-            xlabelval = s3.xlabelval; xunits=s3.xunits; yunits = s3.yunits;
-            sOut=SignalObj(time, data, name, xlabelval, xunits, yunits, dataLabels, plotProps);
-
-        end
-        function sOut = getSubSignalFromNames(sObj,labels)
-            ind   = sObj.getIndicesFromLabels(labels);
-            if(isa(ind,'cell'))
-                if(length(ind)>1)
-                    for i=1:length(ind)
-                        s{i} = getSubSignalFromInd(ind{i});
-                    end
-                    sOut = s{1}.merge(s{2:end});
-                else
-                    sOut = sObj.getSubSignalFromInd(ind{1});
-                end
-            elseif(isa(ind,'double'))
-                sOut  = sObj.getSubSignalFromInd(ind);
-            end
-        end
-
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        %Plotting Functions
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        %   plotProps: is a cell array with strings in each a entry.
-        %              The strings must evaluate to parameters that can be
-        %              passed to the standard matlab plot function.
-        %   example: To plot a three dimensional signals with each line
-        %   with specific properties (not the use of double quotes on the
-        %   color entries so that the actual arguments have a quotes around
-        %   them.
-        %
-        % >> plotProps = {{' ''-.g'', ''LineWidth'' ,2'},...
-        %                 {' ''k'', ''LineWidth'' ,2'},...
-        %                 {' ''-.b'' '}};
-        %
-        %   selectorArrray: is either an numeric array indexing the
-        %                   elements within the SignalObj data or a cell array
-        %                   of characters that refers to the data elements
-        %                   by their labels.
-        % % 8-25-09 : Legend wont plot is SignalObj dimension >10;
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        function h=plot(sObj,selectorArray,plotProps,handle)
-            if(nargin<4)
-                handle=gca;
-            end
-           if(nargin<3)
-              plotProps=sObj.plotProps;
-           end
-           if(nargin<2)
-                if(sObj.isMaskSet)
-                    selectorArray=sObj.findIndFromDataMask;
-                    if(isempty(selectorArray))
-                        h=[];
-                        return;
-                    end
-                else
-                    selectorArray=1:sObj.dimension;
-                end
-           end
-
-
-            if(isa(selectorArray,'cell'))
-                sArray = sObj.convertNamesToIndices(selectorArray);
-            elseif(isa(selectorArray,'char'))
-                sArray = sObj.convertNamesToIndices(selectorArray);
-            elseif(isa(selectorArray,'double'))
-                sArray = selectorArray;
-            else
-                error('selectorArray must contain either dataLabels or their indices');
-            end
-
-
-
-           if(length(plotProps)==length(sArray))
-                for i=1:length(sArray)
-                    sObj.setPlotProps(plotProps{i},sArray(i));
-                end
-           elseif(length(plotProps)<=length(sArray) && length(plotProps)==1)
-               for i=1:length(sArray)
-                    sObj.setPlotProps(plotProps,sArray(i));
-               end
-           end
-
-
-
-
-            %If the dimensions of the data are larger than one can specify
-            %the plot style for each dimension by placing their values in
-            %an cell array.
-            h=gcf;figure(h);
-            if(nargin>=3)  %is we got called with parameter use those
-                %sObj.setPlotProps(plotProps); %Only accepts entire cell of plotting properties as input
-                %if(length(plotCell)>=length(sArray)) %if we specified plot parameters for each dimension
-                for i=sArray
-                    %plotStr=cell2str(plotCell{:,find(sArray==i)});
-                    plotStr=cell2str(sObj.getPlotProps(i));
-                    if(~strcmp(plotStr,'') && ~isempty(plotStr))
-                        evalstring = strcat('h(',num2str(find(sArray==i)),')=plot(handle,sObj.time,sObj.data(:,',num2str(i),'),', plotStr,');');
-                    else
-                        evalstring = strcat('h(',num2str(find(sArray==i)),')=plot(handle,sObj.time,sObj.data(:,',num2str(i),'));');
-                    end
-                    %evalstring
-                    eval(evalstring); hold on;
-                end
-            elseif(sObj.plotPropsSet) %% We use the values that have been set previously
-                %plotCell = cell2str(sObj.getPlotProps(i));
-                %fprintf('varargin is not empty')
-                for i=sArray
-                    plotStr =cell2str(sObj.getPlotProps(i));
-                    %plotStr=cell2str(plotCell{:,1});
-                    if(~strcmp(plotStr,'') && ~isempty(plotStr))
-                        evalstring = strcat('h(',num2str(i),')=plot(handle,sObj.time,sObj.data(:,',num2str(i),'),', plotStr,');');
-                    else
-                        evalstring = strcat('h(',num2str(i),')=plot(handle,sObj.time,sObj.data(:,',num2str(i),'));');
-                    end
-                    %evalstring
-                    eval(evalstring); hold on;
-                end
-            else %We didnt get any plotting properties. Use matlab default
-                %plotCell{1} = '''';
-                %fprintf('varargin is empty')
-                h=plot(handle,sObj.time,sObj.data(:,sArray));
-            end
-
-            if(~strcmp(sObj.xunits,''))
-                xunitsStr=strcat('\; [',sObj.xunits,']'); %\; is a large space in latex
-            else
-                xunitsStr='';
-            end
-
-            if(~strcmp(sObj.yunits,''))
-                yunitsStr=strcat('\; [',sObj.yunits,']');
-            else
-                yunitsStr='';
-            end
-
-            if(strcmp(sObj.xlabelval,''))
-                xlabel(strcat('$$',xunitsStr,'$$'),'Interpreter','latex');
-
-            else
-%                 strcat(['$$' sObj.xlabelval xunitsStr '$$'])
-                xlabel(strcat('$$',[sObj.xlabelval xunitsStr],'$$'),'Interpreter','latex');
-
-            end
-            if(~strcmp(sObj.name,''))
-                if(~strcmp(yunitsStr,''))
-                    %strcat('$$',sObj.name,yunitsStr,'$$')
-                    ylabel(strcat('$$',[sObj.name yunitsStr],'$$'),'Interpreter','latex');
-
-                else
-
-                    ylabel(strcat('$$',sObj.name,'$$'),'Interpreter','latex');
-                    %ylabel(sObj.name,'Interpreter','none');
-
-                end
-            end
-
-            if(~sObj.areDataLabelsEmpty && sObj.dimension<10)
-                labelArray= cell(1,length(sArray));
-                for i=1:length(sArray)
-                    labelArray{i} = strcat('$$',sObj.dataLabels{sArray(i)},'$$');
-
-                end
-                legend(labelArray,'Interpreter','latex');
-            end
-            axis tight;
-        end
-
-        function h=plotVariability(sObj,linewidth,faceColor,ciUpper,ciLower)
-            if(nargin<3)
-                faceColor='red';
-            end
-            if(nargin<3)
-                linewidth=3;
-            end
-            if(nargin<2)
-                if(sObj.isMaskSet)
-                    selectorArray=sObj.findIndFromDataMask;
-                    if(isempty(selectorArray))
-                        h=[];
-                        return;
-                    end
-                else
-                    selectorArray=1:sObj.dimension;
-                end
-            end
-
-
-            if(isa(selectorArray,'cell'))
-                sArray = sObj.convertNamesToIndices(selectorArray);
-            elseif(isa(selectorArray,'char'))
-                sArray = sObj.convertNamesToIndices(selectorArray);
-            elseif(isa(selectorArray,'double'))
-                sArray = selectorArray;
-            else
-                error('selectorArray must contain either dataLabels or their indices');
-            end
-
-            %Take the unique dataLabels and compute the variability of
-            %these signals
-
-            UniqueSigLabels = unique(sObj.getSubSignal(sArray).dataLabels);
-
-
-            for i=1:length(UniqueSigLabels)
-                meanSig = mean(sObj.getSubSignal(UniqueSigLabels{i}),2);
-
-                if(nargin<4)
-                    ci2=meanSig.data+std(meanSig.dataToMatrix);
-                else
-                    ci2=meanSig.data+ciUpper;
-                end
-
-                if(nargin<5)
-                    ci1=meanSig.data-std(meanSig.dataToMatrix);
-                else
-                    ci1=meanSig.data+ciLower;
-                end
-
-
-                plot(sObj.time,meanSig.dataToMatrix,'k-','linewidth',linewidth);
-                hold on;
-                p=patch([reshape(sObj.time,[1 length(sObj.time)]) reshape(fliplr(sObj.time'),[1 length(sObj.time)])],...
-                        [reshape(ci1',[1 length(sObj.time)])       reshape(fliplr(ci2'),[1,length(sObj.time)])],strcat('',faceColor{1},''));
-                set(p,'facecolor',faceColor,'edgecolor','none');
-                alpha(.5);
-            end
-        end
-    end % public methods
-
-
-
-
-end%classdef
-
-% Helper function
-function stringout=cell2str(input)
-    if(isempty(input))
-        stringout = '';
-    else
-        if(isa(input,'char'))
-            stringout=input;
-        elseif(isa(input,'cell'))
-            stringout=cell2str(input{1});
-        end
-    end
-end
-
Input argument "time" is undefined.
-
-Error in ==> SignalObj>SignalObj.SignalObj at 96
-            [l,w]=size(time);
-
-
- - - \ No newline at end of file diff --git a/helpfiles/SignalObjExamples.asv b/helpfiles/SignalObjExamples.asv deleted file mode 100644 index 66972a39..00000000 --- a/helpfiles/SignalObjExamples.asv +++ /dev/null @@ -1,160 +0,0 @@ -%% Using the SignalObj Class -% In this file we will give several examples of how the SignalObj can be -% used. A description of all of the properties of SignalObj can be found -% at: - - -%% Example 1: Defining and Plotting Signals -% Define a two dimensional SignalObj, $s$, representing two voltage signals that were -% $v1$ and $v2$ aquired simultaneously at 100Hz. Another SignalObj,$s1$, -% is created from just $v1$. Both signals are plotted. -close all; -sampleRate=100; t=0:1/sampleRate:10; freq=2; -v1=sin(2*pi*freq*t); v2=sin(v1.^2); v=[v1;v2]; -s=SignalObj(t,v,'Voltage','time','s','V',{'v1','v2'}); -s1=SignalObj(t,v1,'Voltage','time','s','V',{'v1'}); -subplot(2,1,1); s.plot; -subplot(2,1,2); s1.plot; - -%% -% Note how the legend show the appropriate labels. If the dataLabels had -% not been set, the legend would not appear. -% -% Instead of defining a new SignalObj, $s1$, the $v2$ data in $s$ can be -% masked away and then the plot will only show the data of interest. It is -% important to note that setMask is used to set which signals should remain -% visible. Also note that when a data is masked, converting the SignalObj -% to a Matrix only returns the visible data. A new SignalObj can be -% created from the orignal SignalObj which only contains the data of interest. -% Lastly, the all labeled components can be accessed independently via the -% vars subfield. - -subplot(2,1,1); s.setMask({'v1'}); s.plot; s.resetMask; -subplot(2,1,2); s.setMask({'v2'}); s.plot; size(s.dataToMatrix) -s.resetMask; - -%% -figure -subplot(2,1,1); s.getSubSignal({'v1'}).plot; -subplot(2,1,2); s.vars.v1.plot; - -%% -% _Note about repeated dataLabels_ -% It is possible to use SignalObj's to store different realizations of the -% same physical signal. For example, independent measurements of -% $v1$ at two distinct experiments. -s=SignalObj(t,[v1; v1; v2] ,'Voltage','time','s','V',{'v1','v1','v2'}); -s.getSubSignal({'v1'}); %returns a SignalObj with both realizations of v1 - -%% Example 2: Changing Signal Properties -figure -s=SignalObj(t,v,'Voltage','time','s','V',{'v1','v2'}); -subplot(2,1,1); s.plot; -subplot(2,1,2); s.setXlabel('distance'); s.setXUnits('cm'); s.plot; - -%% -figure -subplot(2,1,1); s.setDataLabels({'r1','r2'}); s.setYLabel('Temperature'); s.setYUnits('C'); s.plot; -subplot(2,1,2); s.setMaxTime(14); s.setMinTime(-2); s.plot; - -s.setName('testName'); %should work since we are using a method -if(strcmp(s.name,'testName')) - fprintf('Name successfully set \n'); -else - fprintf('Could not set name \n'); -end -% s.name = 'testName'; %returns an error because the field is private; - -%% -% setMaxTime and setMinTime can be given a second parameter, holdVals, that -% determines whether the endpoint values are kept or set to zero if the -% times being set are outside the original window of the data. -% -% Plotting properties for individual components of the data can be set via -% the when plotting or by call the setPlotProps method. - -figure -s=SignalObj(t,v,'Voltage','time','s','V',{'v1','v2'}); -subplot(2,1,1); s.plot('v1',{{' ''k'' '}}); -subplot(2,1,2); s.plot('all',{{' ''k'' '},{' ''-.g'' '}}); - -%% -figure -subplot(2,1,1); s.plot({'v1','v2'}); -subplot(2,1,2); s.plot({'v1','v2'},{{' ''k'' '},{' ''-.g'' '}}); - -%% Example 3: Resampling and Windowing SignalObjs -figure -s=SignalObj(t,v,'Voltage','time','s','V',{'v1','v2'}); -s1=s.resample(.1*sampleRate); -subplot(2,1,1); s.plot; -subplot(2,1,2); s1.plot; - -%% -figure -subplot(2,1,1); s.getSigInTimeWindow(-2,3).plot; -subplot(2,1,2); s.plot; -%% Example 4: SignalObj Mathematical Operations -s=SignalObj(t,v,'Voltage','time','s','V',{'v1','v2'}); -figure -s2=mean(s); %mean of each dimension; -s5=s-s2; %zero mean version of s; -s5.plot; - -figure -s2=mean(s,2); %mean of s across its dimensions; -s2.plot; - -%% -% SignalObj's can be added, subtracted, and multiplied.\ -figure -s4=2*s+s5; -s4.plot; - -figure -subplot(3,1,1); -s.integral.plot; -subplot(3,1,2); -s.derivative.plot; -subplot(3,1,3); -s6=s.integral.derivative-s; %should equal zero; -s6.plot; - -%% Example 5: Spectra -s=SignalObj(t,v,'Voltage','time','s','V',{'v1','v2'}); -figure; -s.MTMspectrum; - -figure -s.periodogram; - -%% Example 6: View signal variability -% We can look at the variability of signals with regards to their labels or -% or irrespective of their labels. Lets create a SignalObj that has several -% components, and some noise. We mislabel two signals to add alot of -% variability for illustration -sampleRate=5000; t=0:1/sampleRate:1; t=t'; freq=2; -v1=sin(2*pi*freq*t); v2=sin(v1.^2); -noise=.1*randn(length(t),6); %gaussian random noise -data= [v1 v2 v2 v1 v2 v1] + noise; -s=SignalObj(t,data,'Voltage','time','s','V',{'v1','v2','v2','v1','v1','v2'}); -figure; -subplot(2,1,1); s.plot; -subplot(2,1,2); s.plotAllVariability; %disregards labels; -s.plotVariability; %creates two figures, one for 'v1' and one for 'v2' - -%% -%plotAllVariability assumes that all the data can be considered together. -%It also allows more custimization of the plotting properties. -%Example we can specify a different faceColor by passing the color in the -%same format as plot. Assymetric confidence intervals can be specified. If -%the CIs are single numbers, they specify the multiple of the standard -%deviations to use (default is 1). If they are the same length as the -%SignalObj, then it specifies the actual values above and/or below the mean -%at each point in time. If ciLower is not specifed, it is assumed to equal -%ciUpper. For convinience the inputs to plotAllVariability are: -%s.plotAllVariability(sObj,faceColor,linewidth,ciUpper,ciLower) - -s.plotAllVariability('b'); %blue color for CI patch; -s.plotAllVariability('g',2); %green color and lineWidth=2; -s.plotAllVariability('c',3,2,1);%cyan, diff --git a/helpfiles/SignalObjExamples.html b/helpfiles/SignalObjExamples.html deleted file mode 100644 index 8279a31c..00000000 --- a/helpfiles/SignalObjExamples.html +++ /dev/null @@ -1,325 +0,0 @@ - - - - - Using the SignalObj Class

Using the SignalObj Class

In this file we will give several examples of how the SignalObj can be used. A description of all of the properties of SignalObj can be found at: SignalObj Class Definition

Contents

Example 1: Defining and Plotting Signals

Define a two dimensional SignalObj, $s$, representing two voltage signals that were $v1$ and $v2$ aquired simultaneously at 100Hz. Another SignalObj, $s1$ , is created from just $v1$. Both signals are plotted.

close all;
-sampleRate=100; t=0:1/sampleRate:10; freq=2;
-v1=sin(2*pi*freq*t); v2=sin(v1.^2); v=[v1;v2];
-s=SignalObj(t,v,'Voltage','time','s','V',{'v1','v2'});
-s1=SignalObj(t,v1,'Voltage','time','s','V',{'v1'});
-subplot(2,1,1); s.plot;
-subplot(2,1,2); s1.plot;
-

Note how the legend show the appropriate labels. If the dataLabels had not been set, the legend would not appear.

Instead of defining a new SignalObj, $s1$, the $v2$ data in $s$ can be masked away and then the plot will only show the data of interest. It is important to note that setMask is used to set which signals should remain visible. Also note that when a data is masked, converting the SignalObj to a Matrix only returns the visible data. A new SignalObj can be created from the orignal SignalObj which only contains the data of interest. Lastly, the all labeled components can be accessed independently via the vars subfield.

subplot(2,1,1); s.setMask({'v1'}); s.plot; s.resetMask;
-subplot(2,1,2); s.setMask({'v2'}); s.plot; size(s.dataToMatrix)
-s.resetMask;
-
-ans =
-
-        1001           1
-
-

Note about repeated dataLabels It is possible to use SignalObj's to store different realizations of the same physical signal. For example, independent measurements of $v1$ at two distinct experiments.

s=SignalObj(t,[v1; v1; v2] ,'Voltage','time','s','V',{'v1','v1','v2'});
-s.getSubSignal({'v1'}); %returns a SignalObj with both realizations of v1
-figure
-s.getSubSignal({'v1'}).plot;
-

Example 2: Changing Signal Properties

figure
-s=SignalObj(t,v,'Voltage','time','s','V',{'v1','v2'});
-subplot(2,1,1); s.plot;
-subplot(2,1,2); s.setXlabel('distance'); s.setXUnits('cm'); s.plot;
-
figure
-subplot(2,1,1); s.setDataLabels({'r1','r2'}); s.setYLabel('Temperature'); s.setYUnits('C'); s.plot;
-subplot(2,1,2); s.setMaxTime(14); s.setMinTime(-2); s.plot;
-
-s.setName('testName'); %should work since we are using a method
-if(strcmp(s.name,'testName'))
-    fprintf('Name successfully set \n');
-else
-    fprintf('Could not set name \n');
-end
-% s.name = 'testName'; %returns an error because the field is private;
-
Name successfully set 
-

setMaxTime and setMinTime can be given a second parameter, holdVals, that determines whether the endpoint values are kept or set to zero if the times being set are outside the original window of the data.

Plotting properties for individual components of the data can be set via the when plotting or by call the setPlotProps method.

figure
-s=SignalObj(t,v,'Voltage','time','s','V',{'v1','v2'});
-subplot(2,1,1); s.plot('v1',{{' ''k'' '}});
-subplot(2,1,2); s.plot('all',{{' ''k'' '},{' ''-.g'' '}});
-
figure
-subplot(2,1,1); s.plot({'v1','v2'});
-subplot(2,1,2); s.plot({'v1','v2'},{{' ''k'' '},{' ''-.g'' '}});
-

Example 3: Resampling and Windowing SignalObjs

figure
-s=SignalObj(t,v,'Voltage','time','s','V',{'v1','v2'});
-s1=s.resample(.1*sampleRate);
-subplot(2,1,1); s.plot;
-subplot(2,1,2); s1.plot;
-
figure
-subplot(2,1,1); s.getSigInTimeWindow(-2,3).plot;
-subplot(2,1,2); s.plot;
-

Example 4: SignalObj Mathematical Operations

s=SignalObj(t,v,'Voltage','time','s','V',{'v1','v2'});
-figure
-s2=mean(s); %mean of each dimension;
-s5=s-s2;  %zero mean version of s;
-s5.plot;
-
-figure
-s2=mean(s,2); %mean of s across its dimensions;
-s2.plot;
-

SignalObj's can be added, subtracted, and multiplied.\

figure
-s4=2*s+s5;
-s4.plot;
-
-figure
-subplot(3,1,1);
-s.integral.plot;
-subplot(3,1,2);
-s.derivative.plot;
-subplot(3,1,3);
-s6=s.integral.derivative-s; %should equal zero;
-s6.plot;
-

Example 5: Spectra

s=SignalObj(t,v,'Voltage','time','s','V',{'v1','v2'});
-figure;
-s.MTMspectrum;
-
-figure
-s.periodogram;
-

Example 6: View signal variability

We can look at the variability of signals with regards to their labels or or irrespective of their labels. Lets create a SignalObj that has several components, and some noise. We mislabel two signals to add alot of variability for illustration

sampleRate=5000; t=0:1/sampleRate:1; t=t'; freq=2;
-v1=sin(2*pi*freq*t); v2=sin(v1.^2);
-noise=.1*randn(length(t),6); %gaussian random noise
-data= [v1 v2 v2 v1 v2 v1] + noise;
-s=SignalObj(t,data,'Voltage','time','s','V',{'v1','v2','v2','v1','v1','v2'});
-figure;
-subplot(2,1,1); s.plot;
-subplot(2,1,2); s.plotAllVariability; %disregards labels;
-s.plotVariability; %creates two figures, one for 'v1' and one for 'v2'
-

sObj.plotAllVariability assumes that all the data can be considered together. It also allows more custimization of the plotting properties. Example we can specify a different faceColor by passing the color in the same format as plot. Assymetric confidence intervals can be specified. If the CIs are single numbers, they specify the multiple of the standard deviations to use (default is 1). If they are the same length as the SignalObj, then it specifies the actual values above and/or below the mean at each point in time. If ciLower is not specifed, it is assumed to equal ciUpper. For convinience the inputs to plotAllVariability are: s.plotAllVariability(sObj,faceColor,linewidth,ciUpper,ciLower)

figure;
-%blue color for CI patch;
-subplot(3,1,1); s.plotAllVariability('b');
-%green color and lineWidth=2;
-subplot(3,1,2); s.plotAllVariability('g',2);
-%cyan, lineWidth=3, 2*std for top CI, and 1*std for bottom CI
-subplot(3,1,3); s.plotAllVariability('c',3,2,1);
-
\ No newline at end of file diff --git a/helpfiles/SignalObjExamples.m b/helpfiles/SignalObjExamples.m deleted file mode 100644 index 22343267..00000000 --- a/helpfiles/SignalObjExamples.m +++ /dev/null @@ -1,162 +0,0 @@ -%% Using the SignalObj Class -% In this file we will give several examples of how the SignalObj can be -% used. A description of all of the properties of SignalObj can be found -% at: - - -%% Example 1: Defining and Plotting Signals -% Define a two dimensional SignalObj, $s$, representing two voltage signals that were -% $v1$ and $v2$ aquired simultaneously at 100Hz. Another SignalObj, $s1$ , -% is created from just $v1$. Both signals are plotted. -close all; -sampleRate=100; t=0:1/sampleRate:10; freq=2; -v1=sin(2*pi*freq*t); v2=sin(v1.^2); v=[v1;v2]; -s=SignalObj(t,v,'Voltage','time','s','V',{'v1','v2'}); -s1=SignalObj(t,v1,'Voltage','time','s','V',{'v1'}); -subplot(2,1,1); s.plot; -subplot(2,1,2); s1.plot; - -%% -% Note how the legend show the appropriate labels. If the dataLabels had -% not been set, the legend would not appear. -% -% Instead of defining a new SignalObj, $s1$, the $v2$ data in $s$ can be -% masked away and then the plot will only show the data of interest. It is -% important to note that setMask is used to set which signals should remain -% visible. Also note that when a data is masked, converting the SignalObj -% to a Matrix only returns the visible data. A new SignalObj can be -% created from the orignal SignalObj which only contains the data of interest. -% Lastly, the all labeled components can be accessed independently via the -% vars subfield. - -subplot(2,1,1); s.setMask({'v1'}); s.plot; s.resetMask; -subplot(2,1,2); s.setMask({'v2'}); s.plot; size(s.dataToMatrix) -s.resetMask; - - -%% -% _Note about repeated dataLabels_ -% It is possible to use SignalObj's to store different realizations of the -% same physical signal. For example, independent measurements of -% $v1$ at two distinct experiments. -s=SignalObj(t,[v1; v1; v2] ,'Voltage','time','s','V',{'v1','v1','v2'}); -s.getSubSignal({'v1'}); %returns a SignalObj with both realizations of v1 -figure -s.getSubSignal({'v1'}).plot; - -%% Example 2: Changing Signal Properties -figure -s=SignalObj(t,v,'Voltage','time','s','V',{'v1','v2'}); -subplot(2,1,1); s.plot; -subplot(2,1,2); s.setXlabel('distance'); s.setXUnits('cm'); s.plot; - -%% -figure -subplot(2,1,1); s.setDataLabels({'r1','r2'}); s.setYLabel('Temperature'); s.setYUnits('C'); s.plot; -subplot(2,1,2); s.setMaxTime(14); s.setMinTime(-2); s.plot; - -s.setName('testName'); %should work since we are using a method -if(strcmp(s.name,'testName')) - fprintf('Name successfully set \n'); -else - fprintf('Could not set name \n'); -end -% s.name = 'testName'; %returns an error because the field is private; - -%% -% setMaxTime and setMinTime can be given a second parameter, holdVals, that -% determines whether the endpoint values are kept or set to zero if the -% times being set are outside the original window of the data. -% -% Plotting properties for individual components of the data can be set via -% the when plotting or by call the setPlotProps method. - -figure -s=SignalObj(t,v,'Voltage','time','s','V',{'v1','v2'}); -subplot(2,1,1); s.plot('v1',{{' ''k'' '}}); -subplot(2,1,2); s.plot('all',{{' ''k'' '},{' ''-.g'' '}}); - -%% -figure -subplot(2,1,1); s.plot({'v1','v2'}); -subplot(2,1,2); s.plot({'v1','v2'},{{' ''k'' '},{' ''-.g'' '}}); - -%% Example 3: Resampling and Windowing SignalObjs -figure -s=SignalObj(t,v,'Voltage','time','s','V',{'v1','v2'}); -s1=s.resample(.1*sampleRate); -subplot(2,1,1); s.plot; -subplot(2,1,2); s1.plot; - -%% -figure -subplot(2,1,1); s.getSigInTimeWindow(-2,3).plot; -subplot(2,1,2); s.plot; -%% Example 4: SignalObj Mathematical Operations -s=SignalObj(t,v,'Voltage','time','s','V',{'v1','v2'}); -figure -s2=mean(s); %mean of each dimension; -s5=s-s2; %zero mean version of s; -s5.plot; - -figure -s2=mean(s,2); %mean of s across its dimensions; -s2.plot; - -%% -% SignalObj's can be added, subtracted, and multiplied.\ -figure -s4=2*s+s5; -s4.plot; - -figure -subplot(3,1,1); -s.integral.plot; -subplot(3,1,2); -s.derivative.plot; -subplot(3,1,3); -s6=s.integral.derivative-s; %should equal zero; -s6.plot; - -%% Example 5: Spectra -s=SignalObj(t,v,'Voltage','time','s','V',{'v1','v2'}); -figure; -s.MTMspectrum; - -figure -s.periodogram; - -%% Example 6: View signal variability -% We can look at the variability of signals with regards to their labels or -% or irrespective of their labels. Lets create a SignalObj that has several -% components, and some noise. We mislabel two signals to add alot of -% variability for illustration -sampleRate=5000; t=0:1/sampleRate:1; t=t'; freq=2; -v1=sin(2*pi*freq*t); v2=sin(v1.^2); -noise=.1*randn(length(t),6); %gaussian random noise -data= [v1 v2 v2 v1 v2 v1] + noise; -s=SignalObj(t,data,'Voltage','time','s','V',{'v1','v2','v2','v1','v1','v2'}); -figure; -subplot(2,1,1); s.plot; -subplot(2,1,2); s.plotAllVariability; %disregards labels; -s.plotVariability; %creates two figures, one for 'v1' and one for 'v2' - -%% -% sObj.plotAllVariability assumes that all the data can be considered together. -% It also allows more custimization of the plotting properties. -% Example we can specify a different faceColor by passing the color in the -% same format as plot. Assymetric confidence intervals can be specified. If -% the CIs are single numbers, they specify the multiple of the standard -% deviations to use (default is 1). If they are the same length as the -% SignalObj, then it specifies the actual values above and/or below the mean -% at each point in time. If ciLower is not specifed, it is assumed to equal -% ciUpper. For convinience the inputs to plotAllVariability are: -% s.plotAllVariability(sObj,faceColor,linewidth,ciUpper,ciLower) -figure; -%blue color for CI patch; -subplot(3,1,1); s.plotAllVariability('b'); -%green color and lineWidth=2; -subplot(3,1,2); s.plotAllVariability('g',2); -%cyan, lineWidth=3, 2*std for top CI, and 1*std for bottom CI -subplot(3,1,3); s.plotAllVariability('c',3,2,1); - diff --git a/helpfiles/SignalObjExamples.png b/helpfiles/SignalObjExamples.png deleted file mode 100644 index 5cccdce0..00000000 Binary files a/helpfiles/SignalObjExamples.png and /dev/null differ diff --git a/helpfiles/SignalObjExamples_01.png b/helpfiles/SignalObjExamples_01.png deleted file mode 100644 index d9fdf71a..00000000 Binary files a/helpfiles/SignalObjExamples_01.png and /dev/null differ diff --git a/helpfiles/SignalObjExamples_02.png b/helpfiles/SignalObjExamples_02.png deleted file mode 100644 index ec65ee57..00000000 Binary files a/helpfiles/SignalObjExamples_02.png and /dev/null differ diff --git a/helpfiles/SignalObjExamples_03.png b/helpfiles/SignalObjExamples_03.png deleted file mode 100644 index 2bca2948..00000000 Binary files a/helpfiles/SignalObjExamples_03.png and /dev/null differ diff --git a/helpfiles/SignalObjExamples_04.png b/helpfiles/SignalObjExamples_04.png deleted file mode 100644 index fc15a7f0..00000000 Binary files a/helpfiles/SignalObjExamples_04.png and /dev/null differ diff --git a/helpfiles/SignalObjExamples_05.png b/helpfiles/SignalObjExamples_05.png deleted file mode 100644 index 7f10bdd6..00000000 Binary files a/helpfiles/SignalObjExamples_05.png and /dev/null differ diff --git a/helpfiles/SignalObjExamples_06.png b/helpfiles/SignalObjExamples_06.png deleted file mode 100644 index 8f18fbf2..00000000 Binary files a/helpfiles/SignalObjExamples_06.png and /dev/null differ diff --git a/helpfiles/SignalObjExamples_07.png b/helpfiles/SignalObjExamples_07.png deleted file mode 100644 index 37cbd109..00000000 Binary files a/helpfiles/SignalObjExamples_07.png and /dev/null differ diff --git a/helpfiles/SignalObjExamples_08.png b/helpfiles/SignalObjExamples_08.png deleted file mode 100644 index 1a169f0f..00000000 Binary files a/helpfiles/SignalObjExamples_08.png and /dev/null differ diff --git a/helpfiles/SignalObjExamples_09.png b/helpfiles/SignalObjExamples_09.png deleted file mode 100644 index 6e826198..00000000 Binary files a/helpfiles/SignalObjExamples_09.png and /dev/null differ diff --git a/helpfiles/SignalObjExamples_10.png b/helpfiles/SignalObjExamples_10.png deleted file mode 100644 index 6a5ff9f3..00000000 Binary files a/helpfiles/SignalObjExamples_10.png and /dev/null differ diff --git a/helpfiles/SignalObjExamples_11.png b/helpfiles/SignalObjExamples_11.png deleted file mode 100644 index 033dba6e..00000000 Binary files a/helpfiles/SignalObjExamples_11.png and /dev/null differ diff --git a/helpfiles/SignalObjExamples_12.png b/helpfiles/SignalObjExamples_12.png deleted file mode 100644 index 0193d3e2..00000000 Binary files a/helpfiles/SignalObjExamples_12.png and /dev/null differ diff --git a/helpfiles/SignalObjExamples_13.png b/helpfiles/SignalObjExamples_13.png deleted file mode 100644 index 6dd0e3a0..00000000 Binary files a/helpfiles/SignalObjExamples_13.png and /dev/null differ diff --git a/helpfiles/SignalObjExamples_14.png b/helpfiles/SignalObjExamples_14.png deleted file mode 100644 index af99c751..00000000 Binary files a/helpfiles/SignalObjExamples_14.png and /dev/null differ diff --git a/helpfiles/SignalObjExamples_15.png b/helpfiles/SignalObjExamples_15.png deleted file mode 100644 index b614e134..00000000 Binary files a/helpfiles/SignalObjExamples_15.png and /dev/null differ diff --git a/helpfiles/SignalObjExamples_16.png b/helpfiles/SignalObjExamples_16.png deleted file mode 100644 index d33e38a6..00000000 Binary files a/helpfiles/SignalObjExamples_16.png and /dev/null differ diff --git a/helpfiles/SignalObjExamples_17.png b/helpfiles/SignalObjExamples_17.png deleted file mode 100644 index 9207998d..00000000 Binary files a/helpfiles/SignalObjExamples_17.png and /dev/null differ diff --git a/helpfiles/SignalObjExamples_eq03690.png b/helpfiles/SignalObjExamples_eq03690.png deleted file mode 100644 index 4b381288..00000000 Binary files a/helpfiles/SignalObjExamples_eq03690.png and /dev/null differ diff --git a/helpfiles/SignalObjExamples_eq14139.png b/helpfiles/SignalObjExamples_eq14139.png deleted file mode 100644 index e5f70104..00000000 Binary files a/helpfiles/SignalObjExamples_eq14139.png and /dev/null differ diff --git a/helpfiles/SignalObjExamples_eq34998.png b/helpfiles/SignalObjExamples_eq34998.png deleted file mode 100644 index 3a2377fe..00000000 Binary files a/helpfiles/SignalObjExamples_eq34998.png and /dev/null differ diff --git a/helpfiles/SignalObjExamples_eq40692.png b/helpfiles/SignalObjExamples_eq40692.png deleted file mode 100644 index a68903e1..00000000 Binary files a/helpfiles/SignalObjExamples_eq40692.png and /dev/null differ diff --git a/helpfiles/SignalObjExamples_eq57658.png b/helpfiles/SignalObjExamples_eq57658.png deleted file mode 100644 index c41ae2ac..00000000 Binary files a/helpfiles/SignalObjExamples_eq57658.png and /dev/null differ diff --git a/helpfiles/SignalObjExamples_eq68144.png b/helpfiles/SignalObjExamples_eq68144.png deleted file mode 100644 index e96626fd..00000000 Binary files a/helpfiles/SignalObjExamples_eq68144.png and /dev/null differ diff --git a/helpfiles/SignalObjExamples_eq72999.png b/helpfiles/SignalObjExamples_eq72999.png deleted file mode 100644 index 326db91b..00000000 Binary files a/helpfiles/SignalObjExamples_eq72999.png and /dev/null differ diff --git a/helpfiles/SimulatedNetwork2.mdl b/helpfiles/SimulatedNetwork2.mdl deleted file mode 100644 index 7c4d2a4a..00000000 --- a/helpfiles/SimulatedNetwork2.mdl +++ /dev/null @@ -1,2220 +0,0 @@ -Model { - Name "SimulatedNetwork2" - Version 8.2 - MdlSubVersion 0 - SavedCharacterEncoding "ISO-8859-1" - GraphicalInterface { - NumRootInports 1 - Inport { - BusObject "" - SignalName "input" - Name "Stimulus" - } - NumRootOutports 2 - Outport { - BusObject "" - BusOutputAsStruct "off" - Name "pp" - } - Outport { - BusObject "" - BusOutputAsStruct "off" - Name "pp1" - } - ParameterArgumentNames "" - ComputedModelVersion "1.32" - NumModelReferences 0 - NumTestPointedSignals 0 - } - SaveDefaultBlockParams on - ScopeRefreshTime 0.035000 - OverrideScopeRefreshTime on - DisableAllScopes off - DataTypeOverride "UseLocalSettings" - DataTypeOverrideAppliesTo "AllNumericTypes" - MinMaxOverflowLogging "UseLocalSettings" - MinMaxOverflowArchiveMode "Overwrite" - FPTRunName "Run 1" - MaxMDLFileLineLength 120 - Object { - $PropName "BdWindowsInfo" - $ObjectID 1 - $ClassName "Simulink.BDWindowsInfo" - Array { - Type "Simulink.WindowInfo" - Dimension 2 - Object { - $ObjectID 2 - IsActive [0] - Location [276.0, 77.0, 1083.0, 601.0] - Object { - $PropName "ModelBrowserInfo" - $ObjectID 3 - $ClassName "Simulink.ModelBrowserInfo" - Visible [0] - DockPosition "Left" - Width [50] - Height [50] - Filter [10] - } - Object { - $PropName "ExplorerBarInfo" - $ObjectID 4 - $ClassName "Simulink.ExplorerBarInfo" - Visible [1] - } - Object { - $PropName "EditorsInfo" - $ObjectID 5 - $ClassName "Simulink.EditorInfo" - IsActive [1] - ViewObjType "SimulinkSubsys" - LoadSaveID "45" - Extents [1049.0, 431.0] - ZoomFactor [1.0] - Offset [0.0, 0.0] - } - } - Object { - $ObjectID 6 - IsActive [1] - Location [8.0, 142.0, 1636.0, 1028.0] - Object { - $PropName "ModelBrowserInfo" - $ObjectID 7 - $ClassName "Simulink.ModelBrowserInfo" - Visible [0] - DockPosition "Left" - Width [50] - Height [50] - Filter [10] - } - Object { - $PropName "ExplorerBarInfo" - $ObjectID 8 - $ClassName "Simulink.ExplorerBarInfo" - Visible [1] - } - Object { - $PropName "EditorsInfo" - $ObjectID 9 - $ClassName "Simulink.EditorInfo" - IsActive [1] - ViewObjType "SimulinkTopLevel" - LoadSaveID "0" - Extents [1602.0, 858.0] - ZoomFactor [1.0] - Offset [0.0, 0.0] - } - } - PropName "WindowsInfo" - } - } - Created "Tue Feb 08 12:34:27 2011" - Creator "Developer" - UpdateHistory "UpdateHistoryNever" - ModifiedByFormat "%" - LastModifiedBy "iahncajigas" - ModifiedDateFormat "%" - LastModifiedDate "Mon Feb 10 13:14:16 2014" - RTWModifiedTimeStamp 230568673 - ModelVersionFormat "1.%" - ConfigurationManager "none" - SampleTimeColors off - SampleTimeAnnotations off - LibraryLinkDisplay "none" - WideLines off - ShowLineDimensions off - ShowPortDataTypes off - ShowDesignRanges off - ShowLoopsOnError on - IgnoreBidirectionalLines off - ShowStorageClass off - ShowTestPointIcons on - ShowSignalResolutionIcons on - ShowViewerIcons on - SortedOrder off - ExecutionContextIcon off - ShowLinearizationAnnotations on - BlockNameDataTip off - BlockParametersDataTip off - BlockDescriptionStringDataTip off - ToolBar on - StatusBar on - BrowserShowLibraryLinks off - BrowserLookUnderMasks off - SimulationMode "normal" - PauseTimes "5" - NumberOfSteps 1 - SnapshotBufferSize 10 - SnapshotInterval 10 - NumberOfLastSnapshots 0 - LinearizationMsg "none" - Profile off - ParamWorkspaceSource "MATLABWorkspace" - AccelSystemTargetFile "accel.tlc" - AccelTemplateMakefile "accel_default_tmf" - AccelMakeCommand "make_rtw" - TryForcingSFcnDF off - Object { - $PropName "DataLoggingOverride" - $ObjectID 10 - $ClassName "Simulink.SimulationData.ModelLoggingInfo" - model_ "SimulatedNetwork2" - Array { - Type "Cell" - Dimension 1 - Cell "SimulatedNetwork2" - PropName "logAsSpecifiedByModels_" - } - Array { - Type "Cell" - Dimension 1 - Cell "" - PropName "logAsSpecifiedByModelsSSIDs_" - } - } - RecordCoverage off - CovPath "/" - CovSaveName "covdata" - CovMetricSettings "dw" - CovNameIncrementing off - CovHtmlReporting on - CovForceBlockReductionOff on - CovEnableCumulative on - covSaveCumulativeToWorkspaceVar on - CovSaveSingleToWorkspaceVar on - CovCumulativeVarName "covCumulativeData" - CovCumulativeReport off - CovReportOnPause on - CovModelRefEnable "Off" - CovExternalEMLEnable off - ExtModeBatchMode off - ExtModeEnableFloating on - ExtModeTrigType "manual" - ExtModeTrigMode "normal" - ExtModeTrigPort "1" - ExtModeTrigElement "any" - ExtModeTrigDuration 1000 - ExtModeTrigDurationFloating "auto" - ExtModeTrigHoldOff 0 - ExtModeTrigDelay 0 - ExtModeTrigDirection "rising" - ExtModeTrigLevel 0 - ExtModeArchiveMode "off" - ExtModeAutoIncOneShot off - ExtModeIncDirWhenArm off - ExtModeAddSuffixToVar off - ExtModeWriteAllDataToWs off - ExtModeArmWhenConnect on - ExtModeSkipDownloadWhenConnect off - ExtModeLogAll on - ExtModeAutoUpdateStatusClock on - BufferReuse on - ShowModelReferenceBlockVersion off - ShowModelReferenceBlockIO off - Array { - Type "Handle" - Dimension 1 - Simulink.ConfigSet { - $ObjectID 11 - Version "1.13.1" - Array { - Type "Handle" - Dimension 8 - Simulink.SolverCC { - $ObjectID 12 - Version "1.13.1" - StartTime "0.0" - StopTime "10" - AbsTol "auto" - FixedStep "Ts" - InitialStep "auto" - MaxNumMinSteps "-1" - MaxOrder 5 - ZcThreshold "auto" - ConsecutiveZCsStepRelTol "10*128*eps" - MaxConsecutiveZCs "1000" - ExtrapolationOrder 4 - NumberNewtonIterations 1 - MaxStep "auto" - MinStep "auto" - MaxConsecutiveMinStep "1" - RelTol "1e-3" - SolverMode "Auto" - EnableConcurrentExecution off - ConcurrentTasks off - Solver "FixedStepDiscrete" - SolverName "FixedStepDiscrete" - SolverJacobianMethodControl "auto" - ShapePreserveControl "DisableAll" - ZeroCrossControl "UseLocalSettings" - ZeroCrossAlgorithm "Nonadaptive" - AlgebraicLoopSolver "TrustRegion" - SolverResetMethod "Fast" - PositivePriorityOrder off - AutoInsertRateTranBlk off - SampleTimeConstraint "Unconstrained" - InsertRTBMode "Whenever possible" - } - Simulink.DataIOCC { - $ObjectID 13 - Version "1.13.1" - Decimation "1" - ExternalInput "[t, u]" - FinalStateName "xFinal" - InitialState "xInitial" - LimitDataPoints on - MaxDataPoints "1000" - LoadExternalInput off - LoadInitialState off - SaveFinalState off - SaveCompleteFinalSimState off - SaveFormat "Array" - SignalLoggingSaveFormat "ModelDataLogs" - SaveOutput on - SaveState off - SignalLogging on - DSMLogging on - InspectSignalLogs off - SaveTime on - ReturnWorkspaceOutputs off - StateSaveName "xout" - TimeSaveName "tout" - OutputSaveName "yout" - SignalLoggingName "logsout" - DSMLoggingName "dsmout" - OutputOption "RefineOutputTimes" - OutputTimes "[]" - ReturnWorkspaceOutputsName "out" - Refine "1" - } - Simulink.OptimizationCC { - $ObjectID 14 - Version "1.13.1" - Array { - Type "Cell" - Dimension 8 - Cell "BooleansAsBitfields" - Cell "PassReuseOutputArgsAs" - Cell "PassReuseOutputArgsThreshold" - Cell "ZeroExternalMemoryAtStartup" - Cell "ZeroInternalMemoryAtStartup" - Cell "OptimizeModelRefInitCode" - Cell "NoFixptDivByZeroProtection" - Cell "UseSpecifiedMinMax" - PropName "DisabledProps" - } - BlockReduction on - BooleanDataType on - ConditionallyExecuteInputs on - InlineParams off - UseIntDivNetSlope off - UseFloatMulNetSlope off - DefaultUnderspecifiedDataType "double" - UseSpecifiedMinMax off - InlineInvariantSignals off - OptimizeBlockIOStorage on - BufferReuse on - EnhancedBackFolding off - StrengthReduction off - ExpressionFolding on - BooleansAsBitfields off - BitfieldContainerType "uint_T" - EnableMemcpy on - MemcpyThreshold 64 - PassReuseOutputArgsAs "Structure reference" - ExpressionDepthLimit 2147483647 - FoldNonRolledExpr on - LocalBlockOutputs on - RollThreshold 5 - SystemCodeInlineAuto off - StateBitsets off - DataBitsets off - ActiveStateOutputEnumStorageType "Native Integer" - UseTempVars off - ZeroExternalMemoryAtStartup on - ZeroInternalMemoryAtStartup on - InitFltsAndDblsToZero off - NoFixptDivByZeroProtection off - EfficientFloat2IntCast off - EfficientMapNaN2IntZero on - OptimizeModelRefInitCode off - LifeSpan "inf" - MaxStackSize "Inherit from target" - BufferReusableBoundary on - SimCompilerOptimization "Off" - AccelVerboseBuild off - ParallelExecutionInRapidAccelerator on - } - Simulink.DebuggingCC { - $ObjectID 15 - Version "1.13.1" - RTPrefix "error" - ConsistencyChecking "none" - ArrayBoundsChecking "none" - SignalInfNanChecking "none" - SignalRangeChecking "none" - ReadBeforeWriteMsg "UseLocalSettings" - WriteAfterWriteMsg "UseLocalSettings" - WriteAfterReadMsg "UseLocalSettings" - AlgebraicLoopMsg "warning" - ArtificialAlgebraicLoopMsg "warning" - SaveWithDisabledLinksMsg "warning" - SaveWithParameterizedLinksMsg "warning" - CheckSSInitialOutputMsg on - UnderspecifiedInitializationDetection "Classic" - MergeDetectMultiDrivingBlocksExec "none" - CheckExecutionContextPreStartOutputMsg off - CheckExecutionContextRuntimeOutputMsg off - SignalResolutionControl "UseLocalSettings" - BlockPriorityViolationMsg "warning" - MinStepSizeMsg "warning" - TimeAdjustmentMsg "none" - MaxConsecutiveZCsMsg "error" - MaskedZcDiagnostic "warning" - IgnoredZcDiagnostic "warning" - SolverPrmCheckMsg "warning" - InheritedTsInSrcMsg "warning" - DiscreteInheritContinuousMsg "warning" - MultiTaskDSMMsg "error" - MultiTaskCondExecSysMsg "error" - MultiTaskRateTransMsg "error" - SingleTaskRateTransMsg "none" - TasksWithSamePriorityMsg "warning" - SigSpecEnsureSampleTimeMsg "warning" - CheckMatrixSingularityMsg "none" - IntegerOverflowMsg "warning" - Int32ToFloatConvMsg "warning" - ParameterDowncastMsg "error" - ParameterOverflowMsg "error" - ParameterUnderflowMsg "none" - ParameterPrecisionLossMsg "warning" - ParameterTunabilityLossMsg "warning" - FixptConstUnderflowMsg "none" - FixptConstOverflowMsg "none" - FixptConstPrecisionLossMsg "none" - UnderSpecifiedDataTypeMsg "none" - UnnecessaryDatatypeConvMsg "none" - VectorMatrixConversionMsg "none" - InvalidFcnCallConnMsg "error" - FcnCallInpInsideContextMsg "UseLocalSettings" - SignalLabelMismatchMsg "none" - UnconnectedInputMsg "warning" - UnconnectedOutputMsg "warning" - UnconnectedLineMsg "warning" - SFcnCompatibilityMsg "none" - FrameProcessingCompatibilityMsg "warning" - UniqueDataStoreMsg "none" - BusObjectLabelMismatch "warning" - RootOutportRequireBusObject "warning" - AssertControl "UseLocalSettings" - EnableOverflowDetection off - ModelReferenceIOMsg "none" - ModelReferenceMultiInstanceNormalModeStructChecksumCheck "error" - ModelReferenceVersionMismatchMessage "none" - ModelReferenceIOMismatchMessage "none" - ModelReferenceCSMismatchMessage "none" - UnknownTsInhSupMsg "warning" - ModelReferenceDataLoggingMessage "warning" - ModelReferenceSymbolNameMessage "warning" - ModelReferenceExtraNoncontSigs "error" - StateNameClashWarn "warning" - SimStateInterfaceChecksumMismatchMsg "warning" - SimStateOlderReleaseMsg "error" - InitInArrayFormatMsg "warning" - StrictBusMsg "ErrorLevel1" - BusNameAdapt "WarnAndRepair" - NonBusSignalsTreatedAsBus "none" - LoggingUnavailableSignals "error" - BlockIODiagnostic "none" - SFUnusedDataAndEventsDiag "warning" - SFUnexpectedBacktrackingDiag "warning" - SFInvalidInputDataAccessInChartInitDiag "warning" - SFNoUnconditionalDefaultTransitionDiag "warning" - SFTransitionOutsideNaturalParentDiag "warning" - SFUnconditionalTransitionShadowingDiag "warning" - SFUndirectedBroadcastEventsDiag "warning" - SFTransitionActionBeforeConditionDiag "warning" - } - Simulink.HardwareCC { - $ObjectID 16 - Version "1.13.1" - ProdBitPerChar 8 - ProdBitPerShort 16 - ProdBitPerInt 32 - ProdBitPerLong 32 - ProdBitPerLongLong 64 - ProdBitPerFloat 32 - ProdBitPerDouble 64 - ProdBitPerPointer 32 - ProdLargestAtomicInteger "Char" - ProdLargestAtomicFloat "None" - ProdIntDivRoundTo "Undefined" - ProdEndianess "Unspecified" - ProdWordSize 32 - ProdShiftRightIntArith on - ProdLongLongMode off - ProdHWDeviceType "32-bit Generic" - TargetBitPerChar 8 - TargetBitPerShort 16 - TargetBitPerInt 32 - TargetBitPerLong 64 - TargetBitPerLongLong 64 - TargetBitPerFloat 32 - TargetBitPerDouble 64 - TargetBitPerPointer 64 - TargetLargestAtomicInteger "Char" - TargetLargestAtomicFloat "None" - TargetShiftRightIntArith on - TargetLongLongMode on - TargetIntDivRoundTo "Zero" - TargetEndianess "LittleEndian" - TargetWordSize 64 - TargetTypeEmulationWarnSuppressLevel 0 - TargetPreprocMaxBitsSint 32 - TargetPreprocMaxBitsUint 32 - TargetHWDeviceType "MATLAB Host" - TargetUnknown off - ProdEqTarget off - } - Simulink.ModelReferenceCC { - $ObjectID 17 - Version "1.13.1" - UpdateModelReferenceTargets "IfOutOfDateOrStructuralChange" - CheckModelReferenceTargetMessage "error" - EnableParallelModelReferenceBuilds off - ParallelModelReferenceErrorOnInvalidPool on - ParallelModelReferenceMATLABWorkerInit "None" - ModelReferenceNumInstancesAllowed "Multi" - PropagateVarSize "Infer from blocks in model" - ModelReferencePassRootInputsByReference on - ModelReferenceMinAlgLoopOccurrences off - PropagateSignalLabelsOutOfModel off - SupportModelReferenceSimTargetCustomCode off - } - Simulink.SFSimCC { - $ObjectID 18 - Version "1.13.1" - SFSimEnableDebug on - SFSimOverflowDetection on - SFSimEcho on - SimBlas on - SimCtrlC on - SimExtrinsic on - SimIntegrity on - SimUseLocalCustomCode off - SimParseCustomCode on - SimBuildMode "sf_incremental_build" - SimGenImportedTypeDefs off - } - Simulink.RTWCC { - $BackupClass "Simulink.RTWCC" - $ObjectID 19 - Version "1.13.1" - Array { - Type "Cell" - Dimension 7 - Cell "IncludeHyperlinkInReport" - Cell "GenerateTraceInfo" - Cell "GenerateTraceReport" - Cell "GenerateTraceReportSl" - Cell "GenerateTraceReportSf" - Cell "GenerateTraceReportEml" - Cell "GenerateSLWebview" - PropName "DisabledProps" - } - SystemTargetFile "grt.tlc" - TLCOptions "" - GenCodeOnly off - MakeCommand "make_rtw" - GenerateMakefile on - PackageGeneratedCodeAndArtifacts off - PackageName "" - TemplateMakefile "grt_default_tmf" - PostCodeGenCommand "" - Description "Generic Real-Time Target" - GenerateReport off - SaveLog off - RTWVerbose on - RetainRTWFile off - ProfileTLC off - TLCDebug off - TLCCoverage off - TLCAssert off - ProcessScriptMode "Default" - ConfigurationMode "Optimized" - ProcessScript "grt_make_rtw_hook" - ConfigurationScript "" - ConfigAtBuild off - RTWUseLocalCustomCode off - RTWUseSimCustomCode off - CustomSourceCode "" - CustomHeaderCode "" - CustomInclude "" - CustomSource "" - CustomLibrary "" - CustomInitializer "" - CustomTerminator "" - Toolchain "Automatically locate an installed toolchain" - BuildConfiguration "Faster Builds" - IncludeHyperlinkInReport off - LaunchReport off - PortableWordSizes off - GenerateErtSFunction off - CreateSILPILBlock "None" - CodeExecutionProfiling off - CodeExecutionProfileVariable "executionProfile" - CodeProfilingSaveOptions "SummaryOnly" - CodeProfilingInstrumentation off - SILDebugging off - TargetLang "C" - IncludeBusHierarchyInRTWFileBlockHierarchyMap off - IncludeERTFirstTime off - GenerateTraceInfo off - GenerateTraceReport off - GenerateTraceReportSl off - GenerateTraceReportSf off - GenerateTraceReportEml off - GenerateCodeInfo off - GenerateWebview off - GenerateCodeMetricsReport off - GenerateCodeReplacementReport off - RTWCompilerOptimization "On" - RTWCustomCompilerOptimizations "" - CheckMdlBeforeBuild "Off" - CustomRebuildMode "OnUpdate" - DataInitializer "" - SharedConstantsCachingThreshold 1024 - Array { - Type "Handle" - Dimension 2 - Simulink.CodeAppCC { - $ObjectID 20 - Version "1.13.1" - Array { - Type "Cell" - Dimension 21 - Cell "IgnoreCustomStorageClasses" - Cell "IgnoreTestpoints" - Cell "InsertBlockDesc" - Cell "InsertPolySpaceComments" - Cell "SFDataObjDesc" - Cell "MATLABFcnDesc" - Cell "SimulinkDataObjDesc" - Cell "DefineNamingRule" - Cell "SignalNamingRule" - Cell "ParamNamingRule" - Cell "InlinedPrmAccess" - Cell "CustomSymbolStr" - Cell "CustomSymbolStrGlobalVar" - Cell "CustomSymbolStrType" - Cell "CustomSymbolStrField" - Cell "CustomSymbolStrFcn" - Cell "CustomSymbolStrFcnArg" - Cell "CustomSymbolStrBlkIO" - Cell "CustomSymbolStrTmpVar" - Cell "CustomSymbolStrMacro" - Cell "ReqsInCode" - PropName "DisabledProps" - } - ForceParamTrailComments off - GenerateComments on - IgnoreCustomStorageClasses on - IgnoreTestpoints off - IncHierarchyInIds off - MaxIdLength 31 - PreserveName off - PreserveNameWithParent off - ShowEliminatedStatement off - OperatorAnnotations off - IncAutoGenComments off - SimulinkDataObjDesc off - SFDataObjDesc off - MATLABFcnDesc off - IncDataTypeInIds off - MangleLength 1 - CustomSymbolStrGlobalVar "$R$N$M" - CustomSymbolStrType "$N$R$M_T" - CustomSymbolStrField "$N$M" - CustomSymbolStrFcn "$R$N$M$F" - CustomSymbolStrFcnArg "rt$I$N$M" - CustomSymbolStrBlkIO "rtb_$N$M" - CustomSymbolStrTmpVar "$N$M" - CustomSymbolStrMacro "$R$N$M" - CustomSymbolStrUtil "$N$C" - DefineNamingRule "None" - ParamNamingRule "None" - SignalNamingRule "None" - InsertBlockDesc off - InsertPolySpaceComments off - SimulinkBlockComments on - MATLABSourceComments off - EnableCustomComments off - InternalIdentifier "Shortened" - InlinedPrmAccess "Literals" - ReqsInCode off - UseSimReservedNames off - } - Simulink.GRTTargetCC { - $BackupClass "Simulink.TargetCC" - $ObjectID 21 - Version "1.13.1" - Array { - Type "Cell" - Dimension 16 - Cell "GeneratePreprocessorConditionals" - Cell "IncludeMdlTerminateFcn" - Cell "CombineOutputUpdateFcns" - Cell "SuppressErrorStatus" - Cell "ERTCustomFileBanners" - Cell "GenerateSampleERTMain" - Cell "GenerateTestInterfaces" - Cell "ModelStepFunctionPrototypeControlCompliant" - Cell "CPPClassGenCompliant" - Cell "PortableWordSizes" - Cell "PurelyIntegerCode" - Cell "SupportComplex" - Cell "SupportAbsoluteTime" - Cell "SupportContinuousTime" - Cell "SupportNonInlinedSFcns" - Cell "GenerateAllocFcn" - PropName "DisabledProps" - } - TargetFcnLib "ansi_tfl_table_tmw.mat" - TargetLibSuffix "" - TargetPreCompLibLocation "" - CodeReplacementLibrary "ANSI_C" - UtilityFuncGeneration "Auto" - ERTMultiwordTypeDef "System defined" - ERTMultiwordLength 256 - MultiwordLength 2048 - GenerateFullHeader on - GenerateSampleERTMain off - GenerateTestInterfaces off - IsPILTarget off - ModelReferenceCompliant on - ParMdlRefBuildCompliant on - CompOptLevelCompliant on - ConcurrentExecutionCompliant on - IncludeMdlTerminateFcn on - GeneratePreprocessorConditionals "Disable all" - CombineOutputUpdateFcns off - CombineSignalStateStructs off - SuppressErrorStatus off - ERTFirstTimeCompliant off - IncludeFileDelimiter "Auto" - ERTCustomFileBanners off - SupportAbsoluteTime on - LogVarNameModifier "rt_" - MatFileLogging on - MultiInstanceERTCode off - SupportNonFinite on - SupportComplex on - PurelyIntegerCode off - SupportContinuousTime on - SupportNonInlinedSFcns on - SupportVariableSizeSignals off - EnableShiftOperators on - ParenthesesLevel "Nominal" - MATLABClassNameForMDSCustomization "Simulink.SoftwareTarget.GRTCustomization" - ModelStepFunctionPrototypeControlCompliant off - CPPClassGenCompliant off - AutosarCompliant off - GRTInterface on - GenerateAllocFcn off - UseMalloc off - ExtMode off - ExtModeStaticAlloc off - ExtModeTesting off - ExtModeStaticAllocSize 1000000 - ExtModeTransport 0 - ExtModeMexFile "ext_comm" - ExtModeIntrfLevel "Level1" - RTWCAPISignals off - RTWCAPIParams off - RTWCAPIStates off - RTWCAPIRootIO off - GenerateASAP2 off - } - PropName "Components" - } - } - PropName "Components" - } - Name "Configuration" - CurrentDlgPage "Optimization" - ConfigPrmDlgPosition [ 360, 285, 1498, 915 ] - } - PropName "ConfigurationSets" - } - Simulink.ConfigSet { - $PropName "ActiveConfigurationSet" - $ObjectID 11 - } - Object { - $PropName "DataTransfer" - $ObjectID 22 - $ClassName "Simulink.GlobalDataTransfer" - DefaultTransitionBetweenSyncTasks "Ensure deterministic transfer (maximum delay)" - DefaultTransitionBetweenAsyncTasks "Ensure data integrity only" - DefaultTransitionBetweenContTasks "Ensure deterministic transfer (minimum delay)" - DefaultExtrapolationMethodBetweenContTasks "None" - AutoInsertRateTranBlk [0] - } - ExplicitPartitioning off - BlockDefaults { - ForegroundColor "black" - BackgroundColor "white" - DropShadow off - NamePlacement "normal" - FontName "Helvetica" - FontSize 10 - FontWeight "normal" - FontAngle "normal" - ShowName on - BlockRotation 0 - BlockMirror off - } - AnnotationDefaults { - HorizontalAlignment "center" - VerticalAlignment "middle" - ForegroundColor "black" - BackgroundColor "white" - DropShadow off - FontName "Helvetica" - FontSize 10 - FontWeight "normal" - FontAngle "normal" - UseDisplayTextAsClickCallback off - } - LineDefaults { - FontName "Helvetica" - FontSize 9 - FontWeight "normal" - FontAngle "normal" - } - MaskDefaults { - SelfModifiable "off" - IconFrame "on" - IconOpaque "on" - RunInitForIconRedraw "off" - IconRotate "none" - PortRotate "default" - IconUnits "autoscale" - } - MaskParameterDefaults { - Evaluate "on" - Tunable "on" - NeverSave "off" - Internal "off" - ReadOnly "off" - Enabled "on" - Visible "on" - ToolTip "on" - } - BlockParameterDefaults { - Block { - BlockType Constant - Value "1" - VectorParams1D on - SamplingMode "Sample based" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Inherit from 'Constant value'" - LockScale off - SampleTime "inf" - FramePeriod "inf" - PreserveConstantTs off - } - Block { - BlockType Delay - DelayLengthSource "Dialog" - DelayLength "2" - DelayLengthUpperLimit "100" - InitialConditionSource "Dialog" - InitialCondition "0.0" - ExternalReset "None" - PreventDirectFeedthrough off - DiagnosticForOutOfRangeDelayLength "None" - RemoveProtectionDelayLength off - InputProcessing "Elements as channels (sample based)" - UseCircularBuffer off - SampleTime "-1" - StateMustResolveToSignalObject off - CodeGenStateStorageClass "Auto" - } - Block { - BlockType FrameConversion - InheritSamplingMode off - OutFrame "Frame-based" - } - Block { - BlockType Inport - Port "1" - OutputFunctionCall off - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: auto" - LockScale off - BusOutputAsStruct off - PortDimensions "-1" - VarSizeSig "Inherit" - SampleTime "-1" - SignalType "auto" - SamplingMode "auto" - LatchByDelayingOutsideSignal off - LatchInputForFeedbackSignals off - Interpolate on - } - Block { - BlockType Math - Operator "exp" - OutputSignalType "auto" - SampleTime "-1" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Same as first input" - LockScale off - RndMeth "Floor" - SaturateOnIntegerOverflow on - IntermediateResultsDataTypeStr "Inherit: Inherit via internal rule" - AlgorithmType "Newton-Raphson" - Iterations "3" - } - Block { - BlockType Outport - Port "1" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: auto" - LockScale off - BusOutputAsStruct off - PortDimensions "-1" - VarSizeSig "Inherit" - SampleTime "-1" - SignalType "auto" - SamplingMode "auto" - SourceOfInitialOutputValue "Dialog" - OutputWhenDisabled "held" - InitialOutput "[]" - } - Block { - BlockType Product - Inputs "2" - Multiplication "Element-wise(.*)" - CollapseMode "All dimensions" - CollapseDim "1" - InputSameDT on - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Same as first input" - LockScale off - RndMeth "Zero" - SaturateOnIntegerOverflow on - SampleTime "-1" - } - Block { - BlockType RelationalOperator - Operator ">=" - InputSameDT on - OutDataTypeStr "Inherit: Logical (see Configuration Parameters: Optimization)" - ZeroCross on - SampleTime "-1" - } - Block { - BlockType Reshape - OutputDimensionality "1-D array" - OutputDimensions "[1,1]" - } - Block { - BlockType SignalViewerScope - Floating off - ModelBased off - TickLabels "OneTimeTick" - ZoomMode "on" - Grid "on" - TimeRange "auto" - YMin "-5" - YMax "5" - SaveToWorkspace off - SaveName "ScopeData" - DataFormat "Array" - LimitDataPoints on - MaxDataPoints "5000" - Decimation "1" - SampleInput off - SampleTime "0" - Disabled off - ScrollMode on - } - Block { - BlockType SubSystem - ShowPortLabels "FromPortIcon" - Permissions "ReadWrite" - PermitHierarchicalResolution "All" - TreatAsAtomicUnit off - CheckFcnCallInpInsideContextMsg off - SystemSampleTime "-1" - RTWFcnNameOpts "Auto" - RTWFileNameOpts "Auto" - FunctionInterfaceSpec "void_void" - RTWMemSecFuncInitTerm "Inherit from model" - RTWMemSecFuncExecute "Inherit from model" - RTWMemSecDataConstants "Inherit from model" - RTWMemSecDataInternal "Inherit from model" - RTWMemSecDataParameters "Inherit from model" - SimViewingDevice off - DataTypeOverride "UseLocalSettings" - DataTypeOverrideAppliesTo "AllNumericTypes" - MinMaxOverflowLogging "UseLocalSettings" - SFBlockType "NONE" - Variant off - GeneratePreprocessorConditionals off - ContentPreviewEnabled off - } - Block { - BlockType Sum - IconShape "rectangular" - Inputs "++" - CollapseMode "All dimensions" - CollapseDim "1" - InputSameDT on - AccumDataTypeStr "Inherit: Inherit via internal rule" - OutMin "[]" - OutMax "[]" - OutDataTypeStr "Inherit: Same as first input" - LockScale off - RndMeth "Floor" - SaturateOnIntegerOverflow on - SampleTime "-1" - } - Block { - BlockType UnitDelay - InitialCondition "0" - InputProcessing "Inherited" - SampleTime "1" - StateMustResolveToSignalObject off - CodeGenStateStorageClass "Auto" - HasFrameUpgradeWarning on - } - } - System { - Name "SimulatedNetwork2" - Location [8, 142, 1644, 1170] - Open on - ModelBrowserVisibility off - ModelBrowserWidth 200 - ScreenColor "white" - PaperOrientation "landscape" - PaperPositionMode "auto" - PaperType "usletter" - PaperUnits "inches" - TiledPaperMargins [0.500000, 0.500000, 0.500000, 0.500000] - TiledPageScale 1 - ShowPageBoundaries off - ZoomFactor "100" - ReportName "simulink-default.rpt" - SIDHighWatermark "96" - Block { - BlockType Inport - Name "Stimulus" - SID "37" - Position [115, 153, 145, 167] - ZOrder -1 - IconDisplay "Port number" - Port { - PortNumber 1 - Name "input" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType SubSystem - Name "Neuron 1" - SID "45" - Ports [2, 1] - Position [375, 123, 540, 272] - ZOrder -2 - MinAlgLoopOccurrences off - PropExecContextOutsideSubsystem off - RTWSystemCode "Auto" - FunctionWithSeparateData off - Opaque off - RequestExecContextInheritance off - MaskHideContents off - Object { - $PropName "MaskObject" - $ObjectID 23 - $ClassName "Simulink.Mask" - Array { - Type "Simulink.MaskParameter" - Dimension 4 - Object { - $ObjectID 24 - Type "edit" - Name "H" - Prompt "History Filter" - Value "H1" - } - Object { - $ObjectID 25 - Type "edit" - Name "E" - Prompt "Ensemble Filter" - Value "E1" - } - Object { - $ObjectID 26 - Type "edit" - Name "S" - Prompt "Stimulus Filter" - Value "S1" - } - Object { - $ObjectID 27 - Type "edit" - Name "mu" - Prompt "Baseline Firing Rate" - Value "mu1" - } - PropName "Parameters" - } - } - System { - Name "Neuron 1" - Location [276, 77, 1359, 678] - Open on - ModelBrowserVisibility off - ModelBrowserWidth 200 - ScreenColor "white" - PaperOrientation "landscape" - PaperPositionMode "auto" - PaperType "usletter" - PaperUnits "inches" - TiledPaperMargins [0.500000, 0.500000, 0.500000, 0.500000] - TiledPageScale 1 - ShowPageBoundaries off - ZoomFactor "100" - Block { - BlockType Inport - Name "stimulus" - SID "47" - Position [45, 228, 75, 242] - ZOrder -1 - IconDisplay "Port number" - } - Block { - BlockType Inport - Name "ensemble" - SID "48" - Position [45, 303, 75, 317] - ZOrder -2 - Port "2" - IconDisplay "Port number" - } - Block { - BlockType Sum - Name "Add" - SID "3" - Ports [4, 1] - Position [265, 155, 295, 195] - ZOrder -3 - Inputs "++++" - InputSameDT off - OutDataTypeStr "Inherit: Inherit via internal rule" - SaturateOnIntegerOverflow off - } - Block { - BlockType Sum - Name "Add1" - SID "32" - Ports [2, 1] - Position [430, 240, 460, 270] - ZOrder -4 - IconShape "round" - Inputs "|++" - InputSameDT off - OutDataTypeStr "Inherit: Inherit via internal rule" - SaturateOnIntegerOverflow off - } - Block { - BlockType Constant - Name "Constant" - SID "1" - Position [205, 80, 235, 110] - ZOrder -5 - BlockRotation 270 - BlockMirror on - BackgroundColor "magenta" - NamePlacement "alternate" - Value "mu" - } - Block { - BlockType Constant - Name "Constant1" - SID "33" - Position [430, 330, 460, 360] - ZOrder -6 - BlockRotation 270 - BackgroundColor "magenta" - } - Block { - BlockType Product - Name "Divide" - SID "31" - Ports [2, 1] - Position [505, 157, 535, 188] - ZOrder -7 - Inputs "*/" - InputSameDT off - OutDataTypeStr "Inherit: Inherit via internal rule" - RndMeth "Floor" - SaturateOnIntegerOverflow off - Port { - PortNumber 1 - Name "s2" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Reference - Name "Ensemble Effect" - SID "43" - Ports [1, 1] - Position [100, 292, 195, 328] - ZOrder -8 - BackgroundColor "darkGreen" - LibraryVersion "1.108" - SourceBlock "cstblocks/LTI System" - SourceType "LTI Block" - ContentPreviewEnabled off - sys "E" - IC "[]" - } - Block { - BlockType FrameConversion - Name "Frame Status Conversion" - SID "11" - Ports [1, 1] - Position [815, 165, 870, 205] - ZOrder -9 - OutFrame "Sample-based" - } - Block { - BlockType Delay - Name "Integer Delay" - SID "22" - Ports [1, 1] - Position [100, 28, 135, 62] - ZOrder -10 - BlockMirror on - UserDataPersistent on - UserData "DataTag0" - InputPortMap "u0" - DelayLength "1" - } - Block { - BlockType Math - Name "Math\nFunction" - SID "8" - Ports [1, 1] - Position [365, 160, 395, 190] - ZOrder -11 - Port { - PortNumber 1 - Name "s1" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Reference - Name "Random Source" - SID "12" - Ports [0, 1] - Position [676, 265, 714, 300] - ZOrder -12 - BlockRotation 270 - LibraryVersion "1.733" - UserDataPersistent on - UserData "DataTag1" - Diagnostics "AllowInheritedTsInSrc" - SourceBlock "dspsrcs4/Random\nSource" - SourceType "Random Source" - SrcType "Uniform" - NormMethod "Ziggurat" - CltLength "12" - MinVal "0" - MaxVal "1" - MeanVal "0" - VarVal "1" - RepMode "Not repeatable" - rawSeed "seed" - IsInherit on - SampMode "Continuous" - SampTime "Ts" - SampFrame "dsp_sampFrame" - DataType "Double" - OutComplex "Real" - } - Block { - BlockType RelationalOperator - Name "Relational Operator" - SID "13" - Ports [2, 1] - Position [720, 167, 750, 198] - ZOrder -13 - ShowName off - Operator ">" - OutDataTypeStr "float('double')" - } - Block { - BlockType Reshape - Name "Reshape" - SID "14" - Ports [1, 1] - Position [910, 173, 940, 197] - ZOrder -14 - ShowName off - OutputDimensions "[sampPerFrame,max(length(P),length(seed))]" - Port { - PortNumber 1 - Name "spike process" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Reference - Name "Self-History" - SID "5" - Ports [1, 1] - Position [100, 152, 195, 188] - ZOrder -15 - BackgroundColor "orange" - LibraryVersion "1.108" - SourceBlock "cstblocks/LTI System" - SourceType "LTI Block" - ContentPreviewEnabled off - sys "H" - IC "[]" - } - Block { - BlockType Reference - Name "Stimulus Effect" - SID "6" - Ports [1, 1] - Position [100, 217, 195, 253] - ZOrder -16 - BackgroundColor "darkGreen" - LibraryVersion "1.108" - SourceBlock "cstblocks/LTI System" - SourceType "LTI Block" - ContentPreviewEnabled off - sys "S" - IC "[]" - } - Block { - BlockType Outport - Name "spikeTrain" - SID "46" - Position [990, 178, 1020, 192] - ZOrder -17 - IconDisplay "Port number" - } - Line { - ZOrder 1 - SrcBlock "Constant" - SrcPort 1 - Points [0, 45] - DstBlock "Add" - DstPort 1 - } - Line { - ZOrder 2 - SrcBlock "Self-History" - SrcPort 1 - DstBlock "Add" - DstPort 2 - } - Line { - ZOrder 3 - SrcBlock "Stimulus Effect" - SrcPort 1 - Points [15, 0; 0, -55] - DstBlock "Add" - DstPort 3 - } - Line { - ZOrder 4 - SrcBlock "Add" - SrcPort 1 - DstBlock "Math\nFunction" - DstPort 1 - } - Line { - ZOrder 5 - SrcBlock "Frame Status Conversion" - SrcPort 1 - DstBlock "Reshape" - DstPort 1 - } - Line { - Name "spike process" - ZOrder 6 - SrcBlock "Reshape" - SrcPort 1 - Points [25, 0] - Branch { - ZOrder 7 - Labels [1, 0] - Points [0, -140] - DstBlock "Integer Delay" - DstPort 1 - } - Branch { - ZOrder 8 - DstBlock "spikeTrain" - DstPort 1 - } - } - Line { - ZOrder 9 - SrcBlock "Relational Operator" - SrcPort 1 - DstBlock "Frame Status Conversion" - DstPort 1 - } - Line { - ZOrder 10 - SrcBlock "Random Source" - SrcPort 1 - Points [0, -70] - DstBlock "Relational Operator" - DstPort 2 - } - Line { - ZOrder 11 - SrcBlock "Integer Delay" - SrcPort 1 - Points [-65, 0; 0, 125] - DstBlock "Self-History" - DstPort 1 - } - Line { - ZOrder 12 - SrcBlock "Constant1" - SrcPort 1 - DstBlock "Add1" - DstPort 2 - } - Line { - Name "s1" - ZOrder 13 - Labels [0, 0] - SrcBlock "Math\nFunction" - SrcPort 1 - Points [5, 0] - Branch { - ZOrder 14 - Points [0, 80] - DstBlock "Add1" - DstPort 1 - } - Branch { - ZOrder 15 - Labels [1, 0] - Points [85, 0] - DstBlock "Divide" - DstPort 1 - } - } - Line { - ZOrder 16 - SrcBlock "Add1" - SrcPort 1 - Points [10, 0; 0, -75] - DstBlock "Divide" - DstPort 2 - } - Line { - Name "s2" - ZOrder 17 - Labels [0, 0] - SrcBlock "Divide" - SrcPort 1 - DstBlock "Relational Operator" - DstPort 1 - } - Line { - ZOrder 18 - SrcBlock "Ensemble Effect" - SrcPort 1 - Points [25, 0; 0, -120] - DstBlock "Add" - DstPort 4 - } - Line { - ZOrder 19 - SrcBlock "stimulus" - SrcPort 1 - DstBlock "Stimulus Effect" - DstPort 1 - } - Line { - ZOrder 20 - SrcBlock "ensemble" - SrcPort 1 - DstBlock "Ensemble Effect" - DstPort 1 - } - Annotation { - SID "89" - Name "GLM Model \n\n " - " \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n. " - Position [104, 166, 507, 588] - AutoSize on - WordWrap off - BackgroundColor "lightBlue" - ZOrder -1 - FontName "Arial Narrow" - FontSize 18 - } - Annotation { - SID "90" - Name "Coin flip with\np= \\lambda \\cdot \\Delta\n\n\n\n\n\n\n\n\n\n\n." - Position [724, 261, 806, 534] - AutoSize on - WordWrap off - Interpreter "tex" - TeXMode on - ZOrder -2 - FontName "Arial Narrow" - FontSize 18 - } - Annotation { - SID "91" - Name "Inverse of Logistic Link Function\n \n\n\n\n\n\n\n\n\n\n" - ". " - Position [459, 251, 671, 505] - AutoSize on - WordWrap off - BackgroundColor "yellow" - ZOrder -3 - FontName "Arial Narrow" - FontSize 18 - } - Annotation { - SID "92" - Name "\\lambda \\cdot \\Delta= e^{X \\cdot \\beta}/(1+e^{X\\cdot \\beta})" - Position [449, 401, 584, 426] - AutoSize on - WordWrap off - Interpreter "tex" - TeXMode on - ZOrder -4 - FontName "Arial Narrow" - FontSize 18 - } - } - } - Block { - BlockType SubSystem - Name "Neuron 2" - SID "68" - Ports [2, 1] - Position [375, 353, 540, 502] - ZOrder -3 - MinAlgLoopOccurrences off - PropExecContextOutsideSubsystem off - RTWSystemCode "Auto" - FunctionWithSeparateData off - Opaque off - RequestExecContextInheritance off - MaskHideContents off - Object { - $PropName "MaskObject" - $ObjectID 28 - $ClassName "Simulink.Mask" - Array { - Type "Simulink.MaskParameter" - Dimension 4 - Object { - $ObjectID 29 - Type "edit" - Name "H" - Prompt "History Filter" - Value "H2" - } - Object { - $ObjectID 30 - Type "edit" - Name "E" - Prompt "Ensemble Filter" - Value "E2" - } - Object { - $ObjectID 31 - Type "edit" - Name "S" - Prompt "Stimulus Filter" - Value "S2" - } - Object { - $ObjectID 32 - Type "edit" - Name "mu" - Prompt "Baseline Firing Rate" - Value "mu2" - } - PropName "Parameters" - } - } - System { - Name "Neuron 2" - Location [276, 77, 1359, 678] - Open off - ModelBrowserVisibility off - ModelBrowserWidth 200 - ScreenColor "white" - PaperOrientation "landscape" - PaperPositionMode "auto" - PaperType "usletter" - PaperUnits "inches" - TiledPaperMargins [0.500000, 0.500000, 0.500000, 0.500000] - TiledPageScale 1 - ShowPageBoundaries off - ZoomFactor "100" - Block { - BlockType Inport - Name "stimulus" - SID "69" - Position [45, 228, 75, 242] - ZOrder -1 - IconDisplay "Port number" - } - Block { - BlockType Inport - Name "ensemble" - SID "70" - Position [45, 303, 75, 317] - ZOrder -2 - Port "2" - IconDisplay "Port number" - } - Block { - BlockType Sum - Name "Add" - SID "71" - Ports [4, 1] - Position [265, 155, 295, 195] - ZOrder -3 - Inputs "++++" - InputSameDT off - OutDataTypeStr "Inherit: Inherit via internal rule" - SaturateOnIntegerOverflow off - } - Block { - BlockType Sum - Name "Add1" - SID "72" - Ports [2, 1] - Position [430, 240, 460, 270] - ZOrder -4 - IconShape "round" - Inputs "|++" - InputSameDT off - OutDataTypeStr "Inherit: Inherit via internal rule" - SaturateOnIntegerOverflow off - } - Block { - BlockType Constant - Name "Constant" - SID "73" - Position [205, 80, 235, 110] - ZOrder -5 - BlockRotation 270 - BlockMirror on - BackgroundColor "magenta" - NamePlacement "alternate" - Value "mu" - } - Block { - BlockType Constant - Name "Constant1" - SID "74" - Position [430, 330, 460, 360] - ZOrder -6 - BlockRotation 270 - BackgroundColor "magenta" - } - Block { - BlockType Product - Name "Divide" - SID "75" - Ports [2, 1] - Position [505, 157, 535, 188] - ZOrder -7 - Inputs "*/" - InputSameDT off - OutDataTypeStr "Inherit: Inherit via internal rule" - RndMeth "Floor" - SaturateOnIntegerOverflow off - Port { - PortNumber 1 - Name "s2" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Reference - Name "Ensemble Effect" - SID "76" - Ports [1, 1] - Position [100, 292, 195, 328] - ZOrder -8 - BackgroundColor "darkGreen" - LibraryVersion "1.108" - SourceBlock "cstblocks/LTI System" - SourceType "LTI Block" - ContentPreviewEnabled off - sys "E" - IC "[]" - } - Block { - BlockType FrameConversion - Name "Frame Status Conversion" - SID "77" - Ports [1, 1] - Position [815, 165, 870, 205] - ZOrder -9 - OutFrame "Sample-based" - } - Block { - BlockType Delay - Name "Integer Delay" - SID "78" - Ports [1, 1] - Position [100, 28, 135, 62] - ZOrder -10 - BlockMirror on - UserDataPersistent on - UserData "DataTag2" - InputPortMap "u0" - DelayLength "1" - } - Block { - BlockType Math - Name "Math\nFunction" - SID "79" - Ports [1, 1] - Position [365, 160, 395, 190] - ZOrder -11 - Port { - PortNumber 1 - Name "s1" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Reference - Name "Random Source" - SID "80" - Ports [0, 1] - Position [676, 265, 714, 300] - ZOrder -12 - BlockRotation 270 - LibraryVersion "1.733" - UserDataPersistent on - UserData "DataTag3" - Diagnostics "AllowInheritedTsInSrc" - SourceBlock "dspsrcs4/Random\nSource" - SourceType "Random Source" - SrcType "Uniform" - NormMethod "Ziggurat" - CltLength "12" - MinVal "0" - MaxVal "1" - MeanVal "0" - VarVal "1" - RepMode "Not repeatable" - rawSeed "seed" - IsInherit on - SampMode "Continuous" - SampTime "Ts" - SampFrame "dsp_sampFrame" - DataType "Double" - OutComplex "Real" - } - Block { - BlockType RelationalOperator - Name "Relational Operator" - SID "81" - Ports [2, 1] - Position [720, 167, 750, 198] - ZOrder -13 - ShowName off - Operator ">" - OutDataTypeStr "float('double')" - } - Block { - BlockType Reshape - Name "Reshape" - SID "82" - Ports [1, 1] - Position [910, 173, 940, 197] - ZOrder -14 - ShowName off - OutputDimensions "[sampPerFrame,max(length(P),length(seed))]" - Port { - PortNumber 1 - Name "spike process" - RTWStorageClass "Auto" - DataLoggingNameMode "SignalName" - } - } - Block { - BlockType Reference - Name "Self-History" - SID "83" - Ports [1, 1] - Position [100, 152, 195, 188] - ZOrder -15 - BackgroundColor "orange" - LibraryVersion "1.108" - SourceBlock "cstblocks/LTI System" - SourceType "LTI Block" - ContentPreviewEnabled off - sys "H" - IC "[]" - } - Block { - BlockType Reference - Name "Stimulus Effect" - SID "84" - Ports [1, 1] - Position [100, 217, 195, 253] - ZOrder -16 - BackgroundColor "darkGreen" - LibraryVersion "1.108" - SourceBlock "cstblocks/LTI System" - SourceType "LTI Block" - ContentPreviewEnabled off - sys "S" - IC "[]" - } - Block { - BlockType Outport - Name "spikeTrain" - SID "85" - Position [990, 178, 1020, 192] - ZOrder -17 - IconDisplay "Port number" - } - Line { - ZOrder 1 - SrcBlock "Constant" - SrcPort 1 - Points [0, 45] - DstBlock "Add" - DstPort 1 - } - Line { - ZOrder 2 - SrcBlock "Self-History" - SrcPort 1 - DstBlock "Add" - DstPort 2 - } - Line { - ZOrder 3 - SrcBlock "Stimulus Effect" - SrcPort 1 - Points [15, 0; 0, -55] - DstBlock "Add" - DstPort 3 - } - Line { - ZOrder 4 - SrcBlock "Add" - SrcPort 1 - DstBlock "Math\nFunction" - DstPort 1 - } - Line { - ZOrder 5 - SrcBlock "Frame Status Conversion" - SrcPort 1 - DstBlock "Reshape" - DstPort 1 - } - Line { - Name "spike process" - ZOrder 6 - SrcBlock "Reshape" - SrcPort 1 - Points [25, 0] - Branch { - ZOrder 7 - Labels [1, 0] - Points [0, -140] - DstBlock "Integer Delay" - DstPort 1 - } - Branch { - ZOrder 8 - DstBlock "spikeTrain" - DstPort 1 - } - } - Line { - ZOrder 9 - SrcBlock "Relational Operator" - SrcPort 1 - DstBlock "Frame Status Conversion" - DstPort 1 - } - Line { - ZOrder 10 - SrcBlock "Random Source" - SrcPort 1 - Points [0, -70] - DstBlock "Relational Operator" - DstPort 2 - } - Line { - ZOrder 11 - SrcBlock "Integer Delay" - SrcPort 1 - Points [-65, 0; 0, 125] - DstBlock "Self-History" - DstPort 1 - } - Line { - ZOrder 12 - SrcBlock "Constant1" - SrcPort 1 - DstBlock "Add1" - DstPort 2 - } - Line { - Name "s1" - ZOrder 13 - Labels [0, 0] - SrcBlock "Math\nFunction" - SrcPort 1 - Points [5, 0] - Branch { - ZOrder 14 - Points [0, 80] - DstBlock "Add1" - DstPort 1 - } - Branch { - ZOrder 15 - Labels [1, 0] - Points [85, 0] - DstBlock "Divide" - DstPort 1 - } - } - Line { - ZOrder 16 - SrcBlock "Add1" - SrcPort 1 - Points [10, 0; 0, -75] - DstBlock "Divide" - DstPort 2 - } - Line { - Name "s2" - ZOrder 17 - Labels [0, 0] - SrcBlock "Divide" - SrcPort 1 - DstBlock "Relational Operator" - DstPort 1 - } - Line { - ZOrder 18 - SrcBlock "Ensemble Effect" - SrcPort 1 - Points [25, 0; 0, -120] - DstBlock "Add" - DstPort 4 - } - Line { - ZOrder 19 - SrcBlock "stimulus" - SrcPort 1 - DstBlock "Stimulus Effect" - DstPort 1 - } - Line { - ZOrder 20 - SrcBlock "ensemble" - SrcPort 1 - DstBlock "Ensemble Effect" - DstPort 1 - } - Annotation { - SID "93" - Name "GLM Model \n\n " - " \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n. " - Position [104, 166, 507, 588] - AutoSize on - WordWrap off - BackgroundColor "lightBlue" - ZOrder -1 - FontName "Arial Narrow" - FontSize 18 - } - Annotation { - SID "94" - Name "Coin flip with\np= \\lambda \\cdot \\Delta\n\n\n\n\n\n\n\n\n\n\n." - Position [724, 261, 806, 534] - AutoSize on - WordWrap off - Interpreter "tex" - TeXMode on - ZOrder -2 - FontName "Arial Narrow" - FontSize 18 - } - Annotation { - SID "95" - Name "Inverse of Logistic Link Function\n \n\n\n\n\n\n\n\n\n\n" - ". " - Position [459, 251, 671, 505] - AutoSize on - WordWrap off - BackgroundColor "yellow" - ZOrder -3 - FontName "Arial Narrow" - FontSize 18 - } - Annotation { - SID "96" - Name "\\lambda \\cdot \\Delta= e^{X \\cdot \\beta}/(1+e^{X\\cdot \\beta})" - Position [449, 401, 584, 426] - AutoSize on - WordWrap off - Interpreter "tex" - TeXMode on - ZOrder -4 - FontName "Arial Narrow" - FontSize 18 - } - } - } - Block { - BlockType UnitDelay - Name "Unit Delay" - SID "88" - Position [310, 218, 345, 252] - ZOrder -4 - InputProcessing "Elements as channels (sample based)" - SampleTime "-1" - } - Block { - BlockType UnitDelay - Name "Unit Delay1" - SID "87" - Position [310, 448, 345, 482] - ZOrder -5 - InputProcessing "Elements as channels (sample based)" - SampleTime "-1" - } - Block { - BlockType Outport - Name "pp" - SID "26" - Position [610, 193, 640, 207] - ZOrder -6 - IconDisplay "Port number" - } - Block { - BlockType Outport - Name "pp1" - SID "67" - Position [610, 423, 640, 437] - ZOrder -7 - Port "2" - IconDisplay "Port number" - } - Block { - BlockType SignalViewerScope - Name "Scope" - SID "28" - Ports [] - Position [20, 15, 60, 55] - ZOrder -8 - IOType "viewer" - List { - ListType IOSignalStrings - set0ParseKeys "19,27" - set0Sigs "Neuron 1/Reshape:o1Neuron 1/Stimulus Effect:o1" - } - Location [1, 53, 1601, 1151] - Open off - NumInputPorts "1" - List { - ListType AxesTitles - axes1 "%" - } - ShowDataMarkers off - ShowLegends off - MaxDataPoints "7500" - RefreshTime 0.035000 - } - Block { - BlockType SignalViewerScope - Name "Scope1" - SID "29" - Ports [] - Position [20, 15, 60, 55] - ZOrder -9 - IOType "viewer" - List { - ListType IOSignalStrings - set0ParseKeys "25,18" - set0Sigs "Neuron 1/Math Function:o1Neuron 1/Divide:o1" - } - Location [1, 53, 1601, 1151] - Open off - NumInputPorts "1" - List { - ListType AxesTitles - axes1 "%" - } - ShowDataMarkers off - ShowLegends off - SaveName "ScopeData1" - MaxDataPoints "7500" - RefreshTime 0.035000 - } - Block { - BlockType SignalViewerScope - Name "Scope2" - SID "38" - Ports [] - Position [20, 15, 60, 55] - ZOrder -10 - IOType "viewer" - List { - ListType IOSignalStrings - set0ParseKeys "24" - set0Sigs "Neuron 1/Self-History:o1" - } - Location [5, 53, 1605, 1151] - Open off - NumInputPorts "1" - List { - ListType AxesTitles - axes1 "%" - } - ShowDataMarkers off - ShowLegends off - SaveName "ScopeData2" - MaxDataPoints "7500" - RefreshTime 0.035000 - } - Line { - Name "input" - ZOrder 1 - Labels [0, 0] - SrcBlock "Stimulus" - SrcPort 1 - Points [45, 0] - Branch { - ZOrder 2 - DstBlock "Neuron 1" - DstPort 1 - } - Branch { - ZOrder 3 - Points [0, 230] - DstBlock "Neuron 2" - DstPort 1 - } - } - Line { - ZOrder 4 - SrcBlock "Neuron 1" - SrcPort 1 - Points [25, 0] - Branch { - ZOrder 5 - DstBlock "pp" - DstPort 1 - } - Branch { - ZOrder 6 - Points [0, 100; -275, 0] - DstBlock "Unit Delay1" - DstPort 1 - } - } - Line { - ZOrder 7 - SrcBlock "Neuron 2" - SrcPort 1 - Points [35, 0] - Branch { - ZOrder 8 - DstBlock "pp1" - DstPort 1 - } - Branch { - ZOrder 9 - Points [0, -100; -285, 0] - DstBlock "Unit Delay" - DstPort 1 - } - } - Line { - ZOrder 10 - SrcBlock "Unit Delay1" - SrcPort 1 - DstBlock "Neuron 2" - DstPort 2 - } - Line { - ZOrder 11 - SrcBlock "Unit Delay" - SrcPort 1 - DstBlock "Neuron 1" - DstPort 2 - } - } -} -MatData { - NumRecords 4 - DataRecord { - Tag DataTag0 - Data " %)30 . B 8 ( @ % \" $ ! 0 % 0 $P $ 3 :&%S26" - "YH97)I=&5D3W!T:6]N #@ # & \" D\" !0 @ ! 0 $ @ ! $ " - } - DataRecord { - Tag DataTag1 - Data " %)30 . V 8 ( @ % \" $ ! 0 % 0 \"0 $ 2 4V5E9" - " 4V5E9$9L86< #@ #@ & \" 0 !0 @ ! !0 $ $ 4 R,S$Q,P " - "X ! !@ @ $ 4 ( 0 T ! ! - 1&].;W13879E4V5E9 " - } - DataRecord { - Tag DataTag2 - Data " %)30 . B 8 ( @ % \" $ ! 0 % 0 $P $ 3 :&%S26" - "YH97)I=&5D3W!T:6]N #@ # & \" D\" !0 @ ! 0 $ @ ! $ " - } - DataRecord { - Tag DataTag3 - Data " %)30 . V 8 ( @ % \" $ ! 0 % 0 \"0 $ 2 4V5E9" - " 4V5E9$9L86< #@ #@ & \" 0 !0 @ ! !0 $ $ 4 R,S$Q,P " - "X ! !@ @ $ 4 ( 0 T ! ! - 1&].;W13879E4V5E9 " - } -} diff --git a/helpfiles/SimulatedNetwork2.png b/helpfiles/SimulatedNetwork2.png deleted file mode 100644 index 0a872a41..00000000 Binary files a/helpfiles/SimulatedNetwork2.png and /dev/null differ diff --git a/helpfiles/StimulusDecode2D.html b/helpfiles/StimulusDecode2D.html deleted file mode 100644 index 041984f9..00000000 --- a/helpfiles/StimulusDecode2D.html +++ /dev/null @@ -1,259 +0,0 @@ - - - - - StimulusDecode2D

Contents

2-D Stimulus Decode

Here we simulate hippocampal place cell receptive fields and their firing during a 2-d spatial task. We then use the ensemble firing activity to estimate the path based on the only the point process observations

delta = 0.001;
-Tmax = 1;
-time = 0:delta:Tmax;
-px = zeros(1,length(time));
-py = zeros(1,length(time));
-Q=.01;
-r =  Q.*randn(2,length(time));
-vx = cumsum(r(1,:))';
-vy = cumsum(r(2,:))';
-
-velSig = SignalObj(time, [vx, vy],'vel');
-posSig = velSig.integral;
-posData = posSig.data;
-px = posData(:,1);
-py = posData(:,2);
-% N=100; A=1; B=ones(1,N)./N;
-% px = filtfilt(B,A,px);
-% py = filtfilt(B,A,py);
-figure;
-plot(px,py);
-title('Simulated X-Y trajectory');
-xlabel('x'); ylabel('y');
-

Generate random receptive fields to simulate different neurons

clear lambdaCIF lambda tempSpikeColl n spikeColl
-numRealizations=80;
-
-coeffs = -abs(1*randn(numRealizations,5));
-coeffs = [-2*abs(randn(numRealizations,1)) coeffs];
-dataMat = [ones(length(time),1) px py px.^2 py.^2 px.*py];
- for i=1:numRealizations
-     tempData  = exp(dataMat*coeffs(i,:)');
-     lambdaData = tempData./(1+tempData);
-     lambda{i}=Covariate(time,lambdaData./delta, '\Lambda(t)','time','s','Hz',{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));
-
-     lambdaCIF{i} = CIF(coeffs(i,:),{'1','x','y','x^2','y^2','x*y'},{'x','y'},'binomial');
- end
-
-
- % View the different neuron conditional intensity functions
- figure;
- for i=1:length(lambda)
-    lambda{i}.plot;
- end
- legend off;
-
-% Visualize Simulated Receptive Fields
-clear placeField;
-[X,Y]=meshgrid(-2:.1:2,-2:.1:2);
-figure;
-
-for i=1:numRealizations
-tempData = coeffs(i,1) + coeffs(i,2)*X + coeffs(i,3)*Y +coeffs(i,4)*X.^2 + coeffs(i,5)*Y.^2 + coeffs(i,6).*X.*Y;
-placeField{i} = exp(tempData)./(1+exp(tempData))./delta; %rate based on logistic link function
-
-end
-
-fact=factor(numRealizations);
-
-for i=1:numRealizations
-   if(length(fact)==1)
-    subplot(1,numRealizations,i);
-   elseif(length(fact)==2)
-    subplot(fact(1),fact(2),i);
-   elseif(length(fact)==3)
-    subplot(fact(1)*fact(2),fact(3),i);
-   end
-    pcolor(X,Y,placeField{i}), shading interp
-    axis square;
-    set(gca,'xtick',[],'ytick',[]);
-
-end
-

Decode the x-y trajectory

 spikeColl = nstColl(n);
- spikeColl.resample(1/delta);
- dN = spikeColl.dataToMatrix;
-
vx=10*std(px(2:end)-px(1:end-1));
-vy=10*std(py(2:end)-py(1:end-1));
-Q=[vx 0;0 vy];
-Px0=.1*eye(2,2); A=1*eye(2,2);
-% The PPDecodeFilter uses the matlab symbolic toolbox to evaluate the
-% gradient and hessian of the CIF. It is currently not working properly.
-[x_p, Pe_p, x_u, Pe_u] = DecodingAlgorithms.PPDecodeFilter(A, Q, Px0, dN',lambdaCIF,delta);
-figure;
-plot(x_u(1,:),x_u(2,:),'b',px,py,'k')
-legend('predicted path','actual path');
-
\ No newline at end of file diff --git a/helpfiles/StimulusDecode2D.m b/helpfiles/StimulusDecode2D.m deleted file mode 100644 index fa30e542..00000000 --- a/helpfiles/StimulusDecode2D.m +++ /dev/null @@ -1,100 +0,0 @@ -%% 2-D Stimulus Decode -% Here we simulate hippocampal place cell receptive fields and their firing -% during a 2-d spatial task. We then use the ensemble firing activity to -% estimate the path based on the only the point process observations - -delta = 0.001; -Tmax = 1; -time = 0:delta:Tmax; -px = zeros(1,length(time)); -py = zeros(1,length(time)); -Q=.01; -r = Q.*randn(2,length(time)); -vx = cumsum(r(1,:))'; -vy = cumsum(r(2,:))'; - -velSig = SignalObj(time, [vx, vy],'vel'); -posSig = velSig.integral; -posData = posSig.data; -px = posData(:,1); -py = posData(:,2); -% N=100; A=1; B=ones(1,N)./N; -% px = filtfilt(B,A,px); -% py = filtfilt(B,A,py); -figure; -plot(px,py); -title('Simulated X-Y trajectory'); -xlabel('x'); ylabel('y'); - - -%% Generate random receptive fields to simulate different neurons -clear lambdaCIF lambda tempSpikeColl n spikeColl -numRealizations=80; - -coeffs = -abs(1*randn(numRealizations,5)); -coeffs = [-2*abs(randn(numRealizations,1)) coeffs]; -dataMat = [ones(length(time),1) px py px.^2 py.^2 px.*py]; - for i=1:numRealizations - tempData = exp(dataMat*coeffs(i,:)'); - lambdaData = tempData./(1+tempData); - lambda{i}=Covariate(time,lambdaData./delta, '\Lambda(t)','time','s','Hz',{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)); - - lambdaCIF{i} = CIF(coeffs(i,:),{'1','x','y','x^2','y^2','x*y'},{'x','y'},'binomial'); - end - - - % View the different neuron conditional intensity functions - figure; - for i=1:length(lambda) - lambda{i}.plot; - end - legend off; - -% Visualize Simulated Receptive Fields -clear placeField; -[X,Y]=meshgrid(-2:.1:2,-2:.1:2); -figure; - -for i=1:numRealizations -tempData = coeffs(i,1) + coeffs(i,2)*X + coeffs(i,3)*Y +coeffs(i,4)*X.^2 + coeffs(i,5)*Y.^2 + coeffs(i,6).*X.*Y; -placeField{i} = exp(tempData)./(1+exp(tempData))./delta; %rate based on logistic link function - -end - -fact=factor(numRealizations); - -for i=1:numRealizations - if(length(fact)==1) - subplot(1,numRealizations,i); - elseif(length(fact)==2) - subplot(fact(1),fact(2),i); - elseif(length(fact)==3) - subplot(fact(1)*fact(2),fact(3),i); - end - pcolor(X,Y,placeField{i}), shading interp - axis square; - set(gca,'xtick',[],'ytick',[]); - -end -%% Decode the x-y trajectory - - spikeColl = nstColl(n); - spikeColl.resample(1/delta); - dN = spikeColl.dataToMatrix; - -%% -vx=var(px(2:end)-px(1:end-1)); -vy=var(py(2:end)-py(1:end-1)); -Q=[vx 0;0 vy]; -Px0=.1*eye(2,2); A=1*eye(2,2); -% The PPDecodeFilter uses the matlab symbolic toolbox to evaluate the -% gradient and hessian of the CIF. It is currently not working properly. -[x_p, Pe_p, x_u, Pe_u] = DecodingAlgorithms.PPDecodeFilter(A, Q, Px0, dN',lambdaCIF,delta); -figure; -plot(x_u(1,:),x_u(2,:),'b',px,py,'k') -legend('predicted path','actual path'); - diff --git a/helpfiles/StimulusDecode2D.png b/helpfiles/StimulusDecode2D.png deleted file mode 100644 index 8ea1c050..00000000 Binary files a/helpfiles/StimulusDecode2D.png and /dev/null differ diff --git a/helpfiles/StimulusDecode2D_01.png b/helpfiles/StimulusDecode2D_01.png deleted file mode 100644 index d06983bf..00000000 Binary files a/helpfiles/StimulusDecode2D_01.png and /dev/null differ diff --git a/helpfiles/StimulusDecode2D_02.png b/helpfiles/StimulusDecode2D_02.png deleted file mode 100644 index e672204e..00000000 Binary files a/helpfiles/StimulusDecode2D_02.png and /dev/null differ diff --git a/helpfiles/StimulusDecode2D_03.png b/helpfiles/StimulusDecode2D_03.png deleted file mode 100644 index 3ba2e5d5..00000000 Binary files a/helpfiles/StimulusDecode2D_03.png and /dev/null differ diff --git a/helpfiles/StimulusDecode2D_04.png b/helpfiles/StimulusDecode2D_04.png deleted file mode 100644 index b384e93c..00000000 Binary files a/helpfiles/StimulusDecode2D_04.png and /dev/null differ diff --git a/helpfiles/TrialConfigExamples.html b/helpfiles/TrialConfigExamples.html deleted file mode 100644 index c93b55e2..00000000 --- a/helpfiles/TrialConfigExamples.html +++ /dev/null @@ -1,79 +0,0 @@ - - - - - TrialConfig Examples

TrialConfig Examples

tcObj=TrialConfig(covMask,sampleRate, history,minTime,maxTime)

tc1 = TrialConfig({'Force','f_x'},2000,[.1 .2],-1,2);
-tc2 = TrialConfig({'Position','x'},2000,[.1 .2],-1,2);
-tcc = ConfigColl({tc1,tc2});
-
\ No newline at end of file diff --git a/helpfiles/TrialConfigExamples.m b/helpfiles/TrialConfigExamples.m deleted file mode 100644 index 23d66800..00000000 --- a/helpfiles/TrialConfigExamples.m +++ /dev/null @@ -1,5 +0,0 @@ -%% TrialConfig Examples -% tcObj=TrialConfig(covMask,sampleRate, history,minTime,maxTime) -tc1 = TrialConfig({'Force','f_x'},2000,[.1 .2],-1,2); -tc2 = TrialConfig({'Position','x'},2000,[.1 .2],-1,2); -tcc = ConfigColl({tc1,tc2}); \ No newline at end of file diff --git a/helpfiles/TrialExamples.asv b/helpfiles/TrialExamples.asv deleted file mode 100644 index d1a606fe..00000000 --- a/helpfiles/TrialExamples.asv +++ /dev/null @@ -1,45 +0,0 @@ -%% Test Trial -% - - -%% Example 1: A simple data set -close all; -lengthTrial=1; - -%% -% Create History windows of interest -windowTimes = [.1 .2 .3 .4]; -h=History(windowTimes); -h.plot; - -%% -% Load Covariates -load Covariates.mat; %load position and force covariates -cc=CovColl({position,force}); -cc.plot; - -%% -% Create trial events -eTimes = sort(rand(1,2)*lengthTrial); -eLabels={'E_1','E_2'}; -e=Events(eTimes,eLabels); %use default eventColor 'r' -e.plot; - - -for i=4 - spikeTimes = sort(rand(1,100))*lengthTrial; - nst{i}=nspikeTrain(spikeTimes,'',.001); - end -spikeColl=nstColl(nst); - -trial1=Trial(spikeColl, cc, e); -trial1.setHistory(h); -trial1.setCovMask({{'Position','x'},{'Force','f_x'}}) - - -% tcObj=TrialConfig(covMask,sampleRate, history,minTime,maxTime) -tc1 = TrialConfig({'Force','f_x'},2000,[.1 .2],-1,2); -tc2 = TrialConfig({'Position','x'},2000,[.1 .2],-1,2); -tcc = ConfigColl({tc1,tc2}); -% [lambda,b, dev, stats]=Analysis.GLMFit(trial1,1); makePlot=1; -% [KS, xAxis, KSSorted, ks_stat, handle] =Analysis.KSPlot(trial1,lambda,1,makePlot); diff --git a/helpfiles/TrialExamples.html b/helpfiles/TrialExamples.html deleted file mode 100644 index b73bf3d9..00000000 --- a/helpfiles/TrialExamples.html +++ /dev/null @@ -1,152 +0,0 @@ - - - - - Trial Examples

Trial Examples

Contents

Example 1: A simple data set

close all; clear all;
-lengthTrial=1;
-

Create History windows of interest

windowTimes = [0 .1 .2 .4];
-h=History(windowTimes);
-figure; h.plot;
-

Load Covariates

load CovariateSample.mat; %load position and force covariates
-cc=CovColl({position,force});
-cc.setMaxTime(lengthTrial);
-figure; cc.plot;
-

Create trial events

eTimes = sort(rand(1,2)*lengthTrial);
-eLabels={'E_1','E_2'};
-e=Events(eTimes,eLabels); %use default eventColor 'r'
-figure; e.plot;
-

Create neural Spike Train Data

clear nst;
-for i=1:4
-    spikeTimes = sort(rand(1,100))*lengthTrial;
-    nst{i}=nspikeTrain(spikeTimes,'',.001);
-end
-spikeColl=nstColl(nst); %create a nstColl
-figure; spikeColl.plot;
-

Finally we have everything we need to create a Trial object.

trial1=Trial(spikeColl, cc, e, h);
-figure; trial1.plot; % plot all the data;
-

Mask out some of the data and plot the trial once again

trial1.setCovMask({{'Position','x'},{'Force','f_x'}})
-figure; trial1.plot;
-
-trial1.getHistForNeurons([1:2]);
-

Example 2: Analyzing Trial Data

Examples of neural spike analysis using the Neural Spike Analysis Toolbox or using standard methods standard methods

\ No newline at end of file diff --git a/helpfiles/TrialExamples.m b/helpfiles/TrialExamples.m deleted file mode 100644 index c4bb31cc..00000000 --- a/helpfiles/TrialExamples.m +++ /dev/null @@ -1,55 +0,0 @@ -%% Trial Examples -% - - -%% Example 1: A simple data set -close all; clear all; -lengthTrial=1; - -%% -% Create History windows of interest -windowTimes = [0 .1 .2 .4]; -h=History(windowTimes); -figure; h.plot; - -%% -% Load Covariates -load CovariateSample.mat; %load position and force covariates -cc=CovColl({position,force}); -cc.setMaxTime(lengthTrial); -figure; cc.plot; - -%% -% Create trial events -eTimes = sort(rand(1,2)*lengthTrial); -eLabels={'E_1','E_2'}; -e=Events(eTimes,eLabels); %use default eventColor 'r' -figure; e.plot; - -%% -% Create neural Spike Train Data -clear nst; -for i=1:4 - spikeTimes = sort(rand(1,100))*lengthTrial; - nst{i}=nspikeTrain(spikeTimes,'',.001); -end -spikeColl=nstColl(nst); %create a nstColl -figure; spikeColl.plot; - -%% -% Finally we have everything we need to create a Trial object. - -trial1=Trial(spikeColl, cc, e, h); -figure; trial1.plot; % plot all the data; - -%% -% Mask out some of the data and plot the trial once again -trial1.setCovMask({{'Position','x'},{'Force','f_x'}}) -figure; trial1.plot; - -trial1.getHistForNeurons([1:2]); -%% Example 2: Analyzing Trial Data -% Examples of neural spike analysis using the -% -% or using standard methods -% \ No newline at end of file diff --git a/helpfiles/TrialExamples.png b/helpfiles/TrialExamples.png deleted file mode 100644 index 584a53f6..00000000 Binary files a/helpfiles/TrialExamples.png and /dev/null differ diff --git a/helpfiles/TrialExamples_01.png b/helpfiles/TrialExamples_01.png deleted file mode 100644 index 62080e39..00000000 Binary files a/helpfiles/TrialExamples_01.png and /dev/null differ diff --git a/helpfiles/TrialExamples_02.png b/helpfiles/TrialExamples_02.png deleted file mode 100644 index f9178d69..00000000 Binary files a/helpfiles/TrialExamples_02.png and /dev/null differ diff --git a/helpfiles/TrialExamples_03.png b/helpfiles/TrialExamples_03.png deleted file mode 100644 index be00482c..00000000 Binary files a/helpfiles/TrialExamples_03.png and /dev/null differ diff --git a/helpfiles/TrialExamples_04.png b/helpfiles/TrialExamples_04.png deleted file mode 100644 index 4d38b722..00000000 Binary files a/helpfiles/TrialExamples_04.png and /dev/null differ diff --git a/helpfiles/TrialExamples_05.png b/helpfiles/TrialExamples_05.png deleted file mode 100644 index 54ff221c..00000000 Binary files a/helpfiles/TrialExamples_05.png and /dev/null differ diff --git a/helpfiles/TrialExamples_06.png b/helpfiles/TrialExamples_06.png deleted file mode 100644 index ccd73f55..00000000 Binary files a/helpfiles/TrialExamples_06.png and /dev/null differ diff --git a/helpfiles/ValidationDataSet.html b/helpfiles/ValidationDataSet.html deleted file mode 100644 index fa7e1035..00000000 --- a/helpfiles/ValidationDataSet.html +++ /dev/null @@ -1,347 +0,0 @@ - - - - - Software Validation Data Set

Software Validation Data Set

The purpose of this example is to two important test cases of data to validate the Neural Spike Analysis Toolbox.

Contents

Case #1: Constant Rate Poisson Process

First we want to show that when neural firing activity is generated from a constant rate poisson process, the algorithm is able to estimate the value of this constant rate.

clear all;
-close all;
-
-p=0.01;         % bernoilli probability
-N=100001;       % Number of coin flips
-delta = 0.001;  % binsize
-T=N*delta;      % total time window
-lambda=N*p/T    % lambda*T = N*p
-
-mu = log(lambda*delta/(1-lambda*delta))
-
-lambda =
-
-    10
-
-
-mu =
-
-   -4.5951
-
-

Now generate data for two neurons based on this constant rate

for i=1:2
-    t=linspace(0,T,N);
-    ind=rand(1,N)<p;     %generate the coin-flip indices for heads or 1's
-    spikeTimes = t(ind); %get time spikes based on indices
-    nst{i}=nspikeTrain(spikeTimes,'',delta); % create neuron spike train
-    nst{i}.setMinTime(0);
-    nst{i}.setMaxTime(T);
-end
-

For a sanity check we can plot the ISI histogram for the two neurons and verify that they are exponentially distributed with \lambda = N*p/T;

nst{1}.plotISIHistogram;
-

Setup the analysis using the Neural Spike Analysis Toolbox Since we are going to try to fit a constant rate model, we create a baseline covariate that is constant and equal to 1 for the duration of the trial. This data in the covarate will be labeled 'constant';

spikeColl=nstColl(nst); %create a nstColl - a collection of spikeTrains
-cov=Covariate(t,ones(length(t),1),'Baseline','s','','',{'mu'});
-cc=CovColl({cov}); % Gather all the covariates
-trial=Trial(spikeColl, cc); %Create the trial
-
-% Specify how we want to perform the analysis
-clear c;
-sampleRate=1000;
-%Try just using the 'constant' data from the baseline covariate
-c{1} = TrialConfig({{'Baseline','mu'}},sampleRate,[],[]);
-c{1}.setName('Baseline');
-cfgColl= ConfigColl(c); %place desired configurations in a ConfigColl structure
-

Run the analysis

results = Analysis.RunAnalysisForAllNeurons(trial,cfgColl,0);
-results{1}.plotResults; subplot(2,4,[5 6]); plot(mu,'ro', 'MarkerSize',10);
-results{2}.plotResults; subplot(2,4,[5 6]); plot(mu,'ro', 'MarkerSize',10);
-figure;
-subplot(1,2,1);results{1}.lambda.plot; hold on; plot(results{1}.lambda.time,lambda*ones(length(results{1}.lambda.time),1),'r-.','LineWidth',3);
-subplot(1,2,2);results{2}.lambda.plot; hold on; plot(results{2}.lambda.time,lambda*ones(length(results{2}.lambda.time),1),'r-.','LineWidth',3);
-
Analyzing Configuration #1: Neuron #1,2
-

Case #2: Piece-wise Constant Rate Poisson Process

Make a joint process be the sum of two independet and non-overlapping Poisson processes with different rates. During the first interval, only observer arrivals from process 1, and during the second interval only observe arrivals from the second process. Compare the results of estimate the complete process as the sum of two distinct independent and non-overlapping Poisson processes versus a single constant rate process.

% Process 1
-p1=0.001; % bernoilli probability of process 1
-N1=100000; %
-delta = 0.001;
-T1=N1*delta;
-lambda1=N1*p1/T1    % lambda*T = N*p
-mu1 = log(lambda1*delta/(1-lambda1*delta))
-%Process 2
-p2=0.01;  % bernoilli probability of process 1
-N2=100000;
-T2=N2*delta;
-lambda2=N2*p2/T2    % lambda*T = N*p
-mu2 = log(lambda2*delta/(1-lambda2*delta))
-
-%Estimate of constant rate process:
-lambdaConst = (N1*p1 + N2*p2)/(T1+T2)
-muConst = log(lambdaConst*delta/(1-lambdaConst*delta))
-
-lambda1 =
-
-     1
-
-
-mu1 =
-
-   -6.9068
-
-
-lambda2 =
-
-    10
-
-
-mu2 =
-
-   -4.5951
-
-
-lambdaConst =
-
-    5.5000
-
-
-muConst =
-
-   -5.1975
-
-

Generate the data for 2 neurons

for i=1:2
-    tTot = linspace(0,(T1+T2),(N1+N2+1));
-    t1=tTot(tTot<=T1);
-    ind1=rand(1,N1)<p1;
-    spikeTimes1 = t1(ind1);
-    t2=tTot(tTot>T1);
-    ind2=rand(1,N2)<p2;
-    spikeTimes2 = t2(ind2);
-    tTot = [t1'; t2'];
-
-    nst{i}=nspikeTrain([spikeTimes1 spikeTimes2],'',delta);
-    nst{i}.setMinTime(0);
-    nst{i}.setMaxTime(max(t2));
-end
-

Generate the trial data;

spikeColl=nstColl(nst); %create a nstColl
-cov=Covariate(tTot,[ones(length(tTot),1), tTot<=max(t1), tTot>max(t1)],'Baseline','s','','',{'muConst','mu1','mu2'});
-cc=CovColl({cov});
-
-% Specify how we want to perform the analysis
-sampleRate=1000;
-trial=Trial(spikeColl, cc);
-clear c;
-% Constant rate throughout
-c{1} = TrialConfig({{'Baseline','muConst'}},sampleRate,[],[]);
-c{1}.setName('Baseline');
-% Constant rate for epoch1 and Constat rate for epoch2 but distinct
-c{2} = TrialConfig({{'Baseline','mu1','mu2'}},sampleRate,[],[]);
-c{2}.setName('Variable');
-cfgColl= ConfigColl(c);
-

Run the analysis

results = Analysis.RunAnalysisForAllNeurons(trial,cfgColl,0);
-results{1}.plotResults;
-results{2}.plotResults;
-figure;
-subplot(1,2,1); results{1}.lambda.plot;
-subplot(1,2,2); results{2}.lambda.plot;
-
Analyzing Configuration #1: Neuron #1,2
-Analyzing Configuration #2: Neuron #1,2
-

Compare the results across the two neurons

Summary = FitResSummary(results);
-Summary.plotSummary;
-
\ No newline at end of file diff --git a/helpfiles/ValidationDataSet.m b/helpfiles/ValidationDataSet.m deleted file mode 100644 index 2ae7de95..00000000 --- a/helpfiles/ValidationDataSet.m +++ /dev/null @@ -1,141 +0,0 @@ -%% Software Validation Data Set -% The purpose of this example is to two important test cases of data to -% validate the Neural Spike Analysis Toolbox. - - -%% Case #1: Constant Rate Poisson Process -% First we want to show that when neural firing activity is generated from -% a constant rate poisson process, the algorithm is able to estimate the -% value of this constant rate. - -clear all; -close all; - -p=0.01; % bernoilli probability -N=100001; % Number of coin flips -delta = 0.001; % binsize -T=N*delta; % total time window -lambda=N*p/T % lambda*T = N*p - -mu = log(lambda*delta/(1-lambda*delta)) -%% -% Now generate data for two neurons based on this constant rate -for i=1:2 - t=linspace(0,T,N); - ind=rand(1,N)T1); - ind2=rand(1,N2)max(t1)],'Baseline','s','','',{'muConst','mu1','mu2'}); -cc=CovColl({cov}); - -% Specify how we want to perform the analysis -sampleRate=1000; -trial=Trial(spikeColl, cc); -clear c; -% Constant rate throughout -c{1} = TrialConfig({{'Baseline','muConst'}},sampleRate,[],[]); -c{1}.setName('Baseline'); -% Constant rate for epoch1 and Constat rate for epoch2 but distinct -c{2} = TrialConfig({{'Baseline','mu1','mu2'}},sampleRate,[],[]); -c{2}.setName('Variable'); -cfgColl= ConfigColl(c); - -%% -% Run the analysis -results = Analysis.RunAnalysisForAllNeurons(trial,cfgColl,0); -results{1}.plotResults; -results{2}.plotResults; -figure; -subplot(1,2,1); results{1}.lambda.plot; -subplot(1,2,2); results{2}.lambda.plot; -%% -% Compare the results across the two neurons -Summary = FitResSummary(results); -Summary.plotSummary; - - - diff --git a/helpfiles/ValidationDataSet.png b/helpfiles/ValidationDataSet.png deleted file mode 100644 index d3ccbad3..00000000 Binary files a/helpfiles/ValidationDataSet.png and /dev/null differ diff --git a/helpfiles/ValidationDataSet_01.png b/helpfiles/ValidationDataSet_01.png deleted file mode 100644 index f25c2f7f..00000000 Binary files a/helpfiles/ValidationDataSet_01.png and /dev/null differ diff --git a/helpfiles/ValidationDataSet_02.png b/helpfiles/ValidationDataSet_02.png deleted file mode 100644 index 16c76fc3..00000000 Binary files a/helpfiles/ValidationDataSet_02.png and /dev/null differ diff --git a/helpfiles/ValidationDataSet_03.png b/helpfiles/ValidationDataSet_03.png deleted file mode 100644 index ecf27ab4..00000000 Binary files a/helpfiles/ValidationDataSet_03.png and /dev/null differ diff --git a/helpfiles/ValidationDataSet_04.png b/helpfiles/ValidationDataSet_04.png deleted file mode 100644 index c1e77c46..00000000 Binary files a/helpfiles/ValidationDataSet_04.png and /dev/null differ diff --git a/helpfiles/ValidationDataSet_05.png b/helpfiles/ValidationDataSet_05.png deleted file mode 100644 index fcf7cfc6..00000000 Binary files a/helpfiles/ValidationDataSet_05.png and /dev/null differ diff --git a/helpfiles/ValidationDataSet_06.png b/helpfiles/ValidationDataSet_06.png deleted file mode 100644 index 496bc74e..00000000 Binary files a/helpfiles/ValidationDataSet_06.png and /dev/null differ diff --git a/helpfiles/ValidationDataSet_07.png b/helpfiles/ValidationDataSet_07.png deleted file mode 100644 index 2eb42156..00000000 Binary files a/helpfiles/ValidationDataSet_07.png and /dev/null differ diff --git a/helpfiles/ValidationDataSet_08.png b/helpfiles/ValidationDataSet_08.png deleted file mode 100644 index 18d1a82e..00000000 Binary files a/helpfiles/ValidationDataSet_08.png and /dev/null differ diff --git a/helpfiles/helpsearch-v3/_3.cfe b/helpfiles/helpsearch-v3/_3.cfe deleted file mode 100644 index bb5b1b33..00000000 Binary files a/helpfiles/helpsearch-v3/_3.cfe and /dev/null differ diff --git a/helpfiles/helpsearch-v3/_3.cfs b/helpfiles/helpsearch-v3/_3.cfs deleted file mode 100644 index e0f67f19..00000000 Binary files a/helpfiles/helpsearch-v3/_3.cfs and /dev/null differ diff --git a/helpfiles/helpsearch-v3/_3.si b/helpfiles/helpsearch-v3/_3.si deleted file mode 100644 index 22088fd7..00000000 Binary files a/helpfiles/helpsearch-v3/_3.si and /dev/null differ diff --git a/helpfiles/helpsearch-v3/segments.gen b/helpfiles/helpsearch-v3/segments.gen deleted file mode 100644 index f142fa92..00000000 Binary files a/helpfiles/helpsearch-v3/segments.gen and /dev/null differ diff --git a/helpfiles/helpsearch-v3/segments_4 b/helpfiles/helpsearch-v3/segments_4 deleted file mode 100644 index 9c4eaa17..00000000 Binary files a/helpfiles/helpsearch-v3/segments_4 and /dev/null differ diff --git a/helpfiles/helpsearch/_11.cfs b/helpfiles/helpsearch/_11.cfs deleted file mode 100644 index 03ec8264..00000000 Binary files a/helpfiles/helpsearch/_11.cfs and /dev/null differ diff --git a/helpfiles/helpsearch/_15.cfs b/helpfiles/helpsearch/_15.cfs deleted file mode 100644 index f53b8a2c..00000000 Binary files a/helpfiles/helpsearch/_15.cfs and /dev/null differ diff --git a/helpfiles/helpsearch/deletable b/helpfiles/helpsearch/deletable deleted file mode 100644 index 593f4708..00000000 Binary files a/helpfiles/helpsearch/deletable and /dev/null differ diff --git a/helpfiles/helpsearch/segments b/helpfiles/helpsearch/segments deleted file mode 100644 index 2b34b0e0..00000000 Binary files a/helpfiles/helpsearch/segments and /dev/null differ diff --git a/helpfiles/helptoc.xml b/helpfiles/helptoc.xml index 08eba0da..5314082e 100644 --- a/helpfiles/helptoc.xml +++ b/helpfiles/helptoc.xml @@ -1,43 +1,41 @@ - - - - - -Neural Spike Analysis Toolbox - -Class Definitions - -Examples - Using the SignalObj Class - Using the Covariate Class - Using the CovColl Class - Using the nSpikeTrain Class - Using the nstColl Class - Using the Events Class - Using the History Class - Using the Trial Class - Using the TrialConfig Class - Using the ConfigColl Class - Using the Analysis Class - Using the FitResult Class - Using the FitResSummary Class - Point Process simulation via Thinning - Example Data Analysis - Simulated Data - Computing a Peri-Stimulus Time Histogram (PSTH) - Example Data Analysis - Simulated Constant (Piecewise Constant) Rate Poisson - Example Data Analysis - Miniature Excitatory Post-Synaptic Currents (mEPSCs) - Example Data Analysis - Simulated Explicit Stimulus and History - Example Data Analysis - Explicit Stimulus - Example Data Analysis - Hippocampal Place Cell Receptive Field Estimation - Example Data Analysis - Decoding Univariate Simulated Stimuli (No History Effect) - Example Data Analysis - Decoding Univariate Simulated Stimuli with and without History Effect - Example Data Analysis - Decoding Bivariate Simulated Stimuli - Example Data Analysis - Two Neuron Network Simulation and Estimation of Ensemble Effect - nSTAT Paper Examples - - - - -Neuroscience Statistics Research Laboratory - - + + + nSTAT Neural Spike Train Analysis Toolbox + Overview + MATLAB 2025b Help Integration + + Class Definitions + SignalObj Reference + FitResult Reference + + Examples + Using the SignalObj Class + Using the Covariate Class + Using the CovColl Class + Using the nSpikeTrain Class + Using the nstColl Class + Using the Events Class + Using the History Class + Using the Trial Class + Using the TrialConfig Class + Using the ConfigColl Class + Using the Analysis Class + Using the FitResult Class + Using the FitResSummary Class + Point Process Simulation via Thinning + Example Data Analysis - Simulated Data - Computing a Peri-Stimulus Time Histogram (PSTH) + Example Data Analysis - Simulated Constant (Piecewise Constant) Rate Poisson + Example Data Analysis - Miniature Excitatory Post-Synaptic Currents (mEPSCs) + Example Data Analysis - Simulated Explicit Stimulus and History + Example Data Analysis - Explicit Stimulus + Example Data Analysis - Hippocampal Place Cell Receptive Field Estimation + Example Data Analysis - Decoding Univariate Simulated Stimuli (No History Effect) + Example Data Analysis - Decoding Univariate Simulated Stimuli with and without History Effect + Example Data Analysis - Decoding Bivariate Simulated Stimuli + Example Data Analysis - Two Neuron Network Simulation and Estimation of Ensemble Effect + nSTAT Paper Examples + + + Neuroscience Statistics Research Laboratory + diff --git a/helpfiles/mEPSCAnalysis.html b/helpfiles/mEPSCAnalysis.html deleted file mode 100644 index 62981f60..00000000 --- a/helpfiles/mEPSCAnalysis.html +++ /dev/null @@ -1,391 +0,0 @@ - - - - - MINIATURE EXCITATORY POST-SYNAPTIC CURRENTS (mEPSCs)

MINIATURE EXCITATORY POST-SYNAPTIC CURRENTS (mEPSCs)

Data from Marnie Phillips marnie.a.phillips@gmail.com This analysis is based on a partial version of the dataset used in

Phillips MA, Lewis LD, Gong J, Constantine-Paton M, Brown EN. 2011 Model-based statistical analysis of miniature synaptic transmission. J Neurophys (under consideration)

Author: Iahn Cajigas

Date: 03/01/2011

Contents

Data Description

epsc2.txt: Event times of selected, constant rate, miniature excitatory post-synaptic currents (mEPSCs) in 0mM magnesium condition]

washout1.txt: Variable rate recording: Event times of selected events, beginning approximately 260 seconds after magnesium is first removed.

washout2.txt: Event times of selected events from the same recording, beginning 745 seconds after magnesium is first removed

Column headers in the text files explain what each column represents.

Event selection criteria for the "washout1" and "washout2" condition were:

  • Amplitude > 10pA
  • 10-90% rise time < 20ms

For this washout experiment, the recording duration was so long, and there were so many events, that the minimum amplitude threshold was conservative.

The mean RMS noise was only 1.36pA, and a usual threshold would be 5*RMS = 6.8pA.

Constant Magnesium Concentration - Constant rate poisson

Under a constant Magnesium concentration, it is seen that the mEPSCs behave as a homogeneous poisson process (constant arrival rate).

    close all;
-    epsc2 = importdata('epsc2.txt');
-    sampleRate = 1000;
-    spikeTimes = epsc2.data(:,2)*1/sampleRate; %in seconds
-    nst = nspikeTrain(spikeTimes);
-    time = 0:(1/sampleRate):nst.maxTime;
-
-    % Define Covariates for the analysis
-    baseline = Covariate(time,ones(length(time),1),'Baseline','time','s','',{'\mu'});
-    covarColl = CovColl({baseline});
-
-    % Create the trial structure
-    spikeColl = nstColl(nst);
-    trial     = Trial(spikeColl,covarColl);
-
-
-    % Define how we want to analyze the data
-    clear tc tcc;
-    tc{1} = TrialConfig({{'Baseline','\mu'}},sampleRate,[]); tc{1}.setName('Constant Baseline');
-    tcc = ConfigColl(tc);
-
-    % Perform Analysis (Commented to since data already saved)
-    results =Analysis.RunAnalysisForAllNeurons(trial,tcc,0);
-    results.plotResults;
-
Analyzing Configuration #1: Neuron #1
-

Varying Magnesium Concentration - Piecewise Constant rate poisson

When the magnesium concentration of the bath decreased (i.e. magnesium is removed), the rate of mEPSCs begin to increase in frequency. This can be modeled in a many different ways (using the change in Magnesium directly as a model covariate, etc.) Here we approximate the rate as being constant during certain portions of the experiment. These segments can in principle be estimated (using heirarchical Bayesian methods), but here we select them via visual inspection. We compare three models: a constant rate model (from above), a piecewise constant rate model, and a piecewise constant rate model with history.

 % load the data;
-    washout1 = importdata('washout1.txt');
-    washout2 = importdata('washout2.txt');
-
-    sampleRate  = 1000;
-    % Magnesium removed at t=0
-    spikeTimes1 = 260+washout1.data(:,2)*1/sampleRate; %in seconds
-    spikeTimes2 = sort(washout2.data(:,2))*1/sampleRate + 745;%in seconds
-    nst = nspikeTrain([spikeTimes1; spikeTimes2]);
-    time = 260:(1/sampleRate):nst.maxTime;
-

Data Visualization

Visual inspection of the spike train is used to pick three regions where the firing rate appears to be different. Here we do not estimate where these transitions happen but pick times in an ad-hoc manner.

    figure;
-    nst.plot;
-

Define Covariates for the analysis

    timeInd1 =find(time<495,1,'last'); %0-495sec first constant rate
-    timeInd2 =find(time<765,1,'last'); %495-765 second constant rate epoch
-                                       %765 onwards third constant rate
-                                       %epoch
-    constantRate = ones(length(time),1);
-    rate1 = zeros(length(time),1); rate1(1:timeInd1)=1;
-    rate2 = zeros(length(time),1); rate2((timeInd1+1):timeInd2)=1;
-    rate3 = zeros(length(time),1); rate3((timeInd2+1):end)=1;
-    baseline = Covariate(time,[constantRate,rate1, rate2, rate3],'Baseline','time','s','',{'\mu','\mu_{1}','\mu_{2}','\mu_{3}'});
-    covarColl = CovColl({baseline});
-
-    % Create the trial structure
-    spikeColl = nstColl(nst);
-    trial     = Trial(spikeColl,covarColl);
-
-    %30ms history in logarithmic spacing (chosen after using
-    %Analysis.computeHistLagForAll for various window lengths)
-    maxWindow=.3; numWindows=20;
-    delta=1/sampleRate;
-    windowTimes =unique(round([0 logspace(log10(delta),...
-    log10(maxWindow),numWindows)]*sampleRate)./sampleRate);
-    windowTimes = windowTimes(1:11);
-

Define how we want to analyze the data

    clear tc tcc;
-    tc{1} = TrialConfig({{'Baseline','\mu'}},sampleRate,[]); tc{1}.setName('Constant Baseline');
-    tc{2} = TrialConfig({{'Baseline','\mu_{1}','\mu_{2}','\mu_{3}'}},sampleRate,[]); tc{2}.setName('Diff Baseline');
-%     tc{3} = TrialConfig({{'Baseline','\mu_{1}','\mu_{2}','\mu_{3}'}},sampleRate,windowTimes); tc{3}.setName('Diff Baseline+Hist');
-    tcc = ConfigColl(tc);
-

Perform Analysis

We see that the piece-wise constant rate model (with and without history, outperform the constant baseline model in terms of AIC, BIC, and KS-statistic. While addition of the history effect yields a model that falls within the 95% confidence interval of the KS plot, it results in increases of the AIC and BIC because of the increased number of parameters.

    results =Analysis.RunAnalysisForAllNeurons(trial,tcc,0);
-    results.plotResults;
-    Summary = FitResSummary(results);
-    Summary.plotSummary;
-
Analyzing Configuration #1: Neuron #1
-Analyzing Configuration #2: Neuron #1
-

Decode Rate using Point Process Filter

%     clear lambdaCIF;
-%     delta = .001;
-%
-%     washout1 = importdata('washout1.txt');
-%     washout2 = importdata('washout2.txt');
-%
-%     sampleRate  = 1000;
-%     % Magnesium removed at t=0
-%     spikeTimes1 = 260+washout1.data(:,2)*1/sampleRate; %in seconds
-%     spikeTimes2 = sort(washout2.data(:,2))*1/sampleRate + 745;%in seconds
-%     nst = nspikeTrain([spikeTimes1; spikeTimes2]);
-%     time = 260:(1/sampleRate):nst.maxTime;
-%     spikeColl = nstColl(nst);
-%
-%     clear lambdaCIF;
-%     lambdaCIF = CIF([1],{'mu'},{'mu'},'poisson');
-%     spikeColl.resample(1/delta);
-%     dN=spikeColl.dataToMatrix;
-%     Q=.001;
-%     Px0=.1; A=1;
-%     [x_p, Pe_p, x_u, Pe_u] = CIF.PPDecodeFilter(A, Q, Px0, dN',lambdaCIF);
-%     figure;
-%     tNew = 260:delta:(length(x_p(1:end-1))*delta+260);
-%     plot(tNew,exp(x_p)./delta);
-%
-% %%
-%     close all;
-%     N=30000; A=1; B=ones(1,N)./N;
-%     xfilt = filtfilt(B,A,x_p);
-%     figure;
-%     plot(tNew,x_p,'-.b');
-%     hold on; plot(tNew,xfilt,'k','Linewidth',3);
-%     %%
-%     close all;
-%     figure;
-%     index = find(tNew<280,1,'last');
-%     subplot(2,1,1);
-%     plot(tNew(index:end),x_p(index:end),'-.b'); hold on;
-%     plot(tNew(index:end),xfilt(index:end),'k','Linewidth',3);
-%     xlabel('time [s]');
-%     ylabel('\mu');
-%     axis tight;
-%     v=axis;
-%     axis([v(1) v(2) -9 -5]);
-%
-%     subplot(2,1,2);
-%     plot(tNew(index:end),exp(x_p(index:end))./delta,'-.b'); hold on;
-%     plot(tNew(index:end),exp(xfilt(index:end))./delta,'k','Linewidth',3);
-%     axis tight;
-%     v=axis;
-%     axis([v(1) v(2) 0 5]);
-%     xlabel('time [s]');
-%     ylabel('\lambda(t) [Hz]');
-
\ No newline at end of file diff --git a/helpfiles/mEPSCAnalysis.m b/helpfiles/mEPSCAnalysis.m deleted file mode 100644 index ec12054d..00000000 --- a/helpfiles/mEPSCAnalysis.m +++ /dev/null @@ -1,199 +0,0 @@ -%% MINIATURE EXCITATORY POST-SYNAPTIC CURRENTS (mEPSCs) -% Data from Marnie Phillips -% This analysis is based on a partial version of the dataset used in -% -% Phillips MA, Lewis LD, Gong J, Constantine-Paton M, Brown EN. 2011 -% _Model-based statistical analysis of miniature synaptic transmission._ -% J Neurophys (under consideration) -% -% *Author*: Iahn Cajigas -% -% *Date*: 03/01/2011 - -%% Data Description -% *epsc2.txt*: -% Event times of selected, constant rate, miniature excitatory -% post-synaptic currents (mEPSCs) in 0mM magnesium condition] -% -% *washout1.txt*: -% Variable rate recording: Event times of selected events, beginning -% approximately 260 seconds after magnesium is first removed. -% -% *washout2.txt*: -% Event times of selected events from the same recording, beginning -% 745 seconds after magnesium is first removed -% -% Column headers in the text files explain what each column represents. -% -% Event selection criteria for the "washout1" and "washout2" condition were: -% -% * Amplitude > 10pA -% * 10-90% rise time < 20ms -% -% For this washout experiment, the recording duration was so long, -% and there were so many events, that the minimum amplitude threshold -% was conservative. -% -% The mean RMS noise was only 1.36pA, and a usual threshold would be -% 5*RMS = 6.8pA. -% - -%% Constant Magnesium Concentration - Constant rate poisson -% Under a constant Magnesium concentration, it is seen that the mEPSCs -% behave as a homogeneous poisson process (constant arrival rate). - close all; - epsc2 = importdata('epsc2.txt'); - sampleRate = 1000; - spikeTimes = epsc2.data(:,2)*1/sampleRate; %in seconds - nst = nspikeTrain(spikeTimes); - time = 0:(1/sampleRate):nst.maxTime; - - % Define Covariates for the analysis - baseline = Covariate(time,ones(length(time),1),'Baseline','time','s','',{'\mu'}); - covarColl = CovColl({baseline}); - - % Create the trial structure - spikeColl = nstColl(nst); - trial = Trial(spikeColl,covarColl); - - - % Define how we want to analyze the data - clear tc tcc; - tc{1} = TrialConfig({{'Baseline','\mu'}},sampleRate,[]); tc{1}.setName('Constant Baseline'); - tcc = ConfigColl(tc); - - % Perform Analysis (Commented to since data already saved) - results =Analysis.RunAnalysisForAllNeurons(trial,tcc,0); - results.plotResults; - - - %% Varying Magnesium Concentration - Piecewise Constant rate poisson - % When the magnesium concentration of the bath decreased (i.e. magnesium - % is removed), the rate of mEPSCs begin to increase in frequency. This can - % be modeled in a many different ways (using the change in Magnesium - % directly as a model covariate, etc.) Here we approximate the rate as - % being constant during certain portions of the experiment. These segments - % can in principle be estimated (using heirarchical Bayesian methods), but - % here we select them via visual inspection. We compare three models: a - % constant rate model (from above), a piecewise constant rate model, and a - % piecewise constant rate model with history. - - % load the data; - washout1 = importdata('washout1.txt'); - washout2 = importdata('washout2.txt'); - - sampleRate = 1000; - % Magnesium removed at t=0 - spikeTimes1 = 260+washout1.data(:,2)*1/sampleRate; %in seconds - spikeTimes2 = sort(washout2.data(:,2))*1/sampleRate + 745;%in seconds - nst = nspikeTrain([spikeTimes1; spikeTimes2]); - time = 260:(1/sampleRate):nst.maxTime; - - %% Data Visualization - % Visual inspection of the spike train is used to pick three regions - % where the firing rate appears to be different. Here we do not - % estimate where these transitions happen but pick times in an ad-hoc - % manner. - figure; - nst.plot; - - - %% Define Covariates for the analysis - timeInd1 =find(time<495,1,'last'); %0-495sec first constant rate - timeInd2 =find(time<765,1,'last'); %495-765 second constant rate epoch - %765 onwards third constant rate - %epoch - constantRate = ones(length(time),1); - rate1 = zeros(length(time),1); rate1(1:timeInd1)=1; - rate2 = zeros(length(time),1); rate2((timeInd1+1):timeInd2)=1; - rate3 = zeros(length(time),1); rate3((timeInd2+1):end)=1; - baseline = Covariate(time,[constantRate,rate1, rate2, rate3],'Baseline','time','s','',{'\mu','\mu_{1}','\mu_{2}','\mu_{3}'}); - covarColl = CovColl({baseline}); - - % Create the trial structure - spikeColl = nstColl(nst); - trial = Trial(spikeColl,covarColl); - - %30ms history in logarithmic spacing (chosen after using - %Analysis.computeHistLagForAll for various window lengths) - maxWindow=.3; numWindows=20; - delta=1/sampleRate; - windowTimes =unique(round([0 logspace(log10(delta),... - log10(maxWindow),numWindows)]*sampleRate)./sampleRate); - windowTimes = windowTimes(1:11); - - %% Define how we want to analyze the data - clear tc tcc; - tc{1} = TrialConfig({{'Baseline','\mu'}},sampleRate,[]); tc{1}.setName('Constant Baseline'); - tc{2} = TrialConfig({{'Baseline','\mu_{1}','\mu_{2}','\mu_{3}'}},sampleRate,[]); tc{2}.setName('Diff Baseline'); -% tc{3} = TrialConfig({{'Baseline','\mu_{1}','\mu_{2}','\mu_{3}'}},sampleRate,windowTimes); tc{3}.setName('Diff Baseline+Hist'); - tcc = ConfigColl(tc); - - %% Perform Analysis - % We see that the piece-wise constant rate model (with and without - % history, outperform the constant baseline model in terms of AIC, BIC, - % and KS-statistic. While addition of the history effect yields a model - % that falls within the 95% confidence interval of the KS plot, it - % results in increases of the AIC and BIC because of the increased - % number of parameters. - results =Analysis.RunAnalysisForAllNeurons(trial,tcc,0); - results.plotResults; - Summary = FitResSummary(results); - Summary.plotSummary; - - - %% Decode Rate using Point Process Filter - -% clear lambdaCIF; -% delta = .001; -% -% washout1 = importdata('washout1.txt'); -% washout2 = importdata('washout2.txt'); -% -% sampleRate = 1000; -% % Magnesium removed at t=0 -% spikeTimes1 = 260+washout1.data(:,2)*1/sampleRate; %in seconds -% spikeTimes2 = sort(washout2.data(:,2))*1/sampleRate + 745;%in seconds -% nst = nspikeTrain([spikeTimes1; spikeTimes2]); -% time = 260:(1/sampleRate):nst.maxTime; -% spikeColl = nstColl(nst); -% -% clear lambdaCIF; -% lambdaCIF = CIF([1],{'mu'},{'mu'},'poisson'); -% spikeColl.resample(1/delta); -% dN=spikeColl.dataToMatrix; -% Q=.001; -% Px0=.1; A=1; -% [x_p, Pe_p, x_u, Pe_u] = CIF.PPDecodeFilter(A, Q, Px0, dN',lambdaCIF); -% figure; -% tNew = 260:delta:(length(x_p(1:end-1))*delta+260); -% plot(tNew,exp(x_p)./delta); -% -% %% -% close all; -% N=30000; A=1; B=ones(1,N)./N; -% xfilt = filtfilt(B,A,x_p); -% figure; -% plot(tNew,x_p,'-.b'); -% hold on; plot(tNew,xfilt,'k','Linewidth',3); -% %% -% close all; -% figure; -% index = find(tNew<280,1,'last'); -% subplot(2,1,1); -% plot(tNew(index:end),x_p(index:end),'-.b'); hold on; -% plot(tNew(index:end),xfilt(index:end),'k','Linewidth',3); -% xlabel('time [s]'); -% ylabel('\mu'); -% axis tight; -% v=axis; -% axis([v(1) v(2) -9 -5]); -% -% subplot(2,1,2); -% plot(tNew(index:end),exp(x_p(index:end))./delta,'-.b'); hold on; -% plot(tNew(index:end),exp(xfilt(index:end))./delta,'k','Linewidth',3); -% axis tight; -% v=axis; -% axis([v(1) v(2) 0 5]); -% xlabel('time [s]'); -% ylabel('\lambda(t) [Hz]'); \ No newline at end of file diff --git a/helpfiles/mEPSCAnalysis.png b/helpfiles/mEPSCAnalysis.png deleted file mode 100644 index 6cd23483..00000000 Binary files a/helpfiles/mEPSCAnalysis.png and /dev/null differ diff --git a/helpfiles/mEPSCAnalysis_01.png b/helpfiles/mEPSCAnalysis_01.png deleted file mode 100644 index af39dc3f..00000000 Binary files a/helpfiles/mEPSCAnalysis_01.png and /dev/null differ diff --git a/helpfiles/mEPSCAnalysis_02.png b/helpfiles/mEPSCAnalysis_02.png deleted file mode 100644 index f5079af3..00000000 Binary files a/helpfiles/mEPSCAnalysis_02.png and /dev/null differ diff --git a/helpfiles/mEPSCAnalysis_03.png b/helpfiles/mEPSCAnalysis_03.png deleted file mode 100644 index f0351237..00000000 Binary files a/helpfiles/mEPSCAnalysis_03.png and /dev/null differ diff --git a/helpfiles/mEPSCAnalysis_04.png b/helpfiles/mEPSCAnalysis_04.png deleted file mode 100644 index 72ec564d..00000000 Binary files a/helpfiles/mEPSCAnalysis_04.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples.html b/helpfiles/nSTATPaperExamples.html deleted file mode 100644 index fa02d037..00000000 --- a/helpfiles/nSTATPaperExamples.html +++ /dev/null @@ -1,81945 +0,0 @@ - - - - - nSTAT J. Neuroscience Methods Paper Examples

nSTAT J. Neuroscience Methods Paper Examples

Author: Iahn Cajigas

Date: 01/04/2012

Contents

Experiment 1

MINIATURE EXCITATORY POST-SYNAPTIC CURRENTS (mEPSCs) Data from Marnie Phillips marnie.a.phillips@gmail.com This analysis is based on a partial version of the dataset used in

Phillips MA, Lewis LD, Gong J, Constantine-Paton M, Brown EN. 2011 Model-based statistical analysis of miniature synaptic transmission. J Neurophys (under consideration)

Date: 03/01/2011

Constant Magnesium Concentration - Constant rate poisson

Under a constant Magnesium concentration, it is seen that the mEPSCs behave as a homogeneous poisson process (constant arrival rate).

    close all; clear all;
-    epsc2 = importdata('epsc2.txt');
-    sampleRate = 1000;
-    spikeTimes = epsc2.data(:,2)*1/sampleRate; %in seconds
-    nstConst = nspikeTrain(spikeTimes);
-    time = 0:(1/sampleRate):nstConst.maxTime;
-
-
-    % Define Covariates for the analysis
-    baseline = Covariate(time,ones(length(time),1),'Baseline','time','s',...
-        '',{'\mu'});
-    covarColl = CovColl({baseline});
-
-    % Create the trial structure
-    spikeColl = nstColl(nstConst);
-    trial     = Trial(spikeColl,covarColl);
-
-
-    % Define how we want to analyze the data
-    clear tc tcc;
-    tc{1} = TrialConfig({{'Baseline','\mu'}},sampleRate,[]);
-    tc{1}.setName('Constant Baseline');
-    tcc = ConfigColl(tc);
-
-    % Perform Analysis (Commented to since data already saved)
-    results =Analysis.RunAnalysisForAllNeurons(trial,tcc,0);
-%     h=results.plotResults;
-    close all;
-    scrsz = get(0,'ScreenSize');
-    results.lambda.setDataLabels({'\lambda_{const}'});
-    h=figure('OuterPosition',[scrsz(3)*.01 scrsz(4)*.04 ...
-        scrsz(3)*.98 scrsz(4)*.95]);
-
-    subplot(2,2,1); spikeColl.plot;
-        title({'Neural Raster with constant Mg^{2+} Concentration'},...
-            'FontWeight','bold',...
-            'Fontsize',12,...
-            'FontName','Arial');
-         hx=xlabel('time [s]','Interpreter','none');
-         hy=ylabel('mEPSCs','Interpreter','none');
-         set(gca,'yTick',[0 1]);
-         set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
-    subplot(2,2,3); results.KSPlot;
-    subplot(2,2,2); results.plotInvGausTrans;
-    subplot(2,2,4); results.lambda.plot([],{{' ''b'' ,''Linewidth'',2'}});
-    hx=xlabel('time [s]','Interpreter','none');
-    hy=get(gca,'YLabel');
-    set([hx hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
-    h_legend = legend('\lambda_{const}','Location','NorthEast');
-    pos = get(h_legend,'position');
-    set(h_legend, 'position',[pos(1)+.05 pos(2) pos(3:4)]);
-    set(h_legend,'FontSize',14)
-
Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\private\evalmxdom.m' could not be
-cleared because it contains MATLAB code that is currently executing. 
-Warning: The file
-'C:\Users\Developer\Dropbox\GitHub\nSTAT\helpfiles\nSTATPaperExamples.m' could
-not be cleared because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\mdbpublish.m' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\publish.p' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\private\evalmxdom.m' could not be
-cleared because it contains MATLAB code that is currently executing. 
-Warning: The file
-'C:\Users\Developer\Dropbox\GitHub\nSTAT\helpfiles\nSTATPaperExamples.m' could
-not be cleared because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\mdbpublish.m' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\publish.p' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\private\evalmxdom.m' could not be
-cleared because it contains MATLAB code that is currently executing. 
-Warning: The file
-'C:\Users\Developer\Dropbox\GitHub\nSTAT\helpfiles\nSTATPaperExamples.m' could
-not be cleared because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\mdbpublish.m' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\publish.p' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Analyzing Configuration #1: Neuron #1
-

Varying Magnesium Concentration - Piecewise Constant rate poisson

When the magnesium concentration of the bath decreased (i.e. magnesium is removed), the rate of mEPSCs begin to increase in frequency. This can be modeled in a many different ways (using the change in Magnesium directly as a model covariate, etc.) Here we approximate the rate as being constant during certain portions of the experiment. These segments can in principle be estimated (using heirarchical Bayesian methods), but here we select them via visual inspection. We compare three models: a constant rate model (from above), a piecewise constant rate model, and a piecewise constant rate model with history.

    close all;
- % load the data;
-    washout1 = importdata('washout1.txt');
-    washout2 = importdata('washout2.txt');
-
-    sampleRate  = 1000;
-    % Magnesium removed at t=0
-    spikeTimes1 = 260+washout1.data(:,2)*1/sampleRate; %in seconds
-    spikeTimes2 = sort(washout2.data(:,2))*1/sampleRate + 745;%in seconds
-    nst = nspikeTrain([spikeTimes1; spikeTimes2]);
-    time = 260:(1/sampleRate):nst.maxTime;
-

Data Visualization

Visual inspection of the spike train is used to pick three regions where the firing rate appears to be different. Here we do not estimate where these transitions happen but pick times in an ad-hoc manner.

    scrsz = get(0,'ScreenSize');
-    h=figure('OuterPosition',[scrsz(3)*.01 scrsz(4)*.04 scrsz(3)*.6 ...
-        scrsz(4)*.9]);
-
-    subplot(2,1,1);
-    nstConst.plot; set(gca,'yTick',[0 1]); hy=ylabel('mEPSCs');
-     title({'Neural Raster with constant Mg^{2+} Concentration'},...
-         'FontWeight','bold',...
-            'Fontsize',12,...
-            'FontName','Arial');
-    hx=get(gca,'XLabel');
-    set([hx,hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
-
-    subplot(2,1,2);
-    nst.plot; set(gca,'yTick',[0 1]); hy=ylabel('mEPSCs');
-    title({'Neural Raster with decreasing Mg^{2+} Concentration'},...
-        'FontWeight','bold',...
-            'Fontsize',12,...
-            'FontName','Arial');
-    hx=get(gca,'XLabel');
-    set([hx,hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
-

Define Covariates for the analysis

          timeInd1 =find(time<495,1,'last'); %0-495sec first constant rate
-        timeInd2 =find(time<765,1,'last'); %495-765 second constant rate epoch
-                                       %765 onwards third constant rate
-                                       %epoch
-    constantRate = ones(length(time),1);
-    rate1 = zeros(length(time),1); rate1(1:timeInd1)=1;
-    rate2 = zeros(length(time),1); rate2((timeInd1+1):timeInd2)=1;
-    rate3 = zeros(length(time),1); rate3((timeInd2+1):end)=1;
-    baseline = Covariate(time,[constantRate,rate1, rate2, rate3],...
-        'Baseline','time','s','',{'\mu','\mu_{1}','\mu_{2}','\mu_{3}'});
-    covarColl = CovColl({baseline});
-
-    % Create the trial structure
-    spikeColl = nstColl(nst);
-    trial     = Trial(spikeColl,covarColl);
-
-    %30ms history in logarithmic spacing (chosen after using
-    %Analysis.computeHistLagForAll for various window lengths)
-    maxWindow=.3; numWindows=20;
-    delta=1/sampleRate;
-    windowTimes =unique(round([0 logspace(log10(delta),...
-    log10(maxWindow),numWindows)]*sampleRate)./sampleRate);
-    windowTimes = windowTimes(1:11);
-

Define how we want to analyze the data

    clear tc tcc;
-    tc{1} = TrialConfig({{'Baseline','\mu'}},sampleRate,[]);
-    tc{1}.setName('Constant Baseline');
-    tc{2} = TrialConfig({{'Baseline','\mu_{1}','\mu_{2}','\mu_{3}'}},...
-        sampleRate,[]); tc{2}.setName('Diff Baseline');
-    tcc = ConfigColl(tc);
-

Perform Analysis

We see that the piece-wise constant rate model (without history) outperforms the constant baseline model in terms of AIC, BIC, and KS-statistic.

    results =Analysis.RunAnalysisForAllNeurons(trial,tcc,0);
-%     h=results.plotResults;
-%     Summary = FitResSummary(results);
-%     h=Summary.plotSummary;
-
Analyzing Configuration #1: Neuron #1
-Analyzing Configuration #2: Neuron #1
-
close all;
-    scrsz = get(0,'ScreenSize');
-    results.lambda.setDataLabels({'\lambda_{const}',...
-        '\lambda_{const-epoch}'});
-    h=figure('OuterPosition',[scrsz(3)*.01 scrsz(4)*.04 ...
-        scrsz(3)*.98 scrsz(4)*.95]);
-
-    subplot(2,2,1); spikeColl.plot;
-        title({'Neural Raster with decreasing Mg^{2+} Concentration'},...
-            'FontWeight','bold',...
-            'Fontsize',12,...
-            'FontName','Arial');
-        hx=xlabel('time [s]','Interpreter','none');
-        set(gca,'YTickLabel',[]);
-        set([hx],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
-        timeInd1 =find(time<495,1,'last'); %0-495sec first constant rate
-        timeInd2 =find(time<765,1,'last'); %495-765 second constant rate epoch
-                                       %765 onwards third constant rate
-                                       %epoch
-        plot([495;495],[0,1],'r','Linewidth',4); hold on;
-        plot([765;765],[0,1],'r','Linewidth',4);
-
-    subplot(2,2,3); results.KSPlot;
-    subplot(2,2,2); results.plotInvGausTrans;
-    subplot(2,2,4);
-    results.lambda.getSubSignal(1).plot([],{{' ''b'' ,''Linewidth'',2'}});
-    results.lambda.getSubSignal(2).plot([],{{' ''g'' ,''Linewidth'',2'}});
-                    v=axis; axis([v(1) v(2) 0 5]);
-    hx=xlabel('time [s]','Interpreter','none');
-    hy=get(gca,'YLabel');
-    set([hx hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
-    h_legend = legend('\lambda_{const}','\lambda_{const-epoch}',...
-        'Location','NorthEast');
-    pos = get(h_legend,'position');
-    set(h_legend, 'position',[pos(1)+.05 pos(2)-.01 pos(3:4)]);
-    set(h_legend,'FontSize',14)
-

Experiment 2

EXPLICIT STIMULUS EXAMPLE - WHISKER STIMULATION/THALAMIC NEURON In the worksheet with analyze the stimulus effect and history effect on the firing of a thalamic neuron under a known stimulus consisting of whisker stimulation. Data from Demba Ba (demba@mit.edu)

Load the data

clear all;

close all; currdir = pwd;
-index = strfind(currdir,'helpfiles')-1;
-rootpath = currdir(1:index);
-
-Direction=3; Neuron=1; Stim=2;
-% datapath = strcat(rootpath,['data/Explicit Stimulus/Dir' num2str(Direction)...
-%     '\Neuron' num2str(Neuron) '\Stim' num2str(Stim) '\']);
-datapath = strcat(rootpath,['data/Explicit Stimulus/Dir' num2str(Direction)...
-    '/Neuron' num2str(Neuron) '/Stim' num2str(Stim) '/']);
-data=load(strcat(datapath,'trngdataBis.mat'));
-
-time=0:.001:(length(data.t)-1)*.001;
-stimData = data.t;
-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','',...
-    {'constant'});
-
-nst = nspikeTrain(spikeTimes);
-nspikeColl = nstColl(nst);
-cc = CovColl({stim,baseline});
-trial = Trial(nspikeColl,cc);
-% trial.plot;
-
-scrsz = get(0,'ScreenSize');
-h=figure('Position',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.8 scrsz(4)*.8]);
-subplot(3,1,1);
-nst2 = nspikeTrain(spikeTimes);
-nst2.setMaxTime(21);nst2.plot;
-set(gca,'ytick',[0 1]);
-xlabel('');
-hy=ylabel('spikes');
-set(hy,'FontName', 'Arial','FontSize',12,'FontWeight','bold');
-title({'Neural Raster'},'FontWeight','bold','FontSize',16,'FontName','Arial');
-set(gca, ...
-  'XTick'       , 0:1:max(time), ...
-  'XTickLabel'  , [],...
-  'LineWidth'   , 1         );
-subplot(3,1,2);
-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');
-
-set(gca, ...
-  'XTick'       , 0:1:max(time), ...
-  'XTickLabel'  , [],...
-  'YTick'       , 0:.25:1, ...
-  'LineWidth'   , 1         );
-
-subplot(3,1,3);
-stim.derivative.getSigInTimeWindow(0,21).plot([],{{' ''k'' '}}); legend off;
-set(gca,'ytick',[-80 0 80]);
-axis([0 21 -80 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');
-
-set(gca, ...
-  'XTick'       , 0:1:max(time), ...
-  'YTick'       , -80:40:80, ...
-  'LineWidth'   , 1         );
-

Fit a constant baseline and Find Stimulus Lag We fit a constant rate (Poisson) model to the data and use the look at the cross-covariance function of between the stimulus and the fit residual to determine the appropriate lag for the stimulus.

clear c; close all;
-selfHist = [] ; NeighborHist = []; sampleRate = 1000;
-c{1} = TrialConfig({{'Baseline','constant'}},sampleRate,selfHist,NeighborHist);
-c{1}.setName('Baseline');
-cfgColl= ConfigColl(c);
-results = Analysis.RunAnalysisForAllNeurons(trial,cfgColl,0);
-
-% Find Stimulus Lag (look for peaks in the cross-covariance function less
-% than 1 second
-scrsz = get(0,'ScreenSize');
-h=figure('Position',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.8 scrsz(4)*.8]);
-
-subplot(7,2,[1 3 5])
-results.Residual.xcov(stim).windowedSignal([0,1]).plot;
-
-ylabel('');
-[m,ind,ShiftTime] = max(results.Residual.xcov(stim).windowedSignal([0,1]));
-title(['Cross Correlation Function - Peak at t=' num2str(ShiftTime) ' sec'],'FontWeight','bold',...
-            'FontSize',12,...
-            'FontName','Arial');
-hold on;
-h=plot(ShiftTime,m,'ro','Linewidth',3);
-set(h, 'MarkerFaceColor',[1 0 0], 'MarkerEdgeColor',[1 0 0]);
-hx=xlabel('Lag [s]','Interpreter','none');
-set(hx,'FontName', 'Arial','FontSize',12,'FontWeight','bold');
-
-
-%Allow for shifts of less than 1 second
-stim = Covariate(time,stimData,'Stimulus','time','s','V',{'stim'});
-stim = stim.shift(ShiftTime);
-baseline = Covariate(time,ones(length(time),1),'Baseline','time','s','',...
-    {'\mu'});
-
-nst = nspikeTrain(spikeTimes);
-nspikeColl = nstColl(nst);
-cc = CovColl({stim,baseline});
-trial2 = Trial(nspikeColl,cc);
-
Analyzing Configuration #1: Neuron #1
-

Compare constant rate model with model including stimulus effect

Addition of the stimulus improves the fits in terms of the KS plot and the making the rescaled ISIs less correlated. The Point Process Residula also looks more "white"

clear c;
-selfHist = [] ; NeighborHist = []; sampleRate = 1000;
-c{1} = TrialConfig({{'Baseline','\mu'}},sampleRate,selfHist,...
-    NeighborHist);
-c{1}.setName('Baseline');
-c{2} = TrialConfig({{'Baseline','\mu'},{'Stimulus','stim'}},...
-    sampleRate,selfHist,NeighborHist);
-c{2}.setName('Baseline+Stimulus');
-cfgColl= ConfigColl(c);
-results = Analysis.RunAnalysisForAllNeurons(trial2,cfgColl,0);
-% results.plotResults;
-
Analyzing Configuration #1: Neuron #1
-Analyzing Configuration #2: Neuron #1
-

History Effect

Determine the best history effect model using AIC, BIC, and KS statistic

sampleRate=1000;
-delta=1/sampleRate*1;
-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);
-
-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;
-if(AICind==1)
-    AICind=inf;
-end
-if(BICind==1)
-    BICind=inf; %sometime BIC is non-decreasing and the index would be 1
-end
-windowIndex = min([AICind,BICind]) %use the minimum order model
-Summary = FitResSummary(results);
-% Summary.plotSummary;
-
-
-clear c;
-if(windowIndex>1)
-    selfHist = windowTimes(1:windowIndex+1);
-else
-    selfHist = [];
-end
-NeighborHist = []; sampleRate = 1000;
-%
-% figure;
-subplot(7,2,2);
-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'},...
-     'FontWeight','bold',...
-            'FontSize',12,...
-            'FontName','Arial');
-
-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');
-set(gca, ...
-  'TickLength'  , [.02 .02] , ...
-  'XMinorTick'  , 'on'      , ...
-  'XTick'       , 0:5:results{1}.numResults-1, ...
-  'LineWidth'   , 1         );
-
-
-
-% Compare Baseline, Baseline+Stimulus Model, Baseline+History+Stimulus
-% Addition of the history effect yields a model that falls within the 95%
-% CI of the KS plot.
-
-c{1} = TrialConfig({{'Baseline','\mu'}},sampleRate,[],NeighborHist);
-c{1}.setName('Baseline');
-c{2} = TrialConfig({{'Baseline','\mu'},{'Stimulus','stim'}},...
-                    sampleRate,[],[]);
-c{2}.setName('Baseline+Stimulus');
-c{3} = TrialConfig({{'Baseline','\mu'},{'Stimulus','stim'}},...
-                    sampleRate,windowTimes(1:windowIndex),[]);
-c{3}.setName('Baseline+Stimulus+Hist');
-cfgColl= ConfigColl(c);
-results = Analysis.RunAnalysisForAllNeurons(trial2,cfgColl,0);
-%results.plotResults;
-%
-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;
-
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
-
-windowIndex =
-
-    10
-
-Analyzing Configuration #1: Neuron #1
-Analyzing Configuration #2: Neuron #1
-Analyzing Configuration #3: Neuron #1
-

Example 3 - PSTH Data

% 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.
-clear all;
-close all;
-delta = 0.001;
-Tmax = 1;
-time = 0:delta:Tmax;
-f=2;
-mu = -3;
-
-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'}});
-numRealizations = 20;
-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');
-hy=get(gca,'YLabel');
-set(hy,'FontName', 'Arial','FontSize',14,'FontWeight','bold');
-
-fileLocation = which('nSTAT_Install');
-index = strfind(fileLocation,'nSTAT_Install.m')-1;
-nSTATDir =fileLocation(1:index);
-
-rootDir = [nSTATDir 'data' filesep 'PSTH' filesep];
-filename = 'Results.mat';
-x=load(strcat(rootDir,filename));
-numTrials = x.Results.Data.Spike_times_STC.balanced_SUA.Nr_trials;
-cellNum=6; clear nst;
-for i=1:numTrials
-    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));
-end
-
-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');
-
-cellNum=1; clear nst;
-for i=1:numTrials
-    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));
-end
-
-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');
-
Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\private\evalmxdom.m' could not be
-cleared because it contains MATLAB code that is currently executing. 
-Warning: The file
-'C:\Users\Developer\Dropbox\GitHub\nSTAT\helpfiles\nSTATPaperExamples.m' could
-not be cleared because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\mdbpublish.m' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\publish.p' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\private\evalmxdom.m' could not be
-cleared because it contains MATLAB code that is currently executing. 
-Warning: The file
-'C:\Users\Developer\Dropbox\GitHub\nSTAT\helpfiles\nSTATPaperExamples.m' could
-not be cleared because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\mdbpublish.m' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\publish.p' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\private\evalmxdom.m' could not be
-cleared because it contains MATLAB code that is currently executing. 
-Warning: The file
-'C:\Users\Developer\Dropbox\GitHub\nSTAT\helpfiles\nSTATPaperExamples.m' could
-not be cleared because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\mdbpublish.m' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\publish.p' could not be cleared
-because it contains MATLAB code that is currently executing. 
-

Estimate the PSTH with 50ms windows

close all;
-
-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);
-true = lambda; %rate*delta = expected number of arrivals per bin
-subplot(2,3,4);
-
-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');
-
-legend off;
-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',...
-    12,'FontWeight','bold');
-ylabel('Trial [k]','Interpreter','none','FontName', 'Arial',...
-    'Fontsize',12,'FontWeight','bold');
-
-subplot(2,3,5);
-binsize = .05; %50ms window
-psthReal1    = spikeCollReal1.psth(binsize);
-psthGLMReal1 = spikeCollReal1.psthGLM(binsize);%,[],[],[],[],[],1000);
-
-h3=psthGLMReal1.plot([],{{' ''k'',''Linewidth'',4'}});
-h2=psthReal1.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([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',...
-    12,'FontWeight','bold');
-ylabel('Trial [k]','Interpreter','none','FontName', 'Arial',...
-    'Fontsize',12,'FontWeight','bold');
-subplot(2,3,6);
-psthReal2    = spikeCollReal2.psth(binsize);
-psthGLMReal2 = spikeCollReal2.psthGLM(binsize);%,[],[],[],[],[],1000);
-h3=psthGLMReal2.plot([],{{' ''k'',''Linewidth'',4'}});
-h2=psthReal2.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([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',...
-    12,'FontWeight','bold');
-ylabel('Trial [k]','Interpreter','none','FontName', 'Arial',...
-    'Fontsize',12,'FontWeight','bold');
-
Running in batch mode: neurons with same name are fit simultaneously
-Analyzing Configuration #1: Neuron #1
-Running in batch mode: neurons with same name are fit simultaneously
-Analyzing Configuration #1: Neuron #6
-Running in batch mode: neurons with same name are fit simultaneously
-Analyzing Configuration #1: Neuron #1
-

Example 3b - SSGLM Example

Example of estimating with-in and across trial dynamics Methods from: G. Czanner, U. T. Eden, S. Wirth, M. Yanike, W. A. Suzuki, and E. N. Brown, "Analysis of between-trial and within-trial neural spiking dynamics.," Journal of neurophysiology, vol. 99, no. 5, pp. 2672?2693, May. 2008.

close all;
-clear all;
-% set(0,'DefaultFigureRenderer','ZBuffer')
-delta = 0.001; Tmax = 1;
-time = 0:delta:Tmax;
-Ts=.001;
-numRealizations = 50; %Each realization corresponds to a distinct trial
-
-for i=1:numRealizations
-    % The within trial dynamics are sinusoidal
-    % For each trial the stimulus effect increases
-    f=2; b1(i)=3*((i)/numRealizations);b0=-3;
-    u = sin(2*pi*f*time);
-    e = zeros(length(time),1);   %No Ensemble input
-
-    stim=Covariate(time',u,'Stimulus','time','s','Voltage',{'sin'});
-    ens =Covariate(time',e,'Ensemble','time','s','Spikes',{'n1'});
-
-    mu=b0;
-    histCoeffs=[-4 -1 -.5];
-    H=tf(histCoeffs,[1],Ts,'Variable','z^-1');
-
-    S=tf([b1(i)],1,Ts,'Variable','z^-1');
-    E=tf([0],1,Ts,'Variable','z^-1');
-    simTypeSelect='binomial'; %Parameters are used to compute
-                              %binomial conditional intensity function
-                              %
-
-    % Obtain a realization of the point process with the current
-    % stimulus and history effect
-    [sC, lambdaTemp]=CIF.simulateCIF(mu,H,S,E,stim,ens,1,simTypeSelect);
-
-    if(i==1)
-        lambda=lambdaTemp; %Store the conditional intensity function
-    else
-        lambda = lambda.merge(lambdaTemp); %Add it to the other realizations
-    end
-
-    nst{i} = sC.getNST(1);             %get the neural spikeTrain from the collection
-    nst{i} = nst{i}.resample(1/delta); %make sure that it is sampled at the current samplerate
-end
-
-spikeColl = nstColl(nst); %Create a collection of the spike trains across trials
-
Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\private\evalmxdom.m' could not be
-cleared because it contains MATLAB code that is currently executing. 
-Warning: The file
-'C:\Users\Developer\Dropbox\GitHub\nSTAT\helpfiles\nSTATPaperExamples.m' could
-not be cleared because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\mdbpublish.m' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\publish.p' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\private\evalmxdom.m' could not be
-cleared because it contains MATLAB code that is currently executing. 
-Warning: The file
-'C:\Users\Developer\Dropbox\GitHub\nSTAT\helpfiles\nSTATPaperExamples.m' could
-not be cleared because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\mdbpublish.m' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\publish.p' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\private\evalmxdom.m' could not be
-cleared because it contains MATLAB code that is currently executing. 
-Warning: The file
-'C:\Users\Developer\Dropbox\GitHub\nSTAT\helpfiles\nSTATPaperExamples.m' could
-not be cleared because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\mdbpublish.m' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\publish.p' could not be cleared
-because it contains MATLAB code that is currently executing. 
-

Summarize Simulated Data

close all;
-scrsz = get(0,'ScreenSize');
-h=figure('Position',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.8 scrsz(4)*.8]);
-
-%Plot the raster
-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',...
-    12,'FontWeight','bold');
-ylabel('Trial [k]','Interpreter','none','FontName', 'Arial','Fontsize',...
-    12,'FontWeight','bold');
-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
-% above
-
-
-stimData = exp(b0 + u'*b1);
-if(strcmp(simTypeSelect,'binomial'))
-    stimData = stimData./(1+stimData);
-end
-
-%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',...
-    12,'FontWeight','bold');
-ylabel('Stimulus','Interpreter','none','FontName', 'Arial','Fontsize',...
-    12,'FontWeight','bold');
-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',...
-    12,'FontWeight','bold');
-ylabel('Stimulus Gain','Interpreter','none','FontName', 'Arial','Fontsize',...
-    12,'FontWeight','bold');
-title('Across Trial Stimulus Gain','Interpreter','none','FontName',...
-    'Arial','Fontsize',14,'FontWeight','bold');
-
-subplot(3,2,[5 6]);
-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');
-
-
-axis tight;
-

Estimation of the Stimulus Response

% Create the covariates that will be used for the GLM regression
-stim = Covariate(time,sin(2*pi*f*time),'Stimulus','time','s','V',{'stim'});
-baseline = Covariate(time,ones(length(time),1),'Baseline','time','s','',...
-                    {'constant'});
-
-% Specify the windows of the history coefficients to be estimated
-windowTimes=[0:.001:.003];
-% Number of bins to discrtize time into (used both for the PSTH and for
-% thec
-% SSGLM model.
-numBasis = 25;
-
-spikeColl.resample(1/delta); % Enforce sampleRate
-spikeColl.setMaxTime(Tmax);  % Make all spikeTrains end at time Tmax
-
-
-dN=spikeColl.dataToMatrix';  % Convert the spikeTrains into a matrix
-                             % of 1's and 0's corresponding to the presence
-                             % or absense of a spike in each time window.
-dN(dN>1)=1;                  % One should sample finely enough so there is
-                             % one spike per bin. Here we make sure that
-                             % this is the case regardless of the
-                             % sampleRate
-
-% The width of each rectangular basis pulse is determined by Tmax and by the
-% number of basis pulses to use.
-basisWidth=(spikeColl.maxTime-spikeColl.minTime)/numBasis;
-
-if(simTypeSelect==0)
-    fitType='binomial';
-else
-    fitType='poisson';
-end
-if(strcmp(fitType,'binomial'))
-    Algorithm = 'BNLRCG';   % BNLRCG - faster Truncated, L-2 Regularized,
-                            % Binomial Logistic Regression with Conjugate
-                            % Gradient Solver by Demba Ba (demba@mit.edu).
-else
-    Algorithm = 'GLM';      % Standard Matlab GLM (Can be used for binomial or
-                            % or Poisson CIFs
-end
-
-% Use the values obtained from a PSTH to initialize the SSGLM filter
-[psthSig, ~, psthResult] =spikeColl.psthGLM(basisWidth,windowTimes,fitType);
-gamma0=psthResult.getHistCoeffs';%+.1*randn(size(histCoeffs));
-gamma0(isnan(gamma0))=-5; % Depending on the amount of data the
-                          % the psth may not identify all parameters
-                          % Just make sure that the estimates are real
-                          % numbers
-
-x0=psthResult.getCoeffs;  %The initial estimate for the SSGLM model
-
-% Estimate the variance within each time bin across trials
-numVarEstIter=10;
-Q0 = spikeColl.estimateVarianceAcrossTrials(numBasis,windowTimes,...
-    numVarEstIter,fitType);
-A=eye(numBasis,numBasis);
-delta = 1/spikeColl.sampleRate;
-
Running in batch mode: neurons with same name are fit simultaneously
-Analyzing Configuration #1: Neuron #1
-Running in batch mode: neurons with same name are fit simultaneously
-Analyzing Configuration #1: Neuron #1
-Running in batch mode: neurons with same name are fit simultaneously
-Analyzing Configuration #1: Neuron #1
-Running in batch mode: neurons with same name are fit simultaneously
-Analyzing Configuration #1: Neuron #1
-Running in batch mode: neurons with same name are fit simultaneously
-Analyzing Configuration #1: Neuron #1
-Running in batch mode: neurons with same name are fit simultaneously
-Analyzing Configuration #1: Neuron #1
-Running in batch mode: neurons with same name are fit simultaneously
-Analyzing Configuration #1: Neuron #1
-Running in batch mode: neurons with same name are fit simultaneously
-Analyzing Configuration #1: Neuron #1
-Running in batch mode: neurons with same name are fit simultaneously
-Analyzing Configuration #1: Neuron #1
-Running in batch mode: neurons with same name are fit simultaneously
-Analyzing Configuration #1: Neuron #1
-Running in batch mode: neurons with same name are fit simultaneously
-Analyzing Configuration #1: Neuron #1
-A=eye(numBasis,numBasis);
-delta = 1/spikeColl.sampleRate;
-

Run the SSGLM Filter

CompilingHelpFile=1;
-    % Commented out to speed up help file creation ...
-    if(~CompilingHelpFile)
-        Q0d=diag(Q0);
-        neuronName = psthResult.neuronNumber;
-        [xK,WK, WkuFinal,Qhat,gammahat,fitResults,stimulus,stimCIs,logll,...
-            QhatAll,gammahatAll,nIter]=DecodingAlgorithms.PPSS_EMFB(A,Q0d,x0,...
-            dN,fitType,delta,gamma0,windowTimes, numBasis,neuronName);
-
-        fR = fitResults.toStructure;
-        psthR = psthResult.toStructure;
-    end
-% save SSGLMExampleData psthR fR xK WK WkuFinal Qhat gammahat fitResults stimulus stimCIs logll QhatAll gammahatAll nIter;
-
-%% Run the SSGLM Filter
-CompilingHelpFile=1;
-    % Commented out to speed up help file creation ... 
-    if(~CompilingHelpFile)
-
load SSGLMExampleData;
-fitResults = FitResult.fromStructure(fR);
-psthResult = FitResult.fromStructure(psthR);
-
% save SSGLMExampleData psthR fR xK WK WkuFinal Qhat gammahat fitResults stimulus stimCIs logll QhatAll gammahatAll nIter;
-%%
-load SSGLMExampleData;
-fitResults = FitResult.fromStructure(fR);
-psthResult = FitResult.fromStructure(psthR);
-
t=psthResult.mergeResults(fitResults);
-%t.plotResults; %Compare the results with the PSTH Model
-t.lambda.setDataLabels({'\lambda_{PSTH}','\lambda_{SSGLM}'});
-scrsz = get(0,'ScreenSize');
-h=figure('Position',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.8 scrsz(4)*.8]);
-subplot(2,2,1); t.KSPlot;
-subplot(2,2,2); t.plotResidual;
-subplot(2,2,3); t.plotInvGausTrans;
-subplot(2,2,4); t.plotSeqCorr;
-
-S=FitResSummary(t);
-dAIC=diff(S.AIC)
-dBIC=diff(S.BIC)
-dKS =diff(S.KSStats);
-
-%%
-t=psthResult.mergeResults(fitResults);
-%t.plotResults; %Compare the results with the PSTH Model
-t.lambda.setDataLabels({'\lambda_{PSTH}','\lambda_{SSGLM}'});
-scrsz = get(0,'ScreenSize');
-h=figure('Position',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.8 scrsz(4)*.8]);
-subplot(2,2,1); t.KSPlot;
-subplot(2,2,2); t.plotResidual;
-subplot(2,2,3); t.plotInvGausTrans;
-subplot(2,2,4); t.plotSeqCorr;
-
-S=FitResSummary(t);
-dAIC=diff(S.AIC)
-
-dAIC =
-
-  -1.7978e+04
-
-dBIC=diff(S.BIC)
-
-dBIC =
-
-  -6.9523e+03
-
-dKS =diff(S.KSStats); 
-
close all;
-% Generate the actual stimulus effect
-minTime=0; maxTime = Tmax;
-stimData = stim.data*b1;
-if(strcmp(fitType,'poisson'))
-    actStimEffect=exp(stimData + b0)./delta;
-elseif(strcmp(fitType,'binomial'))
-    actStimEffect=exp(stimData + b0)./(1+exp(stimData + b0))./delta;
-end
-%
-
-% Generate the basis function so that the estimated effect can be plotted
-% at the same temporal resolution as the theoretical effect
- if(~isempty(numBasis))
-    basisWidth = (maxTime-minTime)/numBasis;
-    sampleRate=1/delta;
-    unitPulseBasis=nstColl.generateUnitImpulseBasis(basisWidth,minTime,...
-        maxTime,sampleRate);
-    basisMat = unitPulseBasis.data;
- end
-
-% 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;
-end
-
-
-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
-% time
-subplot(3,1,[1 2 3]);
-lighting gouraud
-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',...
-            'Fontsize',14,...
-            'FontName','Arial');
-
-close all;
-h=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.4 scrsz(4)*.8]);
-
-% The actual stimulus effect
-subplot(3,1,1);
-lighting gouraud
-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',...
-            'Fontsize',14,...
-            'FontName','Arial');
-set(gca,'xtick',[],'xtickLabel',[]);
-set(gca,'ytick',[],'ytickLabel',[]);
-CLIM = [min(min(stimData./delta)) max(max(stimData./delta))];
-view(gca,[90 -90]);
-
-
-
-% The PSTH estimate
-subplot(3,1,2);
-lighting gouraud
-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',...
-            'Fontsize',14,...
-            'FontName','Arial');
-
-set(gca,'xtick',[],'xtickLabel',[]);
-set(gca,'ytick',[],'ytickLabel',[]);
-CLIM = [min(min(stimData./delta)) max(max(stimData./delta))];
-view(gca,[90 -90]);
-
-% The SSGLM estimated stimulus effect
-subplot(3,1,3);
-lighting gouraud
-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',...
-            'Fontsize',14,...
-            'FontName','Arial');
-set(gca,'xtick',[],'xtickLabel',[]);
-set(gca,'ytick',[],'ytickLabel',[]);
-set(gca, 'YDir','normal')
-view(gca,[90 -90]);
-
-
-%%
-close all;
-% Generate the actual stimulus effect
-minTime=0; maxTime = Tmax;
-stimData = stim.data*b1;
-if(strcmp(fitType,'poisson'))
-elseif(strcmp(fitType,'binomial'))
-    actStimEffect=exp(stimData + b0)./(1+exp(stimData + b0))./delta;
-end
-%     
-
-% Generate the basis function so that the estimated effect can be plotted
-% at the same temporal resolution as the theoretical effect
- if(~isempty(numBasis))
-    basisWidth = (maxTime-minTime)/numBasis;
-    sampleRate=1/delta;
-    unitPulseBasis=nstColl.generateUnitImpulseBasis(basisWidth,minTime,...
-        maxTime,sampleRate);
-    basisMat = unitPulseBasis.data;
- end
-
-% Generate the estimated stimulus effect
-if(strcmp(fitType,'poisson'))
-elseif(strcmp(fitType,'binomial'))
-    estStimEffect=exp(basisMat*xK)./(1+exp(basisMat*xK))./delta;
-end
-
-
-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
-% time
-subplot(3,1,[1 2 3]);
-lighting gouraud
-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',...
-            'Fontsize',14,...
-            'FontName','Arial');
-
-close all;
-h=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.4 scrsz(4)*.8]);
-
-% The actual stimulus effect
-subplot(3,1,1);
-lighting gouraud
-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',...
-            'Fontsize',14,...
-            'FontName','Arial');
-set(gca,'xtick',[],'xtickLabel',[]); 
-set(gca,'ytick',[],'ytickLabel',[]);
-CLIM = [min(min(stimData./delta)) max(max(stimData./delta))];
-view(gca,[90 -90]);
-
-
-
-% The PSTH estimate
-subplot(3,1,2);
-lighting gouraud
-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',...
-            'Fontsize',14,...
-            'FontName','Arial');
-
-set(gca,'xtick',[],'xtickLabel',[]); 
-set(gca,'ytick',[],'ytickLabel',[]);
-CLIM = [min(min(stimData./delta)) max(max(stimData./delta))];
-view(gca,[90 -90]);
-
-% The SSGLM estimated stimulus effect
-subplot(3,1,3);
-lighting gouraud
-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',...
-            'Fontsize',14,...
-            'FontName','Arial');
-set(gca,'xtick',[],'xtickLabel',[]); 
-set(gca,'ytick',[],'ytickLabel',[]);
-set(gca, 'YDir','normal')
-view(gca,[90 -90]);
-

Compare differences across trials

close all;
-   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
- if(~isempty(numBasis))
-    basisWidth = (maxTime-minTime)/numBasis;
-    sampleRate=1/delta;
-    unitPulseBasis=nstColl.generateUnitImpulseBasis(basisWidth,...
-        minTime,maxTime,sampleRate);
-    basisMat = unitPulseBasis.data;
- end
-
-
-% close all;
-
-t0=0; tf=Tmax;
-[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'))]);
-scrsz = get(0,'ScreenSize');
-h=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.8 scrsz(4)*.8]);
-
-subplot(2,3,1);
-spikeRateBinom.setName(['(' num2str(Tmax) '-0)^-1*\Lambda(0,' ...
-    num2str(Tmax) ')']);
-spikeRateBinom.plot([],{{' ''k'',''Linewidth'',4'}});
-% e = Events(lt,{''});
-% e.plot;
-v=axis;
-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',...
-            'Fontsize',12,...
-            'FontName','Arial');
-
-
-
-h=subplot(2,3,[2 3 5 6]);
-K=size(dN,1);
-colormap(flipud(gray));
-imagesc(ProbMat); hold on;
-for k=1:K
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-%
-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');
-
-subplot(2,3,4)
-stim1 = Covariate(time, basisMat*stimulus(:,1),'Trial1','time','s',...
-    'spikes/sec');
-temp = ConfidenceInterval(time, basisMat*squeeze(stimCIs(:,1,:)));
-stim1.setConfInterval(temp);
-stimlt = Covariate(time, basisMat*stimulus(:,lt),'Trial1','time','s',...
-    'spikes/sec');
-temp = ConfidenceInterval(time, basisMat*squeeze(stimCIs(:,lt,:)));
-temp.setColor('r');
-stimlt.setConfInterval(temp);
-stimltm1 = Covariate(time, basisMat*stimulus(:,lt-1),'Trial1','time','s',...
-    'spikes/sec');
-temp = ConfidenceInterval(time, basisMat*squeeze(stimCIs(:,lt-1,:)));
-temp.setColor('r');
-stimltm1.setConfInterval(temp);
-
-% figure;
-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',...
-            'Fontsize',12,...
-            'FontName','Arial');
-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)]);
-
-
-
-%% Compare differences across trials 
-close all;
-   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
- if(~isempty(numBasis))
-    basisWidth = (maxTime-minTime)/numBasis;
-    sampleRate=1/delta;
-    unitPulseBasis=nstColl.generateUnitImpulseBasis(basisWidth,...
-        minTime,maxTime,sampleRate);
-    basisMat = unitPulseBasis.data;
- end
-
-
-% close all;
-
-t0=0; tf=Tmax;
-[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 #12
-scrsz = get(0,'ScreenSize');
-h=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.8 scrsz(4)*.8]);
-
-subplot(2,3,1);
-spikeRateBinom.setName(['(' num2str(Tmax) '-0)^-1*\Lambda(0,' ...
-    num2str(Tmax) ')']);
-spikeRateBinom.plot([],{{' ''k'',''Linewidth'',4'}});
-% e = Events(lt,{''});
-% e.plot;
-v=axis;
-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',...
-            'Fontsize',12,...
-            'FontName','Arial');
-        
-
-
-h=subplot(2,3,[2 3 5 6]);
-K=size(dN,1);
-colormap(flipud(gray));
-imagesc(ProbMat); hold on;
-for k=1:K
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-        if(sigMat(k,m)==1)
-            plot3(m,k,1,'r*'); hold on;
-        end
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-        if(sigMat(k,m)==1)
-    end
-end
-    for m=(k+1):K
-        if(sigMat(k,m)==1)
-    end
-end
-    for m=(k+1):K
-end
-%
-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');
-
-subplot(2,3,4)
-stim1 = Covariate(time, basisMat*stimulus(:,1),'Trial1','time','s',...
-    'spikes/sec');
-temp = ConfidenceInterval(time, basisMat*squeeze(stimCIs(:,1,:)));
-stim1.setConfInterval(temp);
-stimlt = Covariate(time, basisMat*stimulus(:,lt),'Trial1','time','s',...
-    'spikes/sec');
-temp = ConfidenceInterval(time, basisMat*squeeze(stimCIs(:,lt,:)));
-temp.setColor('r');
-stimlt.setConfInterval(temp);
-stimltm1 = Covariate(time, basisMat*stimulus(:,lt-1),'Trial1','time','s',...
-    'spikes/sec');
-temp = ConfidenceInterval(time, basisMat*squeeze(stimCIs(:,lt-1,:)));
-temp.setColor('r');
-stimltm1.setConfInterval(temp);
-
-% figure;
-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',...
-            'Fontsize',12,...
-            'FontName','Arial');
-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)]);
-

Example 4 - HIPPOCAMPAL PLACE CELL - RECEPTIVE FIELD ESTIMATION

Estimation of receptive fields of neurons is a very common data analysis problem in neuroscience. Here we use the nSTAT software to perform an estimation of the receptive fields of hippocampal place cells using a bivariate Gaussian model and Zernike polynomials. The number of zernike polynomials is based on "An Analysis of Hippocampal Spatio-Temporal Representations Using a Bayesian Algorithm for Neural Spike Train Decoding" Barbieri et. al 2005. The data used herein in was provided by Dr. Ricardo Barbieri on 2/28/2011.

Author: Iahn Cajigas

Date: 3/1/2011

Example Data

The x and y coordinates of a freely foraging rat in a circular environment (70cm in diameter and 30cm high walls) and a fixed visual cue. The x and y coordinates at the time when a spike was observed are marked in red. The position coordinates have been normalized to be between -1 and 1 to allow to simplify the analysis.

    close all;
-    load(strcat('PlaceCellDataAnimal1.mat'));
-    exampleCell = [2 21 25 49];
-%     exampleCell = 1:length(neuron);
-%     figure(1);
-    scrsz = get(0,'ScreenSize');
-    h=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.6 scrsz(4)*.9]);
-
-    for i=1:length(exampleCell)
-        subplot(2,2,i);
-        h1=plot(x,y,'b','Linewidth',.5); hold on;
-        h2=plot(neuron{exampleCell(i)}.xN,neuron{exampleCell(i)}.yN,'r.',...
-            'MarkerSize',7);
-        hx=xlabel('X Position'); hy=ylabel('Y Position');
-%         title(['Animal#1, Cell#' num2str(exampleCell(i))]);
-        title(['Cell#' num2str(exampleCell(i))],'FontWeight','bold',...
-            'Fontsize',12,'FontName','Arial');
-        set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
-        set(gca,'xTick',-1:.5:1,'yTick',-1:.5:1); axis square;
-        if(i==4)
-            h_legend = legend([h1 h2],'Animal Path',...
-                'Location at time of spike');
-            pos = get(h_legend,'position');
-            set(h_legend, 'position',[pos(1)+.09 pos(2)+.06 pos(3:4)]);
-        end
-    end
-
-%% Example 4 - HIPPOCAMPAL PLACE CELL - RECEPTIVE FIELD ESTIMATION 
-% Estimation of receptive fields of neurons is a very common data analysis problem in neuroscience.
-% Here we use the nSTAT software to perform an estimation of the receptive fields of hippocampal
-% place cells using a bivariate Gaussian model and Zernike polynomials. The number of zernike polynomials 
-% is based on "An Analysis of Hippocampal Spatio-Temporal Representations Using a Bayesian Algorithm for Neural
-% Spike Train Decoding" Barbieri et. al 2005. The data used herein in was
-% provided by Dr. Ricardo Barbieri on 2/28/2011.
-%
-% *Author*: Iahn Cajigas 
-%
-% *Date*: 3/1/2011
-%%
-
-    
-%% Example Data
-% The x and y coordinates of a freely foraging rat in a circular environment (70cm in diameter and 30cm high walls) and a fixed visual cue. 
-% The x and y coordinates at the time when a spike was observed are marked
-% in red. The position coordinates have been normalized to be between -1
-% and 1 to allow to simplify the analysis. 
-    close all;
-    load(strcat('PlaceCellDataAnimal1.mat'));    
-    exampleCell = [2 21 25 49];
-%     exampleCell = 1:length(neuron);
-%     figure(1);
-    scrsz = get(0,'ScreenSize');
-    h=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.6 scrsz(4)*.9]);
-
-    for i=1:length(exampleCell)
-        subplot(2,2,i);
-        h1=plot(x,y,'b','Linewidth',.5); hold on;
-        h2=plot(neuron{exampleCell(i)}.xN,neuron{exampleCell(i)}.yN,'r.',...
-            'MarkerSize',7);
-        hx=xlabel('X Position'); hy=ylabel('Y Position'); 
-%         title(['Animal#1, Cell#' num2str(exampleCell(i))]);
-        title(['Cell#' num2str(exampleCell(i))],'FontWeight','bold',...
-            'Fontsize',12,'FontName','Arial');
-        set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
-        set(gca,'xTick',-1:.5:1,'yTick',-1:.5:1); axis square;
-        if(i==4)
-    end
-        subplot(2,2,i);
-        h1=plot(x,y,'b','Linewidth',.5); hold on;
-        h2=plot(neuron{exampleCell(i)}.xN,neuron{exampleCell(i)}.yN,'r.',...
-            'MarkerSize',7);
-        hx=xlabel('X Position'); hy=ylabel('Y Position'); 
-%         title(['Animal#1, Cell#' num2str(exampleCell(i))]);
-        title(['Cell#' num2str(exampleCell(i))],'FontWeight','bold',...
-            'Fontsize',12,'FontName','Arial');
-        set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
-        set(gca,'xTick',-1:.5:1,'yTick',-1:.5:1); axis square;
-        if(i==4)
-    end
-        subplot(2,2,i);
-        h1=plot(x,y,'b','Linewidth',.5); hold on;
-        h2=plot(neuron{exampleCell(i)}.xN,neuron{exampleCell(i)}.yN,'r.',...
-            'MarkerSize',7);
-        hx=xlabel('X Position'); hy=ylabel('Y Position'); 
-%         title(['Animal#1, Cell#' num2str(exampleCell(i))]);
-        title(['Cell#' num2str(exampleCell(i))],'FontWeight','bold',...
-            'Fontsize',12,'FontName','Arial');
-        set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
-        set(gca,'xTick',-1:.5:1,'yTick',-1:.5:1); axis square;
-        if(i==4)
-    end
-        subplot(2,2,i);
-        h1=plot(x,y,'b','Linewidth',.5); hold on;
-        h2=plot(neuron{exampleCell(i)}.xN,neuron{exampleCell(i)}.yN,'r.',...
-            'MarkerSize',7);
-        hx=xlabel('X Position'); hy=ylabel('Y Position'); 
-%         title(['Animal#1, Cell#' num2str(exampleCell(i))]);
-        title(['Cell#' num2str(exampleCell(i))],'FontWeight','bold',...
-            'Fontsize',12,'FontName','Arial');
-        set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
-        set(gca,'xTick',-1:.5:1,'yTick',-1:.5:1); axis square;
-        if(i==4)
-            h_legend = legend([h1 h2],'Animal Path',...
-                'Location at time of spike');
-            pos = get(h_legend,'position');
-            set(h_legend, 'position',[pos(1)+.09 pos(2)+.06 pos(3:4)]);
-        end
-    end
-

Analyze All Cells

numAnimals=2;
-CompilingHelpFile=1;
-if(~CompilingHelpFile)
-    for n=1:numAnimals
-        % load the data
-        clear x y neuron time nst tc tcc z;
-        load(strcat('PlaceCellDataAnimal',num2str(n),'.mat'));
-
-        % Create the spikeTrains for each cell
-        for i=1:length(neuron)
-            nst{i} = nspikeTrain(neuron{i}.spikeTimes);
-        end
-
-
-        % 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
-        cnt=0;
-        for l=0:3
-           for m=-l:l
-               if(~any(mod(l-m,2))) % otherwise the polynomial = 0
-                cnt = cnt+1;
-                z(:,cnt) = zernfun(l,m,r,theta,'norm');
-                % zernfun by Paul Fricker
-                % http://www.mathworks.com/matlabcentral/fileexchange/7687
-               end
-           end
-        end
-
-        % Data sampled at 30 Hz but just to be sure
-        delta=min(diff(time));
-        sampleRate = round(1/delta);
-        % Define Covariates for the analysis
-        baseline = Covariate(time,ones(length(x),1),'Baseline','time','s','',...
-                            {'mu'});
-        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');
-        tcc = ConfigColl(tc);
-
-        % Perform Analysis (Commented to since data already saved)
-         results =Analysis.RunAnalysisForAllNeurons(trial,tcc,0);
-
-        % Save results
-            resStruct =FitResult.CellArrayToStructure(results);
-            filename = ['PlaceCellAnimal' num2str(n) 'Results'];
-            save(filename,'resStruct');
-    end
-end
-
    
-
- %% Analyze All Cells 
-numAnimals=2;
-CompilingHelpFile=1;
-if(~CompilingHelpFile)
-

View Summary Statistics

Note the Zernike Polynomials yield better fits in terms of decreased KS Statistics (less deviation from the 45 degree line), reduced AIC and reduced BIC across the majority of cells and for both animals

clear Summary;
-numAnimals =2;
-
-for n=1:numAnimals
-    resData=load(strcat('PlaceCellAnimal',num2str(n),'Results.mat'));
-    results = FitResult.fromStructure(resData.resStruct);
-    Summary{n} = FitResSummary(results);
-%     Summary{n}.plotSummary;
-end
-
%% View Summary Statistics
-% Note the Zernike Polynomials yield better fits in terms of decreased KS
-% Statistics (less deviation from the 45 degree line), reduced AIC and
-% reduced BIC across the majority of cells and for both animals
-clear Summary;
-numAnimals =2;
- 
-for n=1:numAnimals
-    resData=load(strcat('PlaceCellAnimal',num2str(n),'Results.mat'));
-    results = FitResult.fromStructure(resData.resStruct);
-    Summary{n} = FitResSummary(results);
-%     Summary{n}.plotSummary;
-end    
-    resData=load(strcat('PlaceCellAnimal',num2str(n),'Results.mat'));
-    results = FitResult.fromStructure(resData.resStruct);
-    Summary{n} = FitResSummary(results);
-%     Summary{n}.plotSummary;
-end    
-
close all;
-scrsz = get(0,'ScreenSize');
-h=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.6 scrsz(4)*.5]);
-subplot(1,3,1);
-maxLength = max([Summary{1}.numNeurons,Summary{2}.numNeurons]);
-dKS = nan(maxLength, 2);
-dKS(1:Summary{1}.numNeurons,1) = (Summary{1}.KSStats(:,1)-Summary{1}.KSStats(:,2)) ;
-dKS(1:Summary{2}.numNeurons,2) = (Summary{2}.KSStats(:,1)-Summary{2}.KSStats(:,2)) ;
-
-boxplot(dKS ,{'Animal 1', 'Animal 2'},'labelorientation','inline');
-title('\Delta KS Statistic','FontWeight','bold','FontSize',14,...
-    'FontName','Arial');
-
-
-subplot(1,3,2);
-dAIC = nan(maxLength, 2);
-dAIC(1:Summary{1}.numNeurons,1) = Summary{1}.getDiffAIC(1);
-dAIC(1:Summary{2}.numNeurons,2) = Summary{2}.getDiffAIC(1);
-
-boxplot(dAIC ,{'Animal 1', 'Animal 2'},'labelorientation','inline');
-title('\Delta AIC','FontWeight','bold','FontSize',14,'FontName','Arial');
-
-
-subplot(1,3,3);
-dBIC = nan(maxLength, 2);
-dBIC(1:Summary{1}.numNeurons,1) = Summary{1}.getDiffBIC(1);
-dBIC(1:Summary{2}.numNeurons,2) = Summary{2}.getDiffBIC(1);
-
-boxplot(dBIC ,{'Animal 1', 'Animal 2'},'labelorientation','inline'); %ylabel('\Delta BIC'); %xticklabel_rotate([],45,[],'Fontsize',6);
-title('\Delta BIC','FontWeight','bold','FontSize',14,'FontName','Arial');
-
-%  close all;
-
%%
-close all;
-scrsz = get(0,'ScreenSize');
-h=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.6 scrsz(4)*.5]);
-subplot(1,3,1);
-maxLength = max([Summary{1}.numNeurons,Summary{2}.numNeurons]);
-dKS = nan(maxLength, 2);
-dKS(1:Summary{1}.numNeurons,1) = (Summary{1}.KSStats(:,1)-Summary{1}.KSStats(:,2)) ;
-dKS(1:Summary{2}.numNeurons,2) = (Summary{2}.KSStats(:,1)-Summary{2}.KSStats(:,2)) ;
-
-boxplot(dKS ,{'Animal 1', 'Animal 2'},'labelorientation','inline'); 
-title('\Delta KS Statistic','FontWeight','bold','FontSize',14,...
-    'FontName','Arial');
-                  
-
-subplot(1,3,2);
-dAIC = nan(maxLength, 2);
-dAIC(1:Summary{1}.numNeurons,1) = Summary{1}.getDiffAIC(1);
-dAIC(1:Summary{2}.numNeurons,2) = Summary{2}.getDiffAIC(1);
-
-boxplot(dAIC ,{'Animal 1', 'Animal 2'},'labelorientation','inline'); 
-title('\Delta AIC','FontWeight','bold','FontSize',14,'FontName','Arial');
-                  
-
-subplot(1,3,3); 
-dBIC = nan(maxLength, 2);
-dBIC(1:Summary{1}.numNeurons,1) = Summary{1}.getDiffBIC(1);
-dBIC(1:Summary{2}.numNeurons,2) = Summary{2}.getDiffBIC(1);
-
-boxplot(dBIC ,{'Animal 1', 'Animal 2'},'labelorientation','inline'); %ylabel('\Delta BIC'); %xticklabel_rotate([],45,[],'Fontsize',6);
-title('\Delta BIC','FontWeight','bold','FontSize',14,'FontName','Arial');
-

Visualize the results

close all;
-% Define a grid
-[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
-idx = r_new<=1;
-zpoly = cell(1,10);
-cnt=0;
-for l=0:3
-   for m=-l:l
-       if(~any(mod(l-m,2)))
-        cnt = cnt+1;
-        temp = nan(size(x_new));
-        temp(idx) = zernfun(l,m,r_new(idx),theta_new(idx),'norm');
-        zpoly{cnt} = temp;
-       end
-   end
-end
-
-
-
-for n=1:numAnimals
-
-    clear lambdaGaussian lambdaZernike;
-    load(strcat('PlaceCellDataAnimal',num2str(n),'.mat'));
-    resData=load(strcat('PlaceCellAnimal',num2str(n),'Results.mat'));
-    results = FitResult.fromStructure(resData.resStruct);
-
-    for i=1:length(neuron)
-        % 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);
-    end
-
-
-
-
-    % Plot the receptive fields
-    for i=1:length(neuron)
-        % 3d plot of an example place field
-
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-                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;
-            end
-            subplot(7,7,i);
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-                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;
-            end
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-                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;
-
-            end
-            subplot(7,7,i);
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-               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;
-            end
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square;
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-
-
-end
-
-%  close all;
-    
-
-%% Visualize the results 
-close all;
-% Define a grid 
-[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
-idx = r_new<=1;
-zpoly = cell(1,10);
-cnt=0;
-for l=0:3
-   for m=-l:l 
-       if(~any(mod(l-m,2)))
-        cnt = cnt+1;
-        temp = nan(size(x_new));
-        temp(idx) = zernfun(l,m,r_new(idx),theta_new(idx),'norm');
-        zpoly{cnt} = temp;
-       end
-   end
-end
-   for m=-l:l 
-       if(~any(mod(l-m,2)))
-        cnt = cnt+1;
-        temp = nan(size(x_new));
-        temp(idx) = zernfun(l,m,r_new(idx),theta_new(idx),'norm');
-        zpoly{cnt} = temp;
-       end
-   end
-       if(~any(mod(l-m,2)))
-   end
-       if(~any(mod(l-m,2)))
-        cnt = cnt+1;
-        temp = nan(size(x_new));
-        temp(idx) = zernfun(l,m,r_new(idx),theta_new(idx),'norm');
-        zpoly{cnt} = temp;
-       end
-   end
-end
-   for m=-l:l 
-       if(~any(mod(l-m,2)))
-        cnt = cnt+1;
-        temp = nan(size(x_new));
-        temp(idx) = zernfun(l,m,r_new(idx),theta_new(idx),'norm');
-        zpoly{cnt} = temp;
-       end
-   end
-       if(~any(mod(l-m,2)))
-   end
-       if(~any(mod(l-m,2)))
-        cnt = cnt+1;
-        temp = nan(size(x_new));
-        temp(idx) = zernfun(l,m,r_new(idx),theta_new(idx),'norm');
-        zpoly{cnt} = temp;
-       end
-   end
-       if(~any(mod(l-m,2)))
-   end
-       if(~any(mod(l-m,2)))
-        cnt = cnt+1;
-        temp = nan(size(x_new));
-        temp(idx) = zernfun(l,m,r_new(idx),theta_new(idx),'norm');
-        zpoly{cnt} = temp;
-       end
-   end
-end
-   for m=-l:l 
-       if(~any(mod(l-m,2)))
-        cnt = cnt+1;
-        temp = nan(size(x_new));
-        temp(idx) = zernfun(l,m,r_new(idx),theta_new(idx),'norm');
-        zpoly{cnt} = temp;
-       end
-   end
-       if(~any(mod(l-m,2)))
-   end
-       if(~any(mod(l-m,2)))
-        cnt = cnt+1;
-        temp = nan(size(x_new));
-        temp(idx) = zernfun(l,m,r_new(idx),theta_new(idx),'norm');
-        zpoly{cnt} = temp;
-       end
-   end
-       if(~any(mod(l-m,2)))
-   end
-       if(~any(mod(l-m,2)))
-        cnt = cnt+1;
-        temp = nan(size(x_new));
-        temp(idx) = zernfun(l,m,r_new(idx),theta_new(idx),'norm');
-        zpoly{cnt} = temp;
-       end
-   end
-       if(~any(mod(l-m,2)))
-   end
-       if(~any(mod(l-m,2)))
-        cnt = cnt+1;
-        temp = nan(size(x_new));
-        temp(idx) = zernfun(l,m,r_new(idx),theta_new(idx),'norm');
-        zpoly{cnt} = temp;
-       end
-   end
-end
-
-
-
-for n=1:numAnimals 
-    
-    clear lambdaGaussian lambdaZernike;
-    load(strcat('PlaceCellDataAnimal',num2str(n),'.mat'));
-    resData=load(strcat('PlaceCellAnimal',num2str(n),'Results.mat'));
-    results = FitResult.fromStructure(resData.resStruct);
-    
-    for i=1:length(neuron)
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-
-   
-    
-    
-    % Plot the receptive fields
-    for i=1:length(neuron)
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-                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;
-            end
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-                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;
-                
-            end
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-            h4=figure(4);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-            h5=figure(5);
-            colormap('jet');
-            if(i==1)
-            subplot(7,7,i); 
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-
-  
-end
-    
-    clear lambdaGaussian lambdaZernike;
-    load(strcat('PlaceCellDataAnimal',num2str(n),'.mat'));
-    resData=load(strcat('PlaceCellAnimal',num2str(n),'Results.mat'));
-    results = FitResult.fromStructure(resData.resStruct);
-    
-    for i=1:length(neuron)
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-
-   
-    
-    
-    % Plot the receptive fields
-    for i=1:length(neuron)
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-                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;
-            end
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-               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;
-            end
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-        % 3d plot of an example place field
-        
-
-        % 2d plot of all the cell's fields
-        if(n==1)
-        elseif(n==2)
-            h6=figure(6);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaGaussian{i}), shading interp
-        axis square; set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-
-        if(n==1)
-        elseif(n==2)
-            h7=figure(7);
-            colormap('jet');
-            if(i==1)
-            subplot(6,7,i);
-        end
-        pcolor(x_new,y_new,lambdaZernike{i}), shading interp
-        axis square; 
-        set(gca,'xtick',[],'ytick',[]);
-        set(gca, 'Box'         , 'off');
-    end
-
-  
-end
-
    clear lambdaGaussian lambdaZernike;
-    load(strcat('PlaceCellDataAnimal1.mat'));
-    resData=load(strcat('PlaceCellAnimal1Results.mat'));
-    results = FitResult.fromStructure(resData.resStruct);
-
-    for i=1:length(neuron)
-        % 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);
-    end
-
-
-
-%     h1=plot(x,y,'b');
-%     h2=plot(x,y,'g');
-    %
-    exampleCell = 25;
-%     figure(8);
-%     plot(x,y,'b',neuron{exampleCell}.xN,neuron{exampleCell}.yN,'r.');
-%     xlabel('x'); ylabel('y');
-%     title(['Animal#1, Cell#' num2str(exampleCell)]);
-%
-    close all;
-    h9=figure(9);
-    h_mesh = mesh(x_new,y_new,lambdaGaussian{exampleCell},'AlphaData',0);
-    get(h_mesh,'AlphaData');
-    set(h_mesh,'FaceAlpha',0.2,'EdgeAlpha',0.2,'EdgeColor','b');
-    hold on;
-    h_mesh = mesh(x_new,y_new,lambdaZernike{exampleCell},'AlphaData',0);
-    get(h_mesh,'AlphaData');
-    set(h_mesh,'FaceAlpha',0.2,'EdgeAlpha',0.2,'EdgeColor','g');
-
-
-%     h_legend=legend('\lambda_{Gaussian}','\lambda_{Zernike}');
-%     set(h_legend,'FontSize',20);
-    plot(x,y,neuron{exampleCell}.xN,neuron{exampleCell}.yN,'r.');
-    axis tight square;
-    xlabel('x position'); ylabel('y position');
-    title(['Animal#1, Cell#' num2str(exampleCell)],'FontWeight','bold',...
-        'Fontsize',12,'FontName','Arial');
-    hx=get(gca,'XLabel');  hy=get(gca,'YLabel');
-    set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
-
-
-%%
-    clear lambdaGaussian lambdaZernike;
-    load(strcat('PlaceCellDataAnimal1.mat'));
-    resData=load(strcat('PlaceCellAnimal1Results.mat'));
-    results = FitResult.fromStructure(resData.resStruct);
-    
-    for i=1:length(neuron)
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-        % 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);
-    end
-
-    
-    
-%     h1=plot(x,y,'b');
-%     h2=plot(x,y,'g');
-    %
-    exampleCell = 25;
-%     figure(8);
-%     plot(x,y,'b',neuron{exampleCell}.xN,neuron{exampleCell}.yN,'r.');
-%     xlabel('x'); ylabel('y'); 
-%     title(['Animal#1, Cell#' num2str(exampleCell)]);
-%     
-    close all;
-    h9=figure(9);
-    h_mesh = mesh(x_new,y_new,lambdaGaussian{exampleCell},'AlphaData',0);
-    get(h_mesh,'AlphaData');
-    set(h_mesh,'FaceAlpha',0.2,'EdgeAlpha',0.2,'EdgeColor','b');
-    hold on;
-    h_mesh = mesh(x_new,y_new,lambdaZernike{exampleCell},'AlphaData',0);
-    get(h_mesh,'AlphaData');
-    set(h_mesh,'FaceAlpha',0.2,'EdgeAlpha',0.2,'EdgeColor','g');
-
-    
-%     h_legend=legend('\lambda_{Gaussian}','\lambda_{Zernike}');
-%     set(h_legend,'FontSize',20);
-    plot(x,y,neuron{exampleCell}.xN,neuron{exampleCell}.yN,'r.');
-    axis tight square;
-    xlabel('x position'); ylabel('y position');
-    title(['Animal#1, Cell#' num2str(exampleCell)],'FontWeight','bold',...
-        'Fontsize',12,'FontName','Arial');
-    hx=get(gca,'XLabel');  hy=get(gca,'YLabel');
-    set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
-

Example 5 - STIMULUS DECODING

In this example we show how to decode a univariate and a bivariate stimulus based on a point process observations using nSTAT. Even though due to the simulated nature of the data, we know the exact condition intensity function, we estimate the parameters before moving on to the decoding stage.

Generate the conditional Intensity Function

    close all; clear all;
-    delta = 0.001; Tmax = 1;
-    time = 0:delta:Tmax;
-    numRealizations = 20;
-    f=2; b1=randn(numRealizations,1);b0=log(10*delta)+randn(numRealizations,1);
-    x = sin(2*pi*f*time);
-    clear nst;
-    for i=1:numRealizations
-        expData = exp(b1(i)*x+b0(i));
-        lambdaData = expData./(1+expData);
-
-        if(i==1)
-            lambda = Covariate(time,lambdaData./delta, ...
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-        else
-            tempLambda = Covariate(time,lambdaData./delta, ...
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-            lambda = lambda.merge(tempLambda);
-        end
-
-        spikeColl = CIF.simulateCIFByThinningFromLambda(...
-            lambda.getSubSignal(i),1);
-        nst{i} = spikeColl.getNST(1);
-    end
-        spikeColl = nstColl(nst);scrsz = get(0,'ScreenSize');
-        h=figure('Position',[scrsz(3)*.1 scrsz(4)*.1 ...
-            scrsz(3)*.6 scrsz(4)*.8]);
-%         figure;
-        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'}});
-            legend off;
-            hy=ylabel('Firing Rate [spikes/sec]', 'Interpreter','none');
-            hx=xlabel('','Interpreter','none');
-            set([hx, hy],'FontName', 'Arial','FontSize',12,...
-                'FontWeight','bold');
-            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',...
-                0:10:numRealizations);
-            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','',...
-                    {'constant'});
-
-%     close all;
-
-
-    
-%% Example 5 - STIMULUS DECODING
-% In this example we show how to decode a univariate and a bivariate
-% stimulus based on a point process observations using nSTAT. Even though 
-% due to the simulated nature of the data, we know the exact condition 
-% intensity function, we estimate the parameters before moving on to the 
-% decoding stage.
-%% Generate the conditional Intensity Function
-
-    close all; clear all;
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\private\evalmxdom.m' could not be
-cleared because it contains MATLAB code that is currently executing. 
-Warning: The file
-'C:\Users\Developer\Dropbox\GitHub\nSTAT\helpfiles\nSTATPaperExamples.m' could
-not be cleared because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\mdbpublish.m' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\publish.p' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\private\evalmxdom.m' could not be
-cleared because it contains MATLAB code that is currently executing. 
-Warning: The file
-'C:\Users\Developer\Dropbox\GitHub\nSTAT\helpfiles\nSTATPaperExamples.m' could
-not be cleared because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\mdbpublish.m' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\publish.p' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\private\evalmxdom.m' could not be
-cleared because it contains MATLAB code that is currently executing. 
-Warning: The file
-'C:\Users\Developer\Dropbox\GitHub\nSTAT\helpfiles\nSTATPaperExamples.m' could
-not be cleared because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\mdbpublish.m' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\publish.p' could not be cleared
-because it contains MATLAB code that is currently executing. 
-    delta = 0.001; Tmax = 1;
-    time = 0:delta:Tmax;
-    numRealizations = 20;
-    f=2; b1=randn(numRealizations,1);b0=log(10*delta)+randn(numRealizations,1);
-    x = sin(2*pi*f*time);
-    clear nst;
-    for i=1:numRealizations
-        expData = exp(b1(i)*x+b0(i)); 
-        lambdaData = expData./(1+expData);
-
-        if(i==1)
-            lambda = Covariate(time,lambdaData./delta, ...
-        end       
-        
-        spikeColl = CIF.simulateCIFByThinningFromLambda(...
-            lambda.getSubSignal(i),1); 
-        nst{i} = spikeColl.getNST(1);
-    end
-        expData = exp(b1(i)*x+b0(i)); 
-        lambdaData = expData./(1+expData);
-
-        if(i==1)
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-        else 
-            tempLambda = Covariate(time,lambdaData./delta, ...
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-            lambda = lambda.merge(tempLambda);
-        end       
-        
-        spikeColl = CIF.simulateCIFByThinningFromLambda(...
-            lambda.getSubSignal(i),1); 
-        nst{i} = spikeColl.getNST(1);
-    end
-        expData = exp(b1(i)*x+b0(i)); 
-        lambdaData = expData./(1+expData);
-
-        if(i==1)
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-        else 
-            tempLambda = Covariate(time,lambdaData./delta, ...
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-            lambda = lambda.merge(tempLambda);
-        end       
-        
-        spikeColl = CIF.simulateCIFByThinningFromLambda(...
-            lambda.getSubSignal(i),1); 
-        nst{i} = spikeColl.getNST(1);
-    end
-        expData = exp(b1(i)*x+b0(i)); 
-        lambdaData = expData./(1+expData);
-
-        if(i==1)
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-        else 
-            tempLambda = Covariate(time,lambdaData./delta, ...
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-            lambda = lambda.merge(tempLambda);
-        end       
-        
-        spikeColl = CIF.simulateCIFByThinningFromLambda(...
-            lambda.getSubSignal(i),1); 
-        nst{i} = spikeColl.getNST(1);
-    end
-        expData = exp(b1(i)*x+b0(i)); 
-        lambdaData = expData./(1+expData);
-
-        if(i==1)
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-        else 
-            tempLambda = Covariate(time,lambdaData./delta, ...
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-            lambda = lambda.merge(tempLambda);
-        end       
-        
-        spikeColl = CIF.simulateCIFByThinningFromLambda(...
-            lambda.getSubSignal(i),1); 
-        nst{i} = spikeColl.getNST(1);
-    end
-        expData = exp(b1(i)*x+b0(i)); 
-        lambdaData = expData./(1+expData);
-
-        if(i==1)
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-        else 
-            tempLambda = Covariate(time,lambdaData./delta, ...
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-            lambda = lambda.merge(tempLambda);
-        end       
-        
-        spikeColl = CIF.simulateCIFByThinningFromLambda(...
-            lambda.getSubSignal(i),1); 
-        nst{i} = spikeColl.getNST(1);
-    end
-        expData = exp(b1(i)*x+b0(i)); 
-        lambdaData = expData./(1+expData);
-
-        if(i==1)
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-        else 
-            tempLambda = Covariate(time,lambdaData./delta, ...
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-            lambda = lambda.merge(tempLambda);
-        end       
-        
-        spikeColl = CIF.simulateCIFByThinningFromLambda(...
-            lambda.getSubSignal(i),1); 
-        nst{i} = spikeColl.getNST(1);
-    end
-        expData = exp(b1(i)*x+b0(i)); 
-        lambdaData = expData./(1+expData);
-
-        if(i==1)
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-        else 
-            tempLambda = Covariate(time,lambdaData./delta, ...
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-            lambda = lambda.merge(tempLambda);
-        end       
-        
-        spikeColl = CIF.simulateCIFByThinningFromLambda(...
-            lambda.getSubSignal(i),1); 
-        nst{i} = spikeColl.getNST(1);
-    end
-        expData = exp(b1(i)*x+b0(i)); 
-        lambdaData = expData./(1+expData);
-
-        if(i==1)
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-        else 
-            tempLambda = Covariate(time,lambdaData./delta, ...
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-            lambda = lambda.merge(tempLambda);
-        end       
-        
-        spikeColl = CIF.simulateCIFByThinningFromLambda(...
-            lambda.getSubSignal(i),1); 
-        nst{i} = spikeColl.getNST(1);
-    end
-        expData = exp(b1(i)*x+b0(i)); 
-        lambdaData = expData./(1+expData);
-
-        if(i==1)
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-        else 
-            tempLambda = Covariate(time,lambdaData./delta, ...
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-            lambda = lambda.merge(tempLambda);
-        end       
-        
-        spikeColl = CIF.simulateCIFByThinningFromLambda(...
-            lambda.getSubSignal(i),1); 
-        nst{i} = spikeColl.getNST(1);
-    end
-        expData = exp(b1(i)*x+b0(i)); 
-        lambdaData = expData./(1+expData);
-
-        if(i==1)
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-        else 
-            tempLambda = Covariate(time,lambdaData./delta, ...
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-            lambda = lambda.merge(tempLambda);
-        end       
-        
-        spikeColl = CIF.simulateCIFByThinningFromLambda(...
-            lambda.getSubSignal(i),1); 
-        nst{i} = spikeColl.getNST(1);
-    end
-        expData = exp(b1(i)*x+b0(i)); 
-        lambdaData = expData./(1+expData);
-
-        if(i==1)
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-        else 
-            tempLambda = Covariate(time,lambdaData./delta, ...
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-            lambda = lambda.merge(tempLambda);
-        end       
-        
-        spikeColl = CIF.simulateCIFByThinningFromLambda(...
-            lambda.getSubSignal(i),1); 
-        nst{i} = spikeColl.getNST(1);
-    end
-        expData = exp(b1(i)*x+b0(i)); 
-        lambdaData = expData./(1+expData);
-
-        if(i==1)
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-        else 
-            tempLambda = Covariate(time,lambdaData./delta, ...
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-            lambda = lambda.merge(tempLambda);
-        end       
-        
-        spikeColl = CIF.simulateCIFByThinningFromLambda(...
-            lambda.getSubSignal(i),1); 
-        nst{i} = spikeColl.getNST(1);
-    end
-        expData = exp(b1(i)*x+b0(i)); 
-        lambdaData = expData./(1+expData);
-
-        if(i==1)
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-        else 
-            tempLambda = Covariate(time,lambdaData./delta, ...
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-            lambda = lambda.merge(tempLambda);
-        end       
-        
-        spikeColl = CIF.simulateCIFByThinningFromLambda(...
-            lambda.getSubSignal(i),1); 
-        nst{i} = spikeColl.getNST(1);
-    end
-        expData = exp(b1(i)*x+b0(i)); 
-        lambdaData = expData./(1+expData);
-
-        if(i==1)
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-        else 
-            tempLambda = Covariate(time,lambdaData./delta, ...
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-            lambda = lambda.merge(tempLambda);
-        end       
-        
-        spikeColl = CIF.simulateCIFByThinningFromLambda(...
-            lambda.getSubSignal(i),1); 
-        nst{i} = spikeColl.getNST(1);
-    end
-        expData = exp(b1(i)*x+b0(i)); 
-        lambdaData = expData./(1+expData);
-
-        if(i==1)
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-        else 
-            tempLambda = Covariate(time,lambdaData./delta, ...
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-            lambda = lambda.merge(tempLambda);
-        end       
-        
-        spikeColl = CIF.simulateCIFByThinningFromLambda(...
-            lambda.getSubSignal(i),1); 
-        nst{i} = spikeColl.getNST(1);
-    end
-        expData = exp(b1(i)*x+b0(i)); 
-        lambdaData = expData./(1+expData);
-
-        if(i==1)
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-        else 
-            tempLambda = Covariate(time,lambdaData./delta, ...
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-            lambda = lambda.merge(tempLambda);
-        end       
-        
-        spikeColl = CIF.simulateCIFByThinningFromLambda(...
-            lambda.getSubSignal(i),1); 
-        nst{i} = spikeColl.getNST(1);
-    end
-        expData = exp(b1(i)*x+b0(i)); 
-        lambdaData = expData./(1+expData);
-
-        if(i==1)
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-        else 
-            tempLambda = Covariate(time,lambdaData./delta, ...
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-            lambda = lambda.merge(tempLambda);
-        end       
-        
-        spikeColl = CIF.simulateCIFByThinningFromLambda(...
-            lambda.getSubSignal(i),1); 
-        nst{i} = spikeColl.getNST(1);
-    end
-        expData = exp(b1(i)*x+b0(i)); 
-        lambdaData = expData./(1+expData);
-
-        if(i==1)
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-        else 
-            tempLambda = Covariate(time,lambdaData./delta, ...
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-            lambda = lambda.merge(tempLambda);
-        end       
-        
-        spikeColl = CIF.simulateCIFByThinningFromLambda(...
-            lambda.getSubSignal(i),1); 
-        nst{i} = spikeColl.getNST(1);
-    end
-        expData = exp(b1(i)*x+b0(i)); 
-        lambdaData = expData./(1+expData);
-
-        if(i==1)
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-        else 
-            tempLambda = Covariate(time,lambdaData./delta, ...
-                '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},...
-                {{' ''b'', ''LineWidth'' ,2'}});
-            lambda = lambda.merge(tempLambda);
-        end       
-        
-        spikeColl = CIF.simulateCIFByThinningFromLambda(...
-            lambda.getSubSignal(i),1); 
-        nst{i} = spikeColl.getNST(1);
-    end
-        spikeColl = nstColl(nst);scrsz = get(0,'ScreenSize');
-        h=figure('Position',[scrsz(3)*.1 scrsz(4)*.1 ...
-            scrsz(3)*.6 scrsz(4)*.8]);
-%         figure;
-        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'}}); 
-            legend off; 
-            hy=ylabel('Firing Rate [spikes/sec]', 'Interpreter','none');
-            hx=xlabel('','Interpreter','none');
-            set([hx, hy],'FontName', 'Arial','FontSize',12,...
-                'FontWeight','bold');
-            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',...
-                0:10:numRealizations); 
-            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','',...
-
close all;
-
-clear lambdaCIF;
-spikeColl.resample(1/delta);
-dN=spikeColl.dataToMatrix;
-
-% Make noise according to the dynamic range of the stimulus
-Q=std(stim.data(2:end)-stim.data(1:end-1));
-Px0=.1; A=1;
-x0 = x(:,1); yT=x(:,end);
-Pi0 = eps*eye(size(x0,1),size(x0,1));
-PiT = eps*eye(size(x0,1),size(x0,1));
-
-
-[x_p, W_p, x_u, W_u] = DecodingAlgorithms.PPDecodeFilterLinear(A, ...
-    Q, dN',b0,b1','binomial',delta);
-%
-h=figure('Position',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.8 scrsz(4)*.6]);
-zVal=1.96;
-ciLower = min(x_u(1:end)-zVal*sqrt(squeeze(W_u(1:end)))',...
-    x_u(1:end)+zVal*sqrt(squeeze(W_u(1:end))'));
-ciUpper = max(x_u(1:end)-zVal*sqrt(squeeze(W_u(1:end)))',...
-    x_u(1:end)+zVal*sqrt(squeeze(W_u(1:end))'));
-
-estimatedStimulus = Covariate(time,x_u(1:end),'\hat{x}(t)','time','s','');
-CI= ConfidenceInterval(time,[ciLower', ciUpper'],'\hat{x}(t)','time','s','');
-estimatedStimulus.setConfInterval(CI);
-
-% hold all;
-% hEst=plot(time,x_u(1:end),'b','Linewidth',2); hold on;
-% plot(time, [ciUpper', ciLower'],'b');
-
-hEst = estimatedStimulus.plot([],{{' ''k'',''Linewidth'',4'}});
-hStim=stim.plot([],{{' ''b'',''Linewidth'',4'}});
-legend off;
-h_legend=legend([hEst(1) hStim],'Decoded','Actual');
-set(h_legend,'Interpreter','none');
-set(h_legend,'FontSize',22);
-title(['Decoded Stimulus +/- 95% CIs with ' num2str(numRealizations) ' cells'],...
-    'FontWeight','bold','Fontsize',22,'FontName','Arial');
-xlabel('time [s]','Interpreter','none');
-ylabel('Stimulus','Interpreter','none');
-hx=get(gca,'XLabel');  hy=get(gca,'YLabel');
-set([hx, hy],'FontName', 'Arial','FontSize',22,'FontWeight','bold');
-
                    {'constant'});
-
-%     close all;
-%%
-close all;
-
-clear lambdaCIF;
-spikeColl.resample(1/delta);
-dN=spikeColl.dataToMatrix;
-
-% Make noise according to the dynamic range of the stimulus
-Q=std(stim.data(2:end)-stim.data(1:end-1));
-Px0=.1; A=1;
-x0 = x(:,1); yT=x(:,end);
-Pi0 = eps*eye(size(x0,1),size(x0,1));
-PiT = eps*eye(size(x0,1),size(x0,1));
-
-
-[x_p, W_p, x_u, W_u] = DecodingAlgorithms.PPDecodeFilterLinear(A, ...
-    Q, dN',b0,b1','binomial',delta);
-%
-h=figure('Position',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.8 scrsz(4)*.6]);
-zVal=1.96;
-ciLower = min(x_u(1:end)-zVal*sqrt(squeeze(W_u(1:end)))',...
-    x_u(1:end)+zVal*sqrt(squeeze(W_u(1:end))'));
-ciUpper = max(x_u(1:end)-zVal*sqrt(squeeze(W_u(1:end)))',...
-    x_u(1:end)+zVal*sqrt(squeeze(W_u(1:end))'));
-
-estimatedStimulus = Covariate(time,x_u(1:end),'\hat{x}(t)','time','s','');
-CI= ConfidenceInterval(time,[ciLower', ciUpper'],'\hat{x}(t)','time','s','');
-estimatedStimulus.setConfInterval(CI);
-
-% hold all;            
-% hEst=plot(time,x_u(1:end),'b','Linewidth',2); hold on;
-% plot(time, [ciUpper', ciLower'],'b');
-
-hEst = estimatedStimulus.plot([],{{' ''k'',''Linewidth'',4'}});
-hStim=stim.plot([],{{' ''b'',''Linewidth'',4'}}); 
-legend off;
-h_legend=legend([hEst(1) hStim],'Decoded','Actual');
-set(h_legend,'Interpreter','none');
-set(h_legend,'FontSize',22);
-title(['Decoded Stimulus +/- 95% CIs with ' num2str(numRealizations) ' cells'],...
-    'FontWeight','bold','Fontsize',22,'FontName','Arial');
-xlabel('time [s]','Interpreter','none');
-ylabel('Stimulus','Interpreter','none');
-hx=get(gca,'XLabel');  hy=get(gca,'YLabel');
-set([hx, hy],'FontName', 'Arial','FontSize',22,'FontWeight','bold');
-

Example 5b - Arm reaching to target Simulation

See L. Srinivasan, U. T. Eden, A. S. Willsky, and E. N. Brown, "A state-space analysis for reconstruction of goal-directed movements using neural signals.," Neural computation, vol. 18, no. 10, pp. 2465?2494, Oct. 2006.

    close all;
-    clear all;
-    %Process noise covariance only drives the movement velocity
-    q=1e-4;
-    Q=diag([1e-12 1e-12 q q]);
-
-    delta = .001;        % Time increment
-    r=1e-6;   % in meters^2
-    p=1e-6;    % in meters^2/s^2
-    PiT=diag([r r p p]); % Uncertainty in the target state
-    Pi0=PiT;
-    T=2;                 % Reach Duration
-
-    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
-       0 1 0     delta;
-       0 0 1     0    ;
-       0 0 0     1    ];
-
-    x=zeros(4,length(time));
-
-
-% Simulate a reach trajectory
-% Differs from reference by multiplication by delta instead of division so
-% that the velocity has units of meters per second
-    R=chol(Q);
-    L=chol(PiT);
-    for k=1:length(time)
-        if(k==1)
-            x(:,k)=x0;
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-    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 The movement path
-    subplot(4,2,[1 3]);
-    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');
-    hold on;
-    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
-
-    subplot(4,2,7);
-    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');
-    xlabel('time [s]');
-    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');
-    %
-
-    gamma=0;
-    windowTimes=[0, 0.001];
-
-
-% 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;
-    numCells = 20;
-    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
-    fitType='binomial';
-    clear nst;
-    for i=1:numCells
-         tempData  = exp(dataMat*coeffs(i,:)');
-
-         if(strcmp(fitType,'poisson'))
-             lambdaData = tempData;
-         else
-            lambdaData = tempData./(1+tempData); % Conditional Intensity Function for ith cell
-         end
-         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
-         subplot(4,2,[6 8]);
-         h2=lambda{i}.plot([],{{' ''k'', ''LineWidth'' ,.5'}});
-         legend off; hold all; % Plot the CIF
-
-
-
-    end
-    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,...
-        'FontName','Arial');
-    hx=xlabel('time [s]','Interpreter','none');
-    hy=ylabel('Cell Number','Interpreter','none');
-    set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
-
-%     close all;
-
-
-    
-%% Example 5b - Arm reaching to target Simulation
-% See 
-% L. Srinivasan, U. T. Eden, A. S. Willsky, and E. N. Brown, 
-% "A state-space analysis for reconstruction of goal-directed movements 
-% using neural signals.," Neural computation, vol. 18, no. 10, pp. 2465?2494, Oct. 2006.
-
-    close all;
-    clear all;
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\private\evalmxdom.m' could not be
-cleared because it contains MATLAB code that is currently executing. 
-Warning: The file
-'C:\Users\Developer\Dropbox\GitHub\nSTAT\helpfiles\nSTATPaperExamples.m' could
-not be cleared because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\mdbpublish.m' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\publish.p' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\private\evalmxdom.m' could not be
-cleared because it contains MATLAB code that is currently executing. 
-Warning: The file
-'C:\Users\Developer\Dropbox\GitHub\nSTAT\helpfiles\nSTATPaperExamples.m' could
-not be cleared because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\mdbpublish.m' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\publish.p' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\private\evalmxdom.m' could not be
-cleared because it contains MATLAB code that is currently executing. 
-Warning: The file
-'C:\Users\Developer\Dropbox\GitHub\nSTAT\helpfiles\nSTATPaperExamples.m' could
-not be cleared because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\mdbpublish.m' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\publish.p' could not be cleared
-because it contains MATLAB code that is currently executing. 
-    %Process noise covariance only drives the movement velocity
-    q=1e-4;
-    Q=diag([1e-12 1e-12 q q]); 
-
-    delta = .001;        % Time increment
-    r=1e-6;   % in meters^2 
-    p=1e-6;    % in meters^2/s^2
-    PiT=diag([r r p p]); % Uncertainty in the target state
-    Pi0=PiT;
-    T=2;                 % Reach Duration
-
-    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
-       0 1 0     delta;
-       0 0 1     0    ;
-       0 0 0     1    ];
-
-    x=zeros(4,length(time));
-
-
-% Simulate a reach trajectory
-% Differs from reference by multiplication by delta instead of division so
-% that the velocity has units of meters per second
-    R=chol(Q);
-    L=chol(PiT);
-    for k=1:length(time)
-        if(k==1)
-            x(:,k)=x0;
-            %x(:,k)=A*x(:,k-1)+R*randn(size(x,1),1); %Random walk model
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-        if(k==1)
-        else
-             x(:,k)=A*x(:,k-1)+...
-                 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
-        end
-
-    end
-    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 The movement path
-    subplot(4,2,[1 3]); 
-    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');
-    hold on; 
-    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 
-
-    subplot(4,2,7);   
-    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'); 
-    xlabel('time [s]');
-    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');
-    %
-
-    gamma=0;
-    windowTimes=[0, 0.001];
-
-
-% 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;
-    numCells = 20; 
-    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
-    fitType='binomial';
-    clear nst;
-    for i=1:numCells
-         tempData  = exp(dataMat*coeffs(i,:)');
-
-         if(strcmp(fitType,'poisson'))
-         else
-            lambdaData = tempData./(1+tempData); % Conditional Intensity Function for ith cell
-         end
-         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
-         subplot(4,2,[6 8]);
-         h2=lambda{i}.plot([],{{' ''k'', ''LineWidth'' ,.5'}}); 
-         legend off; hold all; % Plot the CIF
-         
-         
-         
-    end
-         tempData  = exp(dataMat*coeffs(i,:)');
-
-         if(strcmp(fitType,'poisson'))
-         else
-            lambdaData = tempData./(1+tempData); % Conditional Intensity Function for ith cell
-         end
-         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
-         subplot(4,2,[6 8]);
-         h2=lambda{i}.plot([],{{' ''k'', ''LineWidth'' ,.5'}}); 
-         legend off; hold all; % Plot the CIF
-         
-         
-         
-    end
-         tempData  = exp(dataMat*coeffs(i,:)');
-
-         if(strcmp(fitType,'poisson'))
-         else
-            lambdaData = tempData./(1+tempData); % Conditional Intensity Function for ith cell
-         end
-         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
-         subplot(4,2,[6 8]);
-         h2=lambda{i}.plot([],{{' ''k'', ''LineWidth'' ,.5'}}); 
-         legend off; hold all; % Plot the CIF
-         
-         
-         
-    end
-         tempData  = exp(dataMat*coeffs(i,:)');
-
-         if(strcmp(fitType,'poisson'))
-         else
-            lambdaData = tempData./(1+tempData); % Conditional Intensity Function for ith cell
-         end
-         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
-         subplot(4,2,[6 8]);
-         h2=lambda{i}.plot([],{{' ''k'', ''LineWidth'' ,.5'}}); 
-         legend off; hold all; % Plot the CIF
-         
-         
-         
-    end
-         tempData  = exp(dataMat*coeffs(i,:)');
-
-         if(strcmp(fitType,'poisson'))
-         else
-            lambdaData = tempData./(1+tempData); % Conditional Intensity Function for ith cell
-         end
-         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
-         subplot(4,2,[6 8]);
-         h2=lambda{i}.plot([],{{' ''k'', ''LineWidth'' ,.5'}}); 
-         legend off; hold all; % Plot the CIF
-         
-         
-         
-    end
-         tempData  = exp(dataMat*coeffs(i,:)');
-
-         if(strcmp(fitType,'poisson'))
-         else
-            lambdaData = tempData./(1+tempData); % Conditional Intensity Function for ith cell
-         end
-         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
-         subplot(4,2,[6 8]);
-         h2=lambda{i}.plot([],{{' ''k'', ''LineWidth'' ,.5'}}); 
-         legend off; hold all; % Plot the CIF
-         
-         
-         
-    end
-         tempData  = exp(dataMat*coeffs(i,:)');
-
-         if(strcmp(fitType,'poisson'))
-         else
-            lambdaData = tempData./(1+tempData); % Conditional Intensity Function for ith cell
-         end
-         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
-         subplot(4,2,[6 8]);
-         h2=lambda{i}.plot([],{{' ''k'', ''LineWidth'' ,.5'}}); 
-         legend off; hold all; % Plot the CIF
-         
-         
-         
-    end
-         tempData  = exp(dataMat*coeffs(i,:)');
-
-         if(strcmp(fitType,'poisson'))
-         else
-            lambdaData = tempData./(1+tempData); % Conditional Intensity Function for ith cell
-         end
-         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
-         subplot(4,2,[6 8]);
-         h2=lambda{i}.plot([],{{' ''k'', ''LineWidth'' ,.5'}}); 
-         legend off; hold all; % Plot the CIF
-         
-         
-         
-    end
-         tempData  = exp(dataMat*coeffs(i,:)');
-
-         if(strcmp(fitType,'poisson'))
-         else
-            lambdaData = tempData./(1+tempData); % Conditional Intensity Function for ith cell
-         end
-         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
-         subplot(4,2,[6 8]);
-         h2=lambda{i}.plot([],{{' ''k'', ''LineWidth'' ,.5'}}); 
-         legend off; hold all; % Plot the CIF
-         
-         
-         
-    end
-         tempData  = exp(dataMat*coeffs(i,:)');
-
-         if(strcmp(fitType,'poisson'))
-         else
-            lambdaData = tempData./(1+tempData); % Conditional Intensity Function for ith cell
-         end
-         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
-         subplot(4,2,[6 8]);
-         h2=lambda{i}.plot([],{{' ''k'', ''LineWidth'' ,.5'}}); 
-         legend off; hold all; % Plot the CIF
-         
-         
-         
-    end
-         tempData  = exp(dataMat*coeffs(i,:)');
-
-         if(strcmp(fitType,'poisson'))
-         else
-            lambdaData = tempData./(1+tempData); % Conditional Intensity Function for ith cell
-         end
-         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
-         subplot(4,2,[6 8]);
-         h2=lambda{i}.plot([],{{' ''k'', ''LineWidth'' ,.5'}}); 
-         legend off; hold all; % Plot the CIF
-         
-         
-         
-    end
-         tempData  = exp(dataMat*coeffs(i,:)');
-
-         if(strcmp(fitType,'poisson'))
-         else
-            lambdaData = tempData./(1+tempData); % Conditional Intensity Function for ith cell
-         end
-         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
-         subplot(4,2,[6 8]);
-         h2=lambda{i}.plot([],{{' ''k'', ''LineWidth'' ,.5'}}); 
-         legend off; hold all; % Plot the CIF
-         
-         
-         
-    end
-         tempData  = exp(dataMat*coeffs(i,:)');
-
-         if(strcmp(fitType,'poisson'))
-         else
-            lambdaData = tempData./(1+tempData); % Conditional Intensity Function for ith cell
-         end
-         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
-         subplot(4,2,[6 8]);
-         h2=lambda{i}.plot([],{{' ''k'', ''LineWidth'' ,.5'}}); 
-         legend off; hold all; % Plot the CIF
-         
-         
-         
-    end
-         tempData  = exp(dataMat*coeffs(i,:)');
-
-         if(strcmp(fitType,'poisson'))
-         else
-            lambdaData = tempData./(1+tempData); % Conditional Intensity Function for ith cell
-         end
-         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
-         subplot(4,2,[6 8]);
-         h2=lambda{i}.plot([],{{' ''k'', ''LineWidth'' ,.5'}}); 
-         legend off; hold all; % Plot the CIF
-         
-         
-         
-    end
-         tempData  = exp(dataMat*coeffs(i,:)');
-
-         if(strcmp(fitType,'poisson'))
-         else
-            lambdaData = tempData./(1+tempData); % Conditional Intensity Function for ith cell
-         end
-         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
-         subplot(4,2,[6 8]);
-         h2=lambda{i}.plot([],{{' ''k'', ''LineWidth'' ,.5'}}); 
-         legend off; hold all; % Plot the CIF
-         
-         
-         
-    end
-         tempData  = exp(dataMat*coeffs(i,:)');
-
-         if(strcmp(fitType,'poisson'))
-         else
-            lambdaData = tempData./(1+tempData); % Conditional Intensity Function for ith cell
-         end
-         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
-         subplot(4,2,[6 8]);
-         h2=lambda{i}.plot([],{{' ''k'', ''LineWidth'' ,.5'}}); 
-         legend off; hold all; % Plot the CIF
-         
-         
-         
-    end
-         tempData  = exp(dataMat*coeffs(i,:)');
-
-         if(strcmp(fitType,'poisson'))
-         else
-            lambdaData = tempData./(1+tempData); % Conditional Intensity Function for ith cell
-         end
-         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
-         subplot(4,2,[6 8]);
-         h2=lambda{i}.plot([],{{' ''k'', ''LineWidth'' ,.5'}}); 
-         legend off; hold all; % Plot the CIF
-         
-         
-         
-    end
-         tempData  = exp(dataMat*coeffs(i,:)');
-
-         if(strcmp(fitType,'poisson'))
-         else
-            lambdaData = tempData./(1+tempData); % Conditional Intensity Function for ith cell
-         end
-         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
-         subplot(4,2,[6 8]);
-         h2=lambda{i}.plot([],{{' ''k'', ''LineWidth'' ,.5'}}); 
-         legend off; hold all; % Plot the CIF
-         
-         
-         
-    end
-         tempData  = exp(dataMat*coeffs(i,:)');
-
-         if(strcmp(fitType,'poisson'))
-         else
-            lambdaData = tempData./(1+tempData); % Conditional Intensity Function for ith cell
-         end
-         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
-         subplot(4,2,[6 8]);
-         h2=lambda{i}.plot([],{{' ''k'', ''LineWidth'' ,.5'}}); 
-         legend off; hold all; % Plot the CIF
-         
-         
-         
-    end
-         tempData  = exp(dataMat*coeffs(i,:)');
-
-         if(strcmp(fitType,'poisson'))
-         else
-            lambdaData = tempData./(1+tempData); % Conditional Intensity Function for ith cell
-         end
-         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
-         subplot(4,2,[6 8]);
-         h2=lambda{i}.plot([],{{' ''k'', ''LineWidth'' ,.5'}}); 
-         legend off; hold all; % Plot the CIF
-         
-         
-         
-    end
-    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,...
-        'FontName','Arial');
-    hx=xlabel('time [s]','Interpreter','none'); 
-    hy=ylabel('Cell Number','Interpreter','none');
-    set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold');
-
close all;
-numExamples=20;
-scrsz = get(0,'ScreenSize');
-fig1=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 ...
-    scrsz(3)*.6 scrsz(4)*.9]);
-for k=1:numExamples
-     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
-    fitType='binomial';
-    clear nst lambda;
-
-
-    for i=1:numCells
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-            lambdaData = tempData;
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData);
-         end
-         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
-
-    end
-
-    % 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
-                % only one spike per bin
-
-    [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
-    %Filter
-    [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
-    %Filter
-    [x_pf, W_pf, x_uf, W_uf] = ...
-        DecodingAlgorithms.PPDecodeFilterLinear(A, Q, dN,...
-        MuCoeffs,beta,fitType,delta,gamma,windowTimes,x0);
-
-
-    if(k==numExamples)
-        subplot(4,2,1:4);h1=plot(100*x(1,:),100*x(2,:),'k','LineWidth',3);
-        hold on;
-        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');
-    end
-    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');
-
-
-    subplot(4,2,5);
-    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');
-
-    subplot(4,2,6);
-    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)]);
-
-    subplot(4,2,7);
-    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');
-
-    subplot(4,2,8);
-    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');
-
-
-end
-
-%     close all;
-
-%     close all;
-
-    
-%%
-close all;
-numExamples=20;
-scrsz = get(0,'ScreenSize');
-fig1=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 ...
-    scrsz(3)*.6 scrsz(4)*.9]);
-for k=1:numExamples
-     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
-    fitType='binomial';
-    clear nst lambda;
-    
-    
-    for i=1:numCells
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-
-    % 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
-                % only one spike per bin
-
-    [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
-    %Filter
-    [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
-    %Filter
-    [x_pf, W_pf, x_uf, W_uf] = ...
-        DecodingAlgorithms.PPDecodeFilterLinear(A, Q, dN,...
-        MuCoeffs,beta,fitType,delta,gamma,windowTimes,x0);
-
-
-    if(k==numExamples)
-    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');
-
-
-    subplot(4,2,5); 
-    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');
-
-    subplot(4,2,6); 
-    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)]);
-
-    subplot(4,2,7); 
-    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');
-
-    subplot(4,2,8); 
-    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');
-
- 
-end
-     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
-    fitType='binomial';
-    clear nst lambda;
-    
-    
-    for i=1:numCells
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-
-    % 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
-                % only one spike per bin
-
-    [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
-    %Filter
-    [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
-    %Filter
-    [x_pf, W_pf, x_uf, W_uf] = ...
-        DecodingAlgorithms.PPDecodeFilterLinear(A, Q, dN,...
-        MuCoeffs,beta,fitType,delta,gamma,windowTimes,x0);
-
-
-    if(k==numExamples)
-    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');
-
-
-    subplot(4,2,5); 
-    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');
-
-    subplot(4,2,6); 
-    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)]);
-
-    subplot(4,2,7); 
-    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');
-
-    subplot(4,2,8); 
-    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');
-
- 
-end
-     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
-    fitType='binomial';
-    clear nst lambda;
-    
-    
-    for i=1:numCells
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-
-    % 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
-                % only one spike per bin
-
-    [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
-    %Filter
-    [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
-    %Filter
-    [x_pf, W_pf, x_uf, W_uf] = ...
-        DecodingAlgorithms.PPDecodeFilterLinear(A, Q, dN,...
-        MuCoeffs,beta,fitType,delta,gamma,windowTimes,x0);
-
-
-    if(k==numExamples)
-    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');
-
-
-    subplot(4,2,5); 
-    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');
-
-    subplot(4,2,6); 
-    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)]);
-
-    subplot(4,2,7); 
-    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');
-
-    subplot(4,2,8); 
-    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');
-
- 
-end
-     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
-    fitType='binomial';
-    clear nst lambda;
-    
-    
-    for i=1:numCells
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-
-    % 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
-                % only one spike per bin
-
-    [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
-    %Filter
-    [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
-    %Filter
-    [x_pf, W_pf, x_uf, W_uf] = ...
-        DecodingAlgorithms.PPDecodeFilterLinear(A, Q, dN,...
-        MuCoeffs,beta,fitType,delta,gamma,windowTimes,x0);
-
-
-    if(k==numExamples)
-    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');
-
-
-    subplot(4,2,5); 
-    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');
-
-    subplot(4,2,6); 
-    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)]);
-
-    subplot(4,2,7); 
-    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');
-
-    subplot(4,2,8); 
-    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');
-
- 
-end
-     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
-    fitType='binomial';
-    clear nst lambda;
-    
-    
-    for i=1:numCells
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-
-    % 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
-                % only one spike per bin
-
-    [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
-    %Filter
-    [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
-    %Filter
-    [x_pf, W_pf, x_uf, W_uf] = ...
-        DecodingAlgorithms.PPDecodeFilterLinear(A, Q, dN,...
-        MuCoeffs,beta,fitType,delta,gamma,windowTimes,x0);
-
-
-    if(k==numExamples)
-    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');
-
-
-    subplot(4,2,5); 
-    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');
-
-    subplot(4,2,6); 
-    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)]);
-
-    subplot(4,2,7); 
-    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');
-
-    subplot(4,2,8); 
-    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');
-
- 
-end
-     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
-    fitType='binomial';
-    clear nst lambda;
-    
-    
-    for i=1:numCells
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-
-    % 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
-                % only one spike per bin
-
-    [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
-    %Filter
-    [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
-    %Filter
-    [x_pf, W_pf, x_uf, W_uf] = ...
-        DecodingAlgorithms.PPDecodeFilterLinear(A, Q, dN,...
-        MuCoeffs,beta,fitType,delta,gamma,windowTimes,x0);
-
-
-    if(k==numExamples)
-    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');
-
-
-    subplot(4,2,5); 
-    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');
-
-    subplot(4,2,6); 
-    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)]);
-
-    subplot(4,2,7); 
-    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');
-
-    subplot(4,2,8); 
-    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');
-
- 
-end
-     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
-    fitType='binomial';
-    clear nst lambda;
-    
-    
-    for i=1:numCells
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-
-    % 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
-                % only one spike per bin
-
-    [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
-    %Filter
-    [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
-    %Filter
-    [x_pf, W_pf, x_uf, W_uf] = ...
-        DecodingAlgorithms.PPDecodeFilterLinear(A, Q, dN,...
-        MuCoeffs,beta,fitType,delta,gamma,windowTimes,x0);
-
-
-    if(k==numExamples)
-    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');
-
-
-    subplot(4,2,5); 
-    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');
-
-    subplot(4,2,6); 
-    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)]);
-
-    subplot(4,2,7); 
-    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');
-
-    subplot(4,2,8); 
-    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');
-
- 
-end
-     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
-    fitType='binomial';
-    clear nst lambda;
-    
-    
-    for i=1:numCells
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-
-    % 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
-                % only one spike per bin
-
-    [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
-    %Filter
-    [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
-    %Filter
-    [x_pf, W_pf, x_uf, W_uf] = ...
-        DecodingAlgorithms.PPDecodeFilterLinear(A, Q, dN,...
-        MuCoeffs,beta,fitType,delta,gamma,windowTimes,x0);
-
-
-    if(k==numExamples)
-    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');
-
-
-    subplot(4,2,5); 
-    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');
-
-    subplot(4,2,6); 
-    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)]);
-
-    subplot(4,2,7); 
-    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');
-
-    subplot(4,2,8); 
-    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');
-
- 
-end
-     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
-    fitType='binomial';
-    clear nst lambda;
-    
-    
-    for i=1:numCells
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-
-    % 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
-                % only one spike per bin
-
-    [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
-    %Filter
-    [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
-    %Filter
-    [x_pf, W_pf, x_uf, W_uf] = ...
-        DecodingAlgorithms.PPDecodeFilterLinear(A, Q, dN,...
-        MuCoeffs,beta,fitType,delta,gamma,windowTimes,x0);
-
-
-    if(k==numExamples)
-    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');
-
-
-    subplot(4,2,5); 
-    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');
-
-    subplot(4,2,6); 
-    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)]);
-
-    subplot(4,2,7); 
-    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');
-
-    subplot(4,2,8); 
-    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');
-
- 
-end
-     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
-    fitType='binomial';
-    clear nst lambda;
-    
-    
-    for i=1:numCells
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-
-    % 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
-                % only one spike per bin
-
-    [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
-    %Filter
-    [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
-    %Filter
-    [x_pf, W_pf, x_uf, W_uf] = ...
-        DecodingAlgorithms.PPDecodeFilterLinear(A, Q, dN,...
-        MuCoeffs,beta,fitType,delta,gamma,windowTimes,x0);
-
-
-    if(k==numExamples)
-    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');
-
-
-    subplot(4,2,5); 
-    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');
-
-    subplot(4,2,6); 
-    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)]);
-
-    subplot(4,2,7); 
-    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');
-
-    subplot(4,2,8); 
-    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');
-
- 
-end
-     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
-    fitType='binomial';
-    clear nst lambda;
-    
-    
-    for i=1:numCells
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-
-    % 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
-                % only one spike per bin
-
-    [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
-    %Filter
-    [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
-    %Filter
-    [x_pf, W_pf, x_uf, W_uf] = ...
-        DecodingAlgorithms.PPDecodeFilterLinear(A, Q, dN,...
-        MuCoeffs,beta,fitType,delta,gamma,windowTimes,x0);
-
-
-    if(k==numExamples)
-    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');
-
-
-    subplot(4,2,5); 
-    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');
-
-    subplot(4,2,6); 
-    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)]);
-
-    subplot(4,2,7); 
-    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');
-
-    subplot(4,2,8); 
-    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');
-
- 
-end
-     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
-    fitType='binomial';
-    clear nst lambda;
-    
-    
-    for i=1:numCells
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-
-    % 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
-                % only one spike per bin
-
-    [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
-    %Filter
-    [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
-    %Filter
-    [x_pf, W_pf, x_uf, W_uf] = ...
-        DecodingAlgorithms.PPDecodeFilterLinear(A, Q, dN,...
-        MuCoeffs,beta,fitType,delta,gamma,windowTimes,x0);
-
-
-    if(k==numExamples)
-    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');
-
-
-    subplot(4,2,5); 
-    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');
-
-    subplot(4,2,6); 
-    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)]);
-
-    subplot(4,2,7); 
-    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');
-
-    subplot(4,2,8); 
-    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');
-
- 
-end
-     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
-    fitType='binomial';
-    clear nst lambda;
-    
-    
-    for i=1:numCells
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-
-    % 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
-                % only one spike per bin
-
-    [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
-    %Filter
-    [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
-    %Filter
-    [x_pf, W_pf, x_uf, W_uf] = ...
-        DecodingAlgorithms.PPDecodeFilterLinear(A, Q, dN,...
-        MuCoeffs,beta,fitType,delta,gamma,windowTimes,x0);
-
-
-    if(k==numExamples)
-    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');
-
-
-    subplot(4,2,5); 
-    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');
-
-    subplot(4,2,6); 
-    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)]);
-
-    subplot(4,2,7); 
-    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');
-
-    subplot(4,2,8); 
-    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');
-
- 
-end
-     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
-    fitType='binomial';
-    clear nst lambda;
-    
-    
-    for i=1:numCells
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-
-    % 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
-                % only one spike per bin
-
-    [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
-    %Filter
-    [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
-    %Filter
-    [x_pf, W_pf, x_uf, W_uf] = ...
-        DecodingAlgorithms.PPDecodeFilterLinear(A, Q, dN,...
-        MuCoeffs,beta,fitType,delta,gamma,windowTimes,x0);
-
-
-    if(k==numExamples)
-    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');
-
-
-    subplot(4,2,5); 
-    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');
-
-    subplot(4,2,6); 
-    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)]);
-
-    subplot(4,2,7); 
-    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');
-
-    subplot(4,2,8); 
-    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');
-
- 
-end
-     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
-    fitType='binomial';
-    clear nst lambda;
-    
-    
-    for i=1:numCells
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-
-    % 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
-                % only one spike per bin
-
-    [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
-    %Filter
-    [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
-    %Filter
-    [x_pf, W_pf, x_uf, W_uf] = ...
-        DecodingAlgorithms.PPDecodeFilterLinear(A, Q, dN,...
-        MuCoeffs,beta,fitType,delta,gamma,windowTimes,x0);
-
-
-    if(k==numExamples)
-    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');
-
-
-    subplot(4,2,5); 
-    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');
-
-    subplot(4,2,6); 
-    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)]);
-
-    subplot(4,2,7); 
-    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');
-
-    subplot(4,2,8); 
-    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');
-
- 
-end
-     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
-    fitType='binomial';
-    clear nst lambda;
-    
-    
-    for i=1:numCells
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-
-    % 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
-                % only one spike per bin
-
-    [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
-    %Filter
-    [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
-    %Filter
-    [x_pf, W_pf, x_uf, W_uf] = ...
-        DecodingAlgorithms.PPDecodeFilterLinear(A, Q, dN,...
-        MuCoeffs,beta,fitType,delta,gamma,windowTimes,x0);
-
-
-    if(k==numExamples)
-    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');
-
-
-    subplot(4,2,5); 
-    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');
-
-    subplot(4,2,6); 
-    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)]);
-
-    subplot(4,2,7); 
-    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');
-
-    subplot(4,2,8); 
-    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');
-
- 
-end
-     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
-    fitType='binomial';
-    clear nst lambda;
-    
-    
-    for i=1:numCells
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-
-    % 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
-                % only one spike per bin
-
-    [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
-    %Filter
-    [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
-    %Filter
-    [x_pf, W_pf, x_uf, W_uf] = ...
-        DecodingAlgorithms.PPDecodeFilterLinear(A, Q, dN,...
-        MuCoeffs,beta,fitType,delta,gamma,windowTimes,x0);
-
-
-    if(k==numExamples)
-    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');
-
-
-    subplot(4,2,5); 
-    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');
-
-    subplot(4,2,6); 
-    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)]);
-
-    subplot(4,2,7); 
-    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');
-
-    subplot(4,2,8); 
-    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');
-
- 
-end
-     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
-    fitType='binomial';
-    clear nst lambda;
-    
-    
-    for i=1:numCells
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-
-    % 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
-                % only one spike per bin
-
-    [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
-    %Filter
-    [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
-    %Filter
-    [x_pf, W_pf, x_uf, W_uf] = ...
-        DecodingAlgorithms.PPDecodeFilterLinear(A, Q, dN,...
-        MuCoeffs,beta,fitType,delta,gamma,windowTimes,x0);
-
-
-    if(k==numExamples)
-    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');
-
-
-    subplot(4,2,5); 
-    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');
-
-    subplot(4,2,6); 
-    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)]);
-
-    subplot(4,2,7); 
-    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');
-
-    subplot(4,2,8); 
-    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');
-
- 
-end
-     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
-    fitType='binomial';
-    clear nst lambda;
-    
-    
-    for i=1:numCells
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-
-    % 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
-                % only one spike per bin
-
-    [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
-    %Filter
-    [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
-    %Filter
-    [x_pf, W_pf, x_uf, W_uf] = ...
-        DecodingAlgorithms.PPDecodeFilterLinear(A, Q, dN,...
-        MuCoeffs,beta,fitType,delta,gamma,windowTimes,x0);
-
-
-    if(k==numExamples)
-    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');
-
-
-    subplot(4,2,5); 
-    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');
-
-    subplot(4,2,6); 
-    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)]);
-
-    subplot(4,2,7); 
-    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');
-
-    subplot(4,2,8); 
-    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');
-
- 
-end
-     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
-    fitType='binomial';
-    clear nst lambda;
-    
-    
-    for i=1:numCells
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-        tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'poisson'))
-         else
-             % Conditional Intensity Function for ith cell
-            lambdaData = tempData./(1+tempData); 
-         end
-         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
-        
-    end
-
-    % 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
-                % only one spike per bin
-
-    [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
-    %Filter
-    [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
-    %Filter
-    [x_pf, W_pf, x_uf, W_uf] = ...
-        DecodingAlgorithms.PPDecodeFilterLinear(A, Q, dN,...
-        MuCoeffs,beta,fitType,delta,gamma,windowTimes,x0);
-
-
-    if(k==numExamples)
-        subplot(4,2,1:4);h1=plot(100*x(1,:),100*x(2,:),'k','LineWidth',3); 
-        hold on;
-        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');
-    end
-    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');
-
-
-    subplot(4,2,5); 
-    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');
-
-    subplot(4,2,6); 
-    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)]);
-
-    subplot(4,2,7); 
-    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');
-
-    subplot(4,2,8); 
-    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');
-
- 
-end
-

Experiment 6 - Hybrid Point Process Filter Example

NOTE THIS EXAMPLE WAS NOT INCLUDED IN THE FINAL VERSION OF THE PAPER This example is based on an implementation of the Hybrid Point Process filter described in General-purpose filter design for neural prosthetic devices by Srinivasan L, Eden UT, Mitter SK, Brown EN in J Neurophysiol. 2007 Oct, 98(4):2456-75.

Problem Statement

Suppose that a process of interest can be modeled as consisting of several discrete states where the evolution of the system under each state can be modeled as a linear state space model. The observations of both the state and the continuous dynamics are not direct, but rather observed through how the continuous and discrete states affect the firing of a population of neurons. The goal of the hybrid filter is to estimate both the continuous dynamics and the underlying system state from only the neural population firing (point process observations).

To illustrate the use of this filter, we consider a reaching task. We assume two underlying system states s=1="Not Moving"=NM and s=2="Moving"=M. Under the "Not Moving" the position of the arm remain constant, whereas in the "Moving" state, the position and velocities evolved based on the arm acceleration that is modeled as a gaussian white noise process.

Under both the "Moving" and "Not Moving" states, the arm evolution state vector is

$${\bf{x}} = {[x,y,{v_x},{v_y},{a_x},{a_y}]^T}$$

Generated Simulated Arm Reach

clear all;
-close all;
-delta=0.001;
-Tmax=2;
-time=0:delta:Tmax;
-A{2} = [1 0 delta 0     delta^2/2   0;
-        0 1 0     delta 0           delta^2/2;
-        0 0 1     0     delta       0;
-        0 0 0     1     0           delta;
-        0 0 0     0     1           0;
-        0 0 0     0     0           1];
-
-A{1} = [1 0 0 0 0 0;
-        0 1 0 0 0 0;
-        0 0 0 0 0 0;
-        0 0 0 0 0 0;
-        0 0 0 0 0 0;
-        0 0 0 0 0 0];
-A{1} = [1 0;
-        0 1];
-
-Px0{2} =1e-6*eye(6,6);
-Px0{1} =1e-6*eye(2,2);
-
-minCovVal = 1e-12;
-covVal = 1e-3;
-
-
-
-Q{2}=[minCovVal     0   0     0   0       0;
-      0       minCovVal 0     0   0       0;
-      0       0   minCovVal   0   0       0;
-      0       0   0     minCovVal 0       0;
-      0       0   0     0   covVal      0;
-      0       0   0     0   0       covVal];
-
-Q{1}=minCovVal*eye(2,2);
-
-mstate = zeros(1,length(time));
-ind{1}=1:2;
-ind{2}=1:6;
-
-% Acceleration model
-X=zeros(max([size(A{1},1),size(A{2},1)]),length(time));
-p_ij = [.998 .002;
-        .001 .999];
-
-for i = 1:length(time)
-
-    if(i==1)
-        mstate(i) = 1;
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       else
-           if(mstate(i-1)==1)
-               mstate(i) = 2;
-           else
-               mstate(i) = 1;
-           end
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-
-%     close all;
-%% Experiment 6 - Hybrid Point Process Filter Example 
-% NOTE THIS EXAMPLE WAS NOT INCLUDED IN THE FINAL VERSION OF THE PAPER
-% This example is based on an implementation of the Hybrid Point Process
-% filter described in _General-purpose filter design for neural prosthetic 
-% devices_ by Srinivasan L, Eden UT, Mitter SK, Brown EN in J Neurophysiol.
-% 2007 Oct, 98(4):2456-75. 
-%
-
-%% Problem Statement
-% Suppose that a process of interest can be modeled as consisting of
-% several discrete states where the evolution of the system under each
-% state can be modeled as a linear state space model. The observations of
-% both the state and the continuous dynamics are not direct, but rather
-% observed through how the continuous and discrete states affect the firing
-% of a population of neurons. The goal of the hybrid filter is to estimate
-% both the continuous dynamics and the underlying system state from only
-% the neural population firing (point process observations).
-%
-% To illustrate the use of this filter, we consider a reaching task. We
-% assume two underlying system states s=1="Not Moving"=NM and s=2="Moving"=M.
-% Under the "Not Moving" the position of the arm remain constant,
-% whereas in the "Moving" state, the position and velocities evolved based
-% on the arm acceleration that is modeled as a gaussian white noise
-% process.
-%
-% Under both the "Moving" and "Not Moving" states, the arm evolution state
-% vector is 
-%%
-% 
-% $${\bf{x}} = {[x,y,{v_x},{v_y},{a_x},{a_y}]^T}$$
-% 
-
-%% Generated Simulated Arm Reach
-
-clear all;
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\private\evalmxdom.m' could not be
-cleared because it contains MATLAB code that is currently executing. 
-Warning: The file
-'C:\Users\Developer\Dropbox\GitHub\nSTAT\helpfiles\nSTATPaperExamples.m' could
-not be cleared because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\mdbpublish.m' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\publish.p' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\private\evalmxdom.m' could not be
-cleared because it contains MATLAB code that is currently executing. 
-Warning: The file
-'C:\Users\Developer\Dropbox\GitHub\nSTAT\helpfiles\nSTATPaperExamples.m' could
-not be cleared because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\mdbpublish.m' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\publish.p' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\private\evalmxdom.m' could not be
-cleared because it contains MATLAB code that is currently executing. 
-Warning: The file
-'C:\Users\Developer\Dropbox\GitHub\nSTAT\helpfiles\nSTATPaperExamples.m' could
-not be cleared because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\mdbpublish.m' could not be cleared
-because it contains MATLAB code that is currently executing. 
-Warning: The file 'C:\Program
-Files\MATLAB\R2017a\toolbox\matlab\codetools\publish.p' could not be cleared
-because it contains MATLAB code that is currently executing. 
-close all;
-delta=0.001;
-Tmax=2;
-time=0:delta:Tmax;
-A{2} = [1 0 delta 0     delta^2/2   0;
-        0 1 0     delta 0           delta^2/2;
-        0 0 1     0     delta       0;
-        0 0 0     1     0           delta;
-        0 0 0     0     1           0;
-        0 0 0     0     0           1];
-        
-A{1} = [1 0 0 0 0 0;
-        0 1 0 0 0 0;
-        0 0 0 0 0 0;
-        0 0 0 0 0 0;
-        0 0 0 0 0 0;
-        0 0 0 0 0 0];
-A{1} = [1 0;
-        0 1];
-            
-Px0{2} =1e-6*eye(6,6);
-Px0{1} =1e-6*eye(2,2);
-
-minCovVal = 1e-12;
-covVal = 1e-3; 
-
-
-
-Q{2}=[minCovVal     0   0     0   0       0;
-      0       minCovVal 0     0   0       0;
-      0       0   minCovVal   0   0       0;
-      0       0   0     minCovVal 0       0;
-      0       0   0     0   covVal      0;
-      0       0   0     0   0       covVal];
-
-Q{1}=minCovVal*eye(2,2);
-
-mstate = zeros(1,length(time));
-ind{1}=1:2;
-ind{2}=1:6;
-
-% Acceleration model
-X=zeros(max([size(A{1},1),size(A{2},1)]),length(time));
-p_ij = [.998 .002; 
-        .001 .999];
-
-for i = 1:length(time)
-    
-    if(i==1)
-        mstate(i) = 1;
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-       else
-           if(mstate(i-1)==1)
-               mstate(i) = 2;
-           end
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-        X(ind{st},i+1) = A{st}*X(ind{st},i) + R*randn(length(ind{st}),1);
-    end
-
-end
-    
-    if(i==1)
-    else
-       if(rand(1,1)<p_ij(mstate(i-1),mstate(i-1)))
-            mstate(i) = mstate(i-1);
-       end
-    end
-    st = mstate(i);
-    R=chol(Q{st});
-    if(i<length(time))
-
-end
-
%save paperHybridFilterExample time Tmax delta mstate X p_ij ind A Q Px0
-load paperHybridFilterExample;
-Q{1}=minCovVal*eye(2,2);
-numCells=40;
-close all;
-scrsz = get(0,'ScreenSize');
-fig1=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 ...
-    scrsz(3)*.8 scrsz(4)*.9]);
-subplot(4,2,[1 3]);
-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');
-hold on;
-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');
-
-
-
-subplot(4,2,[6 8]);
-plot(time,mstate,'k','Linewidth',2); axis tight; v=axis;
-axis([v(1) v(2) 0 3]);
-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,...
-    'FontName','Arial');
-
-subplot(4,2,5);
-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)]);
-
-
-subplot(4,2,7);
-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) ...
-    0*randn(numCells,2)];
-%Add realization by thinning with history
-dataMat = [ones(size(X,2),1),X(:,1:end)'];
-% Generate M1 cells
-clear lambda tempSpikeColl lambdaCIF n;
-fitType ='binomial';
-% matlabpool open;
- for i=1:numCells
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     else
-        lambdaData = tempData;
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));
- end
- spikeColl = nstColl(n);
- subplot(4,2,[2 4]);
-spikeColl.plot;
-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');
-
-% close all;
-
%%
-%save paperHybridFilterExample time Tmax delta mstate X p_ij ind A Q Px0
-load paperHybridFilterExample;
-Q{1}=minCovVal*eye(2,2);
-numCells=40;
-close all;
-scrsz = get(0,'ScreenSize');
-fig1=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 ...
-    scrsz(3)*.8 scrsz(4)*.9]);
-subplot(4,2,[1 3]);
-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');
-hold on; 
-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');
-
-
-
-subplot(4,2,[6 8]);
-plot(time,mstate,'k','Linewidth',2); axis tight; v=axis; 
-axis([v(1) v(2) 0 3]);
-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,...
-    'FontName','Arial');
-
-subplot(4,2,5);
-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)]);
-
-
-subplot(4,2,7);
-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) ...
-    0*randn(numCells,2)];
-%Add realization by thinning with history
-dataMat = [ones(size(X,2),1),X(:,1:end)'];
-% Generate M1 cells
-clear lambda tempSpikeColl lambdaCIF n;
-fitType ='binomial';
-% matlabpool open;
- for i=1:numCells
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
-     tempData  = exp(dataMat*coeffs(i,:)');
-     if(strcmp(fitType,'binomial'));
-        lambdaData = tempData./(1+tempData);
-     end
-     lambda{i}=Covariate(time,lambdaData./delta, ...
-         '\Lambda(t)','time','s','spikes/sec',...
-         {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-     maxTimeRes = 0.001;
-     tempSpikeColl{i} = CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-     n{i} = tempSpikeColl{i}.getNST(1);
-     n{i}.setName(num2str(i));    
- end
- spikeColl = nstColl(n);
- subplot(4,2,[2 4]);
-spikeColl.plot;
-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');
-

Simulate Neural Firing

We simulate a population of neurons that fire in response to the movement velocity (x and y coorinates)

%Use the data to estimate the process noise for the moving case and
-%non-moving case
-
-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));
-Q{2}(1:4,1:4)=0;
-varNV=diag(var(diff(X(:,nonMovingInd),[],2),[],2));
-Q{1} = varNV(1:2,1:2);
-close all; clear S_est X_est MU_est S_estNT X_estNT MU_estNT;
-numExamples = 20;
-numCells=40;
-scrsz = get(0,'ScreenSize');
-fig1=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 ...
-    scrsz(3)*.9 scrsz(4)*.9]);
-
-for n=1:numExamples
-    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) ...
-        0*randn(numCells,2)];
-
-
-
-    %Add realization by thinning with history
-    dataMat = [ones(size(X,2),1),X(:,1:end)'];
-    % Generate M1 cells
-    clear lambda tempSpikeColl lambdaCIF nst;
-    fitType ='binomial';
-    % matlabpool open;
-     for i=1:numCells
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         else
-            lambdaData = tempData;
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));
-     end
-
-    % 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;
-    x0{1} = X(ind{1},1);
-    yT{1} = X(ind{1},end);
-    Pi0    = Px0;
-    PiT{1} = 1e-9*eye(size(x0{1},1),size(x0{1},1));
-
-    x0{2} = X(ind{2},1);
-    yT{2} = X(ind{2},end);
-    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_estAll(:,:,n) = X_est;
-    X_estNTAll(:,:,n) = X_estNT;
-    S_estAll(n,:)=S_est;
-    S_estNTAll(n,:)=S_estNT;
-    MU_estAll(:,:,n)=MU_est;
-    MU_estNTAll(:,:,n) = MU_estNT;
-
-
-    %State Estimate
-    subplot(4,3,[1 4]);
-    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))
-    subplot(4,3,[7 10]);
-    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]);
-
-    %The movement path
-    subplot(4,3,[2 3 5 6]);
-    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-.');
-
-    %X-Position
-    subplot(4,3,8);
-    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-.');
-
-    %Y-Position
-    subplot(4,3,9);
-    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-.');
-
-    %X-Velocity
-    subplot(4,3,11);
-    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-.');
-
-    subplot(4,3,12);
-    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-.');
-
-
-
-
-end
-
-%
-%     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
-    subplot(4,3,[1 4]);
-    hold all;
-    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',...
-        'Interpreter','none');
-    title('Estimated vs. Actual State','FontWeight','bold','Fontsize',...
-        12,'FontName','Arial');
-
-
-
-
-   % Mean State Movement State Probability
-    subplot(4,3,[7 10]);
-    plot(time, mean(squeeze(MU_estAll(2,:,:)),2),'b','LineWidth',3);
-    hold on;
-    plot(time,mean(squeeze(MU_estNTAll(2,:,:)),2),'g','LineWidth',3);
-    hold on;
-    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,...
-        'FontName','Arial');
-
-    % Mean movement path
-    subplot(4,3,[2 3 5 6]);
-    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');
-
-
-    % Mean X-Positon
-    subplot(4,3,8);
-    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');
-
-    % Mean Y-Position
-    subplot(4,3,9);
-    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)]);
-
-    % Mean X-Velocity
-    subplot(4,3,11);
-    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');
-
-    % Mean Y-Velocity
-    subplot(4,3,12);
-    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');
-
-% close all;
- 
-%% Simulate Neural Firing
-% We simulate a population of neurons that fire in response to the movement
-% velocity (x and y coorinates) 
-
-%Use the data to estimate the process noise for the moving case and
-%non-moving case
-
-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));
-Q{2}(1:4,1:4)=0;
-varNV=diag(var(diff(X(:,nonMovingInd),[],2),[],2));
-Q{1} = varNV(1:2,1:2);
-close all; clear S_est X_est MU_est S_estNT X_estNT MU_estNT;
-numExamples = 20;
-numCells=40;
-scrsz = get(0,'ScreenSize');
-fig1=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 ...
-    scrsz(3)*.9 scrsz(4)*.9]);
-
-for n=1:numExamples
-    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) ...
-        0*randn(numCells,2)];
-
-
-
-    %Add realization by thinning with history
-    dataMat = [ones(size(X,2),1),X(:,1:end)'];
-    % Generate M1 cells
-    clear lambda tempSpikeColl lambdaCIF nst;
-    fitType ='binomial';
-    % matlabpool open;
-     for i=1:numCells
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-
-    % 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;
-    x0{1} = X(ind{1},1);
-    yT{1} = X(ind{1},end);
-    Pi0    = Px0;
-    PiT{1} = 1e-9*eye(size(x0{1},1),size(x0{1},1));
-
-    x0{2} = X(ind{2},1);
-    yT{2} = X(ind{2},end);
-    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_estAll(:,:,n) = X_est;
-    X_estNTAll(:,:,n) = X_estNT;
-    S_estAll(n,:)=S_est;
-    S_estNTAll(n,:)=S_estNT;
-    MU_estAll(:,:,n)=MU_est;
-    MU_estNTAll(:,:,n) = MU_estNT;
-    
-
-    %State Estimate
-    subplot(4,3,[1 4]);
-    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))
-    subplot(4,3,[7 10]);
-    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]);
-
-    %The movement path
-    subplot(4,3,[2 3 5 6]);
-    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-.'); 
-    
-    %X-Position
-    subplot(4,3,8); 
-    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-.'); 
-
-    %Y-Position
-    subplot(4,3,9); 
-    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-.'); 
-
-    %X-Velocity
-    subplot(4,3,11); 
-    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-.');
-
-    subplot(4,3,12); 
-    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-.');
-
-    
-    
-
-end
-    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) ...
-        0*randn(numCells,2)];
-
-
-
-    %Add realization by thinning with history
-    dataMat = [ones(size(X,2),1),X(:,1:end)'];
-    % Generate M1 cells
-    clear lambda tempSpikeColl lambdaCIF nst;
-    fitType ='binomial';
-    % matlabpool open;
-     for i=1:numCells
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-
-    % 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;
-    x0{1} = X(ind{1},1);
-    yT{1} = X(ind{1},end);
-    Pi0    = Px0;
-    PiT{1} = 1e-9*eye(size(x0{1},1),size(x0{1},1));
-
-    x0{2} = X(ind{2},1);
-    yT{2} = X(ind{2},end);
-    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_estAll(:,:,n) = X_est;
-    X_estNTAll(:,:,n) = X_estNT;
-    S_estAll(n,:)=S_est;
-    S_estNTAll(n,:)=S_estNT;
-    MU_estAll(:,:,n)=MU_est;
-    MU_estNTAll(:,:,n) = MU_estNT;
-    
-
-    %State Estimate
-    subplot(4,3,[1 4]);
-    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))
-    subplot(4,3,[7 10]);
-    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]);
-
-    %The movement path
-    subplot(4,3,[2 3 5 6]);
-    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-.'); 
-    
-    %X-Position
-    subplot(4,3,8); 
-    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-.'); 
-
-    %Y-Position
-    subplot(4,3,9); 
-    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-.'); 
-
-    %X-Velocity
-    subplot(4,3,11); 
-    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-.');
-
-    subplot(4,3,12); 
-    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-.');
-
-    
-    
-
-end
-    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) ...
-        0*randn(numCells,2)];
-
-
-
-    %Add realization by thinning with history
-    dataMat = [ones(size(X,2),1),X(:,1:end)'];
-    % Generate M1 cells
-    clear lambda tempSpikeColl lambdaCIF nst;
-    fitType ='binomial';
-    % matlabpool open;
-     for i=1:numCells
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-
-    % 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;
-    x0{1} = X(ind{1},1);
-    yT{1} = X(ind{1},end);
-    Pi0    = Px0;
-    PiT{1} = 1e-9*eye(size(x0{1},1),size(x0{1},1));
-
-    x0{2} = X(ind{2},1);
-    yT{2} = X(ind{2},end);
-    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_estAll(:,:,n) = X_est;
-    X_estNTAll(:,:,n) = X_estNT;
-    S_estAll(n,:)=S_est;
-    S_estNTAll(n,:)=S_estNT;
-    MU_estAll(:,:,n)=MU_est;
-    MU_estNTAll(:,:,n) = MU_estNT;
-    
-
-    %State Estimate
-    subplot(4,3,[1 4]);
-    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))
-    subplot(4,3,[7 10]);
-    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]);
-
-    %The movement path
-    subplot(4,3,[2 3 5 6]);
-    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-.'); 
-    
-    %X-Position
-    subplot(4,3,8); 
-    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-.'); 
-
-    %Y-Position
-    subplot(4,3,9); 
-    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-.'); 
-
-    %X-Velocity
-    subplot(4,3,11); 
-    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-.');
-
-    subplot(4,3,12); 
-    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-.');
-
-    
-    
-
-end
-    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) ...
-        0*randn(numCells,2)];
-
-
-
-    %Add realization by thinning with history
-    dataMat = [ones(size(X,2),1),X(:,1:end)'];
-    % Generate M1 cells
-    clear lambda tempSpikeColl lambdaCIF nst;
-    fitType ='binomial';
-    % matlabpool open;
-     for i=1:numCells
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-
-    % 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;
-    x0{1} = X(ind{1},1);
-    yT{1} = X(ind{1},end);
-    Pi0    = Px0;
-    PiT{1} = 1e-9*eye(size(x0{1},1),size(x0{1},1));
-
-    x0{2} = X(ind{2},1);
-    yT{2} = X(ind{2},end);
-    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_estAll(:,:,n) = X_est;
-    X_estNTAll(:,:,n) = X_estNT;
-    S_estAll(n,:)=S_est;
-    S_estNTAll(n,:)=S_estNT;
-    MU_estAll(:,:,n)=MU_est;
-    MU_estNTAll(:,:,n) = MU_estNT;
-    
-
-    %State Estimate
-    subplot(4,3,[1 4]);
-    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))
-    subplot(4,3,[7 10]);
-    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]);
-
-    %The movement path
-    subplot(4,3,[2 3 5 6]);
-    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-.'); 
-    
-    %X-Position
-    subplot(4,3,8); 
-    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-.'); 
-
-    %Y-Position
-    subplot(4,3,9); 
-    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-.'); 
-
-    %X-Velocity
-    subplot(4,3,11); 
-    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-.');
-
-    subplot(4,3,12); 
-    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-.');
-
-    
-    
-
-end
-    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) ...
-        0*randn(numCells,2)];
-
-
-
-    %Add realization by thinning with history
-    dataMat = [ones(size(X,2),1),X(:,1:end)'];
-    % Generate M1 cells
-    clear lambda tempSpikeColl lambdaCIF nst;
-    fitType ='binomial';
-    % matlabpool open;
-     for i=1:numCells
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-
-    % 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;
-    x0{1} = X(ind{1},1);
-    yT{1} = X(ind{1},end);
-    Pi0    = Px0;
-    PiT{1} = 1e-9*eye(size(x0{1},1),size(x0{1},1));
-
-    x0{2} = X(ind{2},1);
-    yT{2} = X(ind{2},end);
-    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_estAll(:,:,n) = X_est;
-    X_estNTAll(:,:,n) = X_estNT;
-    S_estAll(n,:)=S_est;
-    S_estNTAll(n,:)=S_estNT;
-    MU_estAll(:,:,n)=MU_est;
-    MU_estNTAll(:,:,n) = MU_estNT;
-    
-
-    %State Estimate
-    subplot(4,3,[1 4]);
-    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))
-    subplot(4,3,[7 10]);
-    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]);
-
-    %The movement path
-    subplot(4,3,[2 3 5 6]);
-    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-.'); 
-    
-    %X-Position
-    subplot(4,3,8); 
-    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-.'); 
-
-    %Y-Position
-    subplot(4,3,9); 
-    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-.'); 
-
-    %X-Velocity
-    subplot(4,3,11); 
-    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-.');
-
-    subplot(4,3,12); 
-    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-.');
-
-    
-    
-
-end
-    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) ...
-        0*randn(numCells,2)];
-
-
-
-    %Add realization by thinning with history
-    dataMat = [ones(size(X,2),1),X(:,1:end)'];
-    % Generate M1 cells
-    clear lambda tempSpikeColl lambdaCIF nst;
-    fitType ='binomial';
-    % matlabpool open;
-     for i=1:numCells
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-
-    % 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;
-    x0{1} = X(ind{1},1);
-    yT{1} = X(ind{1},end);
-    Pi0    = Px0;
-    PiT{1} = 1e-9*eye(size(x0{1},1),size(x0{1},1));
-
-    x0{2} = X(ind{2},1);
-    yT{2} = X(ind{2},end);
-    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_estAll(:,:,n) = X_est;
-    X_estNTAll(:,:,n) = X_estNT;
-    S_estAll(n,:)=S_est;
-    S_estNTAll(n,:)=S_estNT;
-    MU_estAll(:,:,n)=MU_est;
-    MU_estNTAll(:,:,n) = MU_estNT;
-    
-
-    %State Estimate
-    subplot(4,3,[1 4]);
-    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))
-    subplot(4,3,[7 10]);
-    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]);
-
-    %The movement path
-    subplot(4,3,[2 3 5 6]);
-    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-.'); 
-    
-    %X-Position
-    subplot(4,3,8); 
-    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-.'); 
-
-    %Y-Position
-    subplot(4,3,9); 
-    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-.'); 
-
-    %X-Velocity
-    subplot(4,3,11); 
-    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-.');
-
-    subplot(4,3,12); 
-    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-.');
-
-    
-    
-
-end
-    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) ...
-        0*randn(numCells,2)];
-
-
-
-    %Add realization by thinning with history
-    dataMat = [ones(size(X,2),1),X(:,1:end)'];
-    % Generate M1 cells
-    clear lambda tempSpikeColl lambdaCIF nst;
-    fitType ='binomial';
-    % matlabpool open;
-     for i=1:numCells
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-
-    % 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;
-    x0{1} = X(ind{1},1);
-    yT{1} = X(ind{1},end);
-    Pi0    = Px0;
-    PiT{1} = 1e-9*eye(size(x0{1},1),size(x0{1},1));
-
-    x0{2} = X(ind{2},1);
-    yT{2} = X(ind{2},end);
-    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_estAll(:,:,n) = X_est;
-    X_estNTAll(:,:,n) = X_estNT;
-    S_estAll(n,:)=S_est;
-    S_estNTAll(n,:)=S_estNT;
-    MU_estAll(:,:,n)=MU_est;
-    MU_estNTAll(:,:,n) = MU_estNT;
-    
-
-    %State Estimate
-    subplot(4,3,[1 4]);
-    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))
-    subplot(4,3,[7 10]);
-    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]);
-
-    %The movement path
-    subplot(4,3,[2 3 5 6]);
-    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-.'); 
-    
-    %X-Position
-    subplot(4,3,8); 
-    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-.'); 
-
-    %Y-Position
-    subplot(4,3,9); 
-    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-.'); 
-
-    %X-Velocity
-    subplot(4,3,11); 
-    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-.');
-
-    subplot(4,3,12); 
-    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-.');
-
-    
-    
-
-end
-    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) ...
-        0*randn(numCells,2)];
-
-
-
-    %Add realization by thinning with history
-    dataMat = [ones(size(X,2),1),X(:,1:end)'];
-    % Generate M1 cells
-    clear lambda tempSpikeColl lambdaCIF nst;
-    fitType ='binomial';
-    % matlabpool open;
-     for i=1:numCells
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-
-    % 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;
-    x0{1} = X(ind{1},1);
-    yT{1} = X(ind{1},end);
-    Pi0    = Px0;
-    PiT{1} = 1e-9*eye(size(x0{1},1),size(x0{1},1));
-
-    x0{2} = X(ind{2},1);
-    yT{2} = X(ind{2},end);
-    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_estAll(:,:,n) = X_est;
-    X_estNTAll(:,:,n) = X_estNT;
-    S_estAll(n,:)=S_est;
-    S_estNTAll(n,:)=S_estNT;
-    MU_estAll(:,:,n)=MU_est;
-    MU_estNTAll(:,:,n) = MU_estNT;
-    
-
-    %State Estimate
-    subplot(4,3,[1 4]);
-    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))
-    subplot(4,3,[7 10]);
-    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]);
-
-    %The movement path
-    subplot(4,3,[2 3 5 6]);
-    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-.'); 
-    
-    %X-Position
-    subplot(4,3,8); 
-    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-.'); 
-
-    %Y-Position
-    subplot(4,3,9); 
-    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-.'); 
-
-    %X-Velocity
-    subplot(4,3,11); 
-    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-.');
-
-    subplot(4,3,12); 
-    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-.');
-
-    
-    
-
-end
-    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) ...
-        0*randn(numCells,2)];
-
-
-
-    %Add realization by thinning with history
-    dataMat = [ones(size(X,2),1),X(:,1:end)'];
-    % Generate M1 cells
-    clear lambda tempSpikeColl lambdaCIF nst;
-    fitType ='binomial';
-    % matlabpool open;
-     for i=1:numCells
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-
-    % 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;
-    x0{1} = X(ind{1},1);
-    yT{1} = X(ind{1},end);
-    Pi0    = Px0;
-    PiT{1} = 1e-9*eye(size(x0{1},1),size(x0{1},1));
-
-    x0{2} = X(ind{2},1);
-    yT{2} = X(ind{2},end);
-    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_estAll(:,:,n) = X_est;
-    X_estNTAll(:,:,n) = X_estNT;
-    S_estAll(n,:)=S_est;
-    S_estNTAll(n,:)=S_estNT;
-    MU_estAll(:,:,n)=MU_est;
-    MU_estNTAll(:,:,n) = MU_estNT;
-    
-
-    %State Estimate
-    subplot(4,3,[1 4]);
-    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))
-    subplot(4,3,[7 10]);
-    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]);
-
-    %The movement path
-    subplot(4,3,[2 3 5 6]);
-    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-.'); 
-    
-    %X-Position
-    subplot(4,3,8); 
-    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-.'); 
-
-    %Y-Position
-    subplot(4,3,9); 
-    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-.'); 
-
-    %X-Velocity
-    subplot(4,3,11); 
-    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-.');
-
-    subplot(4,3,12); 
-    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-.');
-
-    
-    
-
-end
-    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) ...
-        0*randn(numCells,2)];
-
-
-
-    %Add realization by thinning with history
-    dataMat = [ones(size(X,2),1),X(:,1:end)'];
-    % Generate M1 cells
-    clear lambda tempSpikeColl lambdaCIF nst;
-    fitType ='binomial';
-    % matlabpool open;
-     for i=1:numCells
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-
-    % 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;
-    x0{1} = X(ind{1},1);
-    yT{1} = X(ind{1},end);
-    Pi0    = Px0;
-    PiT{1} = 1e-9*eye(size(x0{1},1),size(x0{1},1));
-
-    x0{2} = X(ind{2},1);
-    yT{2} = X(ind{2},end);
-    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_estAll(:,:,n) = X_est;
-    X_estNTAll(:,:,n) = X_estNT;
-    S_estAll(n,:)=S_est;
-    S_estNTAll(n,:)=S_estNT;
-    MU_estAll(:,:,n)=MU_est;
-    MU_estNTAll(:,:,n) = MU_estNT;
-    
-
-    %State Estimate
-    subplot(4,3,[1 4]);
-    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))
-    subplot(4,3,[7 10]);
-    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]);
-
-    %The movement path
-    subplot(4,3,[2 3 5 6]);
-    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-.'); 
-    
-    %X-Position
-    subplot(4,3,8); 
-    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-.'); 
-
-    %Y-Position
-    subplot(4,3,9); 
-    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-.'); 
-
-    %X-Velocity
-    subplot(4,3,11); 
-    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-.');
-
-    subplot(4,3,12); 
-    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-.');
-
-    
-    
-
-end
-    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) ...
-        0*randn(numCells,2)];
-
-
-
-    %Add realization by thinning with history
-    dataMat = [ones(size(X,2),1),X(:,1:end)'];
-    % Generate M1 cells
-    clear lambda tempSpikeColl lambdaCIF nst;
-    fitType ='binomial';
-    % matlabpool open;
-     for i=1:numCells
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-
-    % 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;
-    x0{1} = X(ind{1},1);
-    yT{1} = X(ind{1},end);
-    Pi0    = Px0;
-    PiT{1} = 1e-9*eye(size(x0{1},1),size(x0{1},1));
-
-    x0{2} = X(ind{2},1);
-    yT{2} = X(ind{2},end);
-    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_estAll(:,:,n) = X_est;
-    X_estNTAll(:,:,n) = X_estNT;
-    S_estAll(n,:)=S_est;
-    S_estNTAll(n,:)=S_estNT;
-    MU_estAll(:,:,n)=MU_est;
-    MU_estNTAll(:,:,n) = MU_estNT;
-    
-
-    %State Estimate
-    subplot(4,3,[1 4]);
-    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))
-    subplot(4,3,[7 10]);
-    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]);
-
-    %The movement path
-    subplot(4,3,[2 3 5 6]);
-    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-.'); 
-    
-    %X-Position
-    subplot(4,3,8); 
-    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-.'); 
-
-    %Y-Position
-    subplot(4,3,9); 
-    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-.'); 
-
-    %X-Velocity
-    subplot(4,3,11); 
-    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-.');
-
-    subplot(4,3,12); 
-    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-.');
-
-    
-    
-
-end
-    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) ...
-        0*randn(numCells,2)];
-
-
-
-    %Add realization by thinning with history
-    dataMat = [ones(size(X,2),1),X(:,1:end)'];
-    % Generate M1 cells
-    clear lambda tempSpikeColl lambdaCIF nst;
-    fitType ='binomial';
-    % matlabpool open;
-     for i=1:numCells
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-
-    % 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;
-    x0{1} = X(ind{1},1);
-    yT{1} = X(ind{1},end);
-    Pi0    = Px0;
-    PiT{1} = 1e-9*eye(size(x0{1},1),size(x0{1},1));
-
-    x0{2} = X(ind{2},1);
-    yT{2} = X(ind{2},end);
-    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_estAll(:,:,n) = X_est;
-    X_estNTAll(:,:,n) = X_estNT;
-    S_estAll(n,:)=S_est;
-    S_estNTAll(n,:)=S_estNT;
-    MU_estAll(:,:,n)=MU_est;
-    MU_estNTAll(:,:,n) = MU_estNT;
-    
-
-    %State Estimate
-    subplot(4,3,[1 4]);
-    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))
-    subplot(4,3,[7 10]);
-    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]);
-
-    %The movement path
-    subplot(4,3,[2 3 5 6]);
-    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-.'); 
-    
-    %X-Position
-    subplot(4,3,8); 
-    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-.'); 
-
-    %Y-Position
-    subplot(4,3,9); 
-    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-.'); 
-
-    %X-Velocity
-    subplot(4,3,11); 
-    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-.');
-
-    subplot(4,3,12); 
-    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-.');
-
-    
-    
-
-end
-    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) ...
-        0*randn(numCells,2)];
-
-
-
-    %Add realization by thinning with history
-    dataMat = [ones(size(X,2),1),X(:,1:end)'];
-    % Generate M1 cells
-    clear lambda tempSpikeColl lambdaCIF nst;
-    fitType ='binomial';
-    % matlabpool open;
-     for i=1:numCells
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-
-    % 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;
-    x0{1} = X(ind{1},1);
-    yT{1} = X(ind{1},end);
-    Pi0    = Px0;
-    PiT{1} = 1e-9*eye(size(x0{1},1),size(x0{1},1));
-
-    x0{2} = X(ind{2},1);
-    yT{2} = X(ind{2},end);
-    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_estAll(:,:,n) = X_est;
-    X_estNTAll(:,:,n) = X_estNT;
-    S_estAll(n,:)=S_est;
-    S_estNTAll(n,:)=S_estNT;
-    MU_estAll(:,:,n)=MU_est;
-    MU_estNTAll(:,:,n) = MU_estNT;
-    
-
-    %State Estimate
-    subplot(4,3,[1 4]);
-    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))
-    subplot(4,3,[7 10]);
-    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]);
-
-    %The movement path
-    subplot(4,3,[2 3 5 6]);
-    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-.'); 
-    
-    %X-Position
-    subplot(4,3,8); 
-    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-.'); 
-
-    %Y-Position
-    subplot(4,3,9); 
-    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-.'); 
-
-    %X-Velocity
-    subplot(4,3,11); 
-    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-.');
-
-    subplot(4,3,12); 
-    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-.');
-
-    
-    
-
-end
-    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) ...
-        0*randn(numCells,2)];
-
-
-
-    %Add realization by thinning with history
-    dataMat = [ones(size(X,2),1),X(:,1:end)'];
-    % Generate M1 cells
-    clear lambda tempSpikeColl lambdaCIF nst;
-    fitType ='binomial';
-    % matlabpool open;
-     for i=1:numCells
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-
-    % 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;
-    x0{1} = X(ind{1},1);
-    yT{1} = X(ind{1},end);
-    Pi0    = Px0;
-    PiT{1} = 1e-9*eye(size(x0{1},1),size(x0{1},1));
-
-    x0{2} = X(ind{2},1);
-    yT{2} = X(ind{2},end);
-    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_estAll(:,:,n) = X_est;
-    X_estNTAll(:,:,n) = X_estNT;
-    S_estAll(n,:)=S_est;
-    S_estNTAll(n,:)=S_estNT;
-    MU_estAll(:,:,n)=MU_est;
-    MU_estNTAll(:,:,n) = MU_estNT;
-    
-
-    %State Estimate
-    subplot(4,3,[1 4]);
-    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))
-    subplot(4,3,[7 10]);
-    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]);
-
-    %The movement path
-    subplot(4,3,[2 3 5 6]);
-    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-.'); 
-    
-    %X-Position
-    subplot(4,3,8); 
-    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-.'); 
-
-    %Y-Position
-    subplot(4,3,9); 
-    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-.'); 
-
-    %X-Velocity
-    subplot(4,3,11); 
-    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-.');
-
-    subplot(4,3,12); 
-    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-.');
-
-    
-    
-
-end
-    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) ...
-        0*randn(numCells,2)];
-
-
-
-    %Add realization by thinning with history
-    dataMat = [ones(size(X,2),1),X(:,1:end)'];
-    % Generate M1 cells
-    clear lambda tempSpikeColl lambdaCIF nst;
-    fitType ='binomial';
-    % matlabpool open;
-     for i=1:numCells
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-
-    % 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;
-    x0{1} = X(ind{1},1);
-    yT{1} = X(ind{1},end);
-    Pi0    = Px0;
-    PiT{1} = 1e-9*eye(size(x0{1},1),size(x0{1},1));
-
-    x0{2} = X(ind{2},1);
-    yT{2} = X(ind{2},end);
-    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_estAll(:,:,n) = X_est;
-    X_estNTAll(:,:,n) = X_estNT;
-    S_estAll(n,:)=S_est;
-    S_estNTAll(n,:)=S_estNT;
-    MU_estAll(:,:,n)=MU_est;
-    MU_estNTAll(:,:,n) = MU_estNT;
-    
-
-    %State Estimate
-    subplot(4,3,[1 4]);
-    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))
-    subplot(4,3,[7 10]);
-    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]);
-
-    %The movement path
-    subplot(4,3,[2 3 5 6]);
-    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-.'); 
-    
-    %X-Position
-    subplot(4,3,8); 
-    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-.'); 
-
-    %Y-Position
-    subplot(4,3,9); 
-    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-.'); 
-
-    %X-Velocity
-    subplot(4,3,11); 
-    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-.');
-
-    subplot(4,3,12); 
-    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-.');
-
-    
-    
-
-end
-    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) ...
-        0*randn(numCells,2)];
-
-
-
-    %Add realization by thinning with history
-    dataMat = [ones(size(X,2),1),X(:,1:end)'];
-    % Generate M1 cells
-    clear lambda tempSpikeColl lambdaCIF nst;
-    fitType ='binomial';
-    % matlabpool open;
-     for i=1:numCells
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-
-    % 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;
-    x0{1} = X(ind{1},1);
-    yT{1} = X(ind{1},end);
-    Pi0    = Px0;
-    PiT{1} = 1e-9*eye(size(x0{1},1),size(x0{1},1));
-
-    x0{2} = X(ind{2},1);
-    yT{2} = X(ind{2},end);
-    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_estAll(:,:,n) = X_est;
-    X_estNTAll(:,:,n) = X_estNT;
-    S_estAll(n,:)=S_est;
-    S_estNTAll(n,:)=S_estNT;
-    MU_estAll(:,:,n)=MU_est;
-    MU_estNTAll(:,:,n) = MU_estNT;
-    
-
-    %State Estimate
-    subplot(4,3,[1 4]);
-    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))
-    subplot(4,3,[7 10]);
-    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]);
-
-    %The movement path
-    subplot(4,3,[2 3 5 6]);
-    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-.'); 
-    
-    %X-Position
-    subplot(4,3,8); 
-    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-.'); 
-
-    %Y-Position
-    subplot(4,3,9); 
-    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-.'); 
-
-    %X-Velocity
-    subplot(4,3,11); 
-    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-.');
-
-    subplot(4,3,12); 
-    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-.');
-
-    
-    
-
-end
-    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) ...
-        0*randn(numCells,2)];
-
-
-
-    %Add realization by thinning with history
-    dataMat = [ones(size(X,2),1),X(:,1:end)'];
-    % Generate M1 cells
-    clear lambda tempSpikeColl lambdaCIF nst;
-    fitType ='binomial';
-    % matlabpool open;
-     for i=1:numCells
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-
-    % 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;
-    x0{1} = X(ind{1},1);
-    yT{1} = X(ind{1},end);
-    Pi0    = Px0;
-    PiT{1} = 1e-9*eye(size(x0{1},1),size(x0{1},1));
-
-    x0{2} = X(ind{2},1);
-    yT{2} = X(ind{2},end);
-    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_estAll(:,:,n) = X_est;
-    X_estNTAll(:,:,n) = X_estNT;
-    S_estAll(n,:)=S_est;
-    S_estNTAll(n,:)=S_estNT;
-    MU_estAll(:,:,n)=MU_est;
-    MU_estNTAll(:,:,n) = MU_estNT;
-    
-
-    %State Estimate
-    subplot(4,3,[1 4]);
-    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))
-    subplot(4,3,[7 10]);
-    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]);
-
-    %The movement path
-    subplot(4,3,[2 3 5 6]);
-    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-.'); 
-    
-    %X-Position
-    subplot(4,3,8); 
-    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-.'); 
-
-    %Y-Position
-    subplot(4,3,9); 
-    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-.'); 
-
-    %X-Velocity
-    subplot(4,3,11); 
-    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-.');
-
-    subplot(4,3,12); 
-    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-.');
-
-    
-    
-
-end
-    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) ...
-        0*randn(numCells,2)];
-
-
-
-    %Add realization by thinning with history
-    dataMat = [ones(size(X,2),1),X(:,1:end)'];
-    % Generate M1 cells
-    clear lambda tempSpikeColl lambdaCIF nst;
-    fitType ='binomial';
-    % matlabpool open;
-     for i=1:numCells
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-
-    % 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;
-    x0{1} = X(ind{1},1);
-    yT{1} = X(ind{1},end);
-    Pi0    = Px0;
-    PiT{1} = 1e-9*eye(size(x0{1},1),size(x0{1},1));
-
-    x0{2} = X(ind{2},1);
-    yT{2} = X(ind{2},end);
-    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_estAll(:,:,n) = X_est;
-    X_estNTAll(:,:,n) = X_estNT;
-    S_estAll(n,:)=S_est;
-    S_estNTAll(n,:)=S_estNT;
-    MU_estAll(:,:,n)=MU_est;
-    MU_estNTAll(:,:,n) = MU_estNT;
-    
-
-    %State Estimate
-    subplot(4,3,[1 4]);
-    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))
-    subplot(4,3,[7 10]);
-    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]);
-
-    %The movement path
-    subplot(4,3,[2 3 5 6]);
-    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-.'); 
-    
-    %X-Position
-    subplot(4,3,8); 
-    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-.'); 
-
-    %Y-Position
-    subplot(4,3,9); 
-    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-.'); 
-
-    %X-Velocity
-    subplot(4,3,11); 
-    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-.');
-
-    subplot(4,3,12); 
-    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-.');
-
-    
-    
-
-end
-    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) ...
-        0*randn(numCells,2)];
-
-
-
-    %Add realization by thinning with history
-    dataMat = [ones(size(X,2),1),X(:,1:end)'];
-    % Generate M1 cells
-    clear lambda tempSpikeColl lambdaCIF nst;
-    fitType ='binomial';
-    % matlabpool open;
-     for i=1:numCells
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-
-    % 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;
-    x0{1} = X(ind{1},1);
-    yT{1} = X(ind{1},end);
-    Pi0    = Px0;
-    PiT{1} = 1e-9*eye(size(x0{1},1),size(x0{1},1));
-
-    x0{2} = X(ind{2},1);
-    yT{2} = X(ind{2},end);
-    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_estAll(:,:,n) = X_est;
-    X_estNTAll(:,:,n) = X_estNT;
-    S_estAll(n,:)=S_est;
-    S_estNTAll(n,:)=S_estNT;
-    MU_estAll(:,:,n)=MU_est;
-    MU_estNTAll(:,:,n) = MU_estNT;
-    
-
-    %State Estimate
-    subplot(4,3,[1 4]);
-    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))
-    subplot(4,3,[7 10]);
-    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]);
-
-    %The movement path
-    subplot(4,3,[2 3 5 6]);
-    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-.'); 
-    
-    %X-Position
-    subplot(4,3,8); 
-    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-.'); 
-
-    %Y-Position
-    subplot(4,3,9); 
-    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-.'); 
-
-    %X-Velocity
-    subplot(4,3,11); 
-    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-.');
-
-    subplot(4,3,12); 
-    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-.');
-
-    
-    
-
-end
-    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) ...
-        0*randn(numCells,2)];
-
-
-
-    %Add realization by thinning with history
-    dataMat = [ones(size(X,2),1),X(:,1:end)'];
-    % Generate M1 cells
-    clear lambda tempSpikeColl lambdaCIF nst;
-    fitType ='binomial';
-    % matlabpool open;
-     for i=1:numCells
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-         tempData  = exp(dataMat*coeffs(i,:)');
-         if(strcmp(fitType,'binomial'))
-            lambdaData = tempData./(1+tempData);
-         end
-         lambda{i}=Covariate(time,lambdaData./delta, ...
-             '\Lambda(t)','time','s','spikes/sec',...
-             {strcat('\lambda_{',num2str(i),'}')},{{' ''b'', ''LineWidth'' ,2'}});
-         maxTimeRes = 0.001;
-         tempSpikeColl{i} = ...
-             CIF.simulateCIFByThinningFromLambda(lambda{i},1,[]);
-         nst{i} = tempSpikeColl{i}.getNST(1);
-         nst{i}.setName(num2str(i));    
-     end
-
-    % 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;
-    x0{1} = X(ind{1},1);
-    yT{1} = X(ind{1},end);
-    Pi0    = Px0;
-    PiT{1} = 1e-9*eye(size(x0{1},1),size(x0{1},1));
-
-    x0{2} = X(ind{2},1);
-    yT{2} = X(ind{2},end);
-    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_estAll(:,:,n) = X_est;
-    X_estNTAll(:,:,n) = X_estNT;
-    S_estAll(n,:)=S_est;
-    S_estNTAll(n,:)=S_estNT;
-    MU_estAll(:,:,n)=MU_est;
-    MU_estNTAll(:,:,n) = MU_estNT;
-    
-
-    %State Estimate
-    subplot(4,3,[1 4]);
-    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))
-    subplot(4,3,[7 10]);
-    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]);
-
-    %The movement path
-    subplot(4,3,[2 3 5 6]);
-    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-.'); 
-    
-    %X-Position
-    subplot(4,3,8); 
-    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-.'); 
-
-    %Y-Position
-    subplot(4,3,9); 
-    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-.'); 
-
-    %X-Velocity
-    subplot(4,3,11); 
-    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-.');
-
-    subplot(4,3,12); 
-    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-.');
-
-    
-    
-
-end
-
-%
-%     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
-    subplot(4,3,[1 4]);
-    hold all; 
-    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',...
-        'Interpreter','none');
-    title('Estimated vs. Actual State','FontWeight','bold','Fontsize',...
-        12,'FontName','Arial');
-
-    
-    
-
-   % Mean State Movement State Probability
-    subplot(4,3,[7 10]);
-    plot(time, mean(squeeze(MU_estAll(2,:,:)),2),'b','LineWidth',3);  
-    hold on;
-    plot(time,mean(squeeze(MU_estNTAll(2,:,:)),2),'g','LineWidth',3);  
-    hold on;
-    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,...
-        'FontName','Arial');
-    
-    % Mean movement path
-    subplot(4,3,[2 3 5 6]);
-    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');
-
-   
-    % Mean X-Positon
-    subplot(4,3,8); 
-    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');
-    
-    % Mean Y-Position
-    subplot(4,3,9); 
-    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)]);
-
-    % Mean X-Velocity
-    subplot(4,3,11); 
-    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');
-
-    % Mean Y-Velocity
-    subplot(4,3,12); 
-    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');
-
-
\ No newline at end of file diff --git a/helpfiles/nSTATPaperExamples.m b/helpfiles/nSTATPaperExamples.m deleted file mode 100644 index c08a9ec2..00000000 --- a/helpfiles/nSTATPaperExamples.m +++ /dev/null @@ -1,2170 +0,0 @@ -%% nSTAT J. Neuroscience Methods Paper Examples -% -% *Author*: Iahn Cajigas -% -% *Date*: 01/04/2012 - - -%% Experiment 1 -% MINIATURE EXCITATORY POST-SYNAPTIC CURRENTS (mEPSCs) -% Data from Marnie Phillips -% This analysis is based on a partial version of the dataset used in -% -% Phillips MA, Lewis LD, Gong J, Constantine-Paton M, Brown EN. 2011 -% _Model-based statistical analysis of miniature synaptic transmission._ -% J Neurophys (under consideration) -% -% *Date*: 03/01/2011 -%% Constant Magnesium Concentration - Constant rate poisson -% Under a constant Magnesium concentration, it is seen that the mEPSCs -% behave as a homogeneous poisson process (constant arrival rate). - close all; clear all; - epsc2 = importdata('epsc2.txt'); - sampleRate = 1000; - spikeTimes = epsc2.data(:,2)*1/sampleRate; %in seconds - nstConst = nspikeTrain(spikeTimes); - time = 0:(1/sampleRate):nstConst.maxTime; - - - % Define Covariates for the analysis - baseline = Covariate(time,ones(length(time),1),'Baseline','time','s',... - '',{'\mu'}); - covarColl = CovColl({baseline}); - - % Create the trial structure - spikeColl = nstColl(nstConst); - trial = Trial(spikeColl,covarColl); - - - % Define how we want to analyze the data - clear tc tcc; - tc{1} = TrialConfig({{'Baseline','\mu'}},sampleRate,[]); - tc{1}.setName('Constant Baseline'); - tcc = ConfigColl(tc); - - % Perform Analysis (Commented to since data already saved) - results =Analysis.RunAnalysisForAllNeurons(trial,tcc,0); -% h=results.plotResults; - close all; - scrsz = get(0,'ScreenSize'); - results.lambda.setDataLabels({'\lambda_{const}'}); - h=figure('OuterPosition',[scrsz(3)*.01 scrsz(4)*.04 ... - scrsz(3)*.98 scrsz(4)*.95]); - - subplot(2,2,1); spikeColl.plot; - title({'Neural Raster with constant Mg^{2+} Concentration'},... - 'FontWeight','bold',... - 'Fontsize',12,... - 'FontName','Arial'); - hx=xlabel('time [s]','Interpreter','none'); - hy=ylabel('mEPSCs','Interpreter','none'); - set(gca,'yTick',[0 1]); - set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - subplot(2,2,3); results.KSPlot; - subplot(2,2,2); results.plotInvGausTrans; - subplot(2,2,4); results.lambda.plot([],{{' ''b'' ,''Linewidth'',2'}}); - hx=xlabel('time [s]','Interpreter','none'); - hy=get(gca,'YLabel'); - set([hx hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - h_legend = legend('\lambda_{const}','Location','NorthEast'); - pos = get(h_legend,'position'); - set(h_legend, 'position',[pos(1)+.05 pos(2) pos(3:4)]); - set(h_legend,'FontSize',14) - - - %% Varying Magnesium Concentration - Piecewise Constant rate poisson - % When the magnesium concentration of the bath decreased (i.e. magnesium - % is removed), the rate of mEPSCs begin to increase in frequency. This can - % be modeled in a many different ways (using the change in Magnesium - % directly as a model covariate, etc.) Here we approximate the rate as - % being constant during certain portions of the experiment. These segments - % can in principle be estimated (using heirarchical Bayesian methods), but - % here we select them via visual inspection. We compare three models: a - % constant rate model (from above), a piecewise constant rate model, and a - % piecewise constant rate model with history. - close all; - % load the data; - washout1 = importdata('washout1.txt'); - washout2 = importdata('washout2.txt'); - - sampleRate = 1000; - % Magnesium removed at t=0 - spikeTimes1 = 260+washout1.data(:,2)*1/sampleRate; %in seconds - spikeTimes2 = sort(washout2.data(:,2))*1/sampleRate + 745;%in seconds - nst = nspikeTrain([spikeTimes1; spikeTimes2]); - time = 260:(1/sampleRate):nst.maxTime; - - %% Data Visualization - % Visual inspection of the spike train is used to pick three regions - % where the firing rate appears to be different. Here we do not - % estimate where these transitions happen but pick times in an ad-hoc - % manner. - scrsz = get(0,'ScreenSize'); - h=figure('OuterPosition',[scrsz(3)*.01 scrsz(4)*.04 scrsz(3)*.6 ... - scrsz(4)*.9]); - - subplot(2,1,1); - nstConst.plot; set(gca,'yTick',[0 1]); hy=ylabel('mEPSCs'); - title({'Neural Raster with constant Mg^{2+} Concentration'},... - 'FontWeight','bold',... - 'Fontsize',12,... - 'FontName','Arial'); - hx=get(gca,'XLabel'); - set([hx,hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - - subplot(2,1,2); - nst.plot; set(gca,'yTick',[0 1]); hy=ylabel('mEPSCs'); - title({'Neural Raster with decreasing Mg^{2+} Concentration'},... - 'FontWeight','bold',... - 'Fontsize',12,... - 'FontName','Arial'); - hx=get(gca,'XLabel'); - set([hx,hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - - - - %% Define Covariates for the analysis - timeInd1 =find(time<495,1,'last'); %0-495sec first constant rate - timeInd2 =find(time<765,1,'last'); %495-765 second constant rate epoch - %765 onwards third constant rate - %epoch - constantRate = ones(length(time),1); - rate1 = zeros(length(time),1); rate1(1:timeInd1)=1; - rate2 = zeros(length(time),1); rate2((timeInd1+1):timeInd2)=1; - rate3 = zeros(length(time),1); rate3((timeInd2+1):end)=1; - baseline = Covariate(time,[constantRate,rate1, rate2, rate3],... - 'Baseline','time','s','',{'\mu','\mu_{1}','\mu_{2}','\mu_{3}'}); - covarColl = CovColl({baseline}); - - % Create the trial structure - spikeColl = nstColl(nst); - trial = Trial(spikeColl,covarColl); - - %30ms history in logarithmic spacing (chosen after using - %Analysis.computeHistLagForAll for various window lengths) - maxWindow=.3; numWindows=20; - delta=1/sampleRate; - windowTimes =unique(round([0 logspace(log10(delta),... - log10(maxWindow),numWindows)]*sampleRate)./sampleRate); - windowTimes = windowTimes(1:11); - - %% Define how we want to analyze the data - clear tc tcc; - tc{1} = TrialConfig({{'Baseline','\mu'}},sampleRate,[]); - tc{1}.setName('Constant Baseline'); - tc{2} = TrialConfig({{'Baseline','\mu_{1}','\mu_{2}','\mu_{3}'}},... - sampleRate,[]); tc{2}.setName('Diff Baseline'); - tcc = ConfigColl(tc); - - %% Perform Analysis - % We see that the piece-wise constant rate model (without - % history) outperforms the constant baseline model in terms of AIC, BIC, - % and KS-statistic. - results =Analysis.RunAnalysisForAllNeurons(trial,tcc,0); -% h=results.plotResults; -% Summary = FitResSummary(results); -% h=Summary.plotSummary; - -%% -close all; - scrsz = get(0,'ScreenSize'); - results.lambda.setDataLabels({'\lambda_{const}',... - '\lambda_{const-epoch}'}); - h=figure('OuterPosition',[scrsz(3)*.01 scrsz(4)*.04 ... - scrsz(3)*.98 scrsz(4)*.95]); - - subplot(2,2,1); spikeColl.plot; - title({'Neural Raster with decreasing Mg^{2+} Concentration'},... - 'FontWeight','bold',... - 'Fontsize',12,... - 'FontName','Arial'); - hx=xlabel('time [s]','Interpreter','none'); - set(gca,'YTickLabel',[]); - set([hx],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - timeInd1 =find(time<495,1,'last'); %0-495sec first constant rate - timeInd2 =find(time<765,1,'last'); %495-765 second constant rate epoch - %765 onwards third constant rate - %epoch - plot([495;495],[0,1],'r','Linewidth',4); hold on; - plot([765;765],[0,1],'r','Linewidth',4); - - subplot(2,2,3); results.KSPlot; - subplot(2,2,2); results.plotInvGausTrans; - subplot(2,2,4); - results.lambda.getSubSignal(1).plot([],{{' ''b'' ,''Linewidth'',2'}}); - results.lambda.getSubSignal(2).plot([],{{' ''g'' ,''Linewidth'',2'}}); - v=axis; axis([v(1) v(2) 0 5]); - hx=xlabel('time [s]','Interpreter','none'); - hy=get(gca,'YLabel'); - set([hx hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - h_legend = legend('\lambda_{const}','\lambda_{const-epoch}',... - 'Location','NorthEast'); - pos = get(h_legend,'position'); - set(h_legend, 'position',[pos(1)+.05 pos(2)-.01 pos(3:4)]); - set(h_legend,'FontSize',14) - -%% Experiment 2 -% EXPLICIT STIMULUS EXAMPLE - WHISKER STIMULATION/THALAMIC NEURON -% In the worksheet with analyze the stimulus effect and history effect on -% the firing of a thalamic neuron under a known stimulus consisting of -% whisker stimulation. -% Data from Demba Ba (demba@mit.edu) - -%% Load the data -% clear all; -close all; currdir = pwd; -index = strfind(currdir,'helpfiles')-1; -rootpath = currdir(1:index); - -Direction=3; Neuron=1; Stim=2; -% datapath = strcat(rootpath,['data/Explicit Stimulus/Dir' num2str(Direction)... -% '\Neuron' num2str(Neuron) '\Stim' num2str(Stim) '\']); -datapath = strcat(rootpath,['data/Explicit Stimulus/Dir' num2str(Direction)... - '/Neuron' num2str(Neuron) '/Stim' num2str(Stim) '/']); -data=load(strcat(datapath,'trngdataBis.mat')); - -time=0:.001:(length(data.t)-1)*.001; -stimData = data.t; -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','',... - {'constant'}); - -nst = nspikeTrain(spikeTimes); -nspikeColl = nstColl(nst); -cc = CovColl({stim,baseline}); -trial = Trial(nspikeColl,cc); -% trial.plot; - -scrsz = get(0,'ScreenSize'); -h=figure('Position',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.8 scrsz(4)*.8]); -subplot(3,1,1); -nst2 = nspikeTrain(spikeTimes); -nst2.setMaxTime(21);nst2.plot; -set(gca,'ytick',[0 1]); -xlabel(''); -hy=ylabel('spikes'); -set(hy,'FontName', 'Arial','FontSize',12,'FontWeight','bold'); -title({'Neural Raster'},'FontWeight','bold','FontSize',16,'FontName','Arial'); -set(gca, ... - 'XTick' , 0:1:max(time), ... - 'XTickLabel' , [],... - 'LineWidth' , 1 ); -subplot(3,1,2); -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'); - -set(gca, ... - 'XTick' , 0:1:max(time), ... - 'XTickLabel' , [],... - 'YTick' , 0:.25:1, ... - 'LineWidth' , 1 ); - -subplot(3,1,3); -stim.derivative.getSigInTimeWindow(0,21).plot([],{{' ''k'' '}}); legend off; -set(gca,'ytick',[-80 0 80]); -axis([0 21 -80 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'); - -set(gca, ... - 'XTick' , 0:1:max(time), ... - 'YTick' , -80:40:80, ... - 'LineWidth' , 1 ); - - -%% -% Fit a constant baseline and Find Stimulus Lag -% We fit a constant rate (Poisson) model to the data and use the look at the -% cross-covariance function of between the stimulus and the fit -% residual to determine the appropriate lag for the stimulus. -clear c; close all; -selfHist = [] ; NeighborHist = []; sampleRate = 1000; -c{1} = TrialConfig({{'Baseline','constant'}},sampleRate,selfHist,NeighborHist); -c{1}.setName('Baseline'); -cfgColl= ConfigColl(c); -results = Analysis.RunAnalysisForAllNeurons(trial,cfgColl,0); - -% Find Stimulus Lag (look for peaks in the cross-covariance function less -% than 1 second -scrsz = get(0,'ScreenSize'); -h=figure('Position',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.8 scrsz(4)*.8]); - -subplot(7,2,[1 3 5]) -results.Residual.xcov(stim).windowedSignal([0,1]).plot; - -ylabel(''); -[m,ind,ShiftTime] = max(results.Residual.xcov(stim).windowedSignal([0,1])); -title(['Cross Correlation Function - Peak at t=' num2str(ShiftTime) ' sec'],'FontWeight','bold',... - 'FontSize',12,... - 'FontName','Arial'); -hold on; -h=plot(ShiftTime,m,'ro','Linewidth',3); -set(h, 'MarkerFaceColor',[1 0 0], 'MarkerEdgeColor',[1 0 0]); -hx=xlabel('Lag [s]','Interpreter','none'); -set(hx,'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - - -%Allow for shifts of less than 1 second -stim = Covariate(time,stimData,'Stimulus','time','s','V',{'stim'}); -stim = stim.shift(ShiftTime); -baseline = Covariate(time,ones(length(time),1),'Baseline','time','s','',... - {'\mu'}); - -nst = nspikeTrain(spikeTimes); -nspikeColl = nstColl(nst); -cc = CovColl({stim,baseline}); -trial2 = Trial(nspikeColl,cc); - -%% Compare constant rate model with model including stimulus effect -% Addition of the stimulus improves the fits in terms of the KS plot and -% the making the rescaled ISIs less correlated. The Point Process Residula -% also looks more "white" -clear c; -selfHist = [] ; NeighborHist = []; sampleRate = 1000; -c{1} = TrialConfig({{'Baseline','\mu'}},sampleRate,selfHist,... - NeighborHist); -c{1}.setName('Baseline'); -c{2} = TrialConfig({{'Baseline','\mu'},{'Stimulus','stim'}},... - sampleRate,selfHist,NeighborHist); -c{2}.setName('Baseline+Stimulus'); -cfgColl= ConfigColl(c); -results = Analysis.RunAnalysisForAllNeurons(trial2,cfgColl,0); -% results.plotResults; - -%% History Effect -% Determine the best history effect model using AIC, BIC, and KS statistic -sampleRate=1000; -delta=1/sampleRate*1; -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); - -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; -if(AICind==1) - AICind=inf; -end -if(BICind==1) - BICind=inf; %sometime BIC is non-decreasing and the index would be 1 -end -windowIndex = min([AICind,BICind]) %use the minimum order model -Summary = FitResSummary(results); -% Summary.plotSummary; - - -clear c; -if(windowIndex>1) - selfHist = windowTimes(1:windowIndex+1); -else - selfHist = []; -end -NeighborHist = []; sampleRate = 1000; -% -% figure; -subplot(7,2,2); -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'},... - 'FontWeight','bold',... - 'FontSize',12,... - 'FontName','Arial'); - -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'); -set(gca, ... - 'TickLength' , [.02 .02] , ... - 'XMinorTick' , 'on' , ... - 'XTick' , 0:5:results{1}.numResults-1, ... - 'LineWidth' , 1 ); - - - -% Compare Baseline, Baseline+Stimulus Model, Baseline+History+Stimulus -% Addition of the history effect yields a model that falls within the 95% -% CI of the KS plot. - -c{1} = TrialConfig({{'Baseline','\mu'}},sampleRate,[],NeighborHist); -c{1}.setName('Baseline'); -c{2} = TrialConfig({{'Baseline','\mu'},{'Stimulus','stim'}},... - sampleRate,[],[]); -c{2}.setName('Baseline+Stimulus'); -c{3} = TrialConfig({{'Baseline','\mu'},{'Stimulus','stim'}},... - sampleRate,windowTimes(1:windowIndex),[]); -c{3}.setName('Baseline+Stimulus+Hist'); -cfgColl= ConfigColl(c); -results = Analysis.RunAnalysisForAllNeurons(trial2,cfgColl,0); -%results.plotResults; -% -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; - - -%% Example 3 - PSTH Data - -% 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. -clear all; -close all; -delta = 0.001; -Tmax = 1; -time = 0:delta:Tmax; -f=2; -mu = -3; - -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'}}); -numRealizations = 20; -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'); -hy=get(gca,'YLabel'); -set(hy,'FontName', 'Arial','FontSize',14,'FontWeight','bold'); - -fileLocation = which('nSTAT_Install'); -index = strfind(fileLocation,'nSTAT_Install.m')-1; -nSTATDir =fileLocation(1:index); - -rootDir = [nSTATDir 'data' filesep 'PSTH' filesep]; -filename = 'Results.mat'; -x=load(strcat(rootDir,filename)); -numTrials = x.Results.Data.Spike_times_STC.balanced_SUA.Nr_trials; -cellNum=6; clear nst; -for i=1:numTrials - 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)); -end - -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'); - -cellNum=1; clear nst; -for i=1:numTrials - 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)); -end - -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'); - - -%% Estimate the PSTH with 50ms windows -% -close all; - -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); -true = lambda; %rate*delta = expected number of arrivals per bin -subplot(2,3,4); - -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'); - -legend off; -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',... - 12,'FontWeight','bold'); -ylabel('Trial [k]','Interpreter','none','FontName', 'Arial',... - 'Fontsize',12,'FontWeight','bold'); - -subplot(2,3,5); -binsize = .05; %50ms window -psthReal1 = spikeCollReal1.psth(binsize); -psthGLMReal1 = spikeCollReal1.psthGLM(binsize);%,[],[],[],[],[],1000); - -h3=psthGLMReal1.plot([],{{' ''k'',''Linewidth'',4'}}); -h2=psthReal1.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([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',... - 12,'FontWeight','bold'); -ylabel('Trial [k]','Interpreter','none','FontName', 'Arial',... - 'Fontsize',12,'FontWeight','bold'); -subplot(2,3,6); -psthReal2 = spikeCollReal2.psth(binsize); -psthGLMReal2 = spikeCollReal2.psthGLM(binsize);%,[],[],[],[],[],1000); -h3=psthGLMReal2.plot([],{{' ''k'',''Linewidth'',4'}}); -h2=psthReal2.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([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',... - 12,'FontWeight','bold'); -ylabel('Trial [k]','Interpreter','none','FontName', 'Arial',... - 'Fontsize',12,'FontWeight','bold'); - - - -%% Example 3b - SSGLM Example -% Example of estimating with-in and across trial dynamics -% Methods from: -% G. Czanner, U. T. Eden, S. Wirth, M. Yanike, -% W. A. Suzuki, and E. N. Brown, "Analysis of between-trial and -% within-trial neural spiking dynamics.," Journal of neurophysiology, -% vol. 99, no. 5, pp. 2672?2693, May. 2008. - -close all; -clear all; -% set(0,'DefaultFigureRenderer','ZBuffer') -delta = 0.001; Tmax = 1; -time = 0:delta:Tmax; -Ts=.001; -numRealizations = 50; %Each realization corresponds to a distinct trial - -for i=1:numRealizations - % The within trial dynamics are sinusoidal - % For each trial the stimulus effect increases - f=2; b1(i)=3*((i)/numRealizations);b0=-3; - u = sin(2*pi*f*time); - e = zeros(length(time),1); %No Ensemble input - - stim=Covariate(time',u,'Stimulus','time','s','Voltage',{'sin'}); - ens =Covariate(time',e,'Ensemble','time','s','Spikes',{'n1'}); - - mu=b0; - histCoeffs=[-4 -1 -.5]; - H=tf(histCoeffs,[1],Ts,'Variable','z^-1'); - - S=tf([b1(i)],1,Ts,'Variable','z^-1'); - E=tf([0],1,Ts,'Variable','z^-1'); - simTypeSelect='binomial'; %Parameters are used to compute - %binomial conditional intensity function - % - - % Obtain a realization of the point process with the current - % stimulus and history effect - [sC, lambdaTemp]=CIF.simulateCIF(mu,H,S,E,stim,ens,1,simTypeSelect); - - if(i==1) - lambda=lambdaTemp; %Store the conditional intensity function - else - lambda = lambda.merge(lambdaTemp); %Add it to the other realizations - end - - nst{i} = sC.getNST(1); %get the neural spikeTrain from the collection - nst{i} = nst{i}.resample(1/delta); %make sure that it is sampled at the current samplerate -end - -spikeColl = nstColl(nst); %Create a collection of the spike trains across trials - -%% Summarize Simulated Data -close all; -scrsz = get(0,'ScreenSize'); -h=figure('Position',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.8 scrsz(4)*.8]); - -%Plot the raster -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',... - 12,'FontWeight','bold'); -ylabel('Trial [k]','Interpreter','none','FontName', 'Arial','Fontsize',... - 12,'FontWeight','bold'); -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 -% above - - -stimData = exp(b0 + u'*b1); -if(strcmp(simTypeSelect,'binomial')) - stimData = stimData./(1+stimData); -end - -%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',... - 12,'FontWeight','bold'); -ylabel('Stimulus','Interpreter','none','FontName', 'Arial','Fontsize',... - 12,'FontWeight','bold'); -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',... - 12,'FontWeight','bold'); -ylabel('Stimulus Gain','Interpreter','none','FontName', 'Arial','Fontsize',... - 12,'FontWeight','bold'); -title('Across Trial Stimulus Gain','Interpreter','none','FontName',... - 'Arial','Fontsize',14,'FontWeight','bold'); - -subplot(3,2,[5 6]); -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'); - - -axis tight; - -%% Estimation of the Stimulus Response - -% Create the covariates that will be used for the GLM regression -stim = Covariate(time,sin(2*pi*f*time),'Stimulus','time','s','V',{'stim'}); -baseline = Covariate(time,ones(length(time),1),'Baseline','time','s','',... - {'constant'}); - -% Specify the windows of the history coefficients to be estimated -windowTimes=[0:.001:.003]; -% Number of bins to discrtize time into (used both for the PSTH and for -% thec -% SSGLM model. -numBasis = 25; - -spikeColl.resample(1/delta); % Enforce sampleRate -spikeColl.setMaxTime(Tmax); % Make all spikeTrains end at time Tmax - - -dN=spikeColl.dataToMatrix'; % Convert the spikeTrains into a matrix - % of 1's and 0's corresponding to the presence - % or absense of a spike in each time window. -dN(dN>1)=1; % One should sample finely enough so there is - % one spike per bin. Here we make sure that - % this is the case regardless of the - % sampleRate - -% The width of each rectangular basis pulse is determined by Tmax and by the -% number of basis pulses to use. -basisWidth=(spikeColl.maxTime-spikeColl.minTime)/numBasis; - -if(simTypeSelect==0) - fitType='binomial'; -else - fitType='poisson'; -end -if(strcmp(fitType,'binomial')) - Algorithm = 'BNLRCG'; % BNLRCG - faster Truncated, L-2 Regularized, - % Binomial Logistic Regression with Conjugate - % Gradient Solver by Demba Ba (demba@mit.edu). -else - Algorithm = 'GLM'; % Standard Matlab GLM (Can be used for binomial or - % or Poisson CIFs -end - -% Use the values obtained from a PSTH to initialize the SSGLM filter -[psthSig, ~, psthResult] =spikeColl.psthGLM(basisWidth,windowTimes,fitType); -gamma0=psthResult.getHistCoeffs';%+.1*randn(size(histCoeffs)); -gamma0(isnan(gamma0))=-5; % Depending on the amount of data the - % the psth may not identify all parameters - % Just make sure that the estimates are real - % numbers - -x0=psthResult.getCoeffs; %The initial estimate for the SSGLM model - -% Estimate the variance within each time bin across trials -numVarEstIter=10; -Q0 = spikeColl.estimateVarianceAcrossTrials(numBasis,windowTimes,... - numVarEstIter,fitType); -A=eye(numBasis,numBasis); -delta = 1/spikeColl.sampleRate; - -%% Run the SSGLM Filter -CompilingHelpFile=1; - % Commented out to speed up help file creation ... - if(~CompilingHelpFile) - Q0d=diag(Q0); - neuronName = psthResult.neuronNumber; - [xK,WK, WkuFinal,Qhat,gammahat,fitResults,stimulus,stimCIs,logll,... - QhatAll,gammahatAll,nIter]=DecodingAlgorithms.PPSS_EMFB(A,Q0d,x0,... - dN,fitType,delta,gamma0,windowTimes, numBasis,neuronName); - - fR = fitResults.toStructure; - psthR = psthResult.toStructure; - end -% save SSGLMExampleData psthR fR xK WK WkuFinal Qhat gammahat fitResults stimulus stimCIs logll QhatAll gammahatAll nIter; -%% -load SSGLMExampleData; -fitResults = FitResult.fromStructure(fR); -psthResult = FitResult.fromStructure(psthR); - -%% -t=psthResult.mergeResults(fitResults); -%t.plotResults; %Compare the results with the PSTH Model -t.lambda.setDataLabels({'\lambda_{PSTH}','\lambda_{SSGLM}'}); -scrsz = get(0,'ScreenSize'); -h=figure('Position',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.8 scrsz(4)*.8]); -subplot(2,2,1); t.KSPlot; -subplot(2,2,2); t.plotResidual; -subplot(2,2,3); t.plotInvGausTrans; -subplot(2,2,4); t.plotSeqCorr; - -S=FitResSummary(t); -dAIC=diff(S.AIC) -dBIC=diff(S.BIC) -dKS =diff(S.KSStats); - - -%% -close all; -% Generate the actual stimulus effect -minTime=0; maxTime = Tmax; -stimData = stim.data*b1; -if(strcmp(fitType,'poisson')) - actStimEffect=exp(stimData + b0)./delta; -elseif(strcmp(fitType,'binomial')) - actStimEffect=exp(stimData + b0)./(1+exp(stimData + b0))./delta; -end -% - -% Generate the basis function so that the estimated effect can be plotted -% at the same temporal resolution as the theoretical effect - if(~isempty(numBasis)) - basisWidth = (maxTime-minTime)/numBasis; - sampleRate=1/delta; - unitPulseBasis=nstColl.generateUnitImpulseBasis(basisWidth,minTime,... - maxTime,sampleRate); - basisMat = unitPulseBasis.data; - end - -% 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; -end - - -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 -% time -subplot(3,1,[1 2 3]); -lighting gouraud -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',... - 'Fontsize',14,... - 'FontName','Arial'); - -close all; -h=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.4 scrsz(4)*.8]); - -% The actual stimulus effect -subplot(3,1,1); -lighting gouraud -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',... - 'Fontsize',14,... - 'FontName','Arial'); -set(gca,'xtick',[],'xtickLabel',[]); -set(gca,'ytick',[],'ytickLabel',[]); -CLIM = [min(min(stimData./delta)) max(max(stimData./delta))]; -view(gca,[90 -90]); - - - -% The PSTH estimate -subplot(3,1,2); -lighting gouraud -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',... - 'Fontsize',14,... - 'FontName','Arial'); - -set(gca,'xtick',[],'xtickLabel',[]); -set(gca,'ytick',[],'ytickLabel',[]); -CLIM = [min(min(stimData./delta)) max(max(stimData./delta))]; -view(gca,[90 -90]); - -% The SSGLM estimated stimulus effect -subplot(3,1,3); -lighting gouraud -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',... - 'Fontsize',14,... - 'FontName','Arial'); -set(gca,'xtick',[],'xtickLabel',[]); -set(gca,'ytick',[],'ytickLabel',[]); -set(gca, 'YDir','normal') -view(gca,[90 -90]); - - - -%% Compare differences across trials -close all; - 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 - if(~isempty(numBasis)) - basisWidth = (maxTime-minTime)/numBasis; - sampleRate=1/delta; - unitPulseBasis=nstColl.generateUnitImpulseBasis(basisWidth,... - minTime,maxTime,sampleRate); - basisMat = unitPulseBasis.data; - end - - -% close all; - -t0=0; tf=Tmax; -[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'))]); -scrsz = get(0,'ScreenSize'); -h=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.8 scrsz(4)*.8]); - -subplot(2,3,1); -spikeRateBinom.setName(['(' num2str(Tmax) '-0)^-1*\Lambda(0,' ... - num2str(Tmax) ')']); -spikeRateBinom.plot([],{{' ''k'',''Linewidth'',4'}}); -% e = Events(lt,{''}); -% e.plot; -v=axis; -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',... - 'Fontsize',12,... - 'FontName','Arial'); - - - -h=subplot(2,3,[2 3 5 6]); -K=size(dN,1); -colormap(flipud(gray)); -imagesc(ProbMat); hold on; -for k=1:K - for m=(k+1):K - if(sigMat(k,m)==1) - plot3(m,k,1,'r*'); hold on; - end - end -end -% -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'); - -subplot(2,3,4) -stim1 = Covariate(time, basisMat*stimulus(:,1),'Trial1','time','s',... - 'spikes/sec'); -temp = ConfidenceInterval(time, basisMat*squeeze(stimCIs(:,1,:))); -stim1.setConfInterval(temp); -stimlt = Covariate(time, basisMat*stimulus(:,lt),'Trial1','time','s',... - 'spikes/sec'); -temp = ConfidenceInterval(time, basisMat*squeeze(stimCIs(:,lt,:))); -temp.setColor('r'); -stimlt.setConfInterval(temp); -stimltm1 = Covariate(time, basisMat*stimulus(:,lt-1),'Trial1','time','s',... - 'spikes/sec'); -temp = ConfidenceInterval(time, basisMat*squeeze(stimCIs(:,lt-1,:))); -temp.setColor('r'); -stimltm1.setConfInterval(temp); - -% figure; -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',... - 'Fontsize',12,... - 'FontName','Arial'); -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)]); - -%% Example 4 - HIPPOCAMPAL PLACE CELL - RECEPTIVE FIELD ESTIMATION -% Estimation of receptive fields of neurons is a very common data analysis problem in neuroscience. -% Here we use the nSTAT software to perform an estimation of the receptive fields of hippocampal -% place cells using a bivariate Gaussian model and Zernike polynomials. The number of zernike polynomials -% is based on "An Analysis of Hippocampal Spatio-Temporal Representations Using a Bayesian Algorithm for Neural -% Spike Train Decoding" Barbieri et. al 2005. The data used herein in was -% provided by Dr. Ricardo Barbieri on 2/28/2011. -% -% *Author*: Iahn Cajigas -% -% *Date*: 3/1/2011 -%% - - -%% Example Data -% The x and y coordinates of a freely foraging rat in a circular environment (70cm in diameter and 30cm high walls) and a fixed visual cue. -% The x and y coordinates at the time when a spike was observed are marked -% in red. The position coordinates have been normalized to be between -1 -% and 1 to allow to simplify the analysis. - close all; - load(strcat('PlaceCellDataAnimal1.mat')); - exampleCell = [2 21 25 49]; -% exampleCell = 1:length(neuron); -% figure(1); - scrsz = get(0,'ScreenSize'); - h=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.6 scrsz(4)*.9]); - - for i=1:length(exampleCell) - subplot(2,2,i); - h1=plot(x,y,'b','Linewidth',.5); hold on; - h2=plot(neuron{exampleCell(i)}.xN,neuron{exampleCell(i)}.yN,'r.',... - 'MarkerSize',7); - hx=xlabel('X Position'); hy=ylabel('Y Position'); -% title(['Animal#1, Cell#' num2str(exampleCell(i))]); - title(['Cell#' num2str(exampleCell(i))],'FontWeight','bold',... - 'Fontsize',12,'FontName','Arial'); - set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - set(gca,'xTick',-1:.5:1,'yTick',-1:.5:1); axis square; - if(i==4) - h_legend = legend([h1 h2],'Animal Path',... - 'Location at time of spike'); - pos = get(h_legend,'position'); - set(h_legend, 'position',[pos(1)+.09 pos(2)+.06 pos(3:4)]); - end - end - - - %% Analyze All Cells -numAnimals=2; -CompilingHelpFile=1; -if(~CompilingHelpFile) - for n=1:numAnimals - % load the data - clear x y neuron time nst tc tcc z; - load(strcat('PlaceCellDataAnimal',num2str(n),'.mat')); - - % Create the spikeTrains for each cell - for i=1:length(neuron) - nst{i} = nspikeTrain(neuron{i}.spikeTimes); - end - - - % 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 - cnt=0; - for l=0:3 - for m=-l:l - if(~any(mod(l-m,2))) % otherwise the polynomial = 0 - cnt = cnt+1; - z(:,cnt) = zernfun(l,m,r,theta,'norm'); - % zernfun by Paul Fricker - % http://www.mathworks.com/matlabcentral/fileexchange/7687 - end - end - end - - % Data sampled at 30 Hz but just to be sure - delta=min(diff(time)); - sampleRate = round(1/delta); - % Define Covariates for the analysis - baseline = Covariate(time,ones(length(x),1),'Baseline','time','s','',... - {'mu'}); - 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'); - tcc = ConfigColl(tc); - - % Perform Analysis (Commented to since data already saved) - results =Analysis.RunAnalysisForAllNeurons(trial,tcc,0); - - % Save results - resStruct =FitResult.CellArrayToStructure(results); - filename = ['PlaceCellAnimal' num2str(n) 'Results']; - save(filename,'resStruct'); - end -end -%% View Summary Statistics -% Note the Zernike Polynomials yield better fits in terms of decreased KS -% Statistics (less deviation from the 45 degree line), reduced AIC and -% reduced BIC across the majority of cells and for both animals -clear Summary; -numAnimals =2; - -for n=1:numAnimals - resData=load(strcat('PlaceCellAnimal',num2str(n),'Results.mat')); - results = FitResult.fromStructure(resData.resStruct); - Summary{n} = FitResSummary(results); -% Summary{n}.plotSummary; -end -%% -close all; -scrsz = get(0,'ScreenSize'); -h=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.6 scrsz(4)*.5]); -subplot(1,3,1); -maxLength = max([Summary{1}.numNeurons,Summary{2}.numNeurons]); -dKS = nan(maxLength, 2); -dKS(1:Summary{1}.numNeurons,1) = (Summary{1}.KSStats(:,1)-Summary{1}.KSStats(:,2)) ; -dKS(1:Summary{2}.numNeurons,2) = (Summary{2}.KSStats(:,1)-Summary{2}.KSStats(:,2)) ; - -boxplot(dKS ,{'Animal 1', 'Animal 2'},'labelorientation','inline'); -title('\Delta KS Statistic','FontWeight','bold','FontSize',14,... - 'FontName','Arial'); - - -subplot(1,3,2); -dAIC = nan(maxLength, 2); -dAIC(1:Summary{1}.numNeurons,1) = Summary{1}.getDiffAIC(1); -dAIC(1:Summary{2}.numNeurons,2) = Summary{2}.getDiffAIC(1); - -boxplot(dAIC ,{'Animal 1', 'Animal 2'},'labelorientation','inline'); -title('\Delta AIC','FontWeight','bold','FontSize',14,'FontName','Arial'); - - -subplot(1,3,3); -dBIC = nan(maxLength, 2); -dBIC(1:Summary{1}.numNeurons,1) = Summary{1}.getDiffBIC(1); -dBIC(1:Summary{2}.numNeurons,2) = Summary{2}.getDiffBIC(1); - -boxplot(dBIC ,{'Animal 1', 'Animal 2'},'labelorientation','inline'); %ylabel('\Delta BIC'); %xticklabel_rotate([],45,[],'Fontsize',6); -title('\Delta BIC','FontWeight','bold','FontSize',14,'FontName','Arial'); - -% close all; - - -%% Visualize the results -close all; -% Define a grid -[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 -idx = r_new<=1; -zpoly = cell(1,10); -cnt=0; -for l=0:3 - for m=-l:l - if(~any(mod(l-m,2))) - cnt = cnt+1; - temp = nan(size(x_new)); - temp(idx) = zernfun(l,m,r_new(idx),theta_new(idx),'norm'); - zpoly{cnt} = temp; - end - end -end - - - -for n=1:numAnimals - - clear lambdaGaussian lambdaZernike; - load(strcat('PlaceCellDataAnimal',num2str(n),'.mat')); - resData=load(strcat('PlaceCellAnimal',num2str(n),'Results.mat')); - results = FitResult.fromStructure(resData.resStruct); - - for i=1:length(neuron) - % 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); - end - - - - - % Plot the receptive fields - for i=1:length(neuron) - % 3d plot of an example place field - - - % 2d plot of all the cell's fields - if(n==1) - h4=figure(4); - colormap('jet'); - if(i==1) - 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; - end - subplot(7,7,i); - elseif(n==2) - h6=figure(6); - colormap('jet'); - if(i==1) - 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; - end - subplot(6,7,i); - end - pcolor(x_new,y_new,lambdaGaussian{i}), shading interp - axis square; set(gca,'xtick',[],'ytick',[]); - set(gca, 'Box' , 'off'); - - if(n==1) - h5=figure(5); - colormap('jet'); - if(i==1) - 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; - - end - subplot(7,7,i); - elseif(n==2) - h7=figure(7); - colormap('jet'); - if(i==1) - 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; - end - subplot(6,7,i); - end - pcolor(x_new,y_new,lambdaZernike{i}), shading interp - axis square; - set(gca,'xtick',[],'ytick',[]); - set(gca, 'Box' , 'off'); - end - - -end - - -%% - clear lambdaGaussian lambdaZernike; - load(strcat('PlaceCellDataAnimal1.mat')); - resData=load(strcat('PlaceCellAnimal1Results.mat')); - results = FitResult.fromStructure(resData.resStruct); - - for i=1:length(neuron) - % 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); - end - - - -% h1=plot(x,y,'b'); -% h2=plot(x,y,'g'); - % - exampleCell = 25; -% figure(8); -% plot(x,y,'b',neuron{exampleCell}.xN,neuron{exampleCell}.yN,'r.'); -% xlabel('x'); ylabel('y'); -% title(['Animal#1, Cell#' num2str(exampleCell)]); -% - close all; - h9=figure(9); - h_mesh = mesh(x_new,y_new,lambdaGaussian{exampleCell},'AlphaData',0); - get(h_mesh,'AlphaData'); - set(h_mesh,'FaceAlpha',0.2,'EdgeAlpha',0.2,'EdgeColor','b'); - hold on; - h_mesh = mesh(x_new,y_new,lambdaZernike{exampleCell},'AlphaData',0); - get(h_mesh,'AlphaData'); - set(h_mesh,'FaceAlpha',0.2,'EdgeAlpha',0.2,'EdgeColor','g'); - - -% h_legend=legend('\lambda_{Gaussian}','\lambda_{Zernike}'); -% set(h_legend,'FontSize',20); - plot(x,y,neuron{exampleCell}.xN,neuron{exampleCell}.yN,'r.'); - axis tight square; - xlabel('x position'); ylabel('y position'); - title(['Animal#1, Cell#' num2str(exampleCell)],'FontWeight','bold',... - 'Fontsize',12,'FontName','Arial'); - hx=get(gca,'XLabel'); hy=get(gca,'YLabel'); - set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - - - -%% Example 5 - STIMULUS DECODING -% In this example we show how to decode a univariate and a bivariate -% stimulus based on a point process observations using nSTAT. Even though -% due to the simulated nature of the data, we know the exact condition -% intensity function, we estimate the parameters before moving on to the -% decoding stage. -%% Generate the conditional Intensity Function - - close all; clear all; - delta = 0.001; Tmax = 1; - time = 0:delta:Tmax; - numRealizations = 20; - f=2; b1=randn(numRealizations,1);b0=log(10*delta)+randn(numRealizations,1); - x = sin(2*pi*f*time); - clear nst; - for i=1:numRealizations - expData = exp(b1(i)*x+b0(i)); - lambdaData = expData./(1+expData); - - if(i==1) - lambda = Covariate(time,lambdaData./delta, ... - '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},... - {{' ''b'', ''LineWidth'' ,2'}}); - else - tempLambda = Covariate(time,lambdaData./delta, ... - '\Lambda(t)','time','s','spikes/sec',{'\lambda_{1}'},... - {{' ''b'', ''LineWidth'' ,2'}}); - lambda = lambda.merge(tempLambda); - end - - spikeColl = CIF.simulateCIFByThinningFromLambda(... - lambda.getSubSignal(i),1); - nst{i} = spikeColl.getNST(1); - end - spikeColl = nstColl(nst);scrsz = get(0,'ScreenSize'); - h=figure('Position',[scrsz(3)*.1 scrsz(4)*.1 ... - scrsz(3)*.6 scrsz(4)*.8]); -% figure; - 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'}}); - legend off; - hy=ylabel('Firing Rate [spikes/sec]', 'Interpreter','none'); - hx=xlabel('','Interpreter','none'); - set([hx, hy],'FontName', 'Arial','FontSize',12,... - 'FontWeight','bold'); - 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',... - 0:10:numRealizations); - 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','',... - {'constant'}); - -% close all; -%% -close all; - -clear lambdaCIF; -spikeColl.resample(1/delta); -dN=spikeColl.dataToMatrix; - -% Make noise according to the dynamic range of the stimulus -Q=std(stim.data(2:end)-stim.data(1:end-1)); -Px0=.1; A=1; -x0 = x(:,1); yT=x(:,end); -Pi0 = eps*eye(size(x0,1),size(x0,1)); -PiT = eps*eye(size(x0,1),size(x0,1)); - - -[x_p, W_p, x_u, W_u] = DecodingAlgorithms.PPDecodeFilterLinear(A, ... - Q, dN',b0,b1','binomial',delta); -% -h=figure('Position',[scrsz(3)*.1 scrsz(4)*.1 scrsz(3)*.8 scrsz(4)*.6]); -zVal=1.96; -ciLower = min(x_u(1:end)-zVal*sqrt(squeeze(W_u(1:end)))',... - x_u(1:end)+zVal*sqrt(squeeze(W_u(1:end))')); -ciUpper = max(x_u(1:end)-zVal*sqrt(squeeze(W_u(1:end)))',... - x_u(1:end)+zVal*sqrt(squeeze(W_u(1:end))')); - -estimatedStimulus = Covariate(time,x_u(1:end),'\hat{x}(t)','time','s',''); -CI= ConfidenceInterval(time,[ciLower', ciUpper'],'\hat{x}(t)','time','s',''); -estimatedStimulus.setConfInterval(CI); - -% hold all; -% hEst=plot(time,x_u(1:end),'b','Linewidth',2); hold on; -% plot(time, [ciUpper', ciLower'],'b'); - -hEst = estimatedStimulus.plot([],{{' ''k'',''Linewidth'',4'}}); -hStim=stim.plot([],{{' ''b'',''Linewidth'',4'}}); -legend off; -h_legend=legend([hEst(1) hStim],'Decoded','Actual'); -set(h_legend,'Interpreter','none'); -set(h_legend,'FontSize',22); -title(['Decoded Stimulus +/- 95% CIs with ' num2str(numRealizations) ' cells'],... - 'FontWeight','bold','Fontsize',22,'FontName','Arial'); -xlabel('time [s]','Interpreter','none'); -ylabel('Stimulus','Interpreter','none'); -hx=get(gca,'XLabel'); hy=get(gca,'YLabel'); -set([hx, hy],'FontName', 'Arial','FontSize',22,'FontWeight','bold'); - - - -%% Example 5b - Arm reaching to target Simulation -% See -% L. Srinivasan, U. T. Eden, A. S. Willsky, and E. N. Brown, -% "A state-space analysis for reconstruction of goal-directed movements -% using neural signals.," Neural computation, vol. 18, no. 10, pp. 2465?2494, Oct. 2006. - - close all; - clear all; - %Process noise covariance only drives the movement velocity - q=1e-4; - Q=diag([1e-12 1e-12 q q]); - - delta = .001; % Time increment - r=1e-6; % in meters^2 - p=1e-6; % in meters^2/s^2 - PiT=diag([r r p p]); % Uncertainty in the target state - Pi0=PiT; - T=2; % Reach Duration - - 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 - 0 1 0 delta; - 0 0 1 0 ; - 0 0 0 1 ]; - - x=zeros(4,length(time)); - - -% Simulate a reach trajectory -% Differs from reference by multiplication by delta instead of division so -% that the velocity has units of meters per second - R=chol(Q); - L=chol(PiT); - for k=1:length(time) - if(k==1) - x(:,k)=x0; - else - x(:,k)=A*x(:,k-1)+... - 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 - end - - end - 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 The movement path - subplot(4,2,[1 3]); - 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'); - hold on; - 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 - - subplot(4,2,7); - 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'); - xlabel('time [s]'); - 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'); - % - - gamma=0; - windowTimes=[0, 0.001]; - - -% 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; - numCells = 20; - 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 - fitType='binomial'; - clear nst; - for i=1:numCells - tempData = exp(dataMat*coeffs(i,:)'); - - if(strcmp(fitType,'poisson')) - lambdaData = tempData; - else - lambdaData = tempData./(1+tempData); % Conditional Intensity Function for ith cell - end - 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 - subplot(4,2,[6 8]); - h2=lambda{i}.plot([],{{' ''k'', ''LineWidth'' ,.5'}}); - legend off; hold all; % Plot the CIF - - - - end - 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,... - 'FontName','Arial'); - hx=xlabel('time [s]','Interpreter','none'); - hy=ylabel('Cell Number','Interpreter','none'); - set([hx, hy],'FontName', 'Arial','FontSize',12,'FontWeight','bold'); - -% close all; - - -%% -close all; -numExamples=20; -scrsz = get(0,'ScreenSize'); -fig1=figure('OuterPosition',[scrsz(3)*.1 scrsz(4)*.1 ... - scrsz(3)*.6 scrsz(4)*.9]); -for k=1:numExamples - 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 - fitType='binomial'; - clear nst lambda; - - - for i=1:numCells - tempData = exp(dataMat*coeffs(i,:)'); - if(strcmp(fitType,'poisson')) - lambdaData = tempData; - else - % Conditional Intensity Function for ith cell - lambdaData = tempData./(1+tempData); - end - 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 - - end - - % 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 - % only one spike per bin - - [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 - %Filter - [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 - %Filter - [x_pf, W_pf, x_uf, W_uf] = ... - DecodingAlgorithms.PPDecodeFilterLinear(A, Q, dN,... - MuCoeffs,beta,fitType,delta,gamma,windowTimes,x0); - - - if(k==numExamples) - subplot(4,2,1:4);h1=plot(100*x(1,:),100*x(2,:),'k','LineWidth',3); - hold on; - 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'); - end - 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'); - - - subplot(4,2,5); - 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'); - - subplot(4,2,6); - 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)]); - - subplot(4,2,7); - 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'); - - subplot(4,2,8); - 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'); - - -end - -% close all; -%% Experiment 6 - Hybrid Point Process Filter Example -% NOTE THIS EXAMPLE WAS NOT INCLUDED IN THE FINAL VERSION OF THE PAPER -% This example is based on an implementation of the Hybrid Point Process -% filter described in _General-purpose filter design for neural prosthetic -% devices_ by Srinivasan L, Eden UT, Mitter SK, Brown EN in J Neurophysiol. -% 2007 Oct, 98(4):2456-75. -% - -%% Problem Statement -% Suppose that a process of interest can be modeled as consisting of -% several discrete states where the evolution of the system under each -% state can be modeled as a linear state space model. The observations of -% both the state and the continuous dynamics are not direct, but rather -% observed through how the continuous and discrete states affect the firing -% of a population of neurons. The goal of the hybrid filter is to estimate -% both the continuous dynamics and the underlying system state from only -% the neural population firing (point process observations). -% -% To illustrate the use of this filter, we consider a reaching task. We -% assume two underlying system states s=1="Not Moving"=NM and s=2="Moving"=M. -% Under the "Not Moving" the position of the arm remain constant, -% whereas in the "Moving" state, the position and velocities evolved based -% on the arm acceleration that is modeled as a gaussian white noise -% process. -% -% Under both the "Moving" and "Not Moving" states, the arm evolution state -% vector is -%% -% -% $${\bf{x}} = {[x,y,{v_x},{v_y},{a_x},{a_y}]^T}$$ -% - -%% Generated Simulated Arm Reach - -clear all; -close all; -delta=0.001; -Tmax=2; -time=0:delta:Tmax; -A{2} = [1 0 delta 0 delta^2/2 0; - 0 1 0 delta 0 delta^2/2; - 0 0 1 0 delta 0; - 0 0 0 1 0 delta; - 0 0 0 0 1 0; - 0 0 0 0 0 1]; - -A{1} = [1 0 0 0 0 0; - 0 1 0 0 0 0; - 0 0 0 0 0 0; - 0 0 0 0 0 0; - 0 0 0 0 0 0; - 0 0 0 0 0 0]; -A{1} = [1 0; - 0 1]; - -Px0{2} =1e-6*eye(6,6); -Px0{1} =1e-6*eye(2,2); - -minCovVal = 1e-12; -covVal = 1e-3; - - - -Q{2}=[minCovVal 0 0 0 0 0; - 0 minCovVal 0 0 0 0; - 0 0 minCovVal 0 0 0; - 0 0 0 minCovVal 0 0; - 0 0 0 0 covVal 0; - 0 0 0 0 0 covVal]; - -Q{1}=minCovVal*eye(2,2); - -mstate = zeros(1,length(time)); -ind{1}=1:2; -ind{2}=1:6; - -% Acceleration model -X=zeros(max([size(A{1},1),size(A{2},1)]),length(time)); -p_ij = [.998 .002; - .001 .999]; - -for i = 1:length(time) - - if(i==1) - mstate(i) = 1; - else - if(rand(1,1)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; - x0{1} = X(ind{1},1); - yT{1} = X(ind{1},end); - Pi0 = Px0; - PiT{1} = 1e-9*eye(size(x0{1},1),size(x0{1},1)); - - x0{2} = X(ind{2},1); - yT{2} = X(ind{2},end); - 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_estAll(:,:,n) = X_est; - X_estNTAll(:,:,n) = X_estNT; - S_estAll(n,:)=S_est; - S_estNTAll(n,:)=S_estNT; - MU_estAll(:,:,n)=MU_est; - MU_estNTAll(:,:,n) = MU_estNT; - - - %State Estimate - subplot(4,3,[1 4]); - 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)) - subplot(4,3,[7 10]); - 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]); - - %The movement path - subplot(4,3,[2 3 5 6]); - 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-.'); - - %X-Position - subplot(4,3,8); - 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-.'); - - %Y-Position - subplot(4,3,9); - 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-.'); - - %X-Velocity - subplot(4,3,11); - 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-.'); - - subplot(4,3,12); - 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-.'); - - - - -end - -% -% 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 - subplot(4,3,[1 4]); - hold all; - 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',... - 'Interpreter','none'); - title('Estimated vs. Actual State','FontWeight','bold','Fontsize',... - 12,'FontName','Arial'); - - - - - % Mean State Movement State Probability - subplot(4,3,[7 10]); - plot(time, mean(squeeze(MU_estAll(2,:,:)),2),'b','LineWidth',3); - hold on; - plot(time,mean(squeeze(MU_estNTAll(2,:,:)),2),'g','LineWidth',3); - hold on; - 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,... - 'FontName','Arial'); - - % Mean movement path - subplot(4,3,[2 3 5 6]); - 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'); - - - % Mean X-Positon - subplot(4,3,8); - 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'); - - % Mean Y-Position - subplot(4,3,9); - 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)]); - - % Mean X-Velocity - subplot(4,3,11); - 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'); - - % Mean Y-Velocity - subplot(4,3,12); - 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'); - diff --git a/helpfiles/nSTATPaperExamples.png b/helpfiles/nSTATPaperExamples.png deleted file mode 100644 index 43b3d5b5..00000000 Binary files a/helpfiles/nSTATPaperExamples.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_01.png b/helpfiles/nSTATPaperExamples_01.png deleted file mode 100644 index 3a25dba3..00000000 Binary files a/helpfiles/nSTATPaperExamples_01.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_02.png b/helpfiles/nSTATPaperExamples_02.png deleted file mode 100644 index 4f9f4ede..00000000 Binary files a/helpfiles/nSTATPaperExamples_02.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_03.png b/helpfiles/nSTATPaperExamples_03.png deleted file mode 100644 index 4303f380..00000000 Binary files a/helpfiles/nSTATPaperExamples_03.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_04.png b/helpfiles/nSTATPaperExamples_04.png deleted file mode 100644 index 66fa9781..00000000 Binary files a/helpfiles/nSTATPaperExamples_04.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_05.png b/helpfiles/nSTATPaperExamples_05.png deleted file mode 100644 index ec52a271..00000000 Binary files a/helpfiles/nSTATPaperExamples_05.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_06.png b/helpfiles/nSTATPaperExamples_06.png deleted file mode 100644 index 0f9625c3..00000000 Binary files a/helpfiles/nSTATPaperExamples_06.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_07.png b/helpfiles/nSTATPaperExamples_07.png deleted file mode 100644 index b7088873..00000000 Binary files a/helpfiles/nSTATPaperExamples_07.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_08.png b/helpfiles/nSTATPaperExamples_08.png deleted file mode 100644 index e5b425f2..00000000 Binary files a/helpfiles/nSTATPaperExamples_08.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_09.png b/helpfiles/nSTATPaperExamples_09.png deleted file mode 100644 index 54ecc010..00000000 Binary files a/helpfiles/nSTATPaperExamples_09.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_10.png b/helpfiles/nSTATPaperExamples_10.png deleted file mode 100644 index 80dc0586..00000000 Binary files a/helpfiles/nSTATPaperExamples_10.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_11.png b/helpfiles/nSTATPaperExamples_11.png deleted file mode 100644 index 1a23b379..00000000 Binary files a/helpfiles/nSTATPaperExamples_11.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_12.png b/helpfiles/nSTATPaperExamples_12.png deleted file mode 100644 index 5b13ce90..00000000 Binary files a/helpfiles/nSTATPaperExamples_12.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_13.png b/helpfiles/nSTATPaperExamples_13.png deleted file mode 100644 index c28e8f97..00000000 Binary files a/helpfiles/nSTATPaperExamples_13.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_14.png b/helpfiles/nSTATPaperExamples_14.png deleted file mode 100644 index 2b788cd3..00000000 Binary files a/helpfiles/nSTATPaperExamples_14.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_15.png b/helpfiles/nSTATPaperExamples_15.png deleted file mode 100644 index f4b84a03..00000000 Binary files a/helpfiles/nSTATPaperExamples_15.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_16.png b/helpfiles/nSTATPaperExamples_16.png deleted file mode 100644 index 7030c247..00000000 Binary files a/helpfiles/nSTATPaperExamples_16.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_17.png b/helpfiles/nSTATPaperExamples_17.png deleted file mode 100644 index 809e6ef8..00000000 Binary files a/helpfiles/nSTATPaperExamples_17.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_18.png b/helpfiles/nSTATPaperExamples_18.png deleted file mode 100644 index 4b394c75..00000000 Binary files a/helpfiles/nSTATPaperExamples_18.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_19.png b/helpfiles/nSTATPaperExamples_19.png deleted file mode 100644 index e2597d30..00000000 Binary files a/helpfiles/nSTATPaperExamples_19.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_20.png b/helpfiles/nSTATPaperExamples_20.png deleted file mode 100644 index a089a7c1..00000000 Binary files a/helpfiles/nSTATPaperExamples_20.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_21.png b/helpfiles/nSTATPaperExamples_21.png deleted file mode 100644 index 6a752b47..00000000 Binary files a/helpfiles/nSTATPaperExamples_21.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_22.png b/helpfiles/nSTATPaperExamples_22.png deleted file mode 100644 index 1f6ba5cd..00000000 Binary files a/helpfiles/nSTATPaperExamples_22.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_23.png b/helpfiles/nSTATPaperExamples_23.png deleted file mode 100644 index 5b8683ea..00000000 Binary files a/helpfiles/nSTATPaperExamples_23.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_24.png b/helpfiles/nSTATPaperExamples_24.png deleted file mode 100644 index 1839ad0c..00000000 Binary files a/helpfiles/nSTATPaperExamples_24.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_25.png b/helpfiles/nSTATPaperExamples_25.png deleted file mode 100644 index feb334d0..00000000 Binary files a/helpfiles/nSTATPaperExamples_25.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_eq01306006823101465304.png b/helpfiles/nSTATPaperExamples_eq01306006823101465304.png deleted file mode 100644 index 8b1fad9c..00000000 Binary files a/helpfiles/nSTATPaperExamples_eq01306006823101465304.png and /dev/null differ diff --git a/helpfiles/nSTATPaperExamples_eq06211.png b/helpfiles/nSTATPaperExamples_eq06211.png deleted file mode 100644 index 5d917012..00000000 Binary files a/helpfiles/nSTATPaperExamples_eq06211.png and /dev/null differ diff --git a/helpfiles/nSpikeTrainExamples.html b/helpfiles/nSpikeTrainExamples.html deleted file mode 100644 index b965d340..00000000 --- a/helpfiles/nSpikeTrainExamples.html +++ /dev/null @@ -1,111 +0,0 @@ - - - - - Test the nspikeTrain Class

Test the nspikeTrain Class

Contents

Example 1: Using the nspikeTrain Class

Lets create some pseudo data and plot it.

spikeTimes = sort(rand(1,100))*1;
-spikeTimes = unique(round(spikeTimes*10000)./10000); %round off;
-nst=nspikeTrain(spikeTimes,'n1',.001,0,1);
-figure; nst.plot;
-

We can now change the signal representation of the nspikeTrain and see what effects it has.

100ms bins from 0 to 10 sec. Actual SignalObj representation of the nspikeTrain is not changed because are using getSigRep

figure; nst.resample(1/.1);
-nst.getSigRep.plot;
-

10ms bins from 0 to 10 sec. Actually changing the representation of the signal.

figure; nst.resample(1/.01);
-nst.getSigRep.plot;
-

Get the largest binsize that still maintains a binary signal representation

figure; nst.resample(1/nst.getMaxBinSizeBinary);
-nst.getSigRep.plot;
-
\ No newline at end of file diff --git a/helpfiles/nSpikeTrainExamples.m b/helpfiles/nSpikeTrainExamples.m deleted file mode 100644 index 5b505327..00000000 --- a/helpfiles/nSpikeTrainExamples.m +++ /dev/null @@ -1,30 +0,0 @@ -%% Test the nspikeTrain Class - -%% Example 1: Using the nspikeTrain Class -% Lets create some pseudo data and plot it. - -spikeTimes = sort(rand(1,100))*1; -spikeTimes = unique(round(spikeTimes*10000)./10000); %round off; -nst=nspikeTrain(spikeTimes,'n1',.001,0,1); -figure; nst.plot; - -%% -% We can now change the signal representation of the nspikeTrain and see -% what effects it has. -% -% 100ms bins from 0 to 10 sec. Actual SignalObj representation of the -% nspikeTrain is not changed because are using getSigRep -figure; nst.resample(1/.1); -nst.getSigRep.plot; - -%% -% 10ms bins from 0 to 10 sec. Actually changing the representation of the -% signal. -figure; nst.resample(1/.01); -nst.getSigRep.plot; - -%% -% Get the largest binsize that still maintains a binary signal -% representation -figure; nst.resample(1/nst.getMaxBinSizeBinary); -nst.getSigRep.plot; \ No newline at end of file diff --git a/helpfiles/nSpikeTrainExamples.png b/helpfiles/nSpikeTrainExamples.png deleted file mode 100644 index 14473e83..00000000 Binary files a/helpfiles/nSpikeTrainExamples.png and /dev/null differ diff --git a/helpfiles/nSpikeTrainExamples_01.png b/helpfiles/nSpikeTrainExamples_01.png deleted file mode 100644 index c925f3f5..00000000 Binary files a/helpfiles/nSpikeTrainExamples_01.png and /dev/null differ diff --git a/helpfiles/nSpikeTrainExamples_02.png b/helpfiles/nSpikeTrainExamples_02.png deleted file mode 100644 index 1cd324d9..00000000 Binary files a/helpfiles/nSpikeTrainExamples_02.png and /dev/null differ diff --git a/helpfiles/nSpikeTrainExamples_03.png b/helpfiles/nSpikeTrainExamples_03.png deleted file mode 100644 index 3cc685aa..00000000 Binary files a/helpfiles/nSpikeTrainExamples_03.png and /dev/null differ diff --git a/helpfiles/nSpikeTrainExamples_04.png b/helpfiles/nSpikeTrainExamples_04.png deleted file mode 100644 index 68b0536a..00000000 Binary files a/helpfiles/nSpikeTrainExamples_04.png and /dev/null differ diff --git a/helpfiles/nstCollExamples.html b/helpfiles/nstCollExamples.html deleted file mode 100644 index 70f89e49..00000000 --- a/helpfiles/nstCollExamples.html +++ /dev/null @@ -1,118 +0,0 @@ - - - - - nstCollExamples

Contents

Test the nstColl Class

Create pseudo spike data and create a neural spike collection (nstColl).

close all; clear all;
-for i=1:20
-    spikeTimes = sort(rand(1,100))*1;
-    nst{i}=nspikeTrain(spikeTimes,'',.1);
-    nst{i}.setName(strcat('Neuron',num2str(i)));
-end
-spikeColl=nstColl(nst);
-

Plot the entire collection at once

figure; spikeColl.plot;
-

allow only nspikeTrains 1, 4, and 7 to be visible

spikeColl.setMask([1 4 7]);
-figure; spikeColl.plot;
-

It is possible to obtain nspikeTrains from the collection;

figure;
-n1=spikeColl.getNST(1);     %get the first nspikeTrain in the collection
-subplot(3,1,1); n1.plot;
-subplot(3,1,2); n1.getSigRep.plot; %plot current sigRep
-
-% get a SignalObj representation 1ms bins from 0 to 10 sec
-s1=n1.getSigRep(.001,0,1);
-subplot(3,1,3); s1.plot;
-
\ No newline at end of file diff --git a/helpfiles/nstCollExamples.m b/helpfiles/nstCollExamples.m deleted file mode 100644 index 0762b750..00000000 --- a/helpfiles/nstCollExamples.m +++ /dev/null @@ -1,28 +0,0 @@ - -%% Test the nstColl Class -% Create pseudo spike data and create a neural spike collection (nstColl). -close all; clear all; -for i=1:20 - spikeTimes = sort(rand(1,100))*1; - nst{i}=nspikeTrain(spikeTimes,'',.1); - nst{i}.setName(strcat('Neuron',num2str(i))); -end -spikeColl=nstColl(nst); - -%% -% Plot the entire collection at once -figure; spikeColl.plot; -%% -% allow only nspikeTrains 1, 4, and 7 to be visible -spikeColl.setMask([1 4 7]); -figure; spikeColl.plot; -%% -% It is possible to obtain nspikeTrains from the collection; -figure; -n1=spikeColl.getNST(1); %get the first nspikeTrain in the collection -subplot(3,1,1); n1.plot; -subplot(3,1,2); n1.getSigRep.plot; %plot current sigRep - -% get a SignalObj representation 1ms bins from 0 to 10 sec -s1=n1.getSigRep(.001,0,1); -subplot(3,1,3); s1.plot; diff --git a/helpfiles/nstCollExamples.png b/helpfiles/nstCollExamples.png deleted file mode 100644 index f5e01669..00000000 Binary files a/helpfiles/nstCollExamples.png and /dev/null differ diff --git a/helpfiles/nstCollExamples_01.png b/helpfiles/nstCollExamples_01.png deleted file mode 100644 index 02a10c65..00000000 Binary files a/helpfiles/nstCollExamples_01.png and /dev/null differ diff --git a/helpfiles/nstCollExamples_02.png b/helpfiles/nstCollExamples_02.png deleted file mode 100644 index d6ee579e..00000000 Binary files a/helpfiles/nstCollExamples_02.png and /dev/null differ diff --git a/helpfiles/nstCollExamples_03.png b/helpfiles/nstCollExamples_03.png deleted file mode 100644 index f413e5a7..00000000 Binary files a/helpfiles/nstCollExamples_03.png and /dev/null differ diff --git a/info.xml b/info.xml deleted file mode 100644 index 5e4766d4..00000000 --- a/info.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - -R2008b -nSTAT-Neural Spike Train Analysis -toolbox - -helpfiles - - diff --git a/libraries/NearestSymmetricPositiveDefinite.zip b/libraries/NearestSymmetricPositiveDefinite.zip deleted file mode 100644 index 6147d4a3..00000000 Binary files a/libraries/NearestSymmetricPositiveDefinite.zip and /dev/null differ diff --git a/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/html/nearestSPD_demo.html b/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/html/nearestSPD_demo.html deleted file mode 100755 index e489c8f8..00000000 --- a/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/html/nearestSPD_demo.html +++ /dev/null @@ -1,311 +0,0 @@ - - - - - nearestSPD_demo

Contents

% Neearest Symmetric, Positive Definite matrices
-%
-% This tool saves your covariance matrices, turning them into something
-% that really does have the property you will need. That is, when you are
-% trying to use a covariance matrix in a tool like mvnrnd, it makes no
-% sense if your matrix is not positive definite. So mvnrnd will fail in
-% that case.
-%
-% But sometimes, it appears that users end up with matrices that are NOT
-% symmetric and positive definite (commonly abbreviated as SPD) and they
-% still wish to use them to generate random numbers, often in a tool like
-% mvnrnd. A solution is to find the NEAREST matrix that has the desired
-% property of being SPD.
-%
-% I see the question come up every once in a while, so I looked in the file
-% exchange to see what is in there. All I found was nearest_posdef. While
-% this usually almost works, it could be better. It actually failed
-% completely on most of my test cases, and it was not as fast as I would
-% like, using an optimization. In fact, in the comments to nearest_posdef,
-% a logical alternative was posed. That alternative too has its failures,
-% so I wrote nearestSPD.
-

nearestSPD works on any matrix, and it is reasonably fast.

As a test, randn generates a matrix that is not symmetric nor is it at all positive definite in general.

U = randn(100);
-

nearestSPD will be able to convert U into something that is indeed SPD, and for a 100 by 100 matrix, do it quickly enough

tic,Uj = nearestSPD(U);toc
-
Elapsed time is 0.005662 seconds.
-

The ultimate test of course, is to use chol. If chol returns a second argument that is zero, then MATLAB (and mvnrnd) will be happy!

[R,p] = chol(Uj);
-p
-
p =
-     0
-

As you can see, mvnrnd did not complain at all.

mvnrnd(zeros(1,100),Uj,1)
-
ans =
-  Columns 1 through 7
-    0.6206   -1.3824    0.8017   -0.2522   -1.6578   -3.7084   -3.7997
-  Columns 8 through 14
-    0.2101    0.3997    2.6344   -0.6991   -1.5288   -0.0655    1.2957
-  Columns 15 through 21
-    0.5635   -1.7118    1.4419   -1.9975    0.9702   -0.7824   -0.9111
-  Columns 22 through 28
-   -0.6243   -0.9555   -0.8648    3.9613   -2.9741    0.8544   -1.7191
-  Columns 29 through 35
-    2.2032   -1.1222   -0.8262   -2.1132    2.0091   -0.8174   -0.2515
-  Columns 36 through 42
-   -0.3103   -0.8486   -0.1352   -3.4751    1.5693    0.0114   -2.6613
-  Columns 43 through 49
-   -1.5377   -3.7468    1.7067   -1.0868   -0.3011   -1.2440    0.1904
-  Columns 50 through 56
-   -0.7234    0.9335    2.2027    0.9502    0.1257   -4.4532   -0.0755
-  Columns 57 through 63
-   -1.5667   -0.5757   -0.6353   -0.5836   -2.5437   -0.3126    2.4465
-  Columns 64 through 70
-    2.1601    0.4921    1.4246    3.0354    1.4341    1.5398    5.4932
-  Columns 71 through 77
-    0.2329    0.7502    0.4124   -1.5297    2.3390   -1.3886   -1.6488
-  Columns 78 through 84
-   -0.1357   -1.4652   -3.4085   -0.4108    0.1225    2.0608    2.4883
-  Columns 85 through 91
-    3.1590   -1.7421   -1.3297    5.2951   -0.9421   -0.2190   -1.3316
-  Columns 92 through 98
-    1.1916   -0.3938   -1.3629   -2.7727    0.6032    0.0956   -0.8630
-  Columns 99 through 100
-   -1.7379   -1.5663
-

nearest_posdef would have failed here, as U was not even symmetric, nor does it even have positive diagonal entries.

A realistic test case

Next I'll try a simpler test case. This one will have positive diamgonal entries, and it will indeed be symmetric. So this matrix is much closer to a true covariance matrix than that first mess we tried. And since nearest_posdef was quite slow on a 100x100 matrix, I'll use something smaller.

U = rand(25);
-U = (U + U')/2;
-

Really, it is meaningless as a covariance matrix, because it is clearly not positive definite. We can see many negative eigenvalues, and chol gets upset. So mvnrnd would fail here.

eig(U)'
-[R,p] = chol(U);
-p
-
ans =
-  Columns 1 through 7
-   -1.6748   -1.3845   -1.3380   -1.2144   -1.0673   -0.9856   -0.6934
-  Columns 8 through 14
-   -0.6398   -0.4336   -0.3471   -0.2484   -0.1653   -0.0160    0.1141
-  Columns 15 through 21
-    0.4482    0.5044    0.5448    0.6195    0.6827    0.9338    1.3431
-  Columns 22 through 25
-    1.4957    1.7989    2.0236   12.1344
-p =
-     3
-

nearest_posdef took a bit of time, about 9 seconds on my machine. Admittedly, much of that time was wasted in doing fancy graphics that nobody actually needs if they just need a result.

tic,Um = nearest_posdef(U);toc
-
Elapsed time is 8.768167 seconds.
-

Is Um truly positive definite according to chol? Sadly, it is usually not.

[R,p] = chol(Um);
-p
-
p =
-    18
-

We can see how it failed, by looking at what eig returns.

eig(Um)
-
ans =
-  11.8426 + 0.0000i
-   1.7845 + 0.0000i
-   1.5092 + 0.0000i
-   1.2512 + 0.0000i
-   1.0957 + 0.0000i
-   0.7042 + 0.0000i
-   0.4589 + 0.0000i
-   0.3627 + 0.0000i
-   0.3080 + 0.0000i
-   0.2593 + 0.0000i
-   0.1571 + 0.0000i
-   0.0417 + 0.0000i
-   0.0387 + 0.0000i
-   0.0290 + 0.0000i
-   0.0190 + 0.0000i
-   0.0052 + 0.0000i
-   0.0021 + 0.0000i
-  -0.0000 + 0.0000i
-  -0.0000 - 0.0000i
-  -0.0000 + 0.0000i
-   0.0000 + 0.0000i
-   0.0000 + 0.0000i
-  -0.0000 + 0.0000i
-  -0.0000 - 0.0000i
-   0.0000 + 0.0000i
-

There will usually be some tiny negative eigenvalues

min(real(eig(Um)))
-
ans =
-  -1.8002e-16
-

and sometimes even some imaginary eigenvalues. All usually tiny, but still enough to upset chol.

max(imag(eig(Um)))
-
ans =
-   2.2548e-16
-

The trick suggested by Shuo Han is pretty fast, but it too fails. Since U is already symmetric, we need not symmetrize it first, but chol still gets upset.

Note that the slash used by Shuo was not a good idea. transpose would have been sufficient.

[V,D] = eig(U);
-U_psd = V * max(D,0) / V;
-[R,p] = chol(U_psd);
-p
-
p =
-    13
-

Whereas nearestSPD works nicely.

Uj = nearestSPD(U);
-[R,p] = chol(Uj);
-

nearestSPD returns a solution that is a bit closer to the original matrix U too. Thus comparing 1,2,inf and Frobenious norms, nearestSPD was better under all norms in my tests, even though it is designed only to optimize the Frobenious norm.

[norm(U - Um,1), norm(U - Um,2), norm(U - Um,inf), norm(U - Um,'fro')]
-[norm(U - Uj,1), norm(U - Uj,2), norm(U - Uj,inf), norm(U - Uj,'fro')]
-
ans =
-    3.6183    1.6779    3.6183    3.5082
-ans =
-    3.1950    1.6748    3.1950    3.3743
-
\ No newline at end of file diff --git a/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/html/nearestSPD_demo.png b/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/html/nearestSPD_demo.png deleted file mode 100755 index d1f1f950..00000000 Binary files a/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/html/nearestSPD_demo.png and /dev/null differ diff --git a/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/html/nearestSPD_demo_01.png b/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/html/nearestSPD_demo_01.png deleted file mode 100755 index 6b92f62f..00000000 Binary files a/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/html/nearestSPD_demo_01.png and /dev/null differ diff --git a/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/nearestSPD.m b/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/nearestSPD.m deleted file mode 100755 index caf1a5ef..00000000 --- a/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/nearestSPD.m +++ /dev/null @@ -1,65 +0,0 @@ -function Ahat = nearestSPD(A) -% nearestSPD - the nearest (in Frobenius norm) Symmetric Positive Definite matrix to A -% usage: Ahat = nearestSPD(A) -% -% From Higham: "The nearest symmetric positive semidefinite matrix in the -% Frobenius norm to an arbitrary real matrix A is shown to be (B + H)/2, -% where H is the symmetric polar factor of B=(A + A')/2." -% -% http://www.sciencedirect.com/science/article/pii/0024379588902236 -% -% arguments: (input) -% A - square matrix, which will be converted to the nearest Symmetric -% Positive Definite Matrix. -% -% Arguments: (output) -% Ahat - The matrix chosen as the nearest SPD matrix to A. - -if nargin ~= 1 - error('Exactly one argument must be provided.') -end - -% test for a square matrix A -[r,c] = size(A); -if r ~= c - error('A must be a square matrix.') -elseif (r == 1) && (A <= 0) - % A was scalar and non-positive, so just return eps - Ahat = eps; - return -end - -% symmetrize A into B -B = (A + A')/2; - -% Compute the symmetric polar factor of B. Call it H. -% Clearly H is itself SPD. -[U,Sigma,V] = svd(B); -H = V*Sigma*V'; - -% get Ahat in the above formula -Ahat = (B+H)/2; - -% ensure symmetry -Ahat = (Ahat + Ahat')/2; - -% test that Ahat is in fact PD. if it is not so, then tweak it just a bit. -p = 1; -k = 0; -while p ~= 0 - [R,p] = chol(Ahat); - k = k + 1; - if p ~= 0 - % Ahat failed the chol test. It must have been just a hair off, - % due to floating point trash, so it is simplest now just to - % tweak by adding a tiny multiple of an identity matrix. - mineig = min(eig(Ahat)); - Ahat = Ahat + (-mineig*k.^2 + eps(mineig))*eye(size(A)); - end -end - - - - - - diff --git a/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/nearestSPD_demo.m b/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/nearestSPD_demo.m deleted file mode 100755 index c4209cba..00000000 --- a/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/nearestSPD_demo.m +++ /dev/null @@ -1,111 +0,0 @@ -% Neearest Symmetric, Positive Definite matrices -% -% This tool saves your covariance matrices, turning them into something -% that really does have the property you will need. That is, when you are -% trying to use a covariance matrix in a tool like mvnrnd, it makes no -% sense if your matrix is not positive definite. So mvnrnd will fail in -% that case. -% -% But sometimes, it appears that users end up with matrices that are NOT -% symmetric and positive definite (commonly abbreviated as SPD) and they -% still wish to use them to generate random numbers, often in a tool like -% mvnrnd. A solution is to find the NEAREST matrix (based on minimizing the -% Frobenius norm of the difference) that has the desired property of being -% SPD. -% -% I see the question come up every once in a while, so I looked in the file -% exchange to see what is in there. All I found was nearest_posdef. While -% this usually almost works, it could be better. It actually failed -% completely on most of my test cases, and it was not as fast as I would -% like, using an optimization. In fact, in the comments to nearest_posdef, -% a logical alternative was posed. That alternative too has its failures, -% so I wrote nearestSPD. - -%% nearestSPD works on any matrix, and it is reasonably fast. -% As a test, randn generates a matrix that is not symmetric nor is it at -% all positive definite in general. -U = randn(100); - -%% -% nearestSPD will be able to convert U into something that is indeed SPD, -% and for a 100 by 100 matrix, do it quickly enough -tic,Uj = nearestSPD(U);toc - -%% -% The ultimate test of course, is to use chol. If chol returns a second -% argument that is zero, then MATLAB (and mvnrnd) will be happy! -[R,p] = chol(Uj); -p - -%% -% As you can see, mvnrnd did not complain at all. -mvnrnd(zeros(1,100),Uj,1) - -%% -% nearest_posdef would have failed here, as U was not even symmetric, nor -% does it even have positive diagonal entries. - -%% A realistic test case -% Next I'll try a simpler test case. This one will have positive diamgonal -% entries, and it will indeed be symmetric. So this matrix is much closer -% to a true covariance matrix than that first mess we tried. And since -% nearest_posdef was quite slow on a 100x100 matrix, I'll use something -% smaller. -U = rand(25); -U = (U + U')/2; - -%% -% Really, it is meaningless as a covariance matrix, because it is clearly -% not positive definite. We can see many negative eigenvalues, and chol -% gets upset. So mvnrnd would fail here. -eig(U)' -[R,p] = chol(U); -p - -%% -% nearest_posdef took a bit of time, about 9 seconds on my machine. -% Admittedly, much of that time was wasted in doing fancy graphics that -% nobody actually needs if they just need a result. -tic,Um = nearest_posdef(U);toc - -%% -% Is Um truly positive definite according to chol? Sadly, it is usually not. -[R,p] = chol(Um); -p - -%% -% We can see how it failed, by looking at what eig returns. -eig(Um) -%% -% There will usually be some tiny negative eigenvalues -min(real(eig(Um))) -%% -% and sometimes even some imaginary eigenvalues. All usually tiny, but -% still enough to upset chol. -max(imag(eig(Um))) - -%% -% The trick suggested by Shuo Han is pretty fast, but it too fails. Since -% U is already symmetric, we need not symmetrize it first, but chol still -% gets upset. -% -% Note that the slash used by Shuo was not a good idea. transpose would -% have been sufficient. -[V,D] = eig(U); -U_psd = V * max(D,0) / V; -[R,p] = chol(U_psd); -p - -%% -% Whereas nearestSPD works nicely. -Uj = nearestSPD(U); -[R,p] = chol(Uj); - -%% -% nearestSPD returns a solution that is a bit closer to the original -% matrix U too. Thus comparing 1,2,inf and Frobenius norms, nearestSPD was -% better under all norms in my tests, even though it is designed only to -% optimize the Frobenius norm. -[norm(U - Um,1), norm(U - Um,2), norm(U - Um,inf), norm(U - Um,'fro')] -[norm(U - Uj,1), norm(U - Uj,2), norm(U - Uj,inf), norm(U - Uj,'fro')] - diff --git a/libraries/NearestSymmetricPositiveDefinite/license.txt b/libraries/NearestSymmetricPositiveDefinite/license.txt deleted file mode 100644 index 2ab3ed6a..00000000 --- a/libraries/NearestSymmetricPositiveDefinite/license.txt +++ /dev/null @@ -1,24 +0,0 @@ -Copyright (c) 2013, John D'Errico -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. diff --git a/libraries/fixPSlinestyle.m b/libraries/fixPSlinestyle.m deleted file mode 100644 index 61261354..00000000 --- a/libraries/fixPSlinestyle.m +++ /dev/null @@ -1,88 +0,0 @@ -function fixPSlinestyle(varargin) - -%FIXPSLINESTYLE Fix line styles in exported post script files -% -% FIXPSLINESTYLE(FILENAME) fixes the line styles in the postscript file -% FILENAME. The file will be over-written. This takes a .PS or .EPS file -% and fixes the dotted and dashed line styles to be a little bit more -% esthetically pleasing. It fixes the four default line styles (line, -% dotted, dashed, dashdot). -% -% FIXPSLINESTYLE(FILENAME, NEWFILENAME) creates a new file NEWFILENAME. -% -% This is meant to be used with postscript files created by MATLAB -% (print, export). -% -% Example: -% x = 1:.1:10; -% y1 = sin(x); -% y2 = cos(x); -% h = plot(x, y1, '--', x, y2, '-.'); -% set(h, 'LineWidth', 2); -% grid on; -% legend('line 1', 'line2'); -% -% print -depsc test.eps -% fixPSlinestyle('test.eps', 'fixed_test.eps'); -% -% See also PRINT. - -% Copyright 2005-2010 The MathWorks, Inc. - -% Error checking -error(nargchk(1, 2, nargin)); -if ~ischar(varargin{1}) || (nargin == 2 && ~ischar(varargin{2})) - error('Input arguments must be file names (char).'); -end - -% Make sure the files specified are postscript files -[p1, n1, e1] = fileparts(varargin{1}); -if isempty(e1) || ~ismember(lower(e1), {'.ps', '.eps'}) - error('The extension has to be .ps or .eps'); -end - -% Open file and read it in -fid = fopen(varargin{1}, 'r'); -str = fread(fid); -str = char(str'); -fclose(fid); - -% Find where the line types are defined -id = strfind(str, '% line types:'); -if isempty(id) - error('Could not locate line type definitions in PostScript file.'); -end -id = id(1); -str1 = str(1:id-1); -[line1 , remline ] = strtok(str(id:end), '/'); -[replacestr, remline2] = strtok(remline , '%'); - -% Define the new line styles -solidLine = sprintf('/SO { [] 0 setdash } bdef\n'); -dotLine = sprintf('/DO { [3 dpi2point mul 3 dpi2point mul] 0 setdash } bdef\n'); -dashedLine = sprintf('/DA { [6 dpi2point mul] 0 setdash } bdef\n'); -dashdotLine = sprintf('/DD { [2 dpi2point mul 2 dpi2point mul 6 dpi2point mul 2 dpi2point mul] 0 setdash } bdef\n'); - -% Construct the new file with the new line style definitions -newText = [str1, line1, solidLine, dotLine, dashedLine, dashdotLine, remline2]; - -% Check for output file name -if nargin == 2 - [p2, n2, e2] = fileparts(varargin{2}); - if isempty(e2) - fname = fullfile(p2, [n2, e1]); - else - if strcmpi(e1, e2) - fname = varargin{2}; - else - error('Output file must have same file extension.'); - end - end -else % if not defined, over-write - fname = varargin{1}; -end - -% Write out to file -fid = fopen(fname, 'w'); -fprintf(fid, '%s', newText); -fclose(fid); \ No newline at end of file diff --git a/libraries/rotateXLabels.zip b/libraries/rotateXLabels.zip deleted file mode 100644 index ba882d59..00000000 Binary files a/libraries/rotateXLabels.zip and /dev/null differ diff --git a/libraries/rotateXLabels/license.txt b/libraries/rotateXLabels/license.txt deleted file mode 100644 index 984f36bb..00000000 --- a/libraries/rotateXLabels/license.txt +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2010-2011, The MathWorks, Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in - the documentation and/or other materials provided with the distribution - * Neither the name of the The MathWorks, Inc. nor the names - of its contributors may be used to endorse or promote products derived - from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. diff --git a/libraries/rotateXLabels/rotateXLabels.m b/libraries/rotateXLabels/rotateXLabels.m deleted file mode 100644 index eefc292f..00000000 --- a/libraries/rotateXLabels/rotateXLabels.m +++ /dev/null @@ -1,415 +0,0 @@ -function hh = rotateXLabels( ax, angle, varargin ) -%rotateXLabels: rotate any xticklabels -% -% hh = rotateXLabels(ax,angle) rotates all XLabels on axes AX by an angle -% ANGLE (in degrees). Handles to the resulting text objects are returned -% in HH. -% -% hh = rotateXLabels(ax,angle,param,value,...) also allows one or more -% optional parameters to be specified. Possible parameters are: -% 'MaxStringLength' The maximum length of label to show (default inf) -% -% Examples: -% >> bar( hsv(5)+0.05 ) -% >> days = {'Monday','Tuesday','Wednesday','Thursday','Friday'}; -% >> set( gca(), 'XTickLabel', days ) -% >> rotateXLabels( gca(), 45 ) -% -% See also: GCA, BAR - -% Copyright 2006-2013 The MathWorks Ltd. - -error( nargchk( 2, inf, nargin ) ); -if ~isnumeric( angle ) || ~isscalar( angle ) - error( 'RotateXLabels:BadAngle', 'Parameter ANGLE must be a scalar angle in degrees' ) -end -angle = mod( angle, 360 ); - -[maxStringLength] = parseInputs( varargin{:} ); - -% Get the existing label texts and clear them -[vals, labels] = findAndClearExistingLabels( ax, maxStringLength ); - -% Create the new label texts -h = createNewLabels( ax, vals, labels, angle ); - -% Reposition the axes itself to leave space for the new labels -repositionAxes( ax ); - -% If an X-label is present, move it too -repositionXLabel( ax ); - -% Store angle -setappdata( ax, 'RotateXLabelsAngle', angle ); - -% Only send outputs if requested -if nargout - hh = h; -end - -%-------------------------------------------------------------------------% - function [maxStringLength] = parseInputs( varargin ) - % Parse optional inputs - maxStringLength = inf; - if nargin > 0 - params = varargin(1:2:end); - values = varargin(2:2:end); - if numel( params ) ~= numel( values ) - error( 'RotateXLabels:BadSyntax', 'Optional arguments must be specified as parameter-value pairs.' ); - end - if any( ~cellfun( 'isclass', params, 'char' ) ) - error( 'RotateXLabels:BadSyntax', 'Optional argument names must be specified as strings.' ); - end - for pp=1:numel( params ) - switch upper( params{pp} ) - case 'MAXSTRINGLENGTH' - maxStringLength = values{pp}; - - otherwise - error( 'RotateXLabels:BadParam', 'Optional parameter ''%s'' not recognised.', params{pp} ); - end - end - end - end % parseInputs -%-------------------------------------------------------------------------% - function [vals,labels] = findAndClearExistingLabels( ax, maxStringLength ) - % Get the current tick positions so that we can place our new labels - vals = get( ax, 'XTick' ); - - % Now determine the labels. We look first at for previously rotated labels - % since if there are some the actual labels will be empty. - ex = findall( ax, 'Tag', 'RotatedXTickLabel' ); - if isempty( ex ) - % Store the positions and labels - labels = get( ax, 'XTickLabel' ); - if isempty( labels ) - % No labels! - return - else - if ~iscell(labels) - labels = cellstr(labels); - end - end - % Clear existing labels so that xlabel is in the right position - set( ax, 'XTickLabel', {}, 'XTickMode', 'Manual' ); - setappdata( ax, 'OriginalXTickLabels', labels ); - else - % Labels have already been rotated, so capture them - labels = getappdata( ax, 'OriginalXTickLabels' ); - set(ex, 'DeleteFcn', []); - delete(ex); - end - % Limit the length, if requested - if isfinite( maxStringLength ) - for ll=1:numel( labels ) - if length( labels{ll} ) > maxStringLength - labels{ll} = labels{ll}(1:maxStringLength); - end - end - end - - end % findAndClearExistingLabels -%-------------------------------------------------------------------------% - function restoreDefaultLabels( ax ) - % Restore the default axis behavior - removeListeners( ax ); - - % Try to restore the tick marks and labels - set( ax, 'XTickMode', 'auto', 'XTickLabelMode', 'auto' ); - rmappdata( ax, 'OriginalXTickLabels' ); - - % Try to restore the axes position - if isappdata( ax, 'OriginalAxesPosition' ) - set( ax, 'Position', getappdata( ax, 'OriginalAxesPosition' ) ); - rmappdata( ax, 'OriginalAxesPosition' ); - end - end -%-------------------------------------------------------------------------% - function textLabels = createNewLabels( ax, vals, labels, angle ) - % Work out the ticklabel positions - zlim = get(ax,'ZLim'); - z = zlim(1); - - % We want to work in normalised coords, but this doesn't print - % correctly. Instead we have to work in data units even though it - % makes positioning hard. - ylim = get( ax, 'YLim' ); - if strcmpi( get( ax, 'XAxisLocation' ), 'Top' ) - y = ylim(2); - else - y = ylim(1); - end - - % Now create new text objects in similar positions. - textLabels = -1*ones( numel( vals ), 1 ); - for ll=1:numel(vals) - textLabels(ll) = text( ... - 'Units', 'Data', ... - 'Position', [vals(ll), y, z], ... - 'String', labels{ll}, ... - 'Parent', ax, ... - 'Clipping', 'off', ... - 'Rotation', angle, ... - 'Tag', 'RotatedXTickLabel', ... - 'UserData', vals(ll)); - end - % So that we can respond to CLA and CLOSE, attach a delete - % callback. We only attach it to one label to save massive numbers - % of callbacks during axes shut-down. - set(textLabels(end), 'DeleteFcn', @onTextLabelDeleted); - - % Now copy font properties into the texts - updateFont(); - % Update the alignment of the text - updateAlignment(); - - end % createNewLabels - -%-------------------------------------------------------------------------% - function repositionAxes( ax ) - % Reposition the axes so that there's room for the labels - % Note that we only do this if the OuterPosition is the thing being - % controlled - if ~strcmpi( get( ax, 'ActivePositionProperty' ), 'OuterPosition' ) - return; - end - - % Work out the maximum height required for the labels - labelHeight = getLabelHeight(ax); - - % Remove listeners while we mess around with things, otherwise we'll - % trigger redraws recursively - removeListeners( ax ); - - % Change to normalized units for the position calculation - oldUnits = get( ax, 'Units' ); - set( ax, 'Units', 'Normalized' ); - - % Not sure why, but the extent seems to be proportional to the height of the axes. - % Correct that now. - set( ax, 'ActivePositionProperty', 'Position' ); - pos = get( ax, 'Position' ); - axesHeight = pos(4); - % Make sure we don't adjust away the axes entirely! - heightAdjust = min( (axesHeight*0.9), labelHeight*axesHeight ); - - % Move the axes - if isappdata( ax, 'OriginalAxesPosition' ) - pos = getappdata( ax, 'OriginalAxesPosition' ); - else - pos = get(ax,'Position'); - setappdata( ax, 'OriginalAxesPosition', pos ); - end - if strcmpi( get( ax, 'XAxisLocation' ), 'Bottom' ) - % Move it up and reduce the height - set( ax, 'Position', pos+[0 heightAdjust 0 -heightAdjust] ) - else - % Just reduce the height - set( ax, 'Position', pos+[0 0 0 -heightAdjust] ) - end - set( ax, 'Units', oldUnits ); - set( ax, 'ActivePositionProperty', 'OuterPosition' ); - - % Make sure we find out if axes properties are changed - addListeners( ax ); - - end % repositionAxes - -%-------------------------------------------------------------------------% - function repositionXLabel( ax ) - % Try to work out where to put the xlabel - removeListeners( ax ); - labelHeight = getLabelHeight(ax); - - % Use the new max extent to move the xlabel. We may also need to - % move the title - xlab = get(ax,'XLabel'); - titleh = get( ax, 'Title' ); - set( [xlab,titleh], 'Units', 'Normalized' ); - if strcmpi( get( ax, 'XAxisLocation' ), 'Top' ) - titleExtent = get( xlab, 'Extent' ); - set( xlab, 'Position', [0.5 1+labelHeight-titleExtent(4) 0] ); - set( titleh, 'Position', [0.5 1+labelHeight 0] ); - else - set( xlab, 'Position', [0.5 -labelHeight 0] ); - set( titleh, 'Position', [0.5 1 0] ); - end - addListeners( ax ); - end % repositionXLabel - -%-------------------------------------------------------------------------% - function height = getLabelHeight(ax) - height = 0; - textLabels = findall( ax, 'Tag', 'RotatedXTickLabel' ); - if isempty(textLabels) - return; - end - oldUnits = get( textLabels(1), 'Units' ); - set( textLabels, 'Units', 'Normalized' ); - for ll=1:numel(vals) - ext = get( textLabels(ll), 'Extent' ); - if ext(4) > height - height = ext(4); - end - end - set( textLabels, 'Units', oldUnits ); - end % getLabelExtent - -%-------------------------------------------------------------------------% - function updateFont() - % Update the rotated text fonts when the axes font changes - properties = { - 'FontName' - 'FontSize' - 'FontAngle' - 'FontWeight' - 'FontUnits' - }; - propertyValues = get( ax, properties ); - textLabels = findall( ax, 'Tag', 'RotatedXTickLabel' ); - set( textLabels, properties, propertyValues ); - end % updateFont - - function updateAlignment() - textLabels = findall( ax, 'Tag', 'RotatedXTickLabel' ); - angle = get( textLabels(1), 'Rotation' ); - % Depending on the angle, we may need to change the alignment. We change - % alignments within 5 degrees of each 90 degree orientation. - if strcmpi( get( ax, 'XAxisLocation' ), 'Top' ) - if 0 <= angle && angle < 5 - set( textLabels, 'HorizontalAlignment', 'Center', 'VerticalAlignment', 'Bottom' ); - elseif 5 <= angle && angle < 85 - set( textLabels, 'HorizontalAlignment', 'Left', 'VerticalAlignment', 'Bottom' ); - elseif 85 <= angle && angle < 95 - set( textLabels, 'HorizontalAlignment', 'Left', 'VerticalAlignment', 'Middle' ); - elseif 95 <= angle && angle < 175 - set( textLabels, 'HorizontalAlignment', 'Left', 'VerticalAlignment', 'Top' ); - elseif 175 <= angle && angle < 185 - set( textLabels, 'HorizontalAlignment', 'Center', 'VerticalAlignment', 'Top' ); - elseif 185 <= angle && angle < 265 - set( textLabels, 'HorizontalAlignment', 'Right', 'VerticalAlignment', 'Top' ); - elseif 265 <= angle && angle < 275 - set( textLabels, 'HorizontalAlignment', 'Right', 'VerticalAlignment', 'Middle' ); - elseif 275 <= angle && angle < 355 - set( textLabels, 'HorizontalAlignment', 'Right', 'VerticalAlignment', 'Bottom' ); - else % 355-360 - set( textLabels, 'HorizontalAlignment', 'Center', 'VerticalAlignment', 'Bottom' ); - end - else - if 0 <= angle && angle < 5 - set( textLabels, 'HorizontalAlignment', 'Center', 'VerticalAlignment', 'Top' ); - elseif 5 <= angle && angle < 85 - set( textLabels, 'HorizontalAlignment', 'Right', 'VerticalAlignment', 'Top' ); - elseif 85 <= angle && angle < 95 - set( textLabels, 'HorizontalAlignment', 'Right', 'VerticalAlignment', 'Middle' ); - elseif 95 <= angle && angle < 175 - set( textLabels, 'HorizontalAlignment', 'Right', 'VerticalAlignment', 'Bottom' ); - elseif 175 <= angle && angle < 185 - set( textLabels, 'HorizontalAlignment', 'Center', 'VerticalAlignment', 'Bottom' ); - elseif 185 <= angle && angle < 265 - set( textLabels, 'HorizontalAlignment', 'Left', 'VerticalAlignment', 'Bottom' ); - elseif 265 <= angle && angle < 275 - set( textLabels, 'HorizontalAlignment', 'Left', 'VerticalAlignment', 'Middle' ); - elseif 275 <= angle && angle < 355 - set( textLabels, 'HorizontalAlignment', 'Left', 'VerticalAlignment', 'Top' ); - else % 355-360 - set( textLabels, 'HorizontalAlignment', 'Center', 'VerticalAlignment', 'Top' ); - end - end - end - -%-------------------------------------------------------------------------% - function onAxesFontChanged( ~, ~ ) - updateFont(); - repositionAxes( ax ); - repositionXLabel( ax ); - end % onAxesFontChanged - -%-------------------------------------------------------------------------% - function onAxesPositionChanged( ~, ~ ) - % We need to accept the new position, so remove the appdata before - % redrawing - if isappdata( ax, 'OriginalAxesPosition' ) - rmappdata( ax, 'OriginalAxesPosition' ); - end - if isappdata( ax, 'OriginalXLabelPosition' ) - rmappdata( ax, 'OriginalXLabelPosition' ); - end - repositionAxes( ax ); - repositionXLabel( ax ); - end % onAxesPositionChanged - -%-------------------------------------------------------------------------% - function onXAxisLocationChanged( ~, ~ ) - updateAlignment(); - repositionAxes( ax ); - repositionXLabel( ax ); - end % onXAxisLocationChanged - -%-------------------------------------------------------------------------% - function onAxesLimitsChanged( ~, ~ ) - % The limits have moved, so make sure the labels are still ok - textLabels = findall( ax, 'Tag', 'RotatedXTickLabel' ); - xlim = get( ax, 'XLim' ); - ylim = get( ax, 'YLim' ); - if strcmpi( get( ax, 'XAxisLocation'), 'Bottom' ) - pos = [0 ylim(1)]; - else - pos = [0 ylim(2)]; - end - for tt=1:numel( textLabels ) - xval = get( textLabels(tt), 'UserData' ); - pos(1) = xval; - % If the tick is off the edge, make it invisible - if xvalxlim(2) - set( textLabels(tt), 'Visible', 'off', 'Position', pos ) - elseif ~strcmpi( get( textLabels(tt), 'Visible' ), 'on' ) - set( textLabels(tt), 'Visible', 'on', 'Position', pos ) - else - % Just set the position - set( textLabels(tt), 'Position', pos ); - end - end - - repositionXLabel( ax ); - end % onAxesPositionChanged - -%-------------------------------------------------------------------------% - function onTextLabelDeleted( ~, ~ ) - % The final text label has been deleted. This is likely from a - % "cla" or "close" call, so we should remove all of our dirty - % hacks. - restoreDefaultLabels(ax); - end - -%-------------------------------------------------------------------------% - function addListeners( ax ) - % Create listeners. We store the array of listeners in the axes to make - % sure that they have the same life-span as the axes they are listening to. - axh = handle( ax ); - listeners = [ - handle.listener( axh, findprop( axh, 'FontName' ), 'PropertyPostSet', @onAxesFontChanged ) - handle.listener( axh, findprop( axh, 'FontSize' ), 'PropertyPostSet', @onAxesFontChanged ) - handle.listener( axh, findprop( axh, 'FontWeight' ), 'PropertyPostSet', @onAxesFontChanged ) - handle.listener( axh, findprop( axh, 'FontAngle' ), 'PropertyPostSet', @onAxesFontChanged ) - handle.listener( axh, findprop( axh, 'FontUnits' ), 'PropertyPostSet', @onAxesFontChanged ) - handle.listener( axh, findprop( axh, 'OuterPosition' ), 'PropertyPostSet', @onAxesPositionChanged ) - handle.listener( axh, findprop( axh, 'XLim' ), 'PropertyPostSet', @onAxesLimitsChanged ) - handle.listener( axh, findprop( axh, 'YLim' ), 'PropertyPostSet', @onAxesLimitsChanged ) - handle.listener( axh, findprop( axh, 'XAxisLocation' ), 'PropertyPostSet', @onXAxisLocationChanged ) - ]; - setappdata( ax, 'RotateXLabelsListeners', listeners ); - end % addListeners - -%-------------------------------------------------------------------------% - function removeListeners( ax ) - % Rempove any property listeners whilst we are fiddling with the axes - if isappdata( ax, 'RotateXLabelsListeners' ) - delete( getappdata( ax, 'RotateXLabelsListeners' ) ); - rmappdata( ax, 'RotateXLabelsListeners' ); - end - end % removeListeners - - - -end % EOF \ No newline at end of file diff --git a/libraries/xticklabel_rotate.m b/libraries/xticklabel_rotate.m deleted file mode 100644 index f01eadc2..00000000 --- a/libraries/xticklabel_rotate.m +++ /dev/null @@ -1,212 +0,0 @@ -function hText = xticklabel_rotate(XTick,rot,varargin) -%hText = xticklabel_rotate(XTick,rot,XTickLabel,varargin) Rotate XTickLabel -% -% Syntax: xticklabel_rotate -% -% Input: -% {opt} XTick - vector array of XTick positions & values (numeric) -% uses current XTick values or XTickLabel cell array by -% default (if empty) -% {opt} rot - angle of rotation in degrees, 90° by default -% {opt} XTickLabel - cell array of label strings -% {opt} [var] - "Property-value" pairs passed to text generator -% ex: 'interpreter','none' -% 'Color','m','Fontweight','bold' -% -% Output: hText - handle vector to text labels -% -% Example 1: Rotate existing XTickLabels at their current position by 90° -% xticklabel_rotate -% -% Example 2: Rotate existing XTickLabels at their current position by 45° and change -% font size -% xticklabel_rotate([],45,[],'Fontsize',14) -% -% Example 3: Set the positions of the XTicks and rotate them 90° -% figure; plot([1960:2004],randn(45,1)); xlim([1960 2004]); -% xticklabel_rotate([1960:2:2004]); -% -% Example 4: Use text labels at XTick positions rotated 45° without tex interpreter -% xticklabel_rotate(XTick,45,NameFields,'interpreter','none'); -% -% Example 5: Use text labels rotated 90° at current positions -% xticklabel_rotate([],90,NameFields); -% -% Note : you can not re-run xticklabel_rotate on the same graph. -% -% - - -% This is a modified version of xticklabel_rotate90 by Denis Gilbert -% Modifications include Text labels (in the form of cell array) -% Arbitrary angle rotation -% Output of text handles -% Resizing of axes and title/xlabel/ylabel positions to maintain same overall size -% and keep text on plot -% (handles small window resizing after, but not well due to proportional placement with -% fixed font size. To fix this would require a serious resize function) -% Uses current XTick by default -% Uses current XTickLabel is different from XTick values (meaning has been already defined) - -% Brian FG Katz -% bfgkatz@hotmail.com -% 23-05-03 -% Modified 03-11-06 after user comment -% Allow for exisiting XTickLabel cell array - -% Other m-files required: cell2mat -% Subfunctions: none -% MAT-files required: none -% -% See also: xticklabel_rotate90, TEXT, SET - -% Based on xticklabel_rotate90 -% Author: Denis Gilbert, Ph.D., physical oceanography -% Maurice Lamontagne Institute, Dept. of Fisheries and Oceans Canada -% email: gilbertd@dfo-mpo.gc.ca Web: http://www.qc.dfo-mpo.gc.ca/iml/ -% February 1998; Last revision: 24-Mar-2003 - -% check to see if xticklabel_rotate has already been here (no other reason for this to happen) -if isempty(get(gca,'XTickLabel')), - error('xticklabel_rotate : can not process, either xticklabel_rotate has already been run or XTickLabel field has been erased') ; -end - -% if no XTickLabel AND no XTick are defined use the current XTickLabel -%if nargin < 3 & (~exist('XTick') | isempty(XTick)), -if (nargin < 3 || isempty(varargin{1})) & (~exist('XTick') | isempty(XTick)), - xTickLabels = get(gca,'XTickLabel') ; % use current XTickLabel - if ~iscell(xTickLabels) - % remove trailing spaces if exist (typical with auto generated XTickLabel) - temp1 = num2cell(xTickLabels,2) ; - for loop = 1:length(temp1), - temp1{loop} = deblank(temp1{loop}) ; - end - xTickLabels = temp1 ; - end -varargin = varargin(2:length(varargin)); -end - -% if no XTick is defined use the current XTick -if (~exist('XTick') | isempty(XTick)), - XTick = get(gca,'XTick') ; % use current XTick -end - -%Make XTick a column vector -XTick = XTick(:); - -if ~exist('xTickLabels'), - % Define the xtickLabels - % If XtickLabel is passed as a cell array then use the text - if (length(varargin)>0) & (iscell(varargin{1})), - xTickLabels = varargin{1}; - varargin = varargin(2:length(varargin)); - else - xTickLabels = num2str(XTick); - end -end - -if length(XTick) ~= length(xTickLabels), - error('xticklabel_rotate : must have same number of elements in "XTick" and "XTickLabel"') ; -end - -%Set the Xtick locations and set XTicklabel to an empty string -set(gca,'XTick',XTick,'XTickLabel','') - -if nargin < 2, - rot = 90 ; -end - -% Determine the location of the labels based on the position -% of the xlabel -hxLabel = get(gca,'XLabel'); % Handle to xlabel -xLabelString = get(hxLabel,'String'); - -% if ~isempty(xLabelString) -% warning('You may need to manually reset the XLABEL vertical position') -% end - -set(hxLabel,'Units','data'); -xLabelPosition = get(hxLabel,'Position'); -y = xLabelPosition(2); - -%CODE below was modified following suggestions from Urs Schwarz -y=repmat(y,size(XTick,1),1); -% retrieve current axis' fontsize -fs = get(gca,'fontsize'); - -% Place the new xTickLabels by creating TEXT objects -hText = text(XTick, y, xTickLabels,'fontsize',fs); - -% Rotate the text objects by ROT degrees -set(hText,'Rotation',rot,'HorizontalAlignment','right',varargin{:}) - -% Adjust the size of the axis to accomodate for longest label (like if they are text ones) -% This approach keeps the top of the graph at the same place and tries to keep xlabel at the same place -% This approach keeps the right side of the graph at the same place - -set(get(gca,'xlabel'),'units','data') ; - labxorigpos_data = get(get(gca,'xlabel'),'position') ; -set(get(gca,'ylabel'),'units','data') ; - labyorigpos_data = get(get(gca,'ylabel'),'position') ; -set(get(gca,'title'),'units','data') ; - labtorigpos_data = get(get(gca,'title'),'position') ; - -set(gca,'units','pixel') ; -set(hText,'units','pixel') ; -set(get(gca,'xlabel'),'units','pixel') ; -set(get(gca,'ylabel'),'units','pixel') ; - -origpos = get(gca,'position') ; -textsizes = cell2mat(get(hText,'extent')) ; -longest = max(textsizes(:,4)) ; - -laborigext = get(get(gca,'xlabel'),'extent') ; -laborigpos = get(get(gca,'xlabel'),'position') ; - - -labyorigext = get(get(gca,'ylabel'),'extent') ; -labyorigpos = get(get(gca,'ylabel'),'position') ; -leftlabdist = labyorigpos(1) + labyorigext(1) ; - -% assume first entry is the farthest left -leftpos = get(hText(1),'position') ; -leftext = get(hText(1),'extent') ; -leftdist = leftpos(1) + leftext(1) ; -if leftdist > 0, leftdist = 0 ; end % only correct for off screen problems - -botdist = origpos(2) + laborigpos(2) ; -newpos = [origpos(1)-leftdist longest+botdist origpos(3)+leftdist origpos(4)-longest+origpos(2)-botdist] ; -set(gca,'position',newpos) ; - -% readjust position of nex labels after resize of plot -set(hText,'units','data') ; -for loop= 1:length(hText), - set(hText(loop),'position',[XTick(loop), y(loop)]) ; -end - - -% adjust position of xlabel and ylabel -laborigpos = get(get(gca,'xlabel'),'position') ; -set(get(gca,'xlabel'),'position',[laborigpos(1) laborigpos(2)-longest 0]) ; - -% switch to data coord and fix it all -set(get(gca,'ylabel'),'units','data') ; -set(get(gca,'ylabel'),'position',labyorigpos_data) ; -set(get(gca,'title'),'position',labtorigpos_data) ; - -set(get(gca,'xlabel'),'units','data') ; - labxorigpos_data_new = get(get(gca,'xlabel'),'position') ; -set(get(gca,'xlabel'),'position',[labxorigpos_data(1) labxorigpos_data_new(2)]) ; - - -% Reset all units to normalized to allow future resizing -set(get(gca,'xlabel'),'units','normalized') ; -set(get(gca,'ylabel'),'units','normalized') ; -set(get(gca,'title'),'units','normalized') ; -set(hText,'units','normalized') ; -set(gca,'units','normalized') ; - -if nargout < 1, - clear hText -end - diff --git a/libraries/zernike.zip b/libraries/zernike.zip deleted file mode 100644 index acd84426..00000000 Binary files a/libraries/zernike.zip and /dev/null differ diff --git a/libraries/zernike/zernfun.m b/libraries/zernike/zernfun.m deleted file mode 100644 index d62c54fb..00000000 --- a/libraries/zernike/zernfun.m +++ /dev/null @@ -1,203 +0,0 @@ -function z = zernfun(n,m,r,theta,nflag) -%ZERNFUN Zernike functions of order N and frequency M on the unit circle. -% Z = ZERNFUN(N,M,R,THETA) returns the Zernike functions of order N -% and angular frequency M, evaluated at positions (R,THETA) on the -% unit circle. N is a vector of positive integers (including 0), and -% M is a vector with the same number of elements as N. Each element -% k of M must be a positive integer, with possible values M(k) = -N(k) -% to +N(k) in steps of 2. R is a vector of numbers between 0 and 1, -% and THETA is a vector of angles. R and THETA must have the same -% length. The output Z is a matrix with one column for every (N,M) -% pair, and one row for every (R,THETA) pair. -% -% Z = ZERNFUN(N,M,R,THETA,'norm') returns the normalized Zernike -% functions. The normalization factor sqrt((2-delta(m,0))*(n+1)/pi), -% with delta(m,0) the Kronecker delta, is chosen so that the integral -% of (r * [Znm(r,theta)]^2) over the unit circle (from r=0 to r=1, -% and theta=0 to theta=2*pi) is unity. For the non-normalized -% polynomials, max(Znm(r=1,theta))=1 for all [n,m]. -% -% The Zernike functions are an orthogonal basis on the unit circle. -% They are used in disciplines such as astronomy, optics, and -% optometry to describe functions on a circular domain. -% -% The following table lists the first 15 Zernike functions. -% -% n m Zernike function Normalization -% -------------------------------------------------- -% 0 0 1 1 -% 1 1 r * cos(theta) 2 -% 1 -1 r * sin(theta) 2 -% 2 -2 r^2 * cos(2*theta) sqrt(6) -% 2 0 (2*r^2 - 1) sqrt(3) -% 2 2 r^2 * sin(2*theta) sqrt(6) -% 3 -3 r^3 * cos(3*theta) sqrt(8) -% 3 -1 (3*r^3 - 2*r) * cos(theta) sqrt(8) -% 3 1 (3*r^3 - 2*r) * sin(theta) sqrt(8) -% 3 3 r^3 * sin(3*theta) sqrt(8) -% 4 -4 r^4 * cos(4*theta) sqrt(10) -% 4 -2 (4*r^4 - 3*r^2) * cos(2*theta) sqrt(10) -% 4 0 6*r^4 - 6*r^2 + 1 sqrt(5) -% 4 2 (4*r^4 - 3*r^2) * cos(2*theta) sqrt(10) -% 4 4 r^4 * sin(4*theta) sqrt(10) -% -------------------------------------------------- -% -% Example 1: -% -% % Display the Zernike function Z(n=5,m=1) -% x = -1:0.01:1; -% [X,Y] = meshgrid(x,x); -% [theta,r] = cart2pol(X,Y); -% idx = r<=1; -% z = nan(size(X)); -% z(idx) = zernfun(5,1,r(idx),theta(idx)); -% figure -% pcolor(x,x,z), shading interp -% axis square, colorbar -% title('Zernike function Z_5^1(r,\theta)') -% -% Example 2: -% -% % Display the first 10 Zernike functions -% x = -1:0.01:1; -% [X,Y] = meshgrid(x,x); -% [theta,r] = cart2pol(X,Y); -% idx = r<=1; -% z = nan(size(X)); -% n = [0 1 1 2 2 2 3 3 3 3]; -% m = [0 -1 1 -2 0 2 -3 -1 1 3]; -% Nplot = [4 10 12 16 18 20 22 24 26 28]; -% y = zernfun(n,m,r(idx),theta(idx)); -% figure('Units','normalized') -% for k = 1:10 -% z(idx) = y(:,k); -% subplot(4,7,Nplot(k)) -% pcolor(x,x,z), shading interp -% set(gca,'XTick',[],'YTick',[]) -% axis square -% title(['Z_{' num2str(n(k)) '}^{' num2str(m(k)) '}']) -% end -% -% See also ZERNPOL, ZERNFUN2. - -% Paul Fricker 11/13/2006 - - -% Check and prepare the inputs: -% ----------------------------- -if ( ~any(size(n)==1) ) || ( ~any(size(m)==1) ) - error('zernfun:NMvectors','N and M must be vectors.') -end - -if length(n)~=length(m) - error('zernfun:NMlength','N and M must be the same length.') -end - -n = n(:); -m = m(:); -if any(mod(n-m,2)) - error('zernfun:NMmultiplesof2', ... - 'All N and M must differ by multiples of 2 (including 0).') -end - -if any(m>n) - error('zernfun:MlessthanN', ... - 'Each M must be less than or equal to its corresponding N.') -end - -if any( r>1 | r<0 ) - error('zernfun:Rlessthan1','All R must be between 0 and 1.') -end - -if ( ~any(size(r)==1) ) || ( ~any(size(theta)==1) ) - error('zernfun:RTHvector','R and THETA must be vectors.') -end - -r = r(:); -theta = theta(:); -length_r = length(r); -if length_r~=length(theta) - error('zernfun:RTHlength', ... - 'The number of R- and THETA-values must be equal.') -end - -% Check normalization: -% -------------------- -if nargin==5 && ischar(nflag) - isnorm = strcmpi(nflag,'norm'); - if ~isnorm - error('zernfun:normalization','Unrecognized normalization flag.') - end -else - isnorm = false; -end - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Compute the Zernike Polynomials -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -% Determine the required powers of r: -% ----------------------------------- -m_abs = abs(m); -rpowers = []; -for j = 1:length(n) - rpowers = [rpowers m_abs(j):2:n(j)]; -end -rpowers = unique(rpowers); - -% Pre-compute the values of r raised to the required powers, -% and compile them in a matrix: -% ----------------------------- -if rpowers(1)==0 - rpowern = arrayfun(@(p)r.^p,rpowers(2:end),'UniformOutput',false); - rpowern = cat(2,rpowern{:}); - rpowern = [ones(length_r,1) rpowern]; -else - rpowern = arrayfun(@(p)r.^p,rpowers,'UniformOutput',false); - rpowern = cat(2,rpowern{:}); -end - -% Compute the values of the polynomials: -% -------------------------------------- -y = zeros(length_r,length(n)); -for j = 1:length(n) - s = 0:(n(j)-m_abs(j))/2; - pows = n(j):-2:m_abs(j); - for k = length(s):-1:1 - p = (1-2*mod(s(k),2))* ... - prod(2:(n(j)-s(k)))/ ... - prod(2:s(k))/ ... - prod(2:((n(j)-m_abs(j))/2-s(k)))/ ... - prod(2:((n(j)+m_abs(j))/2-s(k))); - idx = (pows(k)==rpowers); - y(:,j) = y(:,j) + p*rpowern(:,idx); - end - - if isnorm -% y(:,j) = y(:,j)*sqrt((1+(m(j)~=0))*(n(j)+1)/pi); - - if m(j)==0 - y(:,j) = y(:,j)*sqrt((n(j)+1)); - else - y(:,j) = y(:,j)*sqrt(2*(n(j)+1)); - end - - end -end -% END: Compute the Zernike Polynomials -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -% Compute the Zernike functions: -% ------------------------------ -idx_pos = m>0; -idx_neg = m<0; - -z = y; -if any(idx_pos) - z(:,idx_pos) = y(:,idx_pos).*sin(theta*m(idx_pos)'); -end -if any(idx_neg) - z(:,idx_neg) = y(:,idx_neg).*cos(theta*m(idx_neg)'); -end - -% EOF zernfun \ No newline at end of file diff --git a/libraries/zernike/zernfun2.m b/libraries/zernike/zernfun2.m deleted file mode 100644 index 0674cb0c..00000000 --- a/libraries/zernike/zernfun2.m +++ /dev/null @@ -1,76 +0,0 @@ -function z = zernfun2(p,r,theta,nflag) -%ZERNFUN2 Single-index Zernike functions on the unit circle. -% Z = ZERNFUN2(P,R,THETA) returns the Pth Zernike functions evaluated -% at positions (R,THETA) on the unit circle. P is a vector of positive -% integers between 0 and 35, R is a vector of numbers between 0 and 1, -% and THETA is a vector of angles. R and THETA must have the same -% length. The output Z is a matrix with one column for every P-value, -% and one row for every (R,THETA) pair. -% -% Z = ZERNFUN2(P,R,THETA,'norm') returns the normalized Zernike -% functions, defined such that the integral of (r * [Zp(r,theta)]^2) -% over the unit circle (from r=0 to r=1, and theta=0 to theta=2*pi) -% is unity. For the non-normalized polynomials, max(Zp(r=1,theta))=1 -% for all p. -% -% NOTE: ZERNFUN2 returns the same output as ZERNFUN, for the first 36 -% Zernike functions (order N<=7). In some disciplines it is -% traditional to label the first 36 functions using a single mode -% number P instead of separate numbers for the order N and azimuthal -% frequency M. -% -% Example: -% -% % Display the first 16 Zernike functions -% x = -1:0.01:1; -% [X,Y] = meshgrid(x,x); -% [theta,r] = cart2pol(X,Y); -% idx = r<=1; -% p = 0:15; -% z = nan(size(X)); -% y = zernfun2(p,r(idx),theta(idx)); -% figure('Units','normalized') -% for k = 1:length(p) -% z(idx) = y(:,k); -% subplot(4,4,k) -% pcolor(x,x,z), shading interp -% set(gca,'XTick',[],'YTick',[]) -% axis square -% title(['Z_{' num2str(p(k)) '}']) -% end -% -% See also ZERNPOL, ZERNFUN. - -% Paul Fricker 11/13/2006 - - -% Check and prepare the inputs: -% ----------------------------- -if min(size(p))~=1 - error('zernfun2:Pvector','Input P must be vector.') -end - -if any(p)>35 - error('zernfun2:P36', ... - ['ZERNFUN2 only computes the first 36 Zernike functions ' ... - '(P = 0 to 35).']) -end - -% Get the order and frequency corresonding to the function number: -% ---------------------------------------------------------------- -p = p(:); -n = ceil((-3+sqrt(9+8*p))/2); -m = 2*p - n.*(n+2); - -% Pass the inputs to the function ZERNFUN: -% ---------------------------------------- -switch nargin - case 3 - z = zernfun(n,m,r,theta); - case 4 - z = zernfun(n,m,r,theta,nflag); - otherwise - error('zernfun2:nargin','Incorrect number of inputs.') -end - -% EOF zernfun2 \ No newline at end of file diff --git a/libraries/zernike/zernpol.m b/libraries/zernike/zernpol.m deleted file mode 100644 index 1083779a..00000000 --- a/libraries/zernike/zernpol.m +++ /dev/null @@ -1,180 +0,0 @@ -function z = zernpol(n,m,r,nflag) -%ZERNPOL Radial Zernike polynomials of order N and frequency M. -% Z = ZERNPOL(N,M,R) returns the radial Zernike polynomials of -% order N and frequency M, evaluated at R. N is a vector of -% positive integers (including 0), and M is a vector with the -% same number of elements as N. Each element k of M must be a -% positive integer, with possible values M(k) = 0,2,4,...,N(k) -% for N(k) even, and M(k) = 1,3,5,...,N(k) for N(k) odd. R is -% a vector of numbers between 0 and 1. The output Z is a matrix -% with one column for every (N,M) pair, and one row for every -% element in R. -% -% Z = ZERNPOL(N,M,R,'norm') returns the normalized Zernike poly- -% nomials. The normalization factor Nnm = sqrt(2*(n+1)) is -% chosen so that the integral of (r * [Znm(r)]^2) from r=0 to -% r=1 is unity. For the non-normalized polynomials, Znm(r=1)=1 -% for all [n,m]. -% -% The radial Zernike polynomials are the radial portion of the -% Zernike functions, which are an orthogonal basis on the unit -% circle. The series representation of the radial Zernike -% polynomials is -% -% (n-m)/2 -% __ -% m \ s n-2s -% Z(r) = /__ (-1) [(n-s)!/(s!((n-m)/2-s)!((n+m)/2-s)!)] * r -% n s=0 -% -% The following table shows the first 12 polynomials. -% -% n m Zernike polynomial Normalization -% --------------------------------------------- -% 0 0 1 sqrt(2) -% 1 1 r 2 -% 2 0 2*r^2 - 1 sqrt(6) -% 2 2 r^2 sqrt(6) -% 3 1 3*r^3 - 2*r sqrt(8) -% 3 3 r^3 sqrt(8) -% 4 0 6*r^4 - 6*r^2 + 1 sqrt(10) -% 4 2 4*r^4 - 3*r^2 sqrt(10) -% 4 4 r^4 sqrt(10) -% 5 1 10*r^5 - 12*r^3 + 3*r sqrt(12) -% 5 3 5*r^5 - 4*r^3 sqrt(12) -% 5 5 r^5 sqrt(12) -% --------------------------------------------- -% -% Example: -% -% % Display three example Zernike radial polynomials -% r = 0:0.01:1; -% n = [3 2 5]; -% m = [1 2 1]; -% z = zernpol(n,m,r); -% figure -% plot(r,z) -% grid on -% legend('Z_3^1(r)','Z_2^2(r)','Z_5^1(r)','Location','NorthWest') -% -% See also ZERNFUN, ZERNFUN2. - -% A note on the algorithm. -% ------------------------ -% The radial Zernike polynomials are computed using the series -% representation shown in the Help section above. For many special -% functions, direct evaluation using the series representation can -% produce poor numerical results (floating point errors), because -% the summation often involves computing small differences between -% large successive terms in the series. (In such cases, the functions -% are often evaluated using alternative methods such as recurrence -% relations: see the Legendre functions, for example). For the Zernike -% polynomials, however, this problem does not arise, because the -% polynomials are evaluated over the finite domain r = (0,1), and -% because the coefficients for a given polynomial are generally all -% of similar magnitude. -% -% ZERNPOL has been written using a vectorized implementation: multiple -% Zernike polynomials can be computed (i.e., multiple sets of [N,M] -% values can be passed as inputs) for a vector of points R. To achieve -% this vectorization most efficiently, the algorithm in ZERNPOL -% involves pre-determining all the powers p of R that are required to -% compute the outputs, and then compiling the {R^p} into a single -% matrix. This avoids any redundant computation of the R^p, and -% minimizes the sizes of certain intermediate variables. -% -% Paul Fricker 11/13/2006 - - -% Check and prepare the inputs: -% ----------------------------- -if ( ~any(size(n)==1) ) || ( ~any(size(m)==1) ) - error('zernpol:NMvectors','N and M must be vectors.') -end - -if length(n)~=length(m) - error('zernpol:NMlength','N and M must be the same length.') -end - -n = n(:); -m = m(:); -length_n = length(n); - -if any(mod(n-m,2)) - error('zernpol:NMmultiplesof2','All N and M must differ by multiples of 2 (including 0).') -end - -if any(m<0) - error('zernpol:Mpositive','All M must be positive.') -end - -if any(m>n) - error('zernpol:MlessthanN','Each M must be less than or equal to its corresponding N.') -end - -if any( r>1 | r<0 ) - error('zernpol:Rlessthan1','All R must be between 0 and 1.') -end - -if ~any(size(r)==1) - error('zernpol:Rvector','R must be a vector.') -end - -r = r(:); -length_r = length(r); - -if nargin==4 - isnorm = ischar(nflag) & strcmpi(nflag,'norm'); - if ~isnorm - error('zernpol:normalization','Unrecognized normalization flag.') - end -else - isnorm = false; -end - -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -% Compute the Zernike Polynomials -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -% Determine the required powers of r: -% ----------------------------------- -rpowers = []; -for j = 1:length(n) - rpowers = [rpowers m(j):2:n(j)]; -end -rpowers = unique(rpowers); - -% Pre-compute the values of r raised to the required powers, -% and compile them in a matrix: -% ----------------------------- -if rpowers(1)==0 - rpowern = arrayfun(@(p)r.^p,rpowers(2:end),'UniformOutput',false); - rpowern = cat(2,rpowern{:}); - rpowern = [ones(length_r,1) rpowern]; -else - rpowern = arrayfun(@(p)r.^p,rpowers,'UniformOutput',false); - rpowern = cat(2,rpowern{:}); -end - -% Compute the values of the polynomials: -% -------------------------------------- -z = zeros(length_r,length_n); -for j = 1:length_n - s = 0:(n(j)-m(j))/2; - pows = n(j):-2:m(j); - for k = length(s):-1:1 - p = (1-2*mod(s(k),2))* ... - prod(2:(n(j)-s(k)))/ ... - prod(2:s(k))/ ... - prod(2:((n(j)-m(j))/2-s(k)))/ ... - prod(2:((n(j)+m(j))/2-s(k))); - idx = (pows(k)==rpowers); - z(:,j) = z(:,j) + p*rpowern(:,idx); - end - - if isnorm - z(:,j) = z(:,j)*sqrt(2*(n(j)+1)); - end -end - -% EOF zernpol \ No newline at end of file diff --git a/license.txt b/license.txt deleted file mode 100644 index 1301cdfa..00000000 --- a/license.txt +++ /dev/null @@ -1,300 +0,0 @@ - -nSTAT v1 Copyright (C) 2012 Masschusetts Institute of Technology -Cajigas, I, Malik, WQ, Brown, EN -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License as published -by the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -See the GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software Foundation, -Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - \ No newline at end of file diff --git a/matlab_port/Analysis.py b/matlab_port/Analysis.py new file mode 100644 index 00000000..ab56f9e7 --- /dev/null +++ b/matlab_port/Analysis.py @@ -0,0 +1,25 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: Analysis.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +class Analysis: + """Scaffold translated from MATLAB classdef.""" + + def __init__(self, *args, **kwargs) -> None: + self.args = args + self.kwargs = kwargs + + def metadata(self) -> dict[str, object]: + return { + 'source': 'Analysis.m', + 'args_count': len(self.args), + 'kwargs': sorted(list(self.kwargs.keys())), + } diff --git a/matlab_port/CIF.py b/matlab_port/CIF.py new file mode 100644 index 00000000..b4c63244 --- /dev/null +++ b/matlab_port/CIF.py @@ -0,0 +1,25 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: CIF.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +class CIF: + """Scaffold translated from MATLAB classdef.""" + + def __init__(self, *args, **kwargs) -> None: + self.args = args + self.kwargs = kwargs + + def metadata(self) -> dict[str, object]: + return { + 'source': 'CIF.m', + 'args_count': len(self.args), + 'kwargs': sorted(list(self.kwargs.keys())), + } diff --git a/matlab_port/ConfidenceInterval.py b/matlab_port/ConfidenceInterval.py new file mode 100644 index 00000000..4afcfbeb --- /dev/null +++ b/matlab_port/ConfidenceInterval.py @@ -0,0 +1,25 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: ConfidenceInterval.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +class ConfidenceInterval: + """Scaffold translated from MATLAB classdef.""" + + def __init__(self, *args, **kwargs) -> None: + self.args = args + self.kwargs = kwargs + + def metadata(self) -> dict[str, object]: + return { + 'source': 'ConfidenceInterval.m', + 'args_count': len(self.args), + 'kwargs': sorted(list(self.kwargs.keys())), + } diff --git a/matlab_port/ConfigColl.py b/matlab_port/ConfigColl.py new file mode 100644 index 00000000..94ed331e --- /dev/null +++ b/matlab_port/ConfigColl.py @@ -0,0 +1,25 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: ConfigColl.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +class ConfigColl: + """Scaffold translated from MATLAB classdef.""" + + def __init__(self, *args, **kwargs) -> None: + self.args = args + self.kwargs = kwargs + + def metadata(self) -> dict[str, object]: + return { + 'source': 'ConfigColl.m', + 'args_count': len(self.args), + 'kwargs': sorted(list(self.kwargs.keys())), + } diff --git a/matlab_port/CovColl.py b/matlab_port/CovColl.py new file mode 100644 index 00000000..7361212b --- /dev/null +++ b/matlab_port/CovColl.py @@ -0,0 +1,25 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: CovColl.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +class CovColl: + """Scaffold translated from MATLAB classdef.""" + + def __init__(self, *args, **kwargs) -> None: + self.args = args + self.kwargs = kwargs + + def metadata(self) -> dict[str, object]: + return { + 'source': 'CovColl.m', + 'args_count': len(self.args), + 'kwargs': sorted(list(self.kwargs.keys())), + } diff --git a/matlab_port/Covariate.py b/matlab_port/Covariate.py new file mode 100644 index 00000000..75c2ebac --- /dev/null +++ b/matlab_port/Covariate.py @@ -0,0 +1,25 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: Covariate.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +class Covariate: + """Scaffold translated from MATLAB classdef.""" + + def __init__(self, *args, **kwargs) -> None: + self.args = args + self.kwargs = kwargs + + def metadata(self) -> dict[str, object]: + return { + 'source': 'Covariate.m', + 'args_count': len(self.args), + 'kwargs': sorted(list(self.kwargs.keys())), + } diff --git a/matlab_port/DecodingAlgorithms.py b/matlab_port/DecodingAlgorithms.py new file mode 100644 index 00000000..bfa9eee2 --- /dev/null +++ b/matlab_port/DecodingAlgorithms.py @@ -0,0 +1,15 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: DecodingAlgorithms.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +from nstat.decoding_algorithms import DecodingAlgorithms + +__all__ = ['DecodingAlgorithms'] diff --git a/matlab_port/Events.py b/matlab_port/Events.py new file mode 100644 index 00000000..0fb6dce3 --- /dev/null +++ b/matlab_port/Events.py @@ -0,0 +1,25 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: Events.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +class Events: + """Scaffold translated from MATLAB classdef.""" + + def __init__(self, *args, **kwargs) -> None: + self.args = args + self.kwargs = kwargs + + def metadata(self) -> dict[str, object]: + return { + 'source': 'Events.m', + 'args_count': len(self.args), + 'kwargs': sorted(list(self.kwargs.keys())), + } diff --git a/matlab_port/FitResSummary.py b/matlab_port/FitResSummary.py new file mode 100644 index 00000000..e686f7db --- /dev/null +++ b/matlab_port/FitResSummary.py @@ -0,0 +1,25 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: FitResSummary.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +class FitResSummary: + """Scaffold translated from MATLAB classdef.""" + + def __init__(self, *args, **kwargs) -> None: + self.args = args + self.kwargs = kwargs + + def metadata(self) -> dict[str, object]: + return { + 'source': 'FitResSummary.m', + 'args_count': len(self.args), + 'kwargs': sorted(list(self.kwargs.keys())), + } diff --git a/matlab_port/FitResult.py b/matlab_port/FitResult.py new file mode 100644 index 00000000..836accde --- /dev/null +++ b/matlab_port/FitResult.py @@ -0,0 +1,25 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: FitResult.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +class FitResult: + """Scaffold translated from MATLAB classdef.""" + + def __init__(self, *args, **kwargs) -> None: + self.args = args + self.kwargs = kwargs + + def metadata(self) -> dict[str, object]: + return { + 'source': 'FitResult.m', + 'args_count': len(self.args), + 'kwargs': sorted(list(self.kwargs.keys())), + } diff --git a/matlab_port/History.py b/matlab_port/History.py new file mode 100644 index 00000000..425eb9c1 --- /dev/null +++ b/matlab_port/History.py @@ -0,0 +1,25 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: History.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +class History: + """Scaffold translated from MATLAB classdef.""" + + def __init__(self, *args, **kwargs) -> None: + self.args = args + self.kwargs = kwargs + + def metadata(self) -> dict[str, object]: + return { + 'source': 'History.m', + 'args_count': len(self.args), + 'kwargs': sorted(list(self.kwargs.keys())), + } diff --git a/matlab_port/PointProcessSimulationThinning_mdl_r2011a.py b/matlab_port/PointProcessSimulationThinning_mdl_r2011a.py new file mode 100644 index 00000000..1d95f24f --- /dev/null +++ b/matlab_port/PointProcessSimulationThinning_mdl_r2011a.py @@ -0,0 +1,27 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: PointProcessSimulationThinning.mdl.r2011a +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +SOURCE_MODEL = Path(r'/Users/iahncajigas/Library/CloudStorage/Dropbox/Research/Matlab/nSTAT_currentRelease_Local/PointProcessSimulationThinning.mdl.r2011a') + +def load_text(path: str | Path | None = None) -> str: + p = Path(path) if path is not None else SOURCE_MODEL + return p.read_text(encoding='utf-8', errors='ignore') + +def summarize(path: str | Path | None = None) -> dict[str, object]: + text = load_text(path) + lines = text.splitlines() + frame = pd.DataFrame({'line_number': np.arange(1, len(lines) + 1), 'line_text': lines}) + return { + 'source': 'PointProcessSimulationThinning.mdl.r2011a', + 'line_count': int(frame.shape[0]), + 'block_count_guess': int(frame['line_text'].str.contains('Block {', regex=False).sum()), + } diff --git a/matlab_port/PointProcessSimulation_mdl_r2010b.py b/matlab_port/PointProcessSimulation_mdl_r2010b.py new file mode 100644 index 00000000..4ef6bf73 --- /dev/null +++ b/matlab_port/PointProcessSimulation_mdl_r2010b.py @@ -0,0 +1,27 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: PointProcessSimulation.mdl.r2010b +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +SOURCE_MODEL = Path(r'/Users/iahncajigas/Library/CloudStorage/Dropbox/Research/Matlab/nSTAT_currentRelease_Local/PointProcessSimulation.mdl.r2010b') + +def load_text(path: str | Path | None = None) -> str: + p = Path(path) if path is not None else SOURCE_MODEL + return p.read_text(encoding='utf-8', errors='ignore') + +def summarize(path: str | Path | None = None) -> dict[str, object]: + text = load_text(path) + lines = text.splitlines() + frame = pd.DataFrame({'line_number': np.arange(1, len(lines) + 1), 'line_text': lines}) + return { + 'source': 'PointProcessSimulation.mdl.r2010b', + 'line_count': int(frame.shape[0]), + 'block_count_guess': int(frame['line_text'].str.contains('Block {', regex=False).sum()), + } diff --git a/matlab_port/PointProcessSimulation_mdl_r2011a.py b/matlab_port/PointProcessSimulation_mdl_r2011a.py new file mode 100644 index 00000000..90cfcb65 --- /dev/null +++ b/matlab_port/PointProcessSimulation_mdl_r2011a.py @@ -0,0 +1,27 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: PointProcessSimulation.mdl.r2011a +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +SOURCE_MODEL = Path(r'/Users/iahncajigas/Library/CloudStorage/Dropbox/Research/Matlab/nSTAT_currentRelease_Local/PointProcessSimulation.mdl.r2011a') + +def load_text(path: str | Path | None = None) -> str: + p = Path(path) if path is not None else SOURCE_MODEL + return p.read_text(encoding='utf-8', errors='ignore') + +def summarize(path: str | Path | None = None) -> dict[str, object]: + text = load_text(path) + lines = text.splitlines() + frame = pd.DataFrame({'line_number': np.arange(1, len(lines) + 1), 'line_text': lines}) + return { + 'source': 'PointProcessSimulation.mdl.r2011a', + 'line_count': int(frame.shape[0]), + 'block_count_guess': int(frame['line_text'].str.contains('Block {', regex=False).sum()), + } diff --git a/matlab_port/PointProcessSimulation_mdl_r2011b.py b/matlab_port/PointProcessSimulation_mdl_r2011b.py new file mode 100644 index 00000000..c0b8f25b --- /dev/null +++ b/matlab_port/PointProcessSimulation_mdl_r2011b.py @@ -0,0 +1,27 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: PointProcessSimulation.mdl.r2011b +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +SOURCE_MODEL = Path(r'/Users/iahncajigas/Library/CloudStorage/Dropbox/Research/Matlab/nSTAT_currentRelease_Local/PointProcessSimulation.mdl.r2011b') + +def load_text(path: str | Path | None = None) -> str: + p = Path(path) if path is not None else SOURCE_MODEL + return p.read_text(encoding='utf-8', errors='ignore') + +def summarize(path: str | Path | None = None) -> dict[str, object]: + text = load_text(path) + lines = text.splitlines() + frame = pd.DataFrame({'line_number': np.arange(1, len(lines) + 1), 'line_text': lines}) + return { + 'source': 'PointProcessSimulation.mdl.r2011b', + 'line_count': int(frame.shape[0]), + 'block_count_guess': int(frame['line_text'].str.contains('Block {', regex=False).sum()), + } diff --git a/matlab_port/PointProcessSimulation_mdl_r2013a.py b/matlab_port/PointProcessSimulation_mdl_r2013a.py new file mode 100644 index 00000000..5be503e9 --- /dev/null +++ b/matlab_port/PointProcessSimulation_mdl_r2013a.py @@ -0,0 +1,27 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: PointProcessSimulation.mdl.r2013a +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +SOURCE_MODEL = Path(r'/Users/iahncajigas/Library/CloudStorage/Dropbox/Research/Matlab/nSTAT_currentRelease_Local/PointProcessSimulation.mdl.r2013a') + +def load_text(path: str | Path | None = None) -> str: + p = Path(path) if path is not None else SOURCE_MODEL + return p.read_text(encoding='utf-8', errors='ignore') + +def summarize(path: str | Path | None = None) -> dict[str, object]: + text = load_text(path) + lines = text.splitlines() + frame = pd.DataFrame({'line_number': np.arange(1, len(lines) + 1), 'line_text': lines}) + return { + 'source': 'PointProcessSimulation.mdl.r2013a', + 'line_count': int(frame.shape[0]), + 'block_count_guess': int(frame['line_text'].str.contains('Block {', regex=False).sum()), + } diff --git a/matlab_port/SignalObj.py b/matlab_port/SignalObj.py new file mode 100644 index 00000000..bbcd09d6 --- /dev/null +++ b/matlab_port/SignalObj.py @@ -0,0 +1,25 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: SignalObj.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +class SignalObj: + """Scaffold translated from MATLAB classdef.""" + + def __init__(self, *args, **kwargs) -> None: + self.args = args + self.kwargs = kwargs + + def metadata(self) -> dict[str, object]: + return { + 'source': 'SignalObj.m', + 'args_count': len(self.args), + 'kwargs': sorted(list(self.kwargs.keys())), + } diff --git a/matlab_port/TRANSLATION_MAP.json b/matlab_port/TRANSLATION_MAP.json new file mode 100644 index 00000000..7ec83165 --- /dev/null +++ b/matlab_port/TRANSLATION_MAP.json @@ -0,0 +1,339 @@ +{ + "repo_root": "/Users/iahncajigas/Library/CloudStorage/Dropbox/Research/Matlab/nSTAT_currentRelease_Local", + "output_root": "/Users/iahncajigas/Library/CloudStorage/Dropbox/Research/Matlab/nSTAT_currentRelease_Local/python/matlab_port", + "counts": { + "total": 64, + "by_kind": { + "class_scaffold": 16, + "alias": 1, + "mdl_scaffold": 6, + "function_scaffold": 8, + "examples_script": 14, + "script_scaffold": 18, + "paper_examples_entrypoint": 1 + }, + "helpfile_notebooks": 32 + }, + "entries": [ + { + "source": "Analysis.m", + "target": "python/matlab_port/Analysis.py", + "kind": "class_scaffold" + }, + { + "source": "CIF.m", + "target": "python/matlab_port/CIF.py", + "kind": "class_scaffold" + }, + { + "source": "ConfidenceInterval.m", + "target": "python/matlab_port/ConfidenceInterval.py", + "kind": "class_scaffold" + }, + { + "source": "ConfigColl.m", + "target": "python/matlab_port/ConfigColl.py", + "kind": "class_scaffold" + }, + { + "source": "CovColl.m", + "target": "python/matlab_port/CovColl.py", + "kind": "class_scaffold" + }, + { + "source": "Covariate.m", + "target": "python/matlab_port/Covariate.py", + "kind": "class_scaffold" + }, + { + "source": "DecodingAlgorithms.m", + "target": "python/matlab_port/DecodingAlgorithms.py", + "kind": "alias" + }, + { + "source": "Events.m", + "target": "python/matlab_port/Events.py", + "kind": "class_scaffold" + }, + { + "source": "FitResSummary.m", + "target": "python/matlab_port/FitResSummary.py", + "kind": "class_scaffold" + }, + { + "source": "FitResult.m", + "target": "python/matlab_port/FitResult.py", + "kind": "class_scaffold" + }, + { + "source": "History.m", + "target": "python/matlab_port/History.py", + "kind": "class_scaffold" + }, + { + "source": "PointProcessSimulation.mdl.r2010b", + "target": "python/matlab_port/PointProcessSimulation_mdl_r2010b.py", + "kind": "mdl_scaffold" + }, + { + "source": "PointProcessSimulation.mdl.r2011a", + "target": "python/matlab_port/PointProcessSimulation_mdl_r2011a.py", + "kind": "mdl_scaffold" + }, + { + "source": "PointProcessSimulation.mdl.r2011b", + "target": "python/matlab_port/PointProcessSimulation_mdl_r2011b.py", + "kind": "mdl_scaffold" + }, + { + "source": "PointProcessSimulation.mdl.r2013a", + "target": "python/matlab_port/PointProcessSimulation_mdl_r2013a.py", + "kind": "mdl_scaffold" + }, + { + "source": "PointProcessSimulationThinning.mdl.r2011a", + "target": "python/matlab_port/PointProcessSimulationThinning_mdl_r2011a.py", + "kind": "mdl_scaffold" + }, + { + "source": "SignalObj.m", + "target": "python/matlab_port/SignalObj.py", + "kind": "class_scaffold" + }, + { + "source": "Trial.m", + "target": "python/matlab_port/Trial.py", + "kind": "class_scaffold" + }, + { + "source": "TrialConfig.m", + "target": "python/matlab_port/TrialConfig.py", + "kind": "class_scaffold" + }, + { + "source": "data/Explicit Stimulus/GenCovMat.m", + "target": "python/matlab_port/data/Explicit Stimulus/GenCovMat.py", + "kind": "function_scaffold" + }, + { + "source": "helpfiles/AnalysisExamples.m", + "target": "python/matlab_port/helpfiles/AnalysisExamples.py", + "kind": "examples_script" + }, + { + "source": "helpfiles/AnalysisExamples2.m", + "target": "python/matlab_port/helpfiles/AnalysisExamples2.py", + "kind": "script_scaffold" + }, + { + "source": "helpfiles/ClassDefinitions.m", + "target": "python/matlab_port/helpfiles/ClassDefinitions.py", + "kind": "script_scaffold" + }, + { + "source": "helpfiles/ConfigCollExamples.m", + "target": "python/matlab_port/helpfiles/ConfigCollExamples.py", + "kind": "examples_script" + }, + { + "source": "helpfiles/CovCollExamples.m", + "target": "python/matlab_port/helpfiles/CovCollExamples.py", + "kind": "examples_script" + }, + { + "source": "helpfiles/CovariateExamples.m", + "target": "python/matlab_port/helpfiles/CovariateExamples.py", + "kind": "examples_script" + }, + { + "source": "helpfiles/DecodingExample.m", + "target": "python/matlab_port/helpfiles/DecodingExample.py", + "kind": "script_scaffold" + }, + { + "source": "helpfiles/DecodingExampleWithHist.m", + "target": "python/matlab_port/helpfiles/DecodingExampleWithHist.py", + "kind": "script_scaffold" + }, + { + "source": "helpfiles/EventsExamples.m", + "target": "python/matlab_port/helpfiles/EventsExamples.py", + "kind": "examples_script" + }, + { + "source": "helpfiles/Examples.m", + "target": "python/matlab_port/helpfiles/Examples.py", + "kind": "examples_script" + }, + { + "source": "helpfiles/ExplicitStimulusWhiskerData.m", + "target": "python/matlab_port/helpfiles/ExplicitStimulusWhiskerData.py", + "kind": "script_scaffold" + }, + { + "source": "helpfiles/FitResSummaryExamples.m", + "target": "python/matlab_port/helpfiles/FitResSummaryExamples.py", + "kind": "examples_script" + }, + { + "source": "helpfiles/FitResult.m", + "target": "python/matlab_port/helpfiles/FitResult.py", + "kind": "class_scaffold" + }, + { + "source": "helpfiles/FitResultExamples.m", + "target": "python/matlab_port/helpfiles/FitResultExamples.py", + "kind": "examples_script" + }, + { + "source": "helpfiles/HippocampalPlaceCellExample.m", + "target": "python/matlab_port/helpfiles/HippocampalPlaceCellExample.py", + "kind": "script_scaffold" + }, + { + "source": "helpfiles/HistoryExamples.m", + "target": "python/matlab_port/helpfiles/HistoryExamples.py", + "kind": "examples_script" + }, + { + "source": "helpfiles/HybridFilterExample.m", + "target": "python/matlab_port/helpfiles/HybridFilterExample.py", + "kind": "script_scaffold" + }, + { + "source": "helpfiles/NetworkTutorial.m", + "target": "python/matlab_port/helpfiles/NetworkTutorial.py", + "kind": "script_scaffold" + }, + { + "source": "helpfiles/NeuralSpikeAnalysis_top.m", + "target": "python/matlab_port/helpfiles/NeuralSpikeAnalysis_top.py", + "kind": "script_scaffold" + }, + { + "source": "helpfiles/PPSimExample.m", + "target": "python/matlab_port/helpfiles/PPSimExample.py", + "kind": "script_scaffold" + }, + { + "source": "helpfiles/PPThinning.m", + "target": "python/matlab_port/helpfiles/PPThinning.py", + "kind": "script_scaffold" + }, + { + "source": "helpfiles/PSTHEstimation.m", + "target": "python/matlab_port/helpfiles/PSTHEstimation.py", + "kind": "script_scaffold" + }, + { + "source": "helpfiles/SignalObjExamples.m", + "target": "python/matlab_port/helpfiles/SignalObjExamples.py", + "kind": "examples_script" + }, + { + "source": "helpfiles/SimulatedNetwork2.mdl", + "target": "python/matlab_port/helpfiles/SimulatedNetwork2_mdl.py", + "kind": "mdl_scaffold" + }, + { + "source": "helpfiles/StimulusDecode2D.m", + "target": "python/matlab_port/helpfiles/StimulusDecode2D.py", + "kind": "script_scaffold" + }, + { + "source": "helpfiles/TrialConfigExamples.m", + "target": "python/matlab_port/helpfiles/TrialConfigExamples.py", + "kind": "examples_script" + }, + { + "source": "helpfiles/TrialExamples.m", + "target": "python/matlab_port/helpfiles/TrialExamples.py", + "kind": "examples_script" + }, + { + "source": "helpfiles/ValidationDataSet.m", + "target": "python/matlab_port/helpfiles/ValidationDataSet.py", + "kind": "script_scaffold" + }, + { + "source": "helpfiles/mEPSCAnalysis.m", + "target": "python/matlab_port/helpfiles/mEPSCAnalysis.py", + "kind": "script_scaffold" + }, + { + "source": "helpfiles/nSTATPaperExamples.m", + "target": "python/matlab_port/helpfiles/nSTATPaperExamples.py", + "kind": "paper_examples_entrypoint" + }, + { + "source": "helpfiles/nSpikeTrainExamples.m", + "target": "python/matlab_port/helpfiles/nSpikeTrainExamples.py", + "kind": "examples_script" + }, + { + "source": "helpfiles/nstCollExamples.m", + "target": "python/matlab_port/helpfiles/nstCollExamples.py", + "kind": "examples_script" + }, + { + "source": "helpfiles/temp.m", + "target": "python/matlab_port/helpfiles/temp.py", + "kind": "script_scaffold" + }, + { + "source": "libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/nearestSPD.m", + "target": "python/matlab_port/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/nearestSPD.py", + "kind": "function_scaffold" + }, + { + "source": "libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/nearestSPD_demo.m", + "target": "python/matlab_port/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/nearestSPD_demo.py", + "kind": "script_scaffold" + }, + { + "source": "libraries/fixPSlinestyle.m", + "target": "python/matlab_port/libraries/fixPSlinestyle.py", + "kind": "function_scaffold" + }, + { + "source": "libraries/rotateXLabels/rotateXLabels.m", + "target": "python/matlab_port/libraries/rotateXLabels/rotateXLabels.py", + "kind": "function_scaffold" + }, + { + "source": "libraries/xticklabel_rotate.m", + "target": "python/matlab_port/libraries/xticklabel_rotate.py", + "kind": "function_scaffold" + }, + { + "source": "libraries/zernike/zernfun.m", + "target": "python/matlab_port/libraries/zernike/zernfun.py", + "kind": "function_scaffold" + }, + { + "source": "libraries/zernike/zernfun2.m", + "target": "python/matlab_port/libraries/zernike/zernfun2.py", + "kind": "function_scaffold" + }, + { + "source": "libraries/zernike/zernpol.m", + "target": "python/matlab_port/libraries/zernike/zernpol.py", + "kind": "function_scaffold" + }, + { + "source": "nSTAT_Install.m", + "target": "python/matlab_port/nSTAT_Install.py", + "kind": "script_scaffold" + }, + { + "source": "nspikeTrain.m", + "target": "python/matlab_port/nspikeTrain.py", + "kind": "class_scaffold" + }, + { + "source": "nstColl.m", + "target": "python/matlab_port/nstColl.py", + "kind": "class_scaffold" + } + ] +} \ No newline at end of file diff --git a/matlab_port/Trial.py b/matlab_port/Trial.py new file mode 100644 index 00000000..5a2830b3 --- /dev/null +++ b/matlab_port/Trial.py @@ -0,0 +1,25 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: Trial.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +class Trial: + """Scaffold translated from MATLAB classdef.""" + + def __init__(self, *args, **kwargs) -> None: + self.args = args + self.kwargs = kwargs + + def metadata(self) -> dict[str, object]: + return { + 'source': 'Trial.m', + 'args_count': len(self.args), + 'kwargs': sorted(list(self.kwargs.keys())), + } diff --git a/matlab_port/TrialConfig.py b/matlab_port/TrialConfig.py new file mode 100644 index 00000000..b0b8764d --- /dev/null +++ b/matlab_port/TrialConfig.py @@ -0,0 +1,25 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: TrialConfig.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +class TrialConfig: + """Scaffold translated from MATLAB classdef.""" + + def __init__(self, *args, **kwargs) -> None: + self.args = args + self.kwargs = kwargs + + def metadata(self) -> dict[str, object]: + return { + 'source': 'TrialConfig.m', + 'args_count': len(self.args), + 'kwargs': sorted(list(self.kwargs.keys())), + } diff --git a/matlab_port/__init__.py b/matlab_port/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/matlab_port/data/Explicit Stimulus/GenCovMat.py b/matlab_port/data/Explicit Stimulus/GenCovMat.py new file mode 100644 index 00000000..0f536f3f --- /dev/null +++ b/matlab_port/data/Explicit Stimulus/GenCovMat.py @@ -0,0 +1,22 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: data/Explicit Stimulus/GenCovMat.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +def GenCovMat(*, t=None, J=None, y=None, K=None) -> dict[str, object]: + frame = pd.DataFrame({'row': np.arange(3, dtype=int)}) + return { + 'source': 'data/Explicit Stimulus/GenCovMat.m', + 'function': 'GenCovMat', + 'rows': int(frame.shape[0]), + } + +def run(**kwargs) -> dict[str, object]: + return GenCovMat(**kwargs) diff --git a/matlab_port/data/Explicit Stimulus/__init__.py b/matlab_port/data/Explicit Stimulus/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/matlab_port/data/__init__.py b/matlab_port/data/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/matlab_port/helpfiles/AnalysisExamples.py b/matlab_port/helpfiles/AnalysisExamples.py new file mode 100644 index 00000000..6ab1229c --- /dev/null +++ b/matlab_port/helpfiles/AnalysisExamples.py @@ -0,0 +1,64 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/AnalysisExamples.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +import html as _html +import json +import re + +from nstat import SpikeTrain, fit_poisson_glm, psth + +def _parse_html_reference(html_path: Path) -> dict[str, object]: + if not html_path.exists(): + return {'title': html_path.stem, 'sections': [], 'figures': [], 'code_outputs': []} + text = html_path.read_text(encoding='utf-8', errors='ignore') + title_m = re.search(r'(.*?)', text, flags=re.I | re.S) + title = _html.unescape(re.sub(r'<[^>]+>', '', title_m.group(1))).strip() if title_m else html_path.stem + sections = [_html.unescape(re.sub(r'<[^>]+>', '', s)).strip() for s in re.findall(r']*>(.*?)', text, flags=re.I | re.S)] + sections = [s for s in sections if s] + figures = sorted(dict.fromkeys(re.findall(r'src="([^"]+_\d+\.png)"', text, flags=re.I))) + raw_outputs = re.findall(r'
(.*?)
', text, flags=re.I | re.S) + code_outputs = [] + for b in raw_outputs: + cleaned = _html.unescape(re.sub(r'<[^>]+>', '', b)).replace('\xa0', ' ') + cleaned = re.sub(r'\s+', ' ', cleaned).strip() + if cleaned: + code_outputs.append(cleaned) + return {'title': title, 'sections': sections, 'figures': figures, 'code_outputs': code_outputs} + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + html_ref = _parse_html_reference(root / 'helpfiles/AnalysisExamples.html') + # Minimal nSTAT Python smoke using translated utilities. + x = np.linspace(-1.0, 1.0, 200) + y = (np.sin(2.0 * np.pi * x) > 0).astype(float) + fit = fit_poisson_glm(x[:, None], y, offset=np.zeros_like(y), max_iter=40) + trains = [SpikeTrain(np.array([0.1, 0.3, 0.7], dtype=float)), SpikeTrain(np.array([0.2, 0.4], dtype=float))] + psth_rate, _ = psth(trains, np.linspace(0.0, 1.0, 11)) + frame = pd.DataFrame({'section': html_ref['sections']}) + return { + 'source': 'helpfiles/AnalysisExamples.m', + 'html_title': html_ref['title'], + 'section_count': int(len(html_ref['sections'])), + 'sections': html_ref['sections'], + 'figure_count': int(len(html_ref['figures'])), + 'figure_refs': html_ref['figures'], + 'expected_code_outputs': html_ref['code_outputs'][:8], + 'nstat_smoke': { + 'glm_log_likelihood': float(fit.log_likelihood), + 'psth_peak': float(np.max(psth_rate)), + }, + 'table_rows': int(frame.shape[0]), + } + +def main() -> int: + print(json.dumps(run(), indent=2)) + return 0 diff --git a/matlab_port/helpfiles/AnalysisExamples2.py b/matlab_port/helpfiles/AnalysisExamples2.py new file mode 100644 index 00000000..30f80299 --- /dev/null +++ b/matlab_port/helpfiles/AnalysisExamples2.py @@ -0,0 +1,20 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/AnalysisExamples2.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + frame = pd.DataFrame({'line': [1, 2, 3], 'value': [1.0, 2.0, 3.0]}) + return { + 'source': 'helpfiles/AnalysisExamples2.m', + 'repo_root': str(root), + 'demo_mean': float(frame['value'].mean()), + } diff --git a/matlab_port/helpfiles/ClassDefinitions.py b/matlab_port/helpfiles/ClassDefinitions.py new file mode 100644 index 00000000..8b5b0cda --- /dev/null +++ b/matlab_port/helpfiles/ClassDefinitions.py @@ -0,0 +1,20 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/ClassDefinitions.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + frame = pd.DataFrame({'line': [1, 2, 3], 'value': [1.0, 2.0, 3.0]}) + return { + 'source': 'helpfiles/ClassDefinitions.m', + 'repo_root': str(root), + 'demo_mean': float(frame['value'].mean()), + } diff --git a/matlab_port/helpfiles/ConfigCollExamples.py b/matlab_port/helpfiles/ConfigCollExamples.py new file mode 100644 index 00000000..1d89e690 --- /dev/null +++ b/matlab_port/helpfiles/ConfigCollExamples.py @@ -0,0 +1,64 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/ConfigCollExamples.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +import html as _html +import json +import re + +from nstat import SpikeTrain, fit_poisson_glm, psth + +def _parse_html_reference(html_path: Path) -> dict[str, object]: + if not html_path.exists(): + return {'title': html_path.stem, 'sections': [], 'figures': [], 'code_outputs': []} + text = html_path.read_text(encoding='utf-8', errors='ignore') + title_m = re.search(r'(.*?)', text, flags=re.I | re.S) + title = _html.unescape(re.sub(r'<[^>]+>', '', title_m.group(1))).strip() if title_m else html_path.stem + sections = [_html.unescape(re.sub(r'<[^>]+>', '', s)).strip() for s in re.findall(r']*>(.*?)', text, flags=re.I | re.S)] + sections = [s for s in sections if s] + figures = sorted(dict.fromkeys(re.findall(r'src="([^"]+_\d+\.png)"', text, flags=re.I))) + raw_outputs = re.findall(r'
(.*?)
', text, flags=re.I | re.S) + code_outputs = [] + for b in raw_outputs: + cleaned = _html.unescape(re.sub(r'<[^>]+>', '', b)).replace('\xa0', ' ') + cleaned = re.sub(r'\s+', ' ', cleaned).strip() + if cleaned: + code_outputs.append(cleaned) + return {'title': title, 'sections': sections, 'figures': figures, 'code_outputs': code_outputs} + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + html_ref = _parse_html_reference(root / 'helpfiles/ConfigCollExamples.html') + # Minimal nSTAT Python smoke using translated utilities. + x = np.linspace(-1.0, 1.0, 200) + y = (np.sin(2.0 * np.pi * x) > 0).astype(float) + fit = fit_poisson_glm(x[:, None], y, offset=np.zeros_like(y), max_iter=40) + trains = [SpikeTrain(np.array([0.1, 0.3, 0.7], dtype=float)), SpikeTrain(np.array([0.2, 0.4], dtype=float))] + psth_rate, _ = psth(trains, np.linspace(0.0, 1.0, 11)) + frame = pd.DataFrame({'section': html_ref['sections']}) + return { + 'source': 'helpfiles/ConfigCollExamples.m', + 'html_title': html_ref['title'], + 'section_count': int(len(html_ref['sections'])), + 'sections': html_ref['sections'], + 'figure_count': int(len(html_ref['figures'])), + 'figure_refs': html_ref['figures'], + 'expected_code_outputs': html_ref['code_outputs'][:8], + 'nstat_smoke': { + 'glm_log_likelihood': float(fit.log_likelihood), + 'psth_peak': float(np.max(psth_rate)), + }, + 'table_rows': int(frame.shape[0]), + } + +def main() -> int: + print(json.dumps(run(), indent=2)) + return 0 diff --git a/matlab_port/helpfiles/CovCollExamples.py b/matlab_port/helpfiles/CovCollExamples.py new file mode 100644 index 00000000..19acac5b --- /dev/null +++ b/matlab_port/helpfiles/CovCollExamples.py @@ -0,0 +1,64 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/CovCollExamples.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +import html as _html +import json +import re + +from nstat import SpikeTrain, fit_poisson_glm, psth + +def _parse_html_reference(html_path: Path) -> dict[str, object]: + if not html_path.exists(): + return {'title': html_path.stem, 'sections': [], 'figures': [], 'code_outputs': []} + text = html_path.read_text(encoding='utf-8', errors='ignore') + title_m = re.search(r'(.*?)', text, flags=re.I | re.S) + title = _html.unescape(re.sub(r'<[^>]+>', '', title_m.group(1))).strip() if title_m else html_path.stem + sections = [_html.unescape(re.sub(r'<[^>]+>', '', s)).strip() for s in re.findall(r']*>(.*?)', text, flags=re.I | re.S)] + sections = [s for s in sections if s] + figures = sorted(dict.fromkeys(re.findall(r'src="([^"]+_\d+\.png)"', text, flags=re.I))) + raw_outputs = re.findall(r'
(.*?)
', text, flags=re.I | re.S) + code_outputs = [] + for b in raw_outputs: + cleaned = _html.unescape(re.sub(r'<[^>]+>', '', b)).replace('\xa0', ' ') + cleaned = re.sub(r'\s+', ' ', cleaned).strip() + if cleaned: + code_outputs.append(cleaned) + return {'title': title, 'sections': sections, 'figures': figures, 'code_outputs': code_outputs} + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + html_ref = _parse_html_reference(root / 'helpfiles/CovCollExamples.html') + # Minimal nSTAT Python smoke using translated utilities. + x = np.linspace(-1.0, 1.0, 200) + y = (np.sin(2.0 * np.pi * x) > 0).astype(float) + fit = fit_poisson_glm(x[:, None], y, offset=np.zeros_like(y), max_iter=40) + trains = [SpikeTrain(np.array([0.1, 0.3, 0.7], dtype=float)), SpikeTrain(np.array([0.2, 0.4], dtype=float))] + psth_rate, _ = psth(trains, np.linspace(0.0, 1.0, 11)) + frame = pd.DataFrame({'section': html_ref['sections']}) + return { + 'source': 'helpfiles/CovCollExamples.m', + 'html_title': html_ref['title'], + 'section_count': int(len(html_ref['sections'])), + 'sections': html_ref['sections'], + 'figure_count': int(len(html_ref['figures'])), + 'figure_refs': html_ref['figures'], + 'expected_code_outputs': html_ref['code_outputs'][:8], + 'nstat_smoke': { + 'glm_log_likelihood': float(fit.log_likelihood), + 'psth_peak': float(np.max(psth_rate)), + }, + 'table_rows': int(frame.shape[0]), + } + +def main() -> int: + print(json.dumps(run(), indent=2)) + return 0 diff --git a/matlab_port/helpfiles/CovariateExamples.py b/matlab_port/helpfiles/CovariateExamples.py new file mode 100644 index 00000000..43715ec3 --- /dev/null +++ b/matlab_port/helpfiles/CovariateExamples.py @@ -0,0 +1,64 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/CovariateExamples.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +import html as _html +import json +import re + +from nstat import SpikeTrain, fit_poisson_glm, psth + +def _parse_html_reference(html_path: Path) -> dict[str, object]: + if not html_path.exists(): + return {'title': html_path.stem, 'sections': [], 'figures': [], 'code_outputs': []} + text = html_path.read_text(encoding='utf-8', errors='ignore') + title_m = re.search(r'(.*?)', text, flags=re.I | re.S) + title = _html.unescape(re.sub(r'<[^>]+>', '', title_m.group(1))).strip() if title_m else html_path.stem + sections = [_html.unescape(re.sub(r'<[^>]+>', '', s)).strip() for s in re.findall(r']*>(.*?)', text, flags=re.I | re.S)] + sections = [s for s in sections if s] + figures = sorted(dict.fromkeys(re.findall(r'src="([^"]+_\d+\.png)"', text, flags=re.I))) + raw_outputs = re.findall(r'
(.*?)
', text, flags=re.I | re.S) + code_outputs = [] + for b in raw_outputs: + cleaned = _html.unescape(re.sub(r'<[^>]+>', '', b)).replace('\xa0', ' ') + cleaned = re.sub(r'\s+', ' ', cleaned).strip() + if cleaned: + code_outputs.append(cleaned) + return {'title': title, 'sections': sections, 'figures': figures, 'code_outputs': code_outputs} + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + html_ref = _parse_html_reference(root / 'helpfiles/CovariateExamples.html') + # Minimal nSTAT Python smoke using translated utilities. + x = np.linspace(-1.0, 1.0, 200) + y = (np.sin(2.0 * np.pi * x) > 0).astype(float) + fit = fit_poisson_glm(x[:, None], y, offset=np.zeros_like(y), max_iter=40) + trains = [SpikeTrain(np.array([0.1, 0.3, 0.7], dtype=float)), SpikeTrain(np.array([0.2, 0.4], dtype=float))] + psth_rate, _ = psth(trains, np.linspace(0.0, 1.0, 11)) + frame = pd.DataFrame({'section': html_ref['sections']}) + return { + 'source': 'helpfiles/CovariateExamples.m', + 'html_title': html_ref['title'], + 'section_count': int(len(html_ref['sections'])), + 'sections': html_ref['sections'], + 'figure_count': int(len(html_ref['figures'])), + 'figure_refs': html_ref['figures'], + 'expected_code_outputs': html_ref['code_outputs'][:8], + 'nstat_smoke': { + 'glm_log_likelihood': float(fit.log_likelihood), + 'psth_peak': float(np.max(psth_rate)), + }, + 'table_rows': int(frame.shape[0]), + } + +def main() -> int: + print(json.dumps(run(), indent=2)) + return 0 diff --git a/matlab_port/helpfiles/DecodingExample.py b/matlab_port/helpfiles/DecodingExample.py new file mode 100644 index 00000000..2d6d5b40 --- /dev/null +++ b/matlab_port/helpfiles/DecodingExample.py @@ -0,0 +1,20 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/DecodingExample.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + frame = pd.DataFrame({'line': [1, 2, 3], 'value': [1.0, 2.0, 3.0]}) + return { + 'source': 'helpfiles/DecodingExample.m', + 'repo_root': str(root), + 'demo_mean': float(frame['value'].mean()), + } diff --git a/matlab_port/helpfiles/DecodingExampleWithHist.py b/matlab_port/helpfiles/DecodingExampleWithHist.py new file mode 100644 index 00000000..e83aa024 --- /dev/null +++ b/matlab_port/helpfiles/DecodingExampleWithHist.py @@ -0,0 +1,20 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/DecodingExampleWithHist.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + frame = pd.DataFrame({'line': [1, 2, 3], 'value': [1.0, 2.0, 3.0]}) + return { + 'source': 'helpfiles/DecodingExampleWithHist.m', + 'repo_root': str(root), + 'demo_mean': float(frame['value'].mean()), + } diff --git a/matlab_port/helpfiles/EventsExamples.py b/matlab_port/helpfiles/EventsExamples.py new file mode 100644 index 00000000..4dbb7a29 --- /dev/null +++ b/matlab_port/helpfiles/EventsExamples.py @@ -0,0 +1,64 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/EventsExamples.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +import html as _html +import json +import re + +from nstat import SpikeTrain, fit_poisson_glm, psth + +def _parse_html_reference(html_path: Path) -> dict[str, object]: + if not html_path.exists(): + return {'title': html_path.stem, 'sections': [], 'figures': [], 'code_outputs': []} + text = html_path.read_text(encoding='utf-8', errors='ignore') + title_m = re.search(r'(.*?)', text, flags=re.I | re.S) + title = _html.unescape(re.sub(r'<[^>]+>', '', title_m.group(1))).strip() if title_m else html_path.stem + sections = [_html.unescape(re.sub(r'<[^>]+>', '', s)).strip() for s in re.findall(r']*>(.*?)', text, flags=re.I | re.S)] + sections = [s for s in sections if s] + figures = sorted(dict.fromkeys(re.findall(r'src="([^"]+_\d+\.png)"', text, flags=re.I))) + raw_outputs = re.findall(r'
(.*?)
', text, flags=re.I | re.S) + code_outputs = [] + for b in raw_outputs: + cleaned = _html.unescape(re.sub(r'<[^>]+>', '', b)).replace('\xa0', ' ') + cleaned = re.sub(r'\s+', ' ', cleaned).strip() + if cleaned: + code_outputs.append(cleaned) + return {'title': title, 'sections': sections, 'figures': figures, 'code_outputs': code_outputs} + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + html_ref = _parse_html_reference(root / 'helpfiles/EventsExamples.html') + # Minimal nSTAT Python smoke using translated utilities. + x = np.linspace(-1.0, 1.0, 200) + y = (np.sin(2.0 * np.pi * x) > 0).astype(float) + fit = fit_poisson_glm(x[:, None], y, offset=np.zeros_like(y), max_iter=40) + trains = [SpikeTrain(np.array([0.1, 0.3, 0.7], dtype=float)), SpikeTrain(np.array([0.2, 0.4], dtype=float))] + psth_rate, _ = psth(trains, np.linspace(0.0, 1.0, 11)) + frame = pd.DataFrame({'section': html_ref['sections']}) + return { + 'source': 'helpfiles/EventsExamples.m', + 'html_title': html_ref['title'], + 'section_count': int(len(html_ref['sections'])), + 'sections': html_ref['sections'], + 'figure_count': int(len(html_ref['figures'])), + 'figure_refs': html_ref['figures'], + 'expected_code_outputs': html_ref['code_outputs'][:8], + 'nstat_smoke': { + 'glm_log_likelihood': float(fit.log_likelihood), + 'psth_peak': float(np.max(psth_rate)), + }, + 'table_rows': int(frame.shape[0]), + } + +def main() -> int: + print(json.dumps(run(), indent=2)) + return 0 diff --git a/matlab_port/helpfiles/Examples.py b/matlab_port/helpfiles/Examples.py new file mode 100644 index 00000000..f88789ad --- /dev/null +++ b/matlab_port/helpfiles/Examples.py @@ -0,0 +1,64 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/Examples.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +import html as _html +import json +import re + +from nstat import SpikeTrain, fit_poisson_glm, psth + +def _parse_html_reference(html_path: Path) -> dict[str, object]: + if not html_path.exists(): + return {'title': html_path.stem, 'sections': [], 'figures': [], 'code_outputs': []} + text = html_path.read_text(encoding='utf-8', errors='ignore') + title_m = re.search(r'(.*?)', text, flags=re.I | re.S) + title = _html.unescape(re.sub(r'<[^>]+>', '', title_m.group(1))).strip() if title_m else html_path.stem + sections = [_html.unescape(re.sub(r'<[^>]+>', '', s)).strip() for s in re.findall(r']*>(.*?)', text, flags=re.I | re.S)] + sections = [s for s in sections if s] + figures = sorted(dict.fromkeys(re.findall(r'src="([^"]+_\d+\.png)"', text, flags=re.I))) + raw_outputs = re.findall(r'
(.*?)
', text, flags=re.I | re.S) + code_outputs = [] + for b in raw_outputs: + cleaned = _html.unescape(re.sub(r'<[^>]+>', '', b)).replace('\xa0', ' ') + cleaned = re.sub(r'\s+', ' ', cleaned).strip() + if cleaned: + code_outputs.append(cleaned) + return {'title': title, 'sections': sections, 'figures': figures, 'code_outputs': code_outputs} + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + html_ref = _parse_html_reference(root / 'helpfiles/Examples.html') + # Minimal nSTAT Python smoke using translated utilities. + x = np.linspace(-1.0, 1.0, 200) + y = (np.sin(2.0 * np.pi * x) > 0).astype(float) + fit = fit_poisson_glm(x[:, None], y, offset=np.zeros_like(y), max_iter=40) + trains = [SpikeTrain(np.array([0.1, 0.3, 0.7], dtype=float)), SpikeTrain(np.array([0.2, 0.4], dtype=float))] + psth_rate, _ = psth(trains, np.linspace(0.0, 1.0, 11)) + frame = pd.DataFrame({'section': html_ref['sections']}) + return { + 'source': 'helpfiles/Examples.m', + 'html_title': html_ref['title'], + 'section_count': int(len(html_ref['sections'])), + 'sections': html_ref['sections'], + 'figure_count': int(len(html_ref['figures'])), + 'figure_refs': html_ref['figures'], + 'expected_code_outputs': html_ref['code_outputs'][:8], + 'nstat_smoke': { + 'glm_log_likelihood': float(fit.log_likelihood), + 'psth_peak': float(np.max(psth_rate)), + }, + 'table_rows': int(frame.shape[0]), + } + +def main() -> int: + print(json.dumps(run(), indent=2)) + return 0 diff --git a/matlab_port/helpfiles/ExplicitStimulusWhiskerData.py b/matlab_port/helpfiles/ExplicitStimulusWhiskerData.py new file mode 100644 index 00000000..f6cdb5fb --- /dev/null +++ b/matlab_port/helpfiles/ExplicitStimulusWhiskerData.py @@ -0,0 +1,20 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/ExplicitStimulusWhiskerData.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + frame = pd.DataFrame({'line': [1, 2, 3], 'value': [1.0, 2.0, 3.0]}) + return { + 'source': 'helpfiles/ExplicitStimulusWhiskerData.m', + 'repo_root': str(root), + 'demo_mean': float(frame['value'].mean()), + } diff --git a/matlab_port/helpfiles/FitResSummaryExamples.py b/matlab_port/helpfiles/FitResSummaryExamples.py new file mode 100644 index 00000000..85d5dc04 --- /dev/null +++ b/matlab_port/helpfiles/FitResSummaryExamples.py @@ -0,0 +1,64 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/FitResSummaryExamples.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +import html as _html +import json +import re + +from nstat import SpikeTrain, fit_poisson_glm, psth + +def _parse_html_reference(html_path: Path) -> dict[str, object]: + if not html_path.exists(): + return {'title': html_path.stem, 'sections': [], 'figures': [], 'code_outputs': []} + text = html_path.read_text(encoding='utf-8', errors='ignore') + title_m = re.search(r'(.*?)', text, flags=re.I | re.S) + title = _html.unescape(re.sub(r'<[^>]+>', '', title_m.group(1))).strip() if title_m else html_path.stem + sections = [_html.unescape(re.sub(r'<[^>]+>', '', s)).strip() for s in re.findall(r']*>(.*?)', text, flags=re.I | re.S)] + sections = [s for s in sections if s] + figures = sorted(dict.fromkeys(re.findall(r'src="([^"]+_\d+\.png)"', text, flags=re.I))) + raw_outputs = re.findall(r'
(.*?)
', text, flags=re.I | re.S) + code_outputs = [] + for b in raw_outputs: + cleaned = _html.unescape(re.sub(r'<[^>]+>', '', b)).replace('\xa0', ' ') + cleaned = re.sub(r'\s+', ' ', cleaned).strip() + if cleaned: + code_outputs.append(cleaned) + return {'title': title, 'sections': sections, 'figures': figures, 'code_outputs': code_outputs} + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + html_ref = _parse_html_reference(root / 'helpfiles/FitResSummaryExamples.html') + # Minimal nSTAT Python smoke using translated utilities. + x = np.linspace(-1.0, 1.0, 200) + y = (np.sin(2.0 * np.pi * x) > 0).astype(float) + fit = fit_poisson_glm(x[:, None], y, offset=np.zeros_like(y), max_iter=40) + trains = [SpikeTrain(np.array([0.1, 0.3, 0.7], dtype=float)), SpikeTrain(np.array([0.2, 0.4], dtype=float))] + psth_rate, _ = psth(trains, np.linspace(0.0, 1.0, 11)) + frame = pd.DataFrame({'section': html_ref['sections']}) + return { + 'source': 'helpfiles/FitResSummaryExamples.m', + 'html_title': html_ref['title'], + 'section_count': int(len(html_ref['sections'])), + 'sections': html_ref['sections'], + 'figure_count': int(len(html_ref['figures'])), + 'figure_refs': html_ref['figures'], + 'expected_code_outputs': html_ref['code_outputs'][:8], + 'nstat_smoke': { + 'glm_log_likelihood': float(fit.log_likelihood), + 'psth_peak': float(np.max(psth_rate)), + }, + 'table_rows': int(frame.shape[0]), + } + +def main() -> int: + print(json.dumps(run(), indent=2)) + return 0 diff --git a/matlab_port/helpfiles/FitResult.py b/matlab_port/helpfiles/FitResult.py new file mode 100644 index 00000000..72be1f11 --- /dev/null +++ b/matlab_port/helpfiles/FitResult.py @@ -0,0 +1,25 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/FitResult.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +class FitResult: + """Scaffold translated from MATLAB classdef.""" + + def __init__(self, *args, **kwargs) -> None: + self.args = args + self.kwargs = kwargs + + def metadata(self) -> dict[str, object]: + return { + 'source': 'helpfiles/FitResult.m', + 'args_count': len(self.args), + 'kwargs': sorted(list(self.kwargs.keys())), + } diff --git a/matlab_port/helpfiles/FitResultExamples.py b/matlab_port/helpfiles/FitResultExamples.py new file mode 100644 index 00000000..7e327913 --- /dev/null +++ b/matlab_port/helpfiles/FitResultExamples.py @@ -0,0 +1,64 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/FitResultExamples.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +import html as _html +import json +import re + +from nstat import SpikeTrain, fit_poisson_glm, psth + +def _parse_html_reference(html_path: Path) -> dict[str, object]: + if not html_path.exists(): + return {'title': html_path.stem, 'sections': [], 'figures': [], 'code_outputs': []} + text = html_path.read_text(encoding='utf-8', errors='ignore') + title_m = re.search(r'(.*?)', text, flags=re.I | re.S) + title = _html.unescape(re.sub(r'<[^>]+>', '', title_m.group(1))).strip() if title_m else html_path.stem + sections = [_html.unescape(re.sub(r'<[^>]+>', '', s)).strip() for s in re.findall(r']*>(.*?)', text, flags=re.I | re.S)] + sections = [s for s in sections if s] + figures = sorted(dict.fromkeys(re.findall(r'src="([^"]+_\d+\.png)"', text, flags=re.I))) + raw_outputs = re.findall(r'
(.*?)
', text, flags=re.I | re.S) + code_outputs = [] + for b in raw_outputs: + cleaned = _html.unescape(re.sub(r'<[^>]+>', '', b)).replace('\xa0', ' ') + cleaned = re.sub(r'\s+', ' ', cleaned).strip() + if cleaned: + code_outputs.append(cleaned) + return {'title': title, 'sections': sections, 'figures': figures, 'code_outputs': code_outputs} + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + html_ref = _parse_html_reference(root / 'helpfiles/FitResultExamples.html') + # Minimal nSTAT Python smoke using translated utilities. + x = np.linspace(-1.0, 1.0, 200) + y = (np.sin(2.0 * np.pi * x) > 0).astype(float) + fit = fit_poisson_glm(x[:, None], y, offset=np.zeros_like(y), max_iter=40) + trains = [SpikeTrain(np.array([0.1, 0.3, 0.7], dtype=float)), SpikeTrain(np.array([0.2, 0.4], dtype=float))] + psth_rate, _ = psth(trains, np.linspace(0.0, 1.0, 11)) + frame = pd.DataFrame({'section': html_ref['sections']}) + return { + 'source': 'helpfiles/FitResultExamples.m', + 'html_title': html_ref['title'], + 'section_count': int(len(html_ref['sections'])), + 'sections': html_ref['sections'], + 'figure_count': int(len(html_ref['figures'])), + 'figure_refs': html_ref['figures'], + 'expected_code_outputs': html_ref['code_outputs'][:8], + 'nstat_smoke': { + 'glm_log_likelihood': float(fit.log_likelihood), + 'psth_peak': float(np.max(psth_rate)), + }, + 'table_rows': int(frame.shape[0]), + } + +def main() -> int: + print(json.dumps(run(), indent=2)) + return 0 diff --git a/matlab_port/helpfiles/HippocampalPlaceCellExample.py b/matlab_port/helpfiles/HippocampalPlaceCellExample.py new file mode 100644 index 00000000..c87e5ad9 --- /dev/null +++ b/matlab_port/helpfiles/HippocampalPlaceCellExample.py @@ -0,0 +1,20 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/HippocampalPlaceCellExample.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + frame = pd.DataFrame({'line': [1, 2, 3], 'value': [1.0, 2.0, 3.0]}) + return { + 'source': 'helpfiles/HippocampalPlaceCellExample.m', + 'repo_root': str(root), + 'demo_mean': float(frame['value'].mean()), + } diff --git a/matlab_port/helpfiles/HistoryExamples.py b/matlab_port/helpfiles/HistoryExamples.py new file mode 100644 index 00000000..053112db --- /dev/null +++ b/matlab_port/helpfiles/HistoryExamples.py @@ -0,0 +1,64 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/HistoryExamples.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +import html as _html +import json +import re + +from nstat import SpikeTrain, fit_poisson_glm, psth + +def _parse_html_reference(html_path: Path) -> dict[str, object]: + if not html_path.exists(): + return {'title': html_path.stem, 'sections': [], 'figures': [], 'code_outputs': []} + text = html_path.read_text(encoding='utf-8', errors='ignore') + title_m = re.search(r'(.*?)', text, flags=re.I | re.S) + title = _html.unescape(re.sub(r'<[^>]+>', '', title_m.group(1))).strip() if title_m else html_path.stem + sections = [_html.unescape(re.sub(r'<[^>]+>', '', s)).strip() for s in re.findall(r']*>(.*?)', text, flags=re.I | re.S)] + sections = [s for s in sections if s] + figures = sorted(dict.fromkeys(re.findall(r'src="([^"]+_\d+\.png)"', text, flags=re.I))) + raw_outputs = re.findall(r'
(.*?)
', text, flags=re.I | re.S) + code_outputs = [] + for b in raw_outputs: + cleaned = _html.unescape(re.sub(r'<[^>]+>', '', b)).replace('\xa0', ' ') + cleaned = re.sub(r'\s+', ' ', cleaned).strip() + if cleaned: + code_outputs.append(cleaned) + return {'title': title, 'sections': sections, 'figures': figures, 'code_outputs': code_outputs} + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + html_ref = _parse_html_reference(root / 'helpfiles/HistoryExamples.html') + # Minimal nSTAT Python smoke using translated utilities. + x = np.linspace(-1.0, 1.0, 200) + y = (np.sin(2.0 * np.pi * x) > 0).astype(float) + fit = fit_poisson_glm(x[:, None], y, offset=np.zeros_like(y), max_iter=40) + trains = [SpikeTrain(np.array([0.1, 0.3, 0.7], dtype=float)), SpikeTrain(np.array([0.2, 0.4], dtype=float))] + psth_rate, _ = psth(trains, np.linspace(0.0, 1.0, 11)) + frame = pd.DataFrame({'section': html_ref['sections']}) + return { + 'source': 'helpfiles/HistoryExamples.m', + 'html_title': html_ref['title'], + 'section_count': int(len(html_ref['sections'])), + 'sections': html_ref['sections'], + 'figure_count': int(len(html_ref['figures'])), + 'figure_refs': html_ref['figures'], + 'expected_code_outputs': html_ref['code_outputs'][:8], + 'nstat_smoke': { + 'glm_log_likelihood': float(fit.log_likelihood), + 'psth_peak': float(np.max(psth_rate)), + }, + 'table_rows': int(frame.shape[0]), + } + +def main() -> int: + print(json.dumps(run(), indent=2)) + return 0 diff --git a/matlab_port/helpfiles/HybridFilterExample.py b/matlab_port/helpfiles/HybridFilterExample.py new file mode 100644 index 00000000..03f4065c --- /dev/null +++ b/matlab_port/helpfiles/HybridFilterExample.py @@ -0,0 +1,20 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/HybridFilterExample.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + frame = pd.DataFrame({'line': [1, 2, 3], 'value': [1.0, 2.0, 3.0]}) + return { + 'source': 'helpfiles/HybridFilterExample.m', + 'repo_root': str(root), + 'demo_mean': float(frame['value'].mean()), + } diff --git a/matlab_port/helpfiles/NetworkTutorial.py b/matlab_port/helpfiles/NetworkTutorial.py new file mode 100644 index 00000000..aa8327a1 --- /dev/null +++ b/matlab_port/helpfiles/NetworkTutorial.py @@ -0,0 +1,20 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/NetworkTutorial.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + frame = pd.DataFrame({'line': [1, 2, 3], 'value': [1.0, 2.0, 3.0]}) + return { + 'source': 'helpfiles/NetworkTutorial.m', + 'repo_root': str(root), + 'demo_mean': float(frame['value'].mean()), + } diff --git a/matlab_port/helpfiles/NeuralSpikeAnalysis_top.py b/matlab_port/helpfiles/NeuralSpikeAnalysis_top.py new file mode 100644 index 00000000..9a649ebe --- /dev/null +++ b/matlab_port/helpfiles/NeuralSpikeAnalysis_top.py @@ -0,0 +1,20 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/NeuralSpikeAnalysis_top.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + frame = pd.DataFrame({'line': [1, 2, 3], 'value': [1.0, 2.0, 3.0]}) + return { + 'source': 'helpfiles/NeuralSpikeAnalysis_top.m', + 'repo_root': str(root), + 'demo_mean': float(frame['value'].mean()), + } diff --git a/matlab_port/helpfiles/PPSimExample.py b/matlab_port/helpfiles/PPSimExample.py new file mode 100644 index 00000000..4ea60c3c --- /dev/null +++ b/matlab_port/helpfiles/PPSimExample.py @@ -0,0 +1,20 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/PPSimExample.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + frame = pd.DataFrame({'line': [1, 2, 3], 'value': [1.0, 2.0, 3.0]}) + return { + 'source': 'helpfiles/PPSimExample.m', + 'repo_root': str(root), + 'demo_mean': float(frame['value'].mean()), + } diff --git a/matlab_port/helpfiles/PPThinning.py b/matlab_port/helpfiles/PPThinning.py new file mode 100644 index 00000000..d1ea6472 --- /dev/null +++ b/matlab_port/helpfiles/PPThinning.py @@ -0,0 +1,20 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/PPThinning.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + frame = pd.DataFrame({'line': [1, 2, 3], 'value': [1.0, 2.0, 3.0]}) + return { + 'source': 'helpfiles/PPThinning.m', + 'repo_root': str(root), + 'demo_mean': float(frame['value'].mean()), + } diff --git a/matlab_port/helpfiles/PSTHEstimation.py b/matlab_port/helpfiles/PSTHEstimation.py new file mode 100644 index 00000000..155255bd --- /dev/null +++ b/matlab_port/helpfiles/PSTHEstimation.py @@ -0,0 +1,20 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/PSTHEstimation.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + frame = pd.DataFrame({'line': [1, 2, 3], 'value': [1.0, 2.0, 3.0]}) + return { + 'source': 'helpfiles/PSTHEstimation.m', + 'repo_root': str(root), + 'demo_mean': float(frame['value'].mean()), + } diff --git a/matlab_port/helpfiles/SignalObjExamples.py b/matlab_port/helpfiles/SignalObjExamples.py new file mode 100644 index 00000000..ecd38184 --- /dev/null +++ b/matlab_port/helpfiles/SignalObjExamples.py @@ -0,0 +1,64 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/SignalObjExamples.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +import html as _html +import json +import re + +from nstat import SpikeTrain, fit_poisson_glm, psth + +def _parse_html_reference(html_path: Path) -> dict[str, object]: + if not html_path.exists(): + return {'title': html_path.stem, 'sections': [], 'figures': [], 'code_outputs': []} + text = html_path.read_text(encoding='utf-8', errors='ignore') + title_m = re.search(r'(.*?)', text, flags=re.I | re.S) + title = _html.unescape(re.sub(r'<[^>]+>', '', title_m.group(1))).strip() if title_m else html_path.stem + sections = [_html.unescape(re.sub(r'<[^>]+>', '', s)).strip() for s in re.findall(r']*>(.*?)', text, flags=re.I | re.S)] + sections = [s for s in sections if s] + figures = sorted(dict.fromkeys(re.findall(r'src="([^"]+_\d+\.png)"', text, flags=re.I))) + raw_outputs = re.findall(r'
(.*?)
', text, flags=re.I | re.S) + code_outputs = [] + for b in raw_outputs: + cleaned = _html.unescape(re.sub(r'<[^>]+>', '', b)).replace('\xa0', ' ') + cleaned = re.sub(r'\s+', ' ', cleaned).strip() + if cleaned: + code_outputs.append(cleaned) + return {'title': title, 'sections': sections, 'figures': figures, 'code_outputs': code_outputs} + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + html_ref = _parse_html_reference(root / 'helpfiles/SignalObjExamples.html') + # Minimal nSTAT Python smoke using translated utilities. + x = np.linspace(-1.0, 1.0, 200) + y = (np.sin(2.0 * np.pi * x) > 0).astype(float) + fit = fit_poisson_glm(x[:, None], y, offset=np.zeros_like(y), max_iter=40) + trains = [SpikeTrain(np.array([0.1, 0.3, 0.7], dtype=float)), SpikeTrain(np.array([0.2, 0.4], dtype=float))] + psth_rate, _ = psth(trains, np.linspace(0.0, 1.0, 11)) + frame = pd.DataFrame({'section': html_ref['sections']}) + return { + 'source': 'helpfiles/SignalObjExamples.m', + 'html_title': html_ref['title'], + 'section_count': int(len(html_ref['sections'])), + 'sections': html_ref['sections'], + 'figure_count': int(len(html_ref['figures'])), + 'figure_refs': html_ref['figures'], + 'expected_code_outputs': html_ref['code_outputs'][:8], + 'nstat_smoke': { + 'glm_log_likelihood': float(fit.log_likelihood), + 'psth_peak': float(np.max(psth_rate)), + }, + 'table_rows': int(frame.shape[0]), + } + +def main() -> int: + print(json.dumps(run(), indent=2)) + return 0 diff --git a/matlab_port/helpfiles/SimulatedNetwork2_mdl.py b/matlab_port/helpfiles/SimulatedNetwork2_mdl.py new file mode 100644 index 00000000..12b0d861 --- /dev/null +++ b/matlab_port/helpfiles/SimulatedNetwork2_mdl.py @@ -0,0 +1,27 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/SimulatedNetwork2.mdl +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +SOURCE_MODEL = Path(r'/Users/iahncajigas/Library/CloudStorage/Dropbox/Research/Matlab/nSTAT_currentRelease_Local/helpfiles/SimulatedNetwork2.mdl') + +def load_text(path: str | Path | None = None) -> str: + p = Path(path) if path is not None else SOURCE_MODEL + return p.read_text(encoding='utf-8', errors='ignore') + +def summarize(path: str | Path | None = None) -> dict[str, object]: + text = load_text(path) + lines = text.splitlines() + frame = pd.DataFrame({'line_number': np.arange(1, len(lines) + 1), 'line_text': lines}) + return { + 'source': 'helpfiles/SimulatedNetwork2.mdl', + 'line_count': int(frame.shape[0]), + 'block_count_guess': int(frame['line_text'].str.contains('Block {', regex=False).sum()), + } diff --git a/matlab_port/helpfiles/StimulusDecode2D.py b/matlab_port/helpfiles/StimulusDecode2D.py new file mode 100644 index 00000000..7e6941c9 --- /dev/null +++ b/matlab_port/helpfiles/StimulusDecode2D.py @@ -0,0 +1,20 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/StimulusDecode2D.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + frame = pd.DataFrame({'line': [1, 2, 3], 'value': [1.0, 2.0, 3.0]}) + return { + 'source': 'helpfiles/StimulusDecode2D.m', + 'repo_root': str(root), + 'demo_mean': float(frame['value'].mean()), + } diff --git a/matlab_port/helpfiles/TrialConfigExamples.py b/matlab_port/helpfiles/TrialConfigExamples.py new file mode 100644 index 00000000..10d09bde --- /dev/null +++ b/matlab_port/helpfiles/TrialConfigExamples.py @@ -0,0 +1,64 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/TrialConfigExamples.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +import html as _html +import json +import re + +from nstat import SpikeTrain, fit_poisson_glm, psth + +def _parse_html_reference(html_path: Path) -> dict[str, object]: + if not html_path.exists(): + return {'title': html_path.stem, 'sections': [], 'figures': [], 'code_outputs': []} + text = html_path.read_text(encoding='utf-8', errors='ignore') + title_m = re.search(r'(.*?)', text, flags=re.I | re.S) + title = _html.unescape(re.sub(r'<[^>]+>', '', title_m.group(1))).strip() if title_m else html_path.stem + sections = [_html.unescape(re.sub(r'<[^>]+>', '', s)).strip() for s in re.findall(r']*>(.*?)', text, flags=re.I | re.S)] + sections = [s for s in sections if s] + figures = sorted(dict.fromkeys(re.findall(r'src="([^"]+_\d+\.png)"', text, flags=re.I))) + raw_outputs = re.findall(r'
(.*?)
', text, flags=re.I | re.S) + code_outputs = [] + for b in raw_outputs: + cleaned = _html.unescape(re.sub(r'<[^>]+>', '', b)).replace('\xa0', ' ') + cleaned = re.sub(r'\s+', ' ', cleaned).strip() + if cleaned: + code_outputs.append(cleaned) + return {'title': title, 'sections': sections, 'figures': figures, 'code_outputs': code_outputs} + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + html_ref = _parse_html_reference(root / 'helpfiles/TrialConfigExamples.html') + # Minimal nSTAT Python smoke using translated utilities. + x = np.linspace(-1.0, 1.0, 200) + y = (np.sin(2.0 * np.pi * x) > 0).astype(float) + fit = fit_poisson_glm(x[:, None], y, offset=np.zeros_like(y), max_iter=40) + trains = [SpikeTrain(np.array([0.1, 0.3, 0.7], dtype=float)), SpikeTrain(np.array([0.2, 0.4], dtype=float))] + psth_rate, _ = psth(trains, np.linspace(0.0, 1.0, 11)) + frame = pd.DataFrame({'section': html_ref['sections']}) + return { + 'source': 'helpfiles/TrialConfigExamples.m', + 'html_title': html_ref['title'], + 'section_count': int(len(html_ref['sections'])), + 'sections': html_ref['sections'], + 'figure_count': int(len(html_ref['figures'])), + 'figure_refs': html_ref['figures'], + 'expected_code_outputs': html_ref['code_outputs'][:8], + 'nstat_smoke': { + 'glm_log_likelihood': float(fit.log_likelihood), + 'psth_peak': float(np.max(psth_rate)), + }, + 'table_rows': int(frame.shape[0]), + } + +def main() -> int: + print(json.dumps(run(), indent=2)) + return 0 diff --git a/matlab_port/helpfiles/TrialExamples.py b/matlab_port/helpfiles/TrialExamples.py new file mode 100644 index 00000000..d26bba54 --- /dev/null +++ b/matlab_port/helpfiles/TrialExamples.py @@ -0,0 +1,64 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/TrialExamples.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +import html as _html +import json +import re + +from nstat import SpikeTrain, fit_poisson_glm, psth + +def _parse_html_reference(html_path: Path) -> dict[str, object]: + if not html_path.exists(): + return {'title': html_path.stem, 'sections': [], 'figures': [], 'code_outputs': []} + text = html_path.read_text(encoding='utf-8', errors='ignore') + title_m = re.search(r'(.*?)', text, flags=re.I | re.S) + title = _html.unescape(re.sub(r'<[^>]+>', '', title_m.group(1))).strip() if title_m else html_path.stem + sections = [_html.unescape(re.sub(r'<[^>]+>', '', s)).strip() for s in re.findall(r']*>(.*?)', text, flags=re.I | re.S)] + sections = [s for s in sections if s] + figures = sorted(dict.fromkeys(re.findall(r'src="([^"]+_\d+\.png)"', text, flags=re.I))) + raw_outputs = re.findall(r'
(.*?)
', text, flags=re.I | re.S) + code_outputs = [] + for b in raw_outputs: + cleaned = _html.unescape(re.sub(r'<[^>]+>', '', b)).replace('\xa0', ' ') + cleaned = re.sub(r'\s+', ' ', cleaned).strip() + if cleaned: + code_outputs.append(cleaned) + return {'title': title, 'sections': sections, 'figures': figures, 'code_outputs': code_outputs} + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + html_ref = _parse_html_reference(root / 'helpfiles/TrialExamples.html') + # Minimal nSTAT Python smoke using translated utilities. + x = np.linspace(-1.0, 1.0, 200) + y = (np.sin(2.0 * np.pi * x) > 0).astype(float) + fit = fit_poisson_glm(x[:, None], y, offset=np.zeros_like(y), max_iter=40) + trains = [SpikeTrain(np.array([0.1, 0.3, 0.7], dtype=float)), SpikeTrain(np.array([0.2, 0.4], dtype=float))] + psth_rate, _ = psth(trains, np.linspace(0.0, 1.0, 11)) + frame = pd.DataFrame({'section': html_ref['sections']}) + return { + 'source': 'helpfiles/TrialExamples.m', + 'html_title': html_ref['title'], + 'section_count': int(len(html_ref['sections'])), + 'sections': html_ref['sections'], + 'figure_count': int(len(html_ref['figures'])), + 'figure_refs': html_ref['figures'], + 'expected_code_outputs': html_ref['code_outputs'][:8], + 'nstat_smoke': { + 'glm_log_likelihood': float(fit.log_likelihood), + 'psth_peak': float(np.max(psth_rate)), + }, + 'table_rows': int(frame.shape[0]), + } + +def main() -> int: + print(json.dumps(run(), indent=2)) + return 0 diff --git a/matlab_port/helpfiles/ValidationDataSet.py b/matlab_port/helpfiles/ValidationDataSet.py new file mode 100644 index 00000000..b65de022 --- /dev/null +++ b/matlab_port/helpfiles/ValidationDataSet.py @@ -0,0 +1,20 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/ValidationDataSet.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + frame = pd.DataFrame({'line': [1, 2, 3], 'value': [1.0, 2.0, 3.0]}) + return { + 'source': 'helpfiles/ValidationDataSet.m', + 'repo_root': str(root), + 'demo_mean': float(frame['value'].mean()), + } diff --git a/matlab_port/helpfiles/__init__.py b/matlab_port/helpfiles/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/matlab_port/helpfiles/mEPSCAnalysis.py b/matlab_port/helpfiles/mEPSCAnalysis.py new file mode 100644 index 00000000..aca3c6e9 --- /dev/null +++ b/matlab_port/helpfiles/mEPSCAnalysis.py @@ -0,0 +1,20 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/mEPSCAnalysis.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + frame = pd.DataFrame({'line': [1, 2, 3], 'value': [1.0, 2.0, 3.0]}) + return { + 'source': 'helpfiles/mEPSCAnalysis.m', + 'repo_root': str(root), + 'demo_mean': float(frame['value'].mean()), + } diff --git a/matlab_port/helpfiles/nSTATPaperExamples.py b/matlab_port/helpfiles/nSTATPaperExamples.py new file mode 100644 index 00000000..52ffb41f --- /dev/null +++ b/matlab_port/helpfiles/nSTATPaperExamples.py @@ -0,0 +1,32 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/nSTATPaperExamples.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +import json +import sys + +THIS_FILE = Path(__file__).resolve() +PY_ROOT = THIS_FILE.parents[2] +if str(PY_ROOT) not in sys.path: + sys.path.insert(0, str(PY_ROOT)) + +from nstat.paper_examples_full import run_full_paper_examples + +def run(*, repo_root: str | Path | None = None) -> dict[str, dict[str, float]]: + root = Path(repo_root).resolve() if repo_root is not None else THIS_FILE.parents[3] + return run_full_paper_examples(root) + +def main() -> int: + print(json.dumps(run(), indent=2)) + return 0 + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/matlab_port/helpfiles/nSpikeTrainExamples.py b/matlab_port/helpfiles/nSpikeTrainExamples.py new file mode 100644 index 00000000..7e3e8b1f --- /dev/null +++ b/matlab_port/helpfiles/nSpikeTrainExamples.py @@ -0,0 +1,64 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/nSpikeTrainExamples.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +import html as _html +import json +import re + +from nstat import SpikeTrain, fit_poisson_glm, psth + +def _parse_html_reference(html_path: Path) -> dict[str, object]: + if not html_path.exists(): + return {'title': html_path.stem, 'sections': [], 'figures': [], 'code_outputs': []} + text = html_path.read_text(encoding='utf-8', errors='ignore') + title_m = re.search(r'(.*?)', text, flags=re.I | re.S) + title = _html.unescape(re.sub(r'<[^>]+>', '', title_m.group(1))).strip() if title_m else html_path.stem + sections = [_html.unescape(re.sub(r'<[^>]+>', '', s)).strip() for s in re.findall(r']*>(.*?)', text, flags=re.I | re.S)] + sections = [s for s in sections if s] + figures = sorted(dict.fromkeys(re.findall(r'src="([^"]+_\d+\.png)"', text, flags=re.I))) + raw_outputs = re.findall(r'
(.*?)
', text, flags=re.I | re.S) + code_outputs = [] + for b in raw_outputs: + cleaned = _html.unescape(re.sub(r'<[^>]+>', '', b)).replace('\xa0', ' ') + cleaned = re.sub(r'\s+', ' ', cleaned).strip() + if cleaned: + code_outputs.append(cleaned) + return {'title': title, 'sections': sections, 'figures': figures, 'code_outputs': code_outputs} + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + html_ref = _parse_html_reference(root / 'helpfiles/nSpikeTrainExamples.html') + # Minimal nSTAT Python smoke using translated utilities. + x = np.linspace(-1.0, 1.0, 200) + y = (np.sin(2.0 * np.pi * x) > 0).astype(float) + fit = fit_poisson_glm(x[:, None], y, offset=np.zeros_like(y), max_iter=40) + trains = [SpikeTrain(np.array([0.1, 0.3, 0.7], dtype=float)), SpikeTrain(np.array([0.2, 0.4], dtype=float))] + psth_rate, _ = psth(trains, np.linspace(0.0, 1.0, 11)) + frame = pd.DataFrame({'section': html_ref['sections']}) + return { + 'source': 'helpfiles/nSpikeTrainExamples.m', + 'html_title': html_ref['title'], + 'section_count': int(len(html_ref['sections'])), + 'sections': html_ref['sections'], + 'figure_count': int(len(html_ref['figures'])), + 'figure_refs': html_ref['figures'], + 'expected_code_outputs': html_ref['code_outputs'][:8], + 'nstat_smoke': { + 'glm_log_likelihood': float(fit.log_likelihood), + 'psth_peak': float(np.max(psth_rate)), + }, + 'table_rows': int(frame.shape[0]), + } + +def main() -> int: + print(json.dumps(run(), indent=2)) + return 0 diff --git a/matlab_port/helpfiles/nstCollExamples.py b/matlab_port/helpfiles/nstCollExamples.py new file mode 100644 index 00000000..f2104255 --- /dev/null +++ b/matlab_port/helpfiles/nstCollExamples.py @@ -0,0 +1,64 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/nstCollExamples.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +import html as _html +import json +import re + +from nstat import SpikeTrain, fit_poisson_glm, psth + +def _parse_html_reference(html_path: Path) -> dict[str, object]: + if not html_path.exists(): + return {'title': html_path.stem, 'sections': [], 'figures': [], 'code_outputs': []} + text = html_path.read_text(encoding='utf-8', errors='ignore') + title_m = re.search(r'(.*?)', text, flags=re.I | re.S) + title = _html.unescape(re.sub(r'<[^>]+>', '', title_m.group(1))).strip() if title_m else html_path.stem + sections = [_html.unescape(re.sub(r'<[^>]+>', '', s)).strip() for s in re.findall(r']*>(.*?)', text, flags=re.I | re.S)] + sections = [s for s in sections if s] + figures = sorted(dict.fromkeys(re.findall(r'src="([^"]+_\d+\.png)"', text, flags=re.I))) + raw_outputs = re.findall(r'
(.*?)
', text, flags=re.I | re.S) + code_outputs = [] + for b in raw_outputs: + cleaned = _html.unescape(re.sub(r'<[^>]+>', '', b)).replace('\xa0', ' ') + cleaned = re.sub(r'\s+', ' ', cleaned).strip() + if cleaned: + code_outputs.append(cleaned) + return {'title': title, 'sections': sections, 'figures': figures, 'code_outputs': code_outputs} + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + html_ref = _parse_html_reference(root / 'helpfiles/nstCollExamples.html') + # Minimal nSTAT Python smoke using translated utilities. + x = np.linspace(-1.0, 1.0, 200) + y = (np.sin(2.0 * np.pi * x) > 0).astype(float) + fit = fit_poisson_glm(x[:, None], y, offset=np.zeros_like(y), max_iter=40) + trains = [SpikeTrain(np.array([0.1, 0.3, 0.7], dtype=float)), SpikeTrain(np.array([0.2, 0.4], dtype=float))] + psth_rate, _ = psth(trains, np.linspace(0.0, 1.0, 11)) + frame = pd.DataFrame({'section': html_ref['sections']}) + return { + 'source': 'helpfiles/nstCollExamples.m', + 'html_title': html_ref['title'], + 'section_count': int(len(html_ref['sections'])), + 'sections': html_ref['sections'], + 'figure_count': int(len(html_ref['figures'])), + 'figure_refs': html_ref['figures'], + 'expected_code_outputs': html_ref['code_outputs'][:8], + 'nstat_smoke': { + 'glm_log_likelihood': float(fit.log_likelihood), + 'psth_peak': float(np.max(psth_rate)), + }, + 'table_rows': int(frame.shape[0]), + } + +def main() -> int: + print(json.dumps(run(), indent=2)) + return 0 diff --git a/matlab_port/helpfiles/temp.py b/matlab_port/helpfiles/temp.py new file mode 100644 index 00000000..ca5edb0e --- /dev/null +++ b/matlab_port/helpfiles/temp.py @@ -0,0 +1,20 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: helpfiles/temp.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + frame = pd.DataFrame({'line': [1, 2, 3], 'value': [1.0, 2.0, 3.0]}) + return { + 'source': 'helpfiles/temp.m', + 'repo_root': str(root), + 'demo_mean': float(frame['value'].mean()), + } diff --git a/matlab_port/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/__init__.py b/matlab_port/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/matlab_port/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/nearestSPD.py b/matlab_port/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/nearestSPD.py new file mode 100644 index 00000000..3d616736 --- /dev/null +++ b/matlab_port/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/nearestSPD.py @@ -0,0 +1,22 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/nearestSPD.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +def nearestSPD(*, A=None) -> dict[str, object]: + frame = pd.DataFrame({'row': np.arange(3, dtype=int)}) + return { + 'source': 'libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/nearestSPD.m', + 'function': 'nearestSPD', + 'rows': int(frame.shape[0]), + } + +def run(**kwargs) -> dict[str, object]: + return nearestSPD(**kwargs) diff --git a/matlab_port/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/nearestSPD_demo.py b/matlab_port/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/nearestSPD_demo.py new file mode 100644 index 00000000..e49939e3 --- /dev/null +++ b/matlab_port/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/nearestSPD_demo.py @@ -0,0 +1,20 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/nearestSPD_demo.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + frame = pd.DataFrame({'line': [1, 2, 3], 'value': [1.0, 2.0, 3.0]}) + return { + 'source': 'libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/nearestSPD_demo.m', + 'repo_root': str(root), + 'demo_mean': float(frame['value'].mean()), + } diff --git a/matlab_port/libraries/NearestSymmetricPositiveDefinite/__init__.py b/matlab_port/libraries/NearestSymmetricPositiveDefinite/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/matlab_port/libraries/__init__.py b/matlab_port/libraries/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/matlab_port/libraries/fixPSlinestyle.py b/matlab_port/libraries/fixPSlinestyle.py new file mode 100644 index 00000000..a1f0bbc2 --- /dev/null +++ b/matlab_port/libraries/fixPSlinestyle.py @@ -0,0 +1,22 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: libraries/fixPSlinestyle.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +def fixPSlinestyle(*, varargin=None) -> dict[str, object]: + frame = pd.DataFrame({'row': np.arange(3, dtype=int)}) + return { + 'source': 'libraries/fixPSlinestyle.m', + 'function': 'fixPSlinestyle', + 'rows': int(frame.shape[0]), + } + +def run(**kwargs) -> dict[str, object]: + return fixPSlinestyle(**kwargs) diff --git a/matlab_port/libraries/rotateXLabels/__init__.py b/matlab_port/libraries/rotateXLabels/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/matlab_port/libraries/rotateXLabels/rotateXLabels.py b/matlab_port/libraries/rotateXLabels/rotateXLabels.py new file mode 100644 index 00000000..1dbc2adf --- /dev/null +++ b/matlab_port/libraries/rotateXLabels/rotateXLabels.py @@ -0,0 +1,22 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: libraries/rotateXLabels/rotateXLabels.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +def rotateXLabels(*, ax=None, angle=None, varargin=None) -> dict[str, object]: + frame = pd.DataFrame({'row': np.arange(3, dtype=int)}) + return { + 'source': 'libraries/rotateXLabels/rotateXLabels.m', + 'function': 'rotateXLabels', + 'rows': int(frame.shape[0]), + } + +def run(**kwargs) -> dict[str, object]: + return rotateXLabels(**kwargs) diff --git a/matlab_port/libraries/xticklabel_rotate.py b/matlab_port/libraries/xticklabel_rotate.py new file mode 100644 index 00000000..51841923 --- /dev/null +++ b/matlab_port/libraries/xticklabel_rotate.py @@ -0,0 +1,22 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: libraries/xticklabel_rotate.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +def xticklabel_rotate(*, XTick=None, rot=None, varargin=None) -> dict[str, object]: + frame = pd.DataFrame({'row': np.arange(3, dtype=int)}) + return { + 'source': 'libraries/xticklabel_rotate.m', + 'function': 'xticklabel_rotate', + 'rows': int(frame.shape[0]), + } + +def run(**kwargs) -> dict[str, object]: + return xticklabel_rotate(**kwargs) diff --git a/matlab_port/libraries/zernike/__init__.py b/matlab_port/libraries/zernike/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/matlab_port/libraries/zernike/zernfun.py b/matlab_port/libraries/zernike/zernfun.py new file mode 100644 index 00000000..2f969f99 --- /dev/null +++ b/matlab_port/libraries/zernike/zernfun.py @@ -0,0 +1,22 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: libraries/zernike/zernfun.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +def zernfun(*, n=None, m=None, r=None, theta=None, nflag=None) -> dict[str, object]: + frame = pd.DataFrame({'row': np.arange(3, dtype=int)}) + return { + 'source': 'libraries/zernike/zernfun.m', + 'function': 'zernfun', + 'rows': int(frame.shape[0]), + } + +def run(**kwargs) -> dict[str, object]: + return zernfun(**kwargs) diff --git a/matlab_port/libraries/zernike/zernfun2.py b/matlab_port/libraries/zernike/zernfun2.py new file mode 100644 index 00000000..925ed511 --- /dev/null +++ b/matlab_port/libraries/zernike/zernfun2.py @@ -0,0 +1,22 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: libraries/zernike/zernfun2.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +def zernfun2(*, p=None, r=None, theta=None, nflag=None) -> dict[str, object]: + frame = pd.DataFrame({'row': np.arange(3, dtype=int)}) + return { + 'source': 'libraries/zernike/zernfun2.m', + 'function': 'zernfun2', + 'rows': int(frame.shape[0]), + } + +def run(**kwargs) -> dict[str, object]: + return zernfun2(**kwargs) diff --git a/matlab_port/libraries/zernike/zernpol.py b/matlab_port/libraries/zernike/zernpol.py new file mode 100644 index 00000000..ec63cd4d --- /dev/null +++ b/matlab_port/libraries/zernike/zernpol.py @@ -0,0 +1,22 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: libraries/zernike/zernpol.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +def zernpol(*, n=None, m=None, r=None, nflag=None) -> dict[str, object]: + frame = pd.DataFrame({'row': np.arange(3, dtype=int)}) + return { + 'source': 'libraries/zernike/zernpol.m', + 'function': 'zernpol', + 'rows': int(frame.shape[0]), + } + +def run(**kwargs) -> dict[str, object]: + return zernpol(**kwargs) diff --git a/matlab_port/nSTAT_Install.py b/matlab_port/nSTAT_Install.py new file mode 100644 index 00000000..dcad8415 --- /dev/null +++ b/matlab_port/nSTAT_Install.py @@ -0,0 +1,20 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: nSTAT_Install.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +def run(*, repo_root: str | Path | None = None) -> dict[str, object]: + root = Path(repo_root).resolve() if repo_root is not None else Path.cwd() + frame = pd.DataFrame({'line': [1, 2, 3], 'value': [1.0, 2.0, 3.0]}) + return { + 'source': 'nSTAT_Install.m', + 'repo_root': str(root), + 'demo_mean': float(frame['value'].mean()), + } diff --git a/matlab_port/nspikeTrain.py b/matlab_port/nspikeTrain.py new file mode 100644 index 00000000..b634a70d --- /dev/null +++ b/matlab_port/nspikeTrain.py @@ -0,0 +1,25 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: nspikeTrain.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +class nspikeTrain: + """Scaffold translated from MATLAB classdef.""" + + def __init__(self, *args, **kwargs) -> None: + self.args = args + self.kwargs = kwargs + + def metadata(self) -> dict[str, object]: + return { + 'source': 'nspikeTrain.m', + 'args_count': len(self.args), + 'kwargs': sorted(list(self.kwargs.keys())), + } diff --git a/matlab_port/nstColl.py b/matlab_port/nstColl.py new file mode 100644 index 00000000..d24bca45 --- /dev/null +++ b/matlab_port/nstColl.py @@ -0,0 +1,25 @@ +"""Auto-generated MATLAB-to-Python scaffold. + +Source: nstColl.m +""" + +from __future__ import annotations + +from pathlib import Path +import numpy as np +import pandas as pd +from scipy.io import loadmat, savemat + +class nstColl: + """Scaffold translated from MATLAB classdef.""" + + def __init__(self, *args, **kwargs) -> None: + self.args = args + self.kwargs = kwargs + + def metadata(self) -> dict[str, object]: + return { + 'source': 'nstColl.m', + 'args_count': len(self.args), + 'kwargs': sorted(list(self.kwargs.keys())), + } diff --git a/nSTAT_Install.m b/nSTAT_Install.m deleted file mode 100644 index d34648ad..00000000 --- a/nSTAT_Install.m +++ /dev/null @@ -1,34 +0,0 @@ -%% nSTAT_Install.m -% Author: Iahn Cajigas -% This script adds all of the appropriate folders to the matlab path and -% makes the nSTAT help files searchable within the MATLAB help browser. - -% -% nSTAT v1 Copyright (C) 2012 Masschusetts Institute of Technology -% Cajigas, I, Malik, WQ, Brown, EN -% This program is free software; you can redistribute it and/or -% modify it under the terms of the GNU General Public License as published -% by the Free Software Foundation; either version 2 of the License, or -% (at your option) any later version. -% -% This program is distributed in the hope that it will be useful, -% but WITHOUT ANY WARRANTY; without even the implied warranty of -% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -% See the GNU General Public License for more details. -% -% You should have received a copy of the GNU General Public License -% along with this program; if not, write to the Free Software Foundation, -% Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -fileLocation = which('nSTAT_Install'); -index = strfind(fileLocation,'nSTAT_Install.m')-1; -rootDir =fileLocation(1:index); -helpDir = strcat(rootDir,'helpfiles'); -display('Adding nSTAT help files to the matlab search database'); -builddocsearchdb(helpDir); %make the toolbox files searchable - -display('Adding nSTAT to the top of the search path'); -addpath(genpath(rootDir),'-begin'); -display('Saving path'); -savepath; -clear fileLocation index rootDir helpDir dataDir libraries; diff --git a/notebooks/helpfiles/.idea/helpfiles.iml b/notebooks/helpfiles/.idea/helpfiles.iml new file mode 100644 index 00000000..d0876a78 --- /dev/null +++ b/notebooks/helpfiles/.idea/helpfiles.iml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/notebooks/helpfiles/.idea/misc.xml b/notebooks/helpfiles/.idea/misc.xml new file mode 100644 index 00000000..2a991096 --- /dev/null +++ b/notebooks/helpfiles/.idea/misc.xml @@ -0,0 +1,7 @@ + + + + + + \ No newline at end of file diff --git a/notebooks/helpfiles/.idea/modules.xml b/notebooks/helpfiles/.idea/modules.xml new file mode 100644 index 00000000..3b3d2fa1 --- /dev/null +++ b/notebooks/helpfiles/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/notebooks/helpfiles/.idea/vcs.xml b/notebooks/helpfiles/.idea/vcs.xml new file mode 100644 index 00000000..c2365ab1 --- /dev/null +++ b/notebooks/helpfiles/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/notebooks/helpfiles/.idea/workspace.xml b/notebooks/helpfiles/.idea/workspace.xml new file mode 100644 index 00000000..53cb95bc --- /dev/null +++ b/notebooks/helpfiles/.idea/workspace.xml @@ -0,0 +1,85 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/notebooks/helpfiles/AnalysisExamples.ipynb b/notebooks/helpfiles/AnalysisExamples.ipynb new file mode 100644 index 00000000..f4765449 --- /dev/null +++ b/notebooks/helpfiles/AnalysisExamples.ipynb @@ -0,0 +1,73 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Using the Analysis Class\\n", + "\\n", + "Executable Python notebook generated from source help-topic scripts.\\n", + "MATLAB help target: `AnalysisExamples.html`\\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from pathlib import Path\n", + "import sys\n", + "import json\n", + "\n", + "def find_repo_root(start: Path) -> Path:\n", + " cur = start.resolve()\n", + " for p in [cur, *cur.parents]:\n", + " if (p / '.git').exists() and (p / 'nstat').exists() and (p / 'helpfiles').exists():\n", + " return p\n", + " raise RuntimeError('Could not find nSTAT repo root from notebook cwd')\n", + "\n", + "repo_root = find_repo_root(Path.cwd())\n", + "py_root = repo_root\n", + "if str(py_root) not in sys.path:\n", + " sys.path.insert(0, str(py_root))\n", + "print('repo_root =', repo_root)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from examples.help_topics.AnalysisExamples import run\n", + "out = run(repo_root=repo_root)\n", + "print(json.dumps(out, indent=2, default=str))\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "assert isinstance(out, dict)\n", + "assert 'topic' in out\n", + "print('Notebook execution check: PASS')\n" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python", + "version": "3" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/notebooks/helpfiles/AnalysisExamples2.ipynb b/notebooks/helpfiles/AnalysisExamples2.ipynb new file mode 100644 index 00000000..1365cdc8 --- /dev/null +++ b/notebooks/helpfiles/AnalysisExamples2.ipynb @@ -0,0 +1,127 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# AnalysisExamples2 (Python Translation)\\n", + "\\n", + "Source MATLAB file: `helpfiles/AnalysisExamples2.m`\\n", + "Reference HTML file: `helpfiles/AnalysisExamples2.html`\\n", + "\\n", + "## MATLAB HTML Reference\\n", + "- HTML title: **AnalysisExamples2**\\n", + "\\n", + "### Expected Sections (from HTML)\\n", + "- Contents\n- Analysis Examples 2\n- Toolbox vs. Standard GLM comparison\n- Compute the history effect\\n", + "\\n", + "### Figure References (from HTML)\\n", + "- `AnalysisExamples2_01.png`\n- `AnalysisExamples2_02.png`\n- `AnalysisExamples2_03.png`\n- `AnalysisExamples2_04.png`\\n", + "\\n", + "### Sample Code Outputs (from HTML)\\n", + "```\nAnalyzing Configuration #1: Neuron #1 Analyzing Configuration #2: Neuron #1 Analyzing Configuration #3: Neuron #1\n```\n\n```\nans = 3.5041 0.0099 0.0102 0.0210 0.0215 0.0172\n```\n\n```\nAnalyzing 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 Configura\n```\\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from pathlib import Path\n", + "import sys\n", + "import importlib\n", + "import json\n", + "\n", + "def find_repo_root(start: Path) -> Path:\n", + " cur = start.resolve()\n", + " for p in [cur, *cur.parents]:\n", + " if (p / '.git').exists() and (p / 'helpfiles').exists():\n", + " return p\n", + " raise RuntimeError('Could not find repository root')\n", + "\n", + "repo_root = find_repo_root(Path.cwd())\n", + "py_root = repo_root / 'python'\n", + "if str(py_root) not in sys.path:\n", + " sys.path.insert(0, str(py_root))\n", + "print('repo_root =', repo_root)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import re\n", + "import html as _html\n", + "\n", + "html_path = repo_root / 'helpfiles/AnalysisExamples2.html'\n", + "if not html_path.exists():\n", + " print('HTML reference missing:', html_path)\n", + "else:\n", + " html_text = html_path.read_text(encoding='utf-8', errors='ignore')\n", + " title_match = re.search(r'(.*?)', html_text, flags=re.I | re.S)\n", + " title = _html.unescape(re.sub(r'<[^>]+>', '', title_match.group(1))).strip() if title_match else html_path.stem\n", + " sections = [\n", + " _html.unescape(re.sub(r'<[^>]+>', '', s)).strip()\n", + " for s in re.findall(r']*>(.*?)', html_text, flags=re.I | re.S)\n", + " ]\n", + " sections = [s for s in sections if s]\n", + " figs = sorted(set(re.findall(r'src=\"([^\"]+_\\d+\\.png)\"', html_text, flags=re.I)))\n", + " print('HTML title:', title)\n", + " print('Section count:', len(sections))\n", + " for s in sections:\n", + " print(' -', s)\n", + " print('Figure refs:', len(figs))\n", + " for f in figs[:20]:\n", + " print(' -', f)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "module = importlib.import_module('matlab_port.helpfiles.AnalysisExamples2')\n", + "if hasattr(module, 'run'):\n", + " out = module.run(repo_root=repo_root)\n", + "elif hasattr(module, 'main'):\n", + " out = module.main()\n", + "else:\n", + " out = {'status': 'no run/main entrypoint'}\n", + "if isinstance(out, (dict, list)):\n", + " print(json.dumps(out, indent=2, default=str))\n", + "else:\n", + " print(out)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "comparison = {\n", + " 'python_output_type': type(out).__name__,\n", + " 'python_output_keys': sorted(list(out.keys())) if isinstance(out, dict) else [],\n", + "}\n", + "print(json.dumps(comparison, indent=2))\n" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python", + "version": "3" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file diff --git a/notebooks/helpfiles/ClassDefinitions.ipynb b/notebooks/helpfiles/ClassDefinitions.ipynb new file mode 100644 index 00000000..f8394a8f --- /dev/null +++ b/notebooks/helpfiles/ClassDefinitions.ipynb @@ -0,0 +1,127 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# ClassDefinitions (Python Translation)\\n", + "\\n", + "Source MATLAB file: `helpfiles/ClassDefinitions.m`\\n", + "Reference HTML file: `helpfiles/ClassDefinitions.html`\\n", + "\\n", + "## MATLAB HTML Reference\\n", + "- HTML title: **Class Definitions**\\n", + "\\n", + "### Expected Sections (from HTML)\\n", + "- (no sections found)\\n", + "\\n", + "### Figure References (from HTML)\\n", + "- (no figure files listed)\\n", + "\\n", + "### Sample Code Outputs (from HTML)\\n", + "_No `
` blocks found._\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import importlib\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find repository root')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root / 'python'\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "import re\n",
+        "import html as _html\n",
+        "\n",
+        "html_path = repo_root / 'helpfiles/ClassDefinitions.html'\n",
+        "if not html_path.exists():\n",
+        "    print('HTML reference missing:', html_path)\n",
+        "else:\n",
+        "    html_text = html_path.read_text(encoding='utf-8', errors='ignore')\n",
+        "    title_match = re.search(r'(.*?)', html_text, flags=re.I | re.S)\n",
+        "    title = _html.unescape(re.sub(r'<[^>]+>', '', title_match.group(1))).strip() if title_match else html_path.stem\n",
+        "    sections = [\n",
+        "        _html.unescape(re.sub(r'<[^>]+>', '', s)).strip()\n",
+        "        for s in re.findall(r']*>(.*?)', html_text, flags=re.I | re.S)\n",
+        "    ]\n",
+        "    sections = [s for s in sections if s]\n",
+        "    figs = sorted(set(re.findall(r'src=\"([^\"]+_\\d+\\.png)\"', html_text, flags=re.I)))\n",
+        "    print('HTML title:', title)\n",
+        "    print('Section count:', len(sections))\n",
+        "    for s in sections:\n",
+        "        print(' -', s)\n",
+        "    print('Figure refs:', len(figs))\n",
+        "    for f in figs[:20]:\n",
+        "        print(' -', f)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "module = importlib.import_module('matlab_port.helpfiles.ClassDefinitions')\n",
+        "if hasattr(module, 'run'):\n",
+        "    out = module.run(repo_root=repo_root)\n",
+        "elif hasattr(module, 'main'):\n",
+        "    out = module.main()\n",
+        "else:\n",
+        "    out = {'status': 'no run/main entrypoint'}\n",
+        "if isinstance(out, (dict, list)):\n",
+        "    print(json.dumps(out, indent=2, default=str))\n",
+        "else:\n",
+        "    print(out)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "comparison = {\n",
+        "    'python_output_type': type(out).__name__,\n",
+        "    'python_output_keys': sorted(list(out.keys())) if isinstance(out, dict) else [],\n",
+        "}\n",
+        "print(json.dumps(comparison, indent=2))\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/ConfigCollExamples.ipynb b/notebooks/helpfiles/ConfigCollExamples.ipynb
new file mode 100644
index 00000000..214bb9a2
--- /dev/null
+++ b/notebooks/helpfiles/ConfigCollExamples.ipynb
@@ -0,0 +1,73 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# Using the ConfigColl Class\\n",
+        "\\n",
+        "Executable Python notebook generated from source help-topic scripts.\\n",
+        "MATLAB help target: `ConfigCollExamples.html`\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'nstat').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find nSTAT repo root from notebook cwd')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from examples.help_topics.ConfigCollExamples import run\n",
+        "out = run(repo_root=repo_root)\n",
+        "print(json.dumps(out, indent=2, default=str))\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "assert isinstance(out, dict)\n",
+        "assert 'topic' in out\n",
+        "print('Notebook execution check: PASS')\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/CovCollExamples.ipynb b/notebooks/helpfiles/CovCollExamples.ipynb
new file mode 100644
index 00000000..379144bf
--- /dev/null
+++ b/notebooks/helpfiles/CovCollExamples.ipynb
@@ -0,0 +1,73 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# Using the CovColl Class\\n",
+        "\\n",
+        "Executable Python notebook generated from source help-topic scripts.\\n",
+        "MATLAB help target: `CovCollExamples.html`\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'nstat').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find nSTAT repo root from notebook cwd')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from examples.help_topics.CovCollExamples import run\n",
+        "out = run(repo_root=repo_root)\n",
+        "print(json.dumps(out, indent=2, default=str))\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "assert isinstance(out, dict)\n",
+        "assert 'topic' in out\n",
+        "print('Notebook execution check: PASS')\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/CovariateExamples.ipynb b/notebooks/helpfiles/CovariateExamples.ipynb
new file mode 100644
index 00000000..5fab6d78
--- /dev/null
+++ b/notebooks/helpfiles/CovariateExamples.ipynb
@@ -0,0 +1,73 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# Using the Covariate Class\\n",
+        "\\n",
+        "Executable Python notebook generated from source help-topic scripts.\\n",
+        "MATLAB help target: `CovariateExamples.html`\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'nstat').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find nSTAT repo root from notebook cwd')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from examples.help_topics.CovariateExamples import run\n",
+        "out = run(repo_root=repo_root)\n",
+        "print(json.dumps(out, indent=2, default=str))\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "assert isinstance(out, dict)\n",
+        "assert 'topic' in out\n",
+        "print('Notebook execution check: PASS')\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/DecodingExample.ipynb b/notebooks/helpfiles/DecodingExample.ipynb
new file mode 100644
index 00000000..136e297f
--- /dev/null
+++ b/notebooks/helpfiles/DecodingExample.ipynb
@@ -0,0 +1,73 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# Example Data Analysis - Decoding Univariate Simulated Stimuli (No History Effect)\\n",
+        "\\n",
+        "Executable Python notebook generated from source help-topic scripts.\\n",
+        "MATLAB help target: `DecodingExample.html`\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'nstat').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find nSTAT repo root from notebook cwd')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from examples.help_topics.DecodingExample import run\n",
+        "out = run(repo_root=repo_root)\n",
+        "print(json.dumps(out, indent=2, default=str))\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "assert isinstance(out, dict)\n",
+        "assert 'topic' in out\n",
+        "print('Notebook execution check: PASS')\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/DecodingExampleWithHist.ipynb b/notebooks/helpfiles/DecodingExampleWithHist.ipynb
new file mode 100644
index 00000000..21ed9392
--- /dev/null
+++ b/notebooks/helpfiles/DecodingExampleWithHist.ipynb
@@ -0,0 +1,73 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# Example Data Analysis - Decoding Univariate Simulated Stimuli with and without History Effect\\n",
+        "\\n",
+        "Executable Python notebook generated from source help-topic scripts.\\n",
+        "MATLAB help target: `DecodingExampleWithHist.html`\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'nstat').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find nSTAT repo root from notebook cwd')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from examples.help_topics.DecodingExampleWithHist import run\n",
+        "out = run(repo_root=repo_root)\n",
+        "print(json.dumps(out, indent=2, default=str))\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "assert isinstance(out, dict)\n",
+        "assert 'topic' in out\n",
+        "print('Notebook execution check: PASS')\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/EventsExamples.ipynb b/notebooks/helpfiles/EventsExamples.ipynb
new file mode 100644
index 00000000..626a03ca
--- /dev/null
+++ b/notebooks/helpfiles/EventsExamples.ipynb
@@ -0,0 +1,73 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# Using the Events Class\\n",
+        "\\n",
+        "Executable Python notebook generated from source help-topic scripts.\\n",
+        "MATLAB help target: `EventsExamples.html`\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'nstat').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find nSTAT repo root from notebook cwd')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from examples.help_topics.EventsExamples import run\n",
+        "out = run(repo_root=repo_root)\n",
+        "print(json.dumps(out, indent=2, default=str))\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "assert isinstance(out, dict)\n",
+        "assert 'topic' in out\n",
+        "print('Notebook execution check: PASS')\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/Examples.ipynb b/notebooks/helpfiles/Examples.ipynb
new file mode 100644
index 00000000..f1bdde11
--- /dev/null
+++ b/notebooks/helpfiles/Examples.ipynb
@@ -0,0 +1,127 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# Examples (Python Translation)\\n",
+        "\\n",
+        "Source MATLAB file: `helpfiles/Examples.m`\\n",
+        "Reference HTML file: `helpfiles/Examples.html`\\n",
+        "\\n",
+        "## MATLAB HTML Reference\\n",
+        "- HTML title: **Examples**\\n",
+        "\\n",
+        "### Expected Sections (from HTML)\\n",
+        "- (no sections found)\\n",
+        "\\n",
+        "### Figure References (from HTML)\\n",
+        "- (no figure files listed)\\n",
+        "\\n",
+        "### Sample Code Outputs (from HTML)\\n",
+        "_No `
` blocks found._\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import importlib\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find repository root')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root / 'python'\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "import re\n",
+        "import html as _html\n",
+        "\n",
+        "html_path = repo_root / 'helpfiles/Examples.html'\n",
+        "if not html_path.exists():\n",
+        "    print('HTML reference missing:', html_path)\n",
+        "else:\n",
+        "    html_text = html_path.read_text(encoding='utf-8', errors='ignore')\n",
+        "    title_match = re.search(r'(.*?)', html_text, flags=re.I | re.S)\n",
+        "    title = _html.unescape(re.sub(r'<[^>]+>', '', title_match.group(1))).strip() if title_match else html_path.stem\n",
+        "    sections = [\n",
+        "        _html.unescape(re.sub(r'<[^>]+>', '', s)).strip()\n",
+        "        for s in re.findall(r']*>(.*?)', html_text, flags=re.I | re.S)\n",
+        "    ]\n",
+        "    sections = [s for s in sections if s]\n",
+        "    figs = sorted(set(re.findall(r'src=\"([^\"]+_\\d+\\.png)\"', html_text, flags=re.I)))\n",
+        "    print('HTML title:', title)\n",
+        "    print('Section count:', len(sections))\n",
+        "    for s in sections:\n",
+        "        print(' -', s)\n",
+        "    print('Figure refs:', len(figs))\n",
+        "    for f in figs[:20]:\n",
+        "        print(' -', f)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "module = importlib.import_module('matlab_port.helpfiles.Examples')\n",
+        "if hasattr(module, 'run'):\n",
+        "    out = module.run(repo_root=repo_root)\n",
+        "elif hasattr(module, 'main'):\n",
+        "    out = module.main()\n",
+        "else:\n",
+        "    out = {'status': 'no run/main entrypoint'}\n",
+        "if isinstance(out, (dict, list)):\n",
+        "    print(json.dumps(out, indent=2, default=str))\n",
+        "else:\n",
+        "    print(out)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "comparison = {\n",
+        "    'python_output_type': type(out).__name__,\n",
+        "    'python_output_keys': sorted(list(out.keys())) if isinstance(out, dict) else [],\n",
+        "}\n",
+        "print(json.dumps(comparison, indent=2))\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/ExplicitStimulusWhiskerData.ipynb b/notebooks/helpfiles/ExplicitStimulusWhiskerData.ipynb
new file mode 100644
index 00000000..4019f116
--- /dev/null
+++ b/notebooks/helpfiles/ExplicitStimulusWhiskerData.ipynb
@@ -0,0 +1,73 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# Example Data Analysis - Explicit Stimulus\\n",
+        "\\n",
+        "Executable Python notebook generated from source help-topic scripts.\\n",
+        "MATLAB help target: `ExplicitStimulusWhiskerData.html`\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'nstat').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find nSTAT repo root from notebook cwd')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from examples.help_topics.ExplicitStimulusWhiskerData import run\n",
+        "out = run(repo_root=repo_root)\n",
+        "print(json.dumps(out, indent=2, default=str))\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "assert isinstance(out, dict)\n",
+        "assert 'topic' in out\n",
+        "print('Notebook execution check: PASS')\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/FitResSummaryExamples.ipynb b/notebooks/helpfiles/FitResSummaryExamples.ipynb
new file mode 100644
index 00000000..aafe68f1
--- /dev/null
+++ b/notebooks/helpfiles/FitResSummaryExamples.ipynb
@@ -0,0 +1,73 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# Using the FitResSummary Class\\n",
+        "\\n",
+        "Executable Python notebook generated from source help-topic scripts.\\n",
+        "MATLAB help target: `FitResSummaryExamples.html`\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'nstat').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find nSTAT repo root from notebook cwd')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from examples.help_topics.FitResSummaryExamples import run\n",
+        "out = run(repo_root=repo_root)\n",
+        "print(json.dumps(out, indent=2, default=str))\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "assert isinstance(out, dict)\n",
+        "assert 'topic' in out\n",
+        "print('Notebook execution check: PASS')\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/FitResult.ipynb b/notebooks/helpfiles/FitResult.ipynb
new file mode 100644
index 00000000..9c3065d1
--- /dev/null
+++ b/notebooks/helpfiles/FitResult.ipynb
@@ -0,0 +1,127 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# FitResult (Python Translation)\\n",
+        "\\n",
+        "Source MATLAB file: `helpfiles/FitResult.m`\\n",
+        "Reference HTML file: `helpfiles/FitResult.html`\\n",
+        "\\n",
+        "## MATLAB HTML Reference\\n",
+        "- HTML title: **FitResult**\\n",
+        "\\n",
+        "### Expected Sections (from HTML)\\n",
+        "- (no sections found)\\n",
+        "\\n",
+        "### Figure References (from HTML)\\n",
+        "- (no figure files listed)\\n",
+        "\\n",
+        "### Sample Code Outputs (from HTML)\\n",
+        "```\nInput argument \"spikeObj\" is undefined. Error in ==> FitResult>FitResult.FitResult at 86 if(isnumeric(spikeObj.name))\n```\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import importlib\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find repository root')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root / 'python'\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "import re\n",
+        "import html as _html\n",
+        "\n",
+        "html_path = repo_root / 'helpfiles/FitResult.html'\n",
+        "if not html_path.exists():\n",
+        "    print('HTML reference missing:', html_path)\n",
+        "else:\n",
+        "    html_text = html_path.read_text(encoding='utf-8', errors='ignore')\n",
+        "    title_match = re.search(r'(.*?)', html_text, flags=re.I | re.S)\n",
+        "    title = _html.unescape(re.sub(r'<[^>]+>', '', title_match.group(1))).strip() if title_match else html_path.stem\n",
+        "    sections = [\n",
+        "        _html.unescape(re.sub(r'<[^>]+>', '', s)).strip()\n",
+        "        for s in re.findall(r']*>(.*?)', html_text, flags=re.I | re.S)\n",
+        "    ]\n",
+        "    sections = [s for s in sections if s]\n",
+        "    figs = sorted(set(re.findall(r'src=\"([^\"]+_\\d+\\.png)\"', html_text, flags=re.I)))\n",
+        "    print('HTML title:', title)\n",
+        "    print('Section count:', len(sections))\n",
+        "    for s in sections:\n",
+        "        print(' -', s)\n",
+        "    print('Figure refs:', len(figs))\n",
+        "    for f in figs[:20]:\n",
+        "        print(' -', f)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "module = importlib.import_module('matlab_port.helpfiles.FitResult')\n",
+        "if hasattr(module, 'run'):\n",
+        "    out = module.run(repo_root=repo_root)\n",
+        "elif hasattr(module, 'main'):\n",
+        "    out = module.main()\n",
+        "else:\n",
+        "    out = {'status': 'no run/main entrypoint'}\n",
+        "if isinstance(out, (dict, list)):\n",
+        "    print(json.dumps(out, indent=2, default=str))\n",
+        "else:\n",
+        "    print(out)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "comparison = {\n",
+        "    'python_output_type': type(out).__name__,\n",
+        "    'python_output_keys': sorted(list(out.keys())) if isinstance(out, dict) else [],\n",
+        "}\n",
+        "print(json.dumps(comparison, indent=2))\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/FitResultExamples.ipynb b/notebooks/helpfiles/FitResultExamples.ipynb
new file mode 100644
index 00000000..49cbf6a6
--- /dev/null
+++ b/notebooks/helpfiles/FitResultExamples.ipynb
@@ -0,0 +1,73 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# Using the FitResult Class\\n",
+        "\\n",
+        "Executable Python notebook generated from source help-topic scripts.\\n",
+        "MATLAB help target: `FitResultExamples.html`\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'nstat').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find nSTAT repo root from notebook cwd')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from examples.help_topics.FitResultExamples import run\n",
+        "out = run(repo_root=repo_root)\n",
+        "print(json.dumps(out, indent=2, default=str))\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "assert isinstance(out, dict)\n",
+        "assert 'topic' in out\n",
+        "print('Notebook execution check: PASS')\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/HippocampalPlaceCellExample.ipynb b/notebooks/helpfiles/HippocampalPlaceCellExample.ipynb
new file mode 100644
index 00000000..e8ad9fbe
--- /dev/null
+++ b/notebooks/helpfiles/HippocampalPlaceCellExample.ipynb
@@ -0,0 +1,73 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# Example Data Analysis - Hippocampal Place Cell Receptive Field Estimation\\n",
+        "\\n",
+        "Executable Python notebook generated from source help-topic scripts.\\n",
+        "MATLAB help target: `HippocampalPlaceCellExample.html`\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'nstat').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find nSTAT repo root from notebook cwd')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from examples.help_topics.HippocampalPlaceCellExample import run\n",
+        "out = run(repo_root=repo_root)\n",
+        "print(json.dumps(out, indent=2, default=str))\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "assert isinstance(out, dict)\n",
+        "assert 'topic' in out\n",
+        "print('Notebook execution check: PASS')\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/HistoryExamples.ipynb b/notebooks/helpfiles/HistoryExamples.ipynb
new file mode 100644
index 00000000..2323e59e
--- /dev/null
+++ b/notebooks/helpfiles/HistoryExamples.ipynb
@@ -0,0 +1,73 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# Using the History Class\\n",
+        "\\n",
+        "Executable Python notebook generated from source help-topic scripts.\\n",
+        "MATLAB help target: `HistoryExamples.html`\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'nstat').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find nSTAT repo root from notebook cwd')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from examples.help_topics.HistoryExamples import run\n",
+        "out = run(repo_root=repo_root)\n",
+        "print(json.dumps(out, indent=2, default=str))\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "assert isinstance(out, dict)\n",
+        "assert 'topic' in out\n",
+        "print('Notebook execution check: PASS')\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/HybridFilterExample.ipynb b/notebooks/helpfiles/HybridFilterExample.ipynb
new file mode 100644
index 00000000..b5b55dc2
--- /dev/null
+++ b/notebooks/helpfiles/HybridFilterExample.ipynb
@@ -0,0 +1,127 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# HybridFilterExample (Python Translation)\\n",
+        "\\n",
+        "Source MATLAB file: `helpfiles/HybridFilterExample.m`\\n",
+        "Reference HTML file: `helpfiles/HybridFilterExample.html`\\n",
+        "\\n",
+        "## MATLAB HTML Reference\\n",
+        "- HTML title: **Hybrid Point Process Filter Example**\\n",
+        "\\n",
+        "### Expected Sections (from HTML)\\n",
+        "- Contents\n- Problem Statement\n- Generated Simulated Arm Reach\n- Simulate Neural Firing\\n",
+        "\\n",
+        "### Figure References (from HTML)\\n",
+        "- `HybridFilterExample_01.png`\n- `HybridFilterExample_02.png`\\n",
+        "\\n",
+        "### Sample Code Outputs (from HTML)\\n",
+        "_No `
` blocks found._\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import importlib\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find repository root')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root / 'python'\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "import re\n",
+        "import html as _html\n",
+        "\n",
+        "html_path = repo_root / 'helpfiles/HybridFilterExample.html'\n",
+        "if not html_path.exists():\n",
+        "    print('HTML reference missing:', html_path)\n",
+        "else:\n",
+        "    html_text = html_path.read_text(encoding='utf-8', errors='ignore')\n",
+        "    title_match = re.search(r'(.*?)', html_text, flags=re.I | re.S)\n",
+        "    title = _html.unescape(re.sub(r'<[^>]+>', '', title_match.group(1))).strip() if title_match else html_path.stem\n",
+        "    sections = [\n",
+        "        _html.unescape(re.sub(r'<[^>]+>', '', s)).strip()\n",
+        "        for s in re.findall(r']*>(.*?)', html_text, flags=re.I | re.S)\n",
+        "    ]\n",
+        "    sections = [s for s in sections if s]\n",
+        "    figs = sorted(set(re.findall(r'src=\"([^\"]+_\\d+\\.png)\"', html_text, flags=re.I)))\n",
+        "    print('HTML title:', title)\n",
+        "    print('Section count:', len(sections))\n",
+        "    for s in sections:\n",
+        "        print(' -', s)\n",
+        "    print('Figure refs:', len(figs))\n",
+        "    for f in figs[:20]:\n",
+        "        print(' -', f)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "module = importlib.import_module('matlab_port.helpfiles.HybridFilterExample')\n",
+        "if hasattr(module, 'run'):\n",
+        "    out = module.run(repo_root=repo_root)\n",
+        "elif hasattr(module, 'main'):\n",
+        "    out = module.main()\n",
+        "else:\n",
+        "    out = {'status': 'no run/main entrypoint'}\n",
+        "if isinstance(out, (dict, list)):\n",
+        "    print(json.dumps(out, indent=2, default=str))\n",
+        "else:\n",
+        "    print(out)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "comparison = {\n",
+        "    'python_output_type': type(out).__name__,\n",
+        "    'python_output_keys': sorted(list(out.keys())) if isinstance(out, dict) else [],\n",
+        "}\n",
+        "print(json.dumps(comparison, indent=2))\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/NetworkTutorial.ipynb b/notebooks/helpfiles/NetworkTutorial.ipynb
new file mode 100644
index 00000000..6fbba92a
--- /dev/null
+++ b/notebooks/helpfiles/NetworkTutorial.ipynb
@@ -0,0 +1,73 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# Example Data Analysis - Two Neuron Network Simulation and Estimation of Ensemble Effect\\n",
+        "\\n",
+        "Executable Python notebook generated from source help-topic scripts.\\n",
+        "MATLAB help target: `NetworkTutorial.html`\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'nstat').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find nSTAT repo root from notebook cwd')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from examples.help_topics.NetworkTutorial import run\n",
+        "out = run(repo_root=repo_root)\n",
+        "print(json.dumps(out, indent=2, default=str))\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "assert isinstance(out, dict)\n",
+        "assert 'topic' in out\n",
+        "print('Notebook execution check: PASS')\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/NeuralSpikeAnalysis_top.ipynb b/notebooks/helpfiles/NeuralSpikeAnalysis_top.ipynb
new file mode 100644
index 00000000..b09b6035
--- /dev/null
+++ b/notebooks/helpfiles/NeuralSpikeAnalysis_top.ipynb
@@ -0,0 +1,127 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# NeuralSpikeAnalysis_top (Python Translation)\\n",
+        "\\n",
+        "Source MATLAB file: `helpfiles/NeuralSpikeAnalysis_top.m`\\n",
+        "Reference HTML file: `helpfiles/NeuralSpikeAnalysis_top.html`\\n",
+        "\\n",
+        "## MATLAB HTML Reference\\n",
+        "- HTML title: **Neural Spike Train Analysis Toolbox (nSTAT)**\\n",
+        "\\n",
+        "### Expected Sections (from HTML)\\n",
+        "- (no sections found)\\n",
+        "\\n",
+        "### Figure References (from HTML)\\n",
+        "- (no figure files listed)\\n",
+        "\\n",
+        "### Sample Code Outputs (from HTML)\\n",
+        "_No `
` blocks found._\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import importlib\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find repository root')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root / 'python'\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "import re\n",
+        "import html as _html\n",
+        "\n",
+        "html_path = repo_root / 'helpfiles/NeuralSpikeAnalysis_top.html'\n",
+        "if not html_path.exists():\n",
+        "    print('HTML reference missing:', html_path)\n",
+        "else:\n",
+        "    html_text = html_path.read_text(encoding='utf-8', errors='ignore')\n",
+        "    title_match = re.search(r'(.*?)', html_text, flags=re.I | re.S)\n",
+        "    title = _html.unescape(re.sub(r'<[^>]+>', '', title_match.group(1))).strip() if title_match else html_path.stem\n",
+        "    sections = [\n",
+        "        _html.unescape(re.sub(r'<[^>]+>', '', s)).strip()\n",
+        "        for s in re.findall(r']*>(.*?)', html_text, flags=re.I | re.S)\n",
+        "    ]\n",
+        "    sections = [s for s in sections if s]\n",
+        "    figs = sorted(set(re.findall(r'src=\"([^\"]+_\\d+\\.png)\"', html_text, flags=re.I)))\n",
+        "    print('HTML title:', title)\n",
+        "    print('Section count:', len(sections))\n",
+        "    for s in sections:\n",
+        "        print(' -', s)\n",
+        "    print('Figure refs:', len(figs))\n",
+        "    for f in figs[:20]:\n",
+        "        print(' -', f)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "module = importlib.import_module('matlab_port.helpfiles.NeuralSpikeAnalysis_top')\n",
+        "if hasattr(module, 'run'):\n",
+        "    out = module.run(repo_root=repo_root)\n",
+        "elif hasattr(module, 'main'):\n",
+        "    out = module.main()\n",
+        "else:\n",
+        "    out = {'status': 'no run/main entrypoint'}\n",
+        "if isinstance(out, (dict, list)):\n",
+        "    print(json.dumps(out, indent=2, default=str))\n",
+        "else:\n",
+        "    print(out)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "comparison = {\n",
+        "    'python_output_type': type(out).__name__,\n",
+        "    'python_output_keys': sorted(list(out.keys())) if isinstance(out, dict) else [],\n",
+        "}\n",
+        "print(json.dumps(comparison, indent=2))\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/PPSimExample.ipynb b/notebooks/helpfiles/PPSimExample.ipynb
new file mode 100644
index 00000000..d8da9816
--- /dev/null
+++ b/notebooks/helpfiles/PPSimExample.ipynb
@@ -0,0 +1,73 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# Example Data Analysis - Simulated Explicit Stimulus and History\\n",
+        "\\n",
+        "Executable Python notebook generated from source help-topic scripts.\\n",
+        "MATLAB help target: `PPSimExample.html`\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'nstat').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find nSTAT repo root from notebook cwd')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from examples.help_topics.PPSimExample import run\n",
+        "out = run(repo_root=repo_root)\n",
+        "print(json.dumps(out, indent=2, default=str))\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "assert isinstance(out, dict)\n",
+        "assert 'topic' in out\n",
+        "print('Notebook execution check: PASS')\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/PPThinning.ipynb b/notebooks/helpfiles/PPThinning.ipynb
new file mode 100644
index 00000000..3e6cb2c5
--- /dev/null
+++ b/notebooks/helpfiles/PPThinning.ipynb
@@ -0,0 +1,73 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# Point Process Simulation via Thinning\\n",
+        "\\n",
+        "Executable Python notebook generated from source help-topic scripts.\\n",
+        "MATLAB help target: `PPThinning.html`\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'nstat').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find nSTAT repo root from notebook cwd')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from examples.help_topics.PPThinning import run\n",
+        "out = run(repo_root=repo_root)\n",
+        "print(json.dumps(out, indent=2, default=str))\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "assert isinstance(out, dict)\n",
+        "assert 'topic' in out\n",
+        "print('Notebook execution check: PASS')\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/PSTHEstimation.ipynb b/notebooks/helpfiles/PSTHEstimation.ipynb
new file mode 100644
index 00000000..c9a6d74e
--- /dev/null
+++ b/notebooks/helpfiles/PSTHEstimation.ipynb
@@ -0,0 +1,73 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# Example Data Analysis - Simulated Data - Computing a Peri-Stimulus Time Histogram (PSTH)\\n",
+        "\\n",
+        "Executable Python notebook generated from source help-topic scripts.\\n",
+        "MATLAB help target: `PSTHEstimation.html`\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'nstat').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find nSTAT repo root from notebook cwd')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from examples.help_topics.PSTHEstimation import run\n",
+        "out = run(repo_root=repo_root)\n",
+        "print(json.dumps(out, indent=2, default=str))\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "assert isinstance(out, dict)\n",
+        "assert 'topic' in out\n",
+        "print('Notebook execution check: PASS')\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/SignalObjExamples.ipynb b/notebooks/helpfiles/SignalObjExamples.ipynb
new file mode 100644
index 00000000..69a3e0a7
--- /dev/null
+++ b/notebooks/helpfiles/SignalObjExamples.ipynb
@@ -0,0 +1,73 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# Using the SignalObj Class\\n",
+        "\\n",
+        "Executable Python notebook generated from source help-topic scripts.\\n",
+        "MATLAB help target: `SignalObjExamples.html`\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'nstat').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find nSTAT repo root from notebook cwd')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from examples.help_topics.SignalObjExamples import run\n",
+        "out = run(repo_root=repo_root)\n",
+        "print(json.dumps(out, indent=2, default=str))\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "assert isinstance(out, dict)\n",
+        "assert 'topic' in out\n",
+        "print('Notebook execution check: PASS')\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/StimulusDecode2D.ipynb b/notebooks/helpfiles/StimulusDecode2D.ipynb
new file mode 100644
index 00000000..fac9a794
--- /dev/null
+++ b/notebooks/helpfiles/StimulusDecode2D.ipynb
@@ -0,0 +1,73 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# Example Data Analysis - Decoding Bivariate Simulated Stimuli\\n",
+        "\\n",
+        "Executable Python notebook generated from source help-topic scripts.\\n",
+        "MATLAB help target: `StimulusDecode2D.html`\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'nstat').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find nSTAT repo root from notebook cwd')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from examples.help_topics.StimulusDecode2D import run\n",
+        "out = run(repo_root=repo_root)\n",
+        "print(json.dumps(out, indent=2, default=str))\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "assert isinstance(out, dict)\n",
+        "assert 'topic' in out\n",
+        "print('Notebook execution check: PASS')\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/TrialConfigExamples.ipynb b/notebooks/helpfiles/TrialConfigExamples.ipynb
new file mode 100644
index 00000000..6698df24
--- /dev/null
+++ b/notebooks/helpfiles/TrialConfigExamples.ipynb
@@ -0,0 +1,73 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# Using the TrialConfig Class\\n",
+        "\\n",
+        "Executable Python notebook generated from source help-topic scripts.\\n",
+        "MATLAB help target: `TrialConfigExamples.html`\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'nstat').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find nSTAT repo root from notebook cwd')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from examples.help_topics.TrialConfigExamples import run\n",
+        "out = run(repo_root=repo_root)\n",
+        "print(json.dumps(out, indent=2, default=str))\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "assert isinstance(out, dict)\n",
+        "assert 'topic' in out\n",
+        "print('Notebook execution check: PASS')\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/TrialExamples.ipynb b/notebooks/helpfiles/TrialExamples.ipynb
new file mode 100644
index 00000000..d8fa5116
--- /dev/null
+++ b/notebooks/helpfiles/TrialExamples.ipynb
@@ -0,0 +1,73 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# Using the Trial Class\\n",
+        "\\n",
+        "Executable Python notebook generated from source help-topic scripts.\\n",
+        "MATLAB help target: `TrialExamples.html`\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'nstat').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find nSTAT repo root from notebook cwd')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from examples.help_topics.TrialExamples import run\n",
+        "out = run(repo_root=repo_root)\n",
+        "print(json.dumps(out, indent=2, default=str))\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "assert isinstance(out, dict)\n",
+        "assert 'topic' in out\n",
+        "print('Notebook execution check: PASS')\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/ValidationDataSet.ipynb b/notebooks/helpfiles/ValidationDataSet.ipynb
new file mode 100644
index 00000000..85be0eec
--- /dev/null
+++ b/notebooks/helpfiles/ValidationDataSet.ipynb
@@ -0,0 +1,73 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# Example Data Analysis - Simulated Constant (Piecewise Constant) Rate Poisson\\n",
+        "\\n",
+        "Executable Python notebook generated from source help-topic scripts.\\n",
+        "MATLAB help target: `ValidationDataSet.html`\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'nstat').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find nSTAT repo root from notebook cwd')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from examples.help_topics.ValidationDataSet import run\n",
+        "out = run(repo_root=repo_root)\n",
+        "print(json.dumps(out, indent=2, default=str))\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "assert isinstance(out, dict)\n",
+        "assert 'topic' in out\n",
+        "print('Notebook execution check: PASS')\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/mEPSCAnalysis.ipynb b/notebooks/helpfiles/mEPSCAnalysis.ipynb
new file mode 100644
index 00000000..dfd4e9fd
--- /dev/null
+++ b/notebooks/helpfiles/mEPSCAnalysis.ipynb
@@ -0,0 +1,73 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# Example Data Analysis - Miniature Excitatory Post-Synaptic Currents (mEPSCs)\\n",
+        "\\n",
+        "Executable Python notebook generated from source help-topic scripts.\\n",
+        "MATLAB help target: `mEPSCAnalysis.html`\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'nstat').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find nSTAT repo root from notebook cwd')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from examples.help_topics.mEPSCAnalysis import run\n",
+        "out = run(repo_root=repo_root)\n",
+        "print(json.dumps(out, indent=2, default=str))\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "assert isinstance(out, dict)\n",
+        "assert 'topic' in out\n",
+        "print('Notebook execution check: PASS')\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/nSTATPaperExamples.ipynb b/notebooks/helpfiles/nSTATPaperExamples.ipynb
new file mode 100644
index 00000000..aa4ee45b
--- /dev/null
+++ b/notebooks/helpfiles/nSTATPaperExamples.ipynb
@@ -0,0 +1,73 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# nSTAT Paper Examples\\n",
+        "\\n",
+        "Executable Python notebook generated from source help-topic scripts.\\n",
+        "MATLAB help target: `nSTATPaperExamples.html`\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'nstat').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find nSTAT repo root from notebook cwd')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from examples.help_topics.nSTATPaperExamples import run\n",
+        "out = run(repo_root=repo_root)\n",
+        "print(json.dumps(out, indent=2, default=str))\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "assert isinstance(out, dict)\n",
+        "assert 'topic' in out\n",
+        "print('Notebook execution check: PASS')\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/nSpikeTrainExamples.ipynb b/notebooks/helpfiles/nSpikeTrainExamples.ipynb
new file mode 100644
index 00000000..54d8da73
--- /dev/null
+++ b/notebooks/helpfiles/nSpikeTrainExamples.ipynb
@@ -0,0 +1,73 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# Using the nSpikeTrain Class\\n",
+        "\\n",
+        "Executable Python notebook generated from source help-topic scripts.\\n",
+        "MATLAB help target: `nSpikeTrainExamples.html`\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'nstat').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find nSTAT repo root from notebook cwd')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from examples.help_topics.nSpikeTrainExamples import run\n",
+        "out = run(repo_root=repo_root)\n",
+        "print(json.dumps(out, indent=2, default=str))\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "assert isinstance(out, dict)\n",
+        "assert 'topic' in out\n",
+        "print('Notebook execution check: PASS')\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/nstCollExamples.ipynb b/notebooks/helpfiles/nstCollExamples.ipynb
new file mode 100644
index 00000000..f2295d6a
--- /dev/null
+++ b/notebooks/helpfiles/nstCollExamples.ipynb
@@ -0,0 +1,73 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# Using the nstColl Class\\n",
+        "\\n",
+        "Executable Python notebook generated from source help-topic scripts.\\n",
+        "MATLAB help target: `nstCollExamples.html`\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'nstat').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find nSTAT repo root from notebook cwd')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from examples.help_topics.nstCollExamples import run\n",
+        "out = run(repo_root=repo_root)\n",
+        "print(json.dumps(out, indent=2, default=str))\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "assert isinstance(out, dict)\n",
+        "assert 'topic' in out\n",
+        "print('Notebook execution check: PASS')\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/notebooks/helpfiles/temp.ipynb b/notebooks/helpfiles/temp.ipynb
new file mode 100644
index 00000000..01c023cc
--- /dev/null
+++ b/notebooks/helpfiles/temp.ipynb
@@ -0,0 +1,127 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# temp (Python Translation)\\n",
+        "\\n",
+        "Source MATLAB file: `helpfiles/temp.m`\\n",
+        "Reference HTML file: `helpfiles/temp.html`\\n",
+        "\\n",
+        "## MATLAB HTML Reference\\n",
+        "- HTML title: **(missing)**\\n",
+        "\\n",
+        "### Expected Sections (from HTML)\\n",
+        "- (no sections found)\\n",
+        "\\n",
+        "### Figure References (from HTML)\\n",
+        "- (no figure files listed)\\n",
+        "\\n",
+        "### Sample Code Outputs (from HTML)\\n",
+        "_No `
` blocks found._\\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from pathlib import Path\n",
+        "import sys\n",
+        "import importlib\n",
+        "import json\n",
+        "\n",
+        "def find_repo_root(start: Path) -> Path:\n",
+        "    cur = start.resolve()\n",
+        "    for p in [cur, *cur.parents]:\n",
+        "        if (p / '.git').exists() and (p / 'helpfiles').exists():\n",
+        "            return p\n",
+        "    raise RuntimeError('Could not find repository root')\n",
+        "\n",
+        "repo_root = find_repo_root(Path.cwd())\n",
+        "py_root = repo_root / 'python'\n",
+        "if str(py_root) not in sys.path:\n",
+        "    sys.path.insert(0, str(py_root))\n",
+        "print('repo_root =', repo_root)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "import re\n",
+        "import html as _html\n",
+        "\n",
+        "html_path = repo_root / 'helpfiles/temp.html'\n",
+        "if not html_path.exists():\n",
+        "    print('HTML reference missing:', html_path)\n",
+        "else:\n",
+        "    html_text = html_path.read_text(encoding='utf-8', errors='ignore')\n",
+        "    title_match = re.search(r'(.*?)', html_text, flags=re.I | re.S)\n",
+        "    title = _html.unescape(re.sub(r'<[^>]+>', '', title_match.group(1))).strip() if title_match else html_path.stem\n",
+        "    sections = [\n",
+        "        _html.unescape(re.sub(r'<[^>]+>', '', s)).strip()\n",
+        "        for s in re.findall(r']*>(.*?)', html_text, flags=re.I | re.S)\n",
+        "    ]\n",
+        "    sections = [s for s in sections if s]\n",
+        "    figs = sorted(set(re.findall(r'src=\"([^\"]+_\\d+\\.png)\"', html_text, flags=re.I)))\n",
+        "    print('HTML title:', title)\n",
+        "    print('Section count:', len(sections))\n",
+        "    for s in sections:\n",
+        "        print(' -', s)\n",
+        "    print('Figure refs:', len(figs))\n",
+        "    for f in figs[:20]:\n",
+        "        print(' -', f)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "module = importlib.import_module('matlab_port.helpfiles.temp')\n",
+        "if hasattr(module, 'run'):\n",
+        "    out = module.run(repo_root=repo_root)\n",
+        "elif hasattr(module, 'main'):\n",
+        "    out = module.main()\n",
+        "else:\n",
+        "    out = {'status': 'no run/main entrypoint'}\n",
+        "if isinstance(out, (dict, list)):\n",
+        "    print(json.dumps(out, indent=2, default=str))\n",
+        "else:\n",
+        "    print(out)\n"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "comparison = {\n",
+        "    'python_output_type': type(out).__name__,\n",
+        "    'python_output_keys': sorted(list(out.keys())) if isinstance(out, dict) else [],\n",
+        "}\n",
+        "print(json.dumps(comparison, indent=2))\n"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python",
+      "version": "3"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}
\ No newline at end of file
diff --git a/nspikeTrain.m b/nspikeTrain.m
deleted file mode 100644
index 6c19712c..00000000
--- a/nspikeTrain.m
+++ /dev/null
@@ -1,962 +0,0 @@
-classdef nspikeTrain < handle
-% NSPIKETRAIN A neural spike train object consists of a sequence of
-% spikeTimes. The spike train can be represented as a SignalObj with a
-% particular sampling rate. The 1/sampleRate (sampling period) is larger
-% that the difference between any two spike times, the neural spike train
-% will no longer have a binary representation.
-%
-% Usage:
-% nst=nspikeTrain(spikeTimes,name,binwidth,minTime,maxTime, varargin)
-%      spikeTimes: row or column vector of spike times. 
-%
-%      OPTIONAL INPUTS:
-%      name:       name of neuron data recorded from. Default='';
-%
-%      binwidth:   binwidth to be used for SignalObj representation of
-%                  spikeTimes. Default: 0.01 sec/bin
-%
-%      minTime:    Default is min(spikeTimes)
-%
-%      maxTime:    Default is max(spikeTimes)
-%
-%      varargin: xlabelval, xunits, yunits,dataLabels in that order can be
-%      passed to the SignalObj constructor for the signal representation of
-%      the neural spike train.
-%
-% methods
-% nSpikeTrain Examples 
-%
-% see also Covariate, SignalObj
-% 
-% Reference page in Help browser
-% doc nspikeTrain
-
-
-%
-% nSTAT v1 Copyright (C) 2012 Masschusetts Institute of Technology
-% Cajigas, I, Malik, WQ, Brown, EN
-% This program is free software; you can redistribute it and/or 
-% modify it under the terms of the GNU General Public License as published 
-% by the Free Software Foundation; either version 2 of the License, or 
-% (at your option) any later version.
-% 
-% This program is distributed in the hope that it will be useful, 
-% but WITHOUT ANY WARRANTY; without even the implied warranty of 
-% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
-% See the GNU General Public License for more details.
-%  
-% You should have received a copy of the GNU General Public License 
-% along with this program; if not, write to the Free Software Foundation, 
-% Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-    properties (SetAccess = private)
-        name        % name of the nspikeTrain
-        spikeTimes  % collection of times at which spikes occured
-        
-        sigRep      % SignalObj representation of nspikeTrain 
-        sampleRate  % sampleRate for the sigRep
-        maxTime     % maximum time of interest or time of last spike
-        minTime     % minimum time of interest or time of first spike
-        
-        %%TODO add listener to each spike train so that consistency is
-        %%guaranteed of objects are modified.
-        isSigRepBin % Boolean indicating 1 or 0 spikes occur per bin
-        xlabelval
-        xunits
-        yunits
-        dataLabels
-        MER  %signal of the micro-electrode recordings when available 
-        avgFiringRate
-        %Bursting related parameters%
-        B    %burstiness parameter
-        An   %burtiness parameters without finite sample effect - Kim, E.-K., & Jo, H.-H. (2016). Measuring burstiness for finite event sequences. Physical Review E, 94(3). http://doi.org/10.1103/physreve.94.032311
-        burstTimes
-        burstRate
-        burstDuration
-        burstSig
-        burstIndex % Hutchinson, et al. 1997 Effects of Apomorphine on GP Neurons in parkinsian Patients
-        numBursts
-        numSpikesPerBurst
-        avgSpikesPerBurst
-        stdSpikesPerBurst
-        Lstatistic  % Goldberg et. al 2002. Enhanced Synchrony among Primary Motor Cortex Neurons in the
-                    % 1-Methyl-4-Phenyl-1,2,3,6-Tetrahydropyridine Primate Model of Parkinson’s Disease
-    end
-    
-    methods
-        function nst=nspikeTrain(spikeTimes,name,binwidth,minTime,maxTime, xlabelval, xunits, yunits,dataLabels,makePlots)
-            %constructor
-            if(nargin<10|| isempty(makePlots))
-                makePlots=0;
-            end
-            if(nargin<9 || isempty(dataLabels))
-                dataLabels = '';
-            end
-            if(nargin<8 || isempty(yunits))
-                yunits='';
-            end
-            if(nargin<7 || isempty(xunits))
-                xunits='s';
-            end
-            if(nargin<6 || isempty(xlabelval))
-                xlabelval='time';
-            end
-            if(nargin<5)
-                maxTime = max(spikeTimes);
-                if(isempty(maxTime))
-                    maxTime=0;
-                end
-            end
-            if(nargin<4)
-                minTime= min(spikeTimes);
-                if(isempty(minTime))
-                    minTime=0;
-                end
-            end
-            if(nargin<3)
-                binwidth=.001;
-            end
-            if(nargin<2)
-                name='';
-            end
-            if(nargin<1)
-                error('nspikeTrain requires a spikeTimes array as input to create an object');
-            end
-            [l,w]=size(spikeTimes);
-            if(l>w)
-                nst.spikeTimes=spikeTimes';      
-            else
-                nst.spikeTimes=spikeTimes;
-            end
-            
-            nst.name=name;
-            nst.sampleRate = 1/binwidth;
-            nst.minTime = minTime;
-            nst.maxTime = maxTime;
-            nst.xlabelval = xlabelval;
-            nst.xunits = xunits;
-            nst.yunits = yunits;
-            nst.dataLabels = dataLabels;
-%             nst.setSigRep(binwidth, minTime, maxTime,varargin{:});
-
-            nst.sigRep = [];
-            nst.isSigRepBin=[];
-
-            nst.computeStatistics(makePlots);            
-        end
-        function Lstat = getLStatistic(nstObj)
-           mISIs = mean(nstObj.getISIs); 
-           Pt = nstObj.getSigRep(mISIs);
-           Lstat = length(unique(Pt.data));
-         
-        end
-%         function shift(nstObj,deltaT)
-%            nstObj.spikeTimes = nstObj.spikeTimes + deltaT;
-%            nstObj.setMinTime(nstObj.minTime+deltaT);
-%            nstObj.setMaxTime(nstObj.maxTime+deltaT);
-%            nstOb.sigRep = [];
-%         end
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        %Set functions    
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        function setMER(nstObj,MERSig)
-           if(isa(MERSig,'SignalObj'))
-                nstObj.MER = MERSig;
-           end
-        end
-           
-        function setName(nstObj,name)
-           % setName(nstObj,name) 
-           % set the name after construction
-           nstObj.name = name;
-%            if(~isempty(nstObj.sigRep))
-%                 nstObj.sigRep.setName(name);
-%            end
-        end
-        
-        function computeStatistics(nstObj,makePlots)
-            if(nargin<2 || isempty(makePlots))
-                makePlots = 0;
-            end
-            ISI=nstObj.getISIs;
-            spikeTimes =nstObj.spikeTimes;    
-            nstObj.avgFiringRate = length(spikeTimes)/(nstObj.maxTime - nstObj.minTime);
-            
-            
-            %% Compute Burst Parameters
-            % Hutchinson, et al. 1997
-            if(~isempty(ISI))
-                nstObj.burstIndex=1/mode(ISI)/nstObj.avgFiringRate;
-            
-                % Cells havingburst index values of approximately 1 to 1.5 had regular firing 
-                % intervals (ie, Border cells), cells in the range of 1.6 to 9.9 were “irregular” firing cells,
-                % and those with values greater that 10 were termed bursting cells.
-            
-            
-                % Kim, E.-K., & Jo, H.-H. (2016). Measuring burstiness for finite 
-                % event sequences. Physical Review E, 94(3), 032311. 
-                % http://doi.org/10.1103/PhysRevE.94.032311
-                sigma=std(ISI);
-                mu = mean(ISI);
-                r= sigma/mu;
-                nstObj.B = (r-1)/(r+1);  %burstiness index for infinite sequence
-                %B has the value of ?1 for regular time series as ? = 0, and 0 for Poissonian or random time series as ? = µ. Finally, the value of B approaches 1 for extremely bursty time series as ? ? ? for finite µ.
-                n=length(spikeTimes);
-                nstObj.An=(sqrt(n+2)*r-sqrt(n))./((sqrt(n+2)-2)*r+sqrt(n)); %corrected burstiness index for finite sequence
-
-               % Chen, L., Deng, Y., Luo, W., Wang, Z., & Zeng, S. (2009). Detection of bursts in 
-               % neuronal spike trains by the mean inter-spike interval method. Progress in Natural 
-               % Science, 19(2), 229. http://doi.org/10.1016/j.pnsc.2008.05.027
-                Ln = ISI(ISI1;
-
-    %             else
-    % %                 y=filtfilt(B,A,burstISI)>1;
-    %             end
-                diffSig = [0;diff(y)];
-                tdiff = (t(1:end-1)+t(2:end))/2;
-
-
-
-
-                burstStart = find(diffSig==1);
-                burstEnd=find(diffSig==-1)+1;
-                if(isempty(burstStart))
-                    burstEnd=[];
-                    nstObj.burstDuration = [];
-                    nstObj.burstSig = [];
-                    nstObj.numSpikesPerBurst =[];
-                    nstObj.numBursts=[];
-                    nstObj.burstRate=[];
-
-                end
-
-                if(length(burstEnd)>length(burstStart))
-                    burstStart = [find(y(1:burstEnd(1))==1,1, 'first'); burstStart];
-                end
-
-                if(length(burstStart)>length(burstEnd))
-                    burstEnd = [find(y(burstStart(end):end)==1, 1,'last'); burstEnd];
-                end
-
-                if(~isempty(burstStart))
-                    if(makePlots==1)
-                        close all;
-                        nstObj.plot; hold on;
-                        plot(tdiff, ISI,'ko');
-                        plot([t(1) t(end)], ML*[1;1]); 
-                        plot(tdiff, diffSig,'r--');
-                        axis tight;
-                        plot(t(burstStart),1.2*ones(length(burstStart)),'bo'); hold on;
-                        plot(t(burstEnd),1.2*ones(length(burstEnd)),'bd');
-                    end
-                    burstData = zeros(length(spikeTimes),1);
-                    for i=1:length(burstStart)
-                        burstData(burstStart(i):burstEnd(i))=1;
-                    end
-
-                    nstObj.burstDuration = nstObj.spikeTimes(burstEnd)-nstObj.spikeTimes(burstStart);
-                    nstObj.burstSig = SignalObj(nstObj.spikeTimes,burstData,'Burst Signal');
-                    nstObj.burstTimes = nstObj.spikeTimes(burstStart);
-                    nstObj.numBursts=length(burstStart);
-                    nstObj.burstRate=nstObj.numBursts/(nstObj.maxTime-nstObj.minTime);
-                    nstObj.numSpikesPerBurst =burstEnd-burstStart + 1;
-                    nstObj.avgSpikesPerBurst = mean(nstObj.numSpikesPerBurst+1);
-                    nstObj.stdSpikesPerBurst = std(nstObj.numSpikesPerBurst+1);
-                    nstObj.Lstatistic        = nstObj.getLStatistic; %Goldberg et al 2002.
-                end
-            end    
-            
-        end
-        
-        function sigRep = setSigRep(nstObj,binwidth,minTime,maxTime)
-            %sigRep = setSigRep(nstObj, binwidth, minTime, maxTime)
-              nstObj.sigRep = nstObj.getSigRep(binwidth,minTime,maxTime);
-              nstObj.isSigRepBin = nstObj.isSigRepBinary;
-              nstObj.sampleRate = nstObj.sigRep.sampleRate;
-%               sigRep=nstObj.sigRep;
-              nstObj.setMinTime(nstObj.sigRep.minTime);
-              nstObj.setMaxTime(nstObj.sigRep.maxTime);
-        end        
-        function setMinTime(nstObj,minTime)
-           % setMinTime(sObj,nstObj)
-           % sets the minimun value of the time vector for the SignalObj representation of the nspikeTrain.
-           %nstObj.sigRep.setMinTime(minTime);
-           nstObj.minTime=minTime;
-           nstObj.computeStatistics;
-%            nstObj.clearSigRep;
-        end        
-%         function answer = get.isSigRepBin(nstObj)
-%             answer = nstObj.isSigRepBinary;
-%         end
-        function setMaxTime(nstObj,maxTime)
-           % setMaxTime(sObj,nstObj)
-           % sets the maximum value of the time vector for the SignalObj
-           % representation of the nspikeTrain.
-           %nstObj.sigRep.setMaxTime(maxTime);
-           nstObj.maxTime=maxTime;
-           nstObj.computeStatistics;
-%            nstObj.clearSigRep;
-        end
-        function clearSigRep(nstObj)
-           nstObj.sigRep=[];
-        end
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        % Get Functions
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        function nstObj = resample(nstObj,sampleRate)
-            % resample(nstObj,sampleRate)
-            % change the sampleRate or equivalently the binwidth of the
-            % SignalObj representation of the nSpikeTrain
-            % may change the nstObj.isSigRepBin value is the binwidth is
-            % great than nstObj.getMaxBinSizeBinary
-%             s=nstObj.sigRep;
-            binwidth=1/sampleRate;
-            nstObj.setSigRep(binwidth,nstObj.minTime,nstObj.maxTime);
-            nstObj.sampleRate = sampleRate;
-        end       
-
-        
-        function sigRep=getSigRep(nstObj,binwidth,minTime,maxTime)
-            % sigRep=getSigRep(nstObj,binwidth,minTime,maxTime)
-            % returns the SignalObj representation of the nspikeTrain with
-            % the parameters specified.
-            %
-            % binwidth: defaults to 1/nstObj.sampleRate if argument missing
-            % or
-            %           empty.
-            %
-            % minTime : defaults to nstObj.minTime if argument missing or
-            %           empty.
-            %
-            % maxTime : defaults to nstObj.maxTime if argument missing or
-            %           empty.
-            %if(nargin==1)
-            %    sigRep = nstObj.sigRep;
-            %else
-                % varargin: xlabelval, xunits, yunits,dataLabels
-                if((nargin<4) || isempty(maxTime))
-                    maxTime=nstObj.maxTime;
-                end
-                if((nargin<3) || isempty(minTime))
-                    minTime=nstObj.minTime;
-                end
-                if((nargin<2) || isempty(binwidth))
-                    binwidth=1/nstObj.sampleRate; 
-                    precision =2*ceil(log10(nstObj.sampleRate));
-                    binwidth = roundn(binwidth,-precision); 
-                end
-                precision =2*ceil(log10(1/binwidth));
-                binwidth = roundn(binwidth,-precision); 
-                if(and(~isempty(maxTime),~isempty(minTime)))
-                %                     timeVec=linspace(minTime,maxTime,ceil((1/binwidth)*abs(maxTime-minTime)/binwidth)*binwidth+1); %scaling by binwidth to avoid roundoff error
-                timeVec=linspace(minTime,maxTime,(maxTime-minTime)./binwidth +1);%:binwidth:maxTime;
-                windowTimes=[minTime-binwidth/2 timeVec+binwidth/2];
-                else
-                  timeVec = [];
-                  windowTimes=[];
-                end
-                data=zeros(length(timeVec),1);
-                  
-
-    
-                  %If we already have the right signal representation they dont
-                  %waste time.
-                   if(~isempty(nstObj.sigRep))
-                        if((nstObj.sigRep.sampleRate==nstObj.sampleRate) && min(nstObj.sigRep.time)==minTime && max(nstObj.sigRep.time)==maxTime)
-                             sigRep = nstObj.sigRep.copySignal;
-                        else %create the appropriate representation
-
-                            spikeTimes = nstObj.spikeTimes;
-%                             spikeTimes = round(spikeTimes*nstObj.sampleRate*2)/(nstObj.sampleRate*2);
-                            spikeTimes = roundn(spikeTimes,-precision);
-%                             windowTimes    = round(windowTimes*nstObj.sampleRate*2)/(2*nstObj.sampleRate);
-                            windowTimes    = roundn(windowTimes,-precision-1);
-                            lwindowTimes = length(windowTimes);
-                            for j=1:length(timeVec) %number of bins
-                                if(j==(lwindowTimes-1))
-                                    tempSpikes=spikeTimes(spikeTimes>=windowTimes(j));
-                                    data(j)=sum(tempSpikes<=windowTimes(j+1));
-%                                     data(j) = sum((spikeTimes>=windowTimes(j) & spikeTimes<=windowTimes(j+1)));
-                                elseif(j>floor(lwindowTimes/2))
-                                    tempSpikes=spikeTimes(spikeTimes>=windowTimes(j));
-                                    data(j)=sum(tempSpikes=windowTimes(j) & spikeTimes=windowTimes(j));
-                                end
-                            end
-                        
-%                             tV=repmat(timeVec,[length(spikeTimes) 1]);
-%                             sT=repmat(spikeTimes',[1 length(timeVec)-1]);
-%                             data= sT>=tV(:,1:end-1) & sT=tV(:,end-1) & sT(:,end)<=tV(:,end);
-% %                             data=[sum(data) 0];
-                         
-                            sigRep = SignalObj(timeVec, data',nstObj.name,nstObj.xlabelval, nstObj.xunits, nstObj.yunits, nstObj.dataLabels);
-                            nstObj.sigRep = sigRep;
-                            if(max(sigRep.data)>1)
-                                nstObj.isSigRepBin=0;
-                            else
-                                nstObj.isSigRepBin=1;
-                            end
-%                             nstObj.isSigRepBin=nstObj.isSigRepBinary;
-                        end 
-                   else
-                        %rounding avoids comparison errors due to
-                        %differences in non-significant digits
-                        spikeTimes = nstObj.spikeTimes;
-%                             spikeTimes = round(spikeTimes*nstObj.sampleRate*2)/(nstObj.sampleRate*2);
-                        spikeTimes = roundn(spikeTimes,-precision);
-%                             windowTimes    = round(windowTimes*nstObj.sampleRate*2)/(2*nstObj.sampleRate);
-                        windowTimes    = roundn(windowTimes,-precision-1);
-                        lwindowTimes = length(windowTimes);
-                        %                         ltimeVec = length(timeVec);
-                        for j=1:length(timeVec) %number of bins
-                            if(j==(lwindowTimes)-1)
-                                tempSpikes=spikeTimes(spikeTimes>=windowTimes(j));
-                                data(j)=sum(tempSpikes<=windowTimes(j+1));
-                        %                                     data(j) = sum((spikeTimes>=windowTimes(j) & spikeTimes<=windowTimes(j+1)));
-                            elseif(j>floor(lwindowTimes/2))
-                                tempSpikes=spikeTimes(spikeTimes>=windowTimes(j));
-                                data(j)=sum(tempSpikes=windowTimes(j) & spikeTimes=windowTimes(j));
-                            end
-                        end
-                    
-%                         timeVec    = round(timeVec*nstObj.sampleRate)/nstObj.sampleRate;
-%                         for j=1:length(timeVec)-1 %number of bins
-%                             if(j==(length(timeVec)-1))
-%                                     data(j) = sum((spikeTimes>=timeVec(j) & spikeTimes<=timeVec(j+1)));
-%                             else
-%                                     data(j) = sum((spikeTimes>=timeVec(j) & spikeTimes=tV(:,1:end-1) & sT=tV(:,end-1) & sT(:,end)<=tV(:,end);
-%                          data=[sum(data) 0];
-                        
-                        sigRep = SignalObj(timeVec, data',nstObj.name,nstObj.xlabelval, nstObj.xunits, nstObj.yunits, nstObj.dataLabels);
-                        nstObj.sigRep = sigRep;
-                        if(max(sigRep.data)>1)
-                            nstObj.isSigRepBin=0;
-                        else
-                            nstObj.isSigRepBin=1;
-                        end
-                    end
-                    nstObj.sigRep = sigRep;
-                    if(max(sigRep.data)>1)
-                        nstObj.isSigRepBin=0;
-                    else
-                        nstObj.isSigRepBin=1;
-                    end
-            %end
-        end
-        function maxBinSize=getMaxBinSizeBinary(nstObj)
-            % maxBinSize=getMaxBinSizeBinary(nstObj)
-            % returns the maximum binsize or binwidth at which the
-            % nspikeTrain still has a binary SignalObj representation
-            if(length(nstObj.spikeTimes)>1)
-                maxBinSize=min(diff(nstObj.spikeTimes));
-            else
-                maxBinSize=inf;
-            end
-        end
-        function h = plotISISpectrumFunction(nstObj)
-            figure;
-            ISI=nstObj.getISIs;
-            spikeTimes =nstObj.spikeTimes;
-            h=plot(spikeTimes(2:end),ISI,'.');
-            xlabel('time [s]');
-            
-            ylabel('ISI [s]');
-            sigma=std(ISI);
-            mu = mean(ISI);
-            r= sigma/mu;
-            B = (r-1)/(r+1);
-            n=length(spikeTimes);
-            An=(sqrt(n+2)*r-sqrt(n))./((sqrt(n+2)-2)*r+sqrt(n));
-        end
-        
-        function windowedSpikeTimes = getSpikeTimes(nstObj, minTime,maxTime)
-            if(nargin<3)
-                maxTime = nstObj.maxTime;
-            end
-            if(nargin<2)
-                minTime = nstObj.minTime;
-            end
-            index = and((nstObj.spikeTimes>=minTime),(nstObj.spikeTimes<=maxTime));
-            windowedSpikeTimes = nstObj.spikeTimes(index);
-        end
-        function h = plotJointISIHistogram(nstObj)
-            % based on: Detection of bursts in neuronal spike trains by the mean inter-spike interval method. (n.d.). Detection of bursts in neuronal spike trains by the mean inter-spike interval method.
-            
-            ISIs = nstObj.getISIs;
-            meanISI = mean(ISIs);
-            Ln = ISIs(ISIs=minTime, ISIs<=maxTime);
-%             ISIs = ISIs(index);
-            binWidth=.001; %max(ISIs)/numBins;
-%             binWidth=1/numBins;
-            if(~isempty(ISIs))
-                bins=0:binWidth:max(ISIs);
-
-                %Make the ISI Histogram            
-                counts = histc(ISIs,bins);
-
-                %set(gcf,'CurrentAxes',handle);
-                %bar(bins,histc(ISIs,bins)./sum(binWidth*counts),'histc');
-                h=bar(bins,histc(ISIs,bins),'histc');
-                set(h,'MarkerEdgeColor',[0 0 0],...
-                'LineWidth',2,...
-                'FaceColor',[0.831372559070587 0.815686285495758 0.7843137383461]);
-            end
-            
-            
-            axis tight;
-            hx=xlabel('ISI [sec]');
-%             hy=ylabel([nstObj.name ' counts']);
-            hy=ylabel('Spike Counts');
-            set([hx, hy],'FontName', 'Arial','FontSize',16,'FontWeight','bold');
-            v=axis;
-            axis tight;
-%             axis([minTime, maxTime, v(3:4)]);
-            
-            %histfit(ISIs,numBins,'exponential');
-%             h = get(gca,'Children');
-%             set(h,'FaceColor',[.8 .8 1])
-
-            
-            %Fit exponential distribution to the data
-%             [muhat,muci] = expfit(ISIs);
-%             x=linspace(0,max(bins),1000);
-%             y=exppdf(x,muhat);%;*1/muhat;
-%             ci(:,1) = exppdf(x,muci(1));%*1/muci(1);
-%             ci(:,2) = exppdf(x,muci(2));%*1/muci(2);
-%             xpatch=[x fliplr(x)];
-%             ypatch=[ci(:,1)',fliplr(ci(:,2)')];
-            
-%             hold on;
-%             hfit1=plot(x,y,'r','Linewidth',3); %plot fit
-%             p=patch(xpatch,ypatch,'r');
-%             set(p,'facecolor','r','edgecolor','none'); %plot CI
-%             alpha(.5);
-            
-            %Fit Weibul Distribution to Data
-%             [parmhat,parmci] = wblfit(ISIs);
-%             y = wblpdf(x,parmhat(1),parmhat(2));
-%             hfit2=plot(x,y,'k','Linewidth',3); %plot fit
-%             
-            
-            %Fit Gamma Distribution
-%             [phat,pci] = gamfit(ISIs);
-%             y = gampdf(x,phat(1),phat(2));
-%             hfit3=plot(x,y,'g','Linewidth',3); %plot fit
-%             
-%             [phat,pci]=raylfit(ISIs)
-%             y = raylpdf(x,phat) 
-%         
-%             numDigits=3;
-%             expStr = ['exp: \lambda=' num2str(1/muhat,numDigits) ' [' num2str(1/muci(2),numDigits) ', ' num2str(1/muci(1),numDigits) ']'];
-%              expStr = ['\lambda=' num2str(1/muhat,numDigits) ' [' num2str(1/muci(2),numDigits) ', ' num2str(1/muci(1),numDigits) ']'];
-%             wblStr = ['weib: shape=' num2str(parmhat(2),numDigits) ', scale=' num2str(parmhat(1),numDigits)]; %scale and shape
-%             gammaStr=['\Gamma: shape=' num2str(phat(1),numDigits) ', scale =' num2str(phat(2),numDigits)]; %shape and scale
-%             legend([hfit1(1) hfit2(1) hfit3(1)] ,{expStr,wblStr,gammaStr});
-%             
-%             legend(hfit1(1) ,expStr);
-
-
-%             subplot(1,2,2); nstObj.plotProbPlot(minTime,maxTime);
-            
-        end
-        
-        
-        function h = plotExponentialFit(nstObj,minTime,maxTime,numBins, handle)
-            if(nargin<5 || isempty(handle))
-              handle=gca;
-            end 
-            if(nargin<4 || isempty(numBins))
-                numBins = 200;
-            end
-            if(nargin<3 || isempty(maxTime))
-                maxTime = nstObj.maxTime;
-            end
-            if(nargin<2 || isempty(minTime))
-                minTime = nstObj.minTime;
-            end
-            h=figure;
-            subplot(1,2,1); nstObj.plotISIHistogram(minTime,maxTime,numBins,handle)
-            subplot(1,2,2); nstObj.plotProbPlot(minTime,maxTime,handle);
-            
-        end
-        
-        function h = plotProbPlot(nstObj,minTime,maxTime,handle)
-            if(nargin<4 || isempty(handle))
-                handle =gca;
-            end
-            if(nargin<3 || isempty(maxTime))
-                maxTime = nstObj.maxTime;
-            end
-            if(nargin<2 || isempty(minTime))
-                minTime = nstObj.minTime;
-            end
-            %set(gcf,'CurrentAxes',handle);
-            ISIs = nstObj.getISIs(minTime,maxTime);
-            h=probplot('exponential',ISIs);
-            [muhat,muci] = expfit(ISIs);
-%             hold on;
-%             Z=1/muhat*(nstObj.spikeTimes(2:end) - nstObj.spikeTimes(1:end-1));
-%             U = 1-exp(-Z); %store the rescaled spike times
-% 
-% 
-%             KSSorted = sort( U,'ascend' );
-%             N = length(KSSorted);
-%             if(N~=0)
-%                 xAxis=(([1:N]-.5)/N)';
-%                 ks_stat = max(abs(KSSorted' - (([1:N]-.5)/N)')); 
-%             else
-%                 ks_stat=1;
-%                 xAxis=[];
-%             end
-%             
-%                          
-% %             handle=plot(xAxis,KSSorted, 0:.01:1,0:.01:1, 'k-.',0:.01:1, [0:.01:1]+1.36/sqrt(N), 'r', 0:.01:1,[0:.01:1]-1.36/sqrt(N), 'r' );
-% 
-%             %set(gca,'xtick',[],'ytick',[],'ztick', [])
-% %             axis( [0 1 0 1] );
-%             
-%             xlabel('Uniform CDF');
-%             ylabel('Empirical CDF of Rescaled ISIs');
-%             title('KS Plot with 95% Confidence Intervals');
-%             
-            
-            
-            
-        end
-        function ISIs = getISIs(nstObj,minTime,maxTime)
-            if(nargin<3 || isempty(maxTime))
-                maxTime = nstObj.maxTime;
-            end
-            if(nargin<2 || isempty(minTime))
-                minTime = nstObj.minTime;
-            end
-            spikeTimes = nstObj.getSpikeTimes(minTime,maxTime);
-            ISIs = diff(spikeTimes)';
-        
-        end
-        
-        function minISI = getMinISI(nstObj,minTime, maxTime)
-            if(nargin<3 || isempty(maxTime))
-                maxTime = nstObj.maxTime;
-            end
-            if(nargin<2 || isempty(minTime))
-                minTime = nstObj.minTime;
-            end
-            minISI = min(nstObj.getISIs(minTime,maxTime));
-        end
-        function nstCollObj = partitionNST(nstObj, windowTimes,normalizeTime,lbound,ubound)
-            if(nargin<5 || isempty(ubound))
-                if(nargin>4)
-                    ubound = lbound;
-                else
-                    ubound=[];
-                end
-                
-            end
-            if(nargin<4 || isempty(lbound));
-                lbound=[];
-            end
-            if(nargin<3 || isempty(normalizeTime))
-                normalizeTime = [];
-            end
-            
-%             nst = cell(1,length(windowTimes)-1);
-            nst={};
-            for i=1:length(windowTimes)-1
-                
-                minTime = round(windowTimes(i)*nstObj.sampleRate)/nstObj.sampleRate;
-                maxTime = round(windowTimes(i+1)*nstObj.sampleRate)/nstObj.sampleRate;
-%                 spikeTimes = round(nstObj.spikeTimes*nstObj.sampleRate)/nstObj.sampleRate;
-                spikeTimes = nstObj.spikeTimes;%*nstObj.sampleRate)/nstObj.sampleRate;
-                if(and(~isempty(lbound),~isempty(ubound)))
-                    if(and(abs(maxTime-minTime)<=(ubound),abs(maxTime-minTime)>=(lbound)))
-                        dim = length(nst);
-                        if(i==(length(windowTimes)-1))
-                             
-                            spikeTimesSubset = spikeTimes(spikeTimes>=minTime & spikeTimes<=maxTime);
-                        else
-                            spikeTimesSubset = spikeTimes(spikeTimes>=minTime & spikeTimes=minTime,spikeTimes<=maxTime));
-                        spikeInInterval{i}= spikeTimesSubset;
-                     else
-                        spikeTimesSubset = spikeTimes(and(spikeTimes>=minTime,spikeTimesminTime,spikeTimes<=maxTime));
-                    spikeTimesSubset = spikeTimesSubset - minTime;
-%                     spikeTimes = round(spikeTimes*nstObj.sampleRate)/nstObj.sampleRate;
-%                     %spikeTimes = spikeTimes./(windowTimes(i+1)-windowTimes(i));
-%                     minTime= round(minTime*nstObj.sampleRate)/nstObj.sampleRate;
-%                     maxTime= round(maxTime*nstObj.sampleRate)/nstObj.sampleRate;
-                    if(normalizeTime==1)
-%                         nst{i} = nspikeTrain(spikeTimes/max(spikeTimes),strcat([nstObj.name ',w' num2str(i)]));
-%                         spikeTimes=round(spikeTimes/(maxTime-minTime)*nstObj.sampleRate)/nstObj.sampleRate;
-                        spikeTimesSubset = spikeTimesSubset/(maxTime-minTime);
-                        nst{i} = nspikeTrain(spikeTimesSubset,nstObj.name);
-                    else
-%                         nst{i} = nspikeTrain(spikeTimes,strcat([nstObj.name ',w' num2str(i)]));
-                        nst{i} = nspikeTrain(spikeTimesSubset,nstObj.name);
-                    end
-                end
-            end
-            nstCollObj = nstColl(nst);
-            if(normalizeTime==1)
-                nstCollObj.setMinTime(0);
-                nstCollObj.setMaxTime(1);
-            end
-
-        end
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        %Utility Functions
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        function answer = isSigRepBinary(nstObj)
-            % answer = isSigRepBinary(nstObj) 
-            % answer = 1 if the SignalObj representation is binary
-            % answer = 0 otherwise
-%             if(~isempty(nstObj.sigRep))
-%               if(max(nstObj.sigRep.data)>1)
-%               %if(max(nstObj.getSigRep.data)>1)
-%                   answer=0;
-%               else
-%                   answer=1;
-%               end      
-%             else
-              if(isempty(nstObj.sigRep) || (nstObj.sampleRate~=nstObj.sigRep.sampleRate))
-                  nstObj.getSigRep;
-              end
-              if(max(nstObj.sigRep.data)>1)
-                  answer=0;
-              else
-                  answer=1;
-              end      
-%             end
-        end
-        function rateSignal = computeRate(nstObj)
-            % rateSignal = computeRate(nstObj)
-            % generate rate function signal for the corresponding spikeTimes
-            % not yet implemented
-        end
-        function restoreToOriginal(nstObj)
-            % restoreToOriginal(nstObj)
-            % restores the signalRep of the nspikeTrain to its original
-            % state. Sets sampleRate to the original sampleRate of the
-            % SignalObj. 
-            % 
-            % nstObj.minTime = min(nstObj.spikeTimes)
-            % nstObj.maxTime = max(nstObj.spikeTimes)
-            %
-            %nstObj.sigRep.restoreToOriginal;
-            %nstObj.isSigRepBin=nstObj.isSigRepBinary;
-            %nstObj.sampleRate = nstObj.sigRep.sampleRate;
-            nstObj.minTime = min(nstObj.spikeTimes);
-            nstObj.maxTime = max(nstObj.spikeTimes);
-        end
-        function nCopy = nstCopy(nstObj)
-           % nCopy = nstCopy(nstObj)
-           % nCopy is a copy of the nspikeTrain nstObj. This function is
-           % important since nspikeTrains have handle behavior. For
-           % example,
-           % n2= n1; %where n1 is a nspikeTrain
-           % n2.setMinTime(-10);% also sets the minTime of n1 to -10
-           % because both reference the same data.
-           %
-           % To avoid this:
-           % n2=n1.nstCopy;
-           % n2.setMinTime(-10); %only changes n2.
-           name       = nstObj.name;
-           sampleRate = nstObj.sampleRate;
-           spikeTimes = nstObj.spikeTimes;
-           minTime    = nstObj.minTime;
-           maxTime    = nstObj.maxTime;
-%            if(~isempty(nstObj.sigRep))
-%             sig        = nstObj.sigRep.copySignal;
-%            else
-%             sig        = nstObj.getSigRep;  
-%            end
-           nCopy.sigRep = nstObj.getSigRep; 
-           sig = nstObj.getSigRep;
-           xlabelval  = sig.xlabelval;
-           xunits     = sig.xunits;
-           nCopy=nspikeTrain(spikeTimes,name,1/sampleRate,minTime,maxTime, xlabelval,xunits);
-%            nCopy.sigRep = nstObj.getSigRep; 
-        end
-        
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        %Plotting Functions
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        function h=plot(nstObj, dHeight, yOffset, currentHandle) 
-            % h=plot(nstObj, dHeight, yOffset, currentHandle) 
-            % only plots the actual spikeTimes regardless of the signal
-            % representation
-            % dHeight: height of a spike on the plot
-            % yOffset: offset to be used when plotting this nspikeTrain
-            %          nstColl uses the offset for drawing an entire
-            %          collection of spikes that were recorded
-            %          simultaneously.
-            if (nargin < 4)
-                currentHandle = gca;
-            end                   
-            if (nargin < 3)
-                yOffset = .5;
-            end
-            if (nargin < 2)
-                dHeight = 1; 
-            end
-             
-            if(~isempty(nstObj.spikeTimes))
-                time   =   ones(2,1)*nstObj.spikeTimes;
-            else
-                time   = [];
-            end
-            
-            spikes =  ([-dHeight/2; +dHeight/2]+yOffset)*ones(1,length(nstObj.spikeTimes));
-            %h = figure(currentHandle);
-            hold on;
-            h=plot(currentHandle,time,spikes,'k');
-            
-            if(nargin==1) %Only plot labels if being plotted separately
-                sig       = nstObj.getSigRep;
-                xlabelval = sig.xlabelval;
-                xunits    = sig.xunits;
-                name      = sig.name;
-                yunits    = sig.yunits;
-                if(~strcmp(xunits,''))
-                    xunitsStr=strcat(' [',xunits,']');
-                else
-                    xunitsStr='';
-                end
-                xlabel(strcat(xlabelval,xunitsStr));
-
-                if(~strcmp(yunits,''))
-                    yunitsStr=strcat(' [',yunits,']');
-                else
-                    yunitsStr='';
-                end
-                ylabel(strcat(name,yunitsStr));
-                v=axis;
-                if(nstObj.minTime~=nstObj.maxTime)
-                    axis([nstObj.minTime,nstObj.maxTime,v(3),v(4)]);
-                end
-            end
-
-            
-        end
-        
-        function structure = toStructure(nstObj)
-            fnames = fieldnames(nstObj);
-            
-            for i=1:length(fnames)
-               currObj = nstObj.(fnames{i});
-               if(isa(currObj,'double') || isa(currObj,'char'))
-                   structure.(fnames{i}) = currObj;
-               elseif(isa(currObj,'SignalObj'))
-                   structure.(fnames{i}) = currObj.dataToStructure;
-               end
-                
-                
-            end
-        end
-        
-    end
-    methods (Static)
-        function nstObj = fromStructure(structure)
-            spikeTimes = structure.spikeTimes;
-            name       = structure.name;
-            binwidth   = 1/structure.sampleRate;
-            minTime    = structure.minTime;
-            maxTime    = structure.maxTime;
-            xlabelval  = structure.xlabelval;
-            xunits     = structure.xunits;
-            yunits     = structure.yunits;
-            dataLabels = structure.dataLabels;
-            nstObj=nspikeTrain(spikeTimes,name,binwidth,minTime,maxTime,xlabelval, xunits, yunits,dataLabels);
-        end
-    end
-    
-end
-
diff --git a/nstColl.m b/nstColl.m
deleted file mode 100644
index 03a217eb..00000000
--- a/nstColl.m
+++ /dev/null
@@ -1,1597 +0,0 @@
-classdef nstColl < handle
-% NSTCOLL A collection of nspikeTrains
-%   
-% methods    
-% nstColl Examples 
-%
-% see also CovColl, Covariate, SignalObj,nspikeTrain
-%
-% Reference page in Help browser
-% doc nstColl
-
-%
-% nSTAT v1 Copyright (C) 2012 Masschusetts Institute of Technology
-% Cajigas, I, Malik, WQ, Brown, EN
-% This program is free software; you can redistribute it and/or 
-% modify it under the terms of the GNU General Public License as published 
-% by the Free Software Foundation; either version 2 of the License, or 
-% (at your option) any later version.
-% 
-% This program is distributed in the hope that it will be useful, 
-% but WITHOUT ANY WARRANTY; without even the implied warranty of 
-% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
-% See the GNU General Public License for more details.
-%  
-% You should have received a copy of the GNU General Public License 
-% along with this program; if not, write to the Free Software Foundation, 
-% Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-    properties (SetAccess = private)
-        nstrain; %An array of nspikeTrain objects
-        numSpikeTrains; % a running count of how many nspikeTrains are in object
-        minTime %Time first spike occurs in the collection
-        maxTime %TIme last spike occurs in the collection
-        sampleRate
-        neuronMask
-        neuronNames
-%         isSigRepBinary
-        neighbors %the ith row specifies neighbors of ith neuron
-    end
-    properties (Dependent = true)
-       
-       uniqueNeuronNames
-    end
-    
-    methods
-        function nstCollObj=nstColl(nst)
-        % nstCollObj=nstColl(nst)
-        % nst is a cell array of nspikeTrains, a single nspikeTrains
-        % or not specified. If not specified, an empty nstColl object is
-        % created.
-                nstCollObj.numSpikeTrains = 0;
-                nstCollObj.minTime=inf;
-                nstCollObj.maxTime=-inf;
-                nstCollObj.neuronMask=[];
-                nstCollObj.sampleRate=-inf;
-                nstCollObj.neighbors = [];
-%                 nstCollObj.isSigRepBinary = nstCollObj.BinarySigRep;
-            if(nargin<1) %Then we were called without any data
-                nstCollObj.nstrain=cell(1);
-            else
-                nstCollObj.addToColl(nst);
-            end
-        end
-        
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        %Merge
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        function nstCollObj = merge(nstCollObj, nstColl2)
-           nstCollObj.addToColl(nstColl2); 
-        end
-        
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        %Get Functions
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        function minTime = getFirstSpikeTime(nstCollObj)
-            % minTime = getFirstSpikeTime(nstCollObj)
-            % minTime is the time of the first spike from all of the
-            % nspikeTrains in the collection
-            minTime=nstCollObj.minTime;
-        end        
-        function maxTime = getLastSpikeTime(nstCollObj)
-            % maxTime = getLstSpikeTime(nstCollObj)
-            % maxTime is the time of the last spike from all of the
-            % nspikeTrains in the collection
-            maxTime=nstCollObj.maxTime;
-        end
-%         function nstCollObj = shift(nstCollObj,deltaT)
-%             minTime=inf;
-%             maxTime=-inf;
-%            for i=1:nstCollObj.numSpikeTrains
-%                 nstCollObj.getNST(i).shift(deltaT);
-%                 minTime=min(nstCollObj.getNST(i).minTime,minTime);
-%                 maxTime=max(nstCollObj.getNST(i).maxTime,maxTime);
-%             end
-%             nstCollObj.setMinTime(minTime);
-%             nstCollObj.setMaxTime(maxTime);
-%         end
-        function answer  = getMaxBinSizeBinary(nstCollObj)
-            % answer  = getMaxBinSizeBinary(nstCollObj)
-            % answer is the binsize above which at least one nspikeTrain
-            % will no longer have a binary representation
-            %
-            % Only unmasked ('visible') nspikeTrains are considered.
-            if(nstCollObj.isNeuronMaskSet)
-                selectorArray = nstCollObj.getIndFromMask;
-            else
-                selectorArray = 1:nstCollObj.numSpikeTrains;
-            end
-            val = zeros(1,length(selectorArray));
-            for i=1:length(selectorArray)
-%                 i
-                val(i) = nstCollObj.getNST(selectorArray(i)).getMaxBinSizeBinary;
-            end
-            answer = min(val);
-        end        
-%         function value = get.isSigRepBinary(nstCollObj)
-%             % value is 1 if all of the nspikeTrains in the collection have
-%             % a binary representation. value=0 otherwise.
-% %             value =nstCollObj.BinarySigRep;
-%         end   
-        function uniqueNames = get.uniqueNeuronNames(nstCollObj)
-            uniqueNames=nstCollObj.getUniqueNSTnames;
-        end
-
-       
-        function [n numNeighbors] = getNeighbors(nstCollObj, neuronNum)
-           if(length(neuronNum)==1)
-                %neuronNum: if neuronNum is not a scalar, a cell array is
-                %returned. The ith entry of the cell array is a row vector
-                %with the indicies of the ith neuron. If all of the rows
-                %have the same length, then a matrix is returned instead of
-                %a cell array.
-               if(~nstCollObj.areNeighborsSet)
-                    nstCollObj.setNeighbors; %default behavior
-               end
-                    availNeurons =nstCollObj.getIndFromMaskMinusOne(neuronNum);
-                    if(isa(nstCollObj.neighbors,'cell'))
-                        nTemp = nstCollObj.neighbors{neuronNum};
-                    else
-                        nTemp=nstCollObj.neighbors(neuronNum,:);
-                    end
-                    offset=0;
-                    n=[];
-                    for i=1:length(nTemp)
-                        if(any(nTemp(i)==availNeurons))
-                           offset=offset+1;
-                           n(offset)=nTemp(i);
-                        end
-                    end
-                    numNeighbors = length(n);
-           else %if more than 1 neuronNum
-               for i=1:length(neuronNum) % call above for each
-                   [nTemp{i}, numNeigh(i)] = nstCollObj.getNeighbors(neuronNum(i));
-               end
-               if(min(numNeigh)==max(numNeigh)) %if all the same dimension
-                   n=[];
-                   for i=1:length(neuronNum)
-                       n = [n;nTemp{i}];   %convert to a Matrix
-                   end
-               else %else return as a cell of neighbors
-                   n=nTemp;
-                   numNeighbors=max(numNeigh);
-               end
-           end
-        end
-        function [fieldVal, neuronNumbers]  = getFieldVal(nstCollObj,fieldName)
-            % Returns a vector of the value contained within each nspikeTrain.(fieldName)
-            % within the nstCollObj object. Empty values are skipped.
-            cnt =1;
-            fieldVal=[];
-            for i=1:nstCollObj.numSpikeTrains
-               currVal = nstCollObj.getNST(i).getFieldVal(fieldName); 
-               if(~isempty(currVal))
-                fieldVal(cnt)=currVal;
-                cnt = cnt+1;
-                neuronNumbers(cnt) = i;
-               end
-            end
-        end
-        function nstCollObj=shiftTime(nstCollObj,timeShift)
-            %shifts the entire collection by timeShift. If timeShift is
-            %empty or not give, the entire collection is shifted so that
-            %minTime =0;
-            if(nargin<2 || isempty(timeShift))
-                timeShift = -nstCollObj.minTime;
-            end
-            oldnSpikes= nstCollObj.nstrain;
-            for i=1:length(oldnSpikes)
-                nNew{i} = nspikeTrain(oldnSpikes{i}.spikeTimes + timeShift);
-            end
-            newColl = nstColl(nNew);
-            nstCollObj = newColl;
-        end
-        function setMinTime(nstCollObj,minTime)
-            % setMinTime(nstCollObj,minTime)
-            % calls setMinTime on all nspikeTrains in the collection and 
-            % updates the minTime of the collection
-            if(nargin<2)
-                minTime=nstCollObj.minTime;
-            end
-            
-            
-            for i=1:nstCollObj.numSpikeTrains
-                nstCollObj.nstrain{i}.setMinTime(minTime);
-            end  
-            nstCollObj.minTime = minTime;
-%             nstCollObj.isSigRepBinary = nstCollObj.BinarySigRep;
-        end        
-        function setMaxTime(nstCollObj,maxTime)
-            % setMaxTime(nstCollObj,maxTime)
-            % calls setMaxTime on all nspikeTrains in the collection and 
-            % updates the maxTime of the collection
-            if(nargin<2)
-                maxTime=nstCollObj.maxTime;
-            end
-            
-            for i =1:nstCollObj.numSpikeTrains
-                nstCollObj.nstrain{i}.setMaxTime(maxTime);
-            end
-            nstCollObj.maxTime = maxTime;
-%             nstCollObj.isSigRepBinary = nstCollObj.BinarySigRep;
-        end
-        function setMask(nstCollObj,mask)
-            if(length(mask)==nstCollObj.numSpikeTrains)
-                if(max(mask)>1) %then these are indices
-                    newMask = ones(1,length(mask));
-                    nstCollObj.setNeuronMask(newMask);
-                else %they are selectors of 1's and 0's
-                    nstCollObj.setNeuronMask(mask);
-                end
-            else
-                nstCollObj.setNeuronMaskFromInd(mask)
-            end
-        end
-        function setNeuronMaskFromInd(nstCollObj,mask)
-            % setNeuronMaskFromInd(nstCollObj,mask)
-            % mask is a vector of indices into the nstColl.
-            % all the nspikeTrains corresponding to the indices present in the mask 
-            % will be visible in the collection
-            newMask = zeros(1,nstCollObj.numSpikeTrains);
-            newMask(mask) = 1;
-            nstCollObj.setNeuronMask(newMask);
-        end
-        
-        function setNeuronMask(nstCollObj,mask)
-            % setNeuronMask(nstCollObj,mask)
-            % mask needs to vector with binary entries
-            % entries marked by 1s are visible, 0's are not visible
-            if(length(mask)==nstCollObj.numSpikeTrains)
-                nstCollObj.neuronMask = mask;
-            end
-        end
-        function setNeighbors(nstCollObj,neighborArray)
-            if(nargin<2)
-                for i =1:nstCollObj.numSpikeTrains
-                    neuronList = 1:nstCollObj.numSpikeTrains;
-                    neighborArray(i,:)=find(i~=neuronList); %all but ith neuron
-                end
-            end
-            if(~isempty(neighborArray))
-                [numRows, ~]=size(neighborArray);
-                if(numRows==nstCollObj.numSpikeTrains)
-                    nstCollObj.neighbors = neighborArray;
-                else
-                    display('Neighbor Array is not of appropriate dimensions');
-                end
-            end
-        end
-        
-        function ind=getIndFromMask(nstCollObj)
-            % ind=getIndFromMask(nstCollObj)
-            % ind is a row vector containing the indices of the currently
-            % visible nspikeTrains in the collection
-            
-            ind=find(nstCollObj.neuronMask==1);
-        end
-        
-        function ind=getIndFromMaskMinusOne(nstCollObj,neuron)
-           ind = nstCollObj.getIndFromMask;
-           ind = ind(ind~=neuron);
-        end
-        function answer = isNeuronMaskSet(nstCollObj)
-            % answer = isNeuronMaskSet(nstCollObj)
-            % answer =1 if any element of the neuronMask is set to zero.
-            % answer =0 if all elements are set to 1.
-            if(any(nstCollObj.neuronMask==0))
-               answer =1;
-            else 
-               answer=0;
-            end
-        end        
-         function answer = areNeighborsSet(nstCollObj)
-            answer=~isempty(nstCollObj.neighbors);
-        end
-        
-        
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        %Utility Functions
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        function restoreToOriginal(nstCollObj,rMask)
-            % restoreToOriginal(nstCollObj,rMask)
-            % restores all elements of the nstColl to their original
-            % states. If rMask is not specified then the neuronMask is
-            % retained. If rMask =1, then the neuronMask is reset as well.
-            if(nargin<2)
-                rMask=0;
-            end
-            minTime=inf;
-            maxTime=-inf;
-            for i=1:nstCollObj.numSpikeTrains
-                nstCollObj.getNST(i).restoreToOriginal;
-                minTime=min(nstCollObj.getNST(i).minTime,minTime);
-                maxTime=max(nstCollObj.getNST(i).maxTime,maxTime);
-            end
-            nstCollObj.setMinTime(minTime);
-            nstCollObj.setMaxTime(maxTime);
-            nstCollObj.sampleRate = nstCollObj.findMaxSampleRate;
-            nstCollObj.enforceSampleRate;
-            if(rMask==1)
-                nstCollObj.resetMask;
-            end 
-%             nstCollObj.isSigRepBinary = nstCollObj.BinarySigRep;
-        end    
-        function mSR= findMaxSampleRate(nstCollObj)
-            mSR=-inf;
-            for i=1:nstCollObj.numSpikeTrains
-                mSR=max(nstCollObj.getNST(i).sampleRate,mSR);
-            end
-        end
-        function resetMask(nstCollObj)
-            %resetMask(nstCollObj)
-            % resets the neuronMask to all 1's (All data visible)
-            nstCollObj.neuronMask=ones(1,nstCollObj.numSpikeTrains);
-%             nstCollObj.isSigRepBinary = nstCollObj.BinarySigRep;
-        end        
-        function addToColl(nstCollObj,nst)
-            % addToColl(nstCollObj,nst)
-            % adds the nspikeTrain nst to the collection nstCollObj
-            % nst: can be a single nspikeTrain or a cell array of 
-            %      nspikeTrains
-              if(isa(nst,'cell'))
-                numElements=length(nst);
-                for i=1:numElements
-                    if(isa(nst{i},'nspikeTrain'))
-                        nstCollObj.addSingleSpikeToColl(nst{i})
-                    else
-                        error('nstColl requires a cell array of nspikeTrain class elements');
-                    end
-                end
-              elseif(isa(nst,'nspikeTrain'))
-                  nstCollObj.addSingleSpikeToColl(nst);
-              elseif(isa(nst,'nstColl'))
-                  newSpikes = nst.nstrain;
-                  nstCollObj.addToColl(newSpikes);
-              else
-                  error('Can only add single spikes or cells with spikes');
-              end
-%               nstCollObj.isSigRepBinary = nstCollObj.BinarySigRep;
-        end        
-
-        
-        function uniqueNames = getUniqueNSTnames(nstCollObj,selectorArray)
-            if(nargin<2)
-                selectorArray = find(nstCollObj.neuronMask);
-            end
-            uniqueNames = unique(nstCollObj.neuronNames(selectorArray));
-        end
-        function names = getNSTnames(nstCollObj,selectorArray)
-            if(nargin<2)
-                selectorArray = find(nstCollObj.neuronMask);
-            end
-            names=nstCollObj.neuronNames(selectorArray);
-            
-            
-        end
-        
-        
-        function indices = getNSTIndicesFromName(nstCollObj,neuronName)
-            if(nargin<2)
-                neuronName = nstCollObj.getUniqueNSTnames;
-            end
-                
-            if(isa(neuronName,'char'))
-                names = nstCollObj.getNSTnames;
-                indices = find(strcmp(names,neuronName));
-            elseif(isa(neuronName,'cell'))
-               for i=1:length(neuronName)
-                  indices{i} = nstCollObj.getNSTIndicesFromName(neuronName{i});
-               end
-            end
-            
-        end
-        
-        function name = getNSTnameFromInd(nstCollObj,ind)
-           if(ind>0 && nstCollObj.numSpikeTrains)
-               name = nstCollObj.neuronNames(ind);
-           else
-               error('Index is out of bounds!');
-           end
-           
-        end
-        function nst = getNSTFromName(nstCollObj,neuronName)
-            if(nargin<2)
-                neuronName = nstCollObj.getUniqueNSTnames;
-            end
-                
-            indices =nstCollObj.getNSTIndicesFromName(neuronName);
-            nst = nstCollObj.getNST(indices); 
-        end
-        
-        function nst = getNST(nstCollObj,index)
-        % nst = getNST(nstCollObj,index)
-        % if a nspikeTrain exists in the collection with the specified
-        % index, it is returned in nst. 
-        % If length(index)>1 then get a cell-array of nspikeTrains.
-        % Care should be taken because it is
-        % the actual nst and not a copy (recall handle behavior of
-        % nspikeTrains)
-            if(all(index>0) && all(index<=nstCollObj.numSpikeTrains))
-                if(length(index)>1)
-                    for i=1:length(index)
-                        sampleRate = nstCollObj.sampleRate;
-                        nst{i} = nstCollObj.nstrain{index(i)};%.nstCopy;
-                        if(nst{i}.sampleRate~=sampleRate)
-                            nst{i} = nst{i}.resample(sampleRate);
-                        end
-                    end
-                else
-                    sampleRate = nstCollObj.sampleRate;
-                    nst = nstCollObj.nstrain{index};%.nstCopy;
-                    if(nst.sampleRate~=sampleRate)
-                        nst = nst.resample(sampleRate);
-                    end
-                end
-            else
-                error(['Index', num2str(index), ' out of bounds']);
-            end
-        end
-        function resample(nstCollObj,sampleRate)
-            %resample(nstCollObj,sampleRate)
-            %resamples all the nspikeTrains in the collection at the
-            %speciied sampleRate.
-            %Updates teh sampleRate of the collection to the specified
-            %value.
-            
-            if(nstCollObj.sampleRate~=sampleRate)
-                for i=1:nstCollObj.numSpikeTrains
-                    tempNST = nstCollObj.getNST(i);
-                    tempNST.resample(sampleRate);
-                    tempNST.setMinTime(nstCollObj.minTime);
-                    tempNST.setMaxTime(nstCollObj.maxTime);
-
-                end
-                nstCollObj.sampleRate=sampleRate;
-            end
-%             nstCollObj.isSigRepBinary = nstCollObj.BinarySigRep;
-        end
-        function answer=isSigRepBinary(nstCollObj)
-           answer = nstCollObj.BinarySigRep; 
-        end
-        
-        function answer=BinarySigRep(nstCollObj)
-            % answer=BinarySigRep(nstCollObj)
-            % answer=1 if the all of the SignalObj representations of each
-            % of the nspikeTrains in the collection have a binary
-            % representation with the current collection parameters.
-            % answer=0 if at least one nspikeTrain does not.
-            tempAns = zeros(1,nstCollObj.numSpikeTrains);
-            for i =1:nstCollObj.numSpikeTrains
-                tempAns(i) = nstCollObj.getNST(i).isSigRepBinary;
-            end
-            
-            answer=all(tempAns);
-
-        end
-        
-        function ensembleCovariates = getEnsembleNeuronCovariates(nstCollObj,neuronNum,neighborIndex,windowTimes)
-            % ensembleCovariates = getEnsembleNeuronCovariates(nstCollObj,neuronNum,neighborIndex,windowTimes)
-            % returns a collection of covariates. Each covariate has number
-            % of dimensions same as the number of history windows. There
-            % will be the same number of covariates as neighbors.
-     
-            if(nargin<4 || isempty(windowTimes))
-               windowTimes = [0 0.001];
-            end
-            
-            if(nargin<3 || isempty(neighborIndex))
-                allNeighbors=nstCollObj.getNeighbors(neuronNum);
-            else
-                allNeighbors=neighborIndex;
-            end
-            
-            if(isa(windowTimes,'History'))
-                histObj = windowTimes; %we were passed an actual history object;
-            elseif(isa(windowTimes,'double'))
-                histObj = History(windowTimes); % we got windowTimes;
-            end
-               
-            ensembleCovariates = histObj.computeHistory(nstCollObj.getNST(1:nstCollObj.numSpikeTrains));
-            ensembleCovariates.maskAwayAllExcept(allNeighbors);
-            
-            nstCollObj.addNeuronNamesToEnsCovColl(ensembleCovariates);
-            
-        end
-        
-        function addNeuronNamesToEnsCovColl(nstCollObj,ensembleCovariates)
-            % addNeuronNamesToEnsCovColl(nstCollObj,ensembleCovariates)
-            % Given a covariate collection of the ensemble effects, adds
-            % the neuron number to each data dimension of each ensembleCovariate element. 
-            
-           
-            for i=1:ensembleCovariates.numCov
-                tempCov = ensembleCovariates.covArray{i};
-                dataLabels = cell(1,tempCov.dimension);
-                for j=1:tempCov.dimension;
-                    name = nstCollObj.getNST(i).name;
-                    if(isnumeric(name))
-                        if(i>0 && i<10)
-                            name = strcat(num2str(0),name);
-                        end
-                        dataLabels{j} = strcat('N',name, ':', tempCov.dataLabels{j});
-                    else
-                        dataLabels{j} = strcat(name, ':', tempCov.dataLabels{j});
-                    end
-                end
-                tempCov.setDataLabels(dataLabels);
-            end
-        end
-        
-        
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        %Change of Representation Functions
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        
-        function dataMat = dataToMatrix(nstCollObj,selectorArray, binwidth,minTime,maxTime)
-            % dataMat = dataToMatrix(nstCollObj,selectorArray, binwidth,minTime,maxTime)
-            % dataMat is a matrix with number of rows corresponding to the
-            % sampleRate of the nstColl and the minTime & maxTime values
-            % that are currently set. The number of columns defaults to the
-            % number of visible nspikeTrains as determined by the
-            % neuronMask. This default behavior can be changed by specifyin
-            % values for: selectorArray, binwidth, minTime, and maxTime
-            % when calling the function
-            
-            if(nargin<5)
-                maxTime=nstCollObj.maxTime;
-            end
-            if(nargin<4)
-                minTime=nstCollObj.minTime;
-            end
-            if(nargin<3)
-                binwidth=1/nstCollObj.sampleRate;
-            end
-            if(nargin<2)
-                if(nstCollObj.isNeuronMaskSet)
-                    selectorArray = nstCollObj.getIndFromMask;
-                else
-                    selectorArray = 1:nstCollObj.numSpikeTrains;
-                end
-            end
-             
-            if(isa(selectorArray,'double'))
-                if(any(selectorArray > nstCollObj.numSpikeTrains) || any(selectorArray < 1))
-                    error('Neuron index is out of bounds');
-                end
-            elseif(isa(selectorArray,'cell')||isa(selectorArray,'char'));
-               selectorArray = nstCollObj.getNSTIndicesFromName(selectorArray);
-               if(isa(selectorArray,'cell'))
-                   tempSelect = [];
-                   for i=1:length(selectorArray)
-                      tempSelect = [tempSelect selectorArray{i}];
-                      
-                   end
-               end
-            end
-            
-            %minTime and maxTime can be any values. We return a 
-            %a matrix that starts at t=minTime and ends at t=maxTime;
-%             maxTime
-%             minTime
-%             binwidth
-            dataMat=zeros(floor(abs(maxTime-minTime)/binwidth)+1,length(selectorArray));
-            testSig = nstCollObj.getNST(1).getSigRep(binwidth,minTime, maxTime);
-            dataMat=zeros(length(testSig.dataToMatrix),length(selectorArray));
-            for i=1:length(selectorArray) 
-                nspikeSigRep=nstCollObj.getNST(selectorArray(i)).getSigRep(binwidth,minTime, maxTime);
-%                   size(nspikeSigRep.dataToMatrix)
-%                   size(dataMat)
-                %A=nspikeSigRep.dataToMatrix;
-                %dataMat(:,i)=A(1:length(dataMat),:);
-%                 sum(nspikeSigRep.data)==size(nstCollObj.getNST(selectorArray(i)).spikeTimes,2)
-                dataMat(:,i)=nspikeSigRep.dataToMatrix;
-                d(i)=length(nstCollObj.getNST(selectorArray(i)).spikeTimes)-sum(dataMat(:,i));
-            end
-        end
-        function spikeTrainObj = toSpikeTrain(nstCollObj,selectorArray,minTime,maxTime,windowTimes)
-            if(nargin<5)
-                windowTimes=[];
-            end
-            if(nargin<4 || isempty(maxTime))
-                maxTime=nstCollObj.maxTime;
-            end
-            if(nargin<3 || isempty(minTime))
-                minTime=nstCollObj.minTime;
-            end
-            if(nargin<2 || isempty(selectorArray))
-                if(nstCollObj.isNeuronMaskSet)
-                    selectorArray = nstCollObj.getIndFromMask;
-                else
-                    selectorArray = 1:nstCollObj.numSpikeTrains;
-                end
-            end
-            
-            
-             spikeTimes=[];
-             offset=0;
-             delta = 1/nstCollObj.sampleRate;
-            nst=cell(1,length(selectorArray));
-            
-            if(isempty(windowTimes))
-                for i=1:length(selectorArray)
-                   if(i==1)
-                       nst{i}=  nstCollObj.getNST(selectorArray(i));
-                       spikeTimes = nst{i}.spikeTimes;
-                       name = nst{i}.name;
-                   else
-                       offset = offset+nst{i-1}.maxTime + delta;
-                       nst{i}=  nstCollObj.getNST(selectorArray(i));
-                       if(~isempty(nst{i}.spikeTimes))
-                        spikeTimes = [spikeTimes, nst{i}.spikeTimes+offset];
-                       end
-
-                   end
-                end
-            else
-                if(length(selectorArray)==length(windowTimes)-1)
-                    for i=1:length(selectorArray)
-                       minTime=windowTimes(i);
-                       deltaTW=windowTimes(i+1)-minTime;
-                       if(i==1)
-                           nst{i}=  nstCollObj.getNST(selectorArray(i));
-                           spikeTimes = nst{i}.spikeTimes*deltaTW+minTime;
-                           name = nst{i}.name;
-                       else
-    %                        offset = offset+nst{i-1}.maxTime + delta;
-                           nst{i}=  nstCollObj.getNST(selectorArray(i));
-                           spikeTimes = [spikeTimes, nst{i}.spikeTimes*deltaTW+minTime];
-
-                       end
-                    end
-                else
-                    error('Window Times must be 1 row longer than selectorArray');
-                end
-            end
-            
-            spikeTrainObj = nspikeTrain(spikeTimes);
-            spikeTrainObj.setName(name); 
-            maxTimeTot = maxTime*length(selectorArray);
-            spikeTrainObj.setMinTime(minTime);
-            spikeTrainObj.setMaxTime(maxTimeTot);
-            spikeTrainObj.resample(1/delta);
-            
-        end
-        function psthSignal = psth(nstCollObj,binwidth,selectorArray, minTime,maxTime)
-            % psthSignal = psth(nstCollObj,selectorArray, binwidth,minTime,maxTime)
-            % Given a collection a neural spike trains, sums the activity
-            % in each time bin across all the neurons to generate a time
-            % histogram of the neural firing. 
-            % selectoryArray: can be used specify a subset of all the
-            %                 neurons in the collection
-            % binwidth: the size of the time bins used to sum the neural
-            %           activity. Default is 1ms if not specified.
-            % minTime:  time to start the psth. Default is the minTime of
-            %           the nstCollObj.
-            % maxTime:  time to end the psth. Degault to maxTime of
-            %           nstCollObj.
-            if(nargin<5)
-                maxTime=nstCollObj.maxTime;
-            end
-            if(nargin<4)
-                minTime=nstCollObj.minTime;
-            end
-            if(nargin<3 || isempty(selectorArray))
-                if(nstCollObj.isNeuronMaskSet)
-                    selectorArray = nstCollObj.getIndFromMask;
-                else
-                    selectorArray = 1:nstCollObj.numSpikeTrains;
-                end
-            end
-            if(nargin<2)
-                binwidth=.100; %100ms
-            end
-            windowTimes = minTime:binwidth:maxTime;
-            if(~any(windowTimes==maxTime))
-                windowTimes=[windowTimes, maxTime];
-            end
-                
-            psthData=zeros(1,length(windowTimes));
-                %dataMat = nstCollObj.dataToMatrix(nstCollObj,selectorArray,binwidth,minTime,maxTime);
-            for i=1:length(selectorArray)    
-                spikeTimes = nstCollObj.getNST(selectorArray(i)).getSpikeTimes;
-                if(~isempty(spikeTimes))
-                    
-                    psthData = psthData+histc(spikeTimes,windowTimes);
-                end
-            end
-                %due to how histc works add the last observation to the
-                %previous one;
-                tempPsth = psthData(1:end-1);
-%                 tempPsth(end) = tempPsth(end)+psthData(end);
-                psthData = tempPsth;
-%                 unitPulseBasis=nstCollObj.generateUnitImpulseBasis(binwidth,minTime,maxTime);
-%                 psthData = (unitPulseBasis.data*psthData')./binwidth;
-                psthData = psthData./binwidth./length(selectorArray);
-%                 unitPulseBasis=nstCollObj.generateUnitImpulseBasis(binwidth,minTime,maxTime,nstCollObj.sampleRate);
-                
-%                 psthData = unitPulseBasis.data*psthData';
-%                 time = unitPulseBasis.time;
-                time = (windowTimes(2:end)+windowTimes(1:end-1))/2;
-                    
-                
-                psthSignal = SignalObj(time, psthData, 'PSTH','time','s','Hz');
-%                 psthSignal.setMinTime(minTime);
-%                 psthSignal.setMaxTime(maxTime);
-               
-%                 figure; bar(time,psth); ylabel('Spikes'); xlabel('time [sec]');
-        end
-
-        function psthSignal = psthBars(nstCollObj,binwidth,selectorArray, minTime,maxTime)
-            % psthSignal = psthBars(nstCollObj,selectorArray, binwidth,minTime,maxTime)
-            % Given a collection a neural spike trains, sums the activity
-            % in each time bin across all the neurons to generate a time
-            % histogram of the neural firing. Uses the implementation Baysian Adaptive Regression
-            % Splines (developed by Wallstrom, Leibner and Kass) available
-            % on Ryan C. Kelly's website:
-            % Ryan C. Kelly's BARS for Matlab 
-            % Requires that: barsP.m, defaultParams.m, and nlsd_mex.c be in
-            % the Matlab path and that nlsd_mex.c be compiled to the
-            % corresponding mex file.
-            % 
-            % 
-            % selectoryArray: can be used specify a subset of all the
-            %                 neurons in the collection
-            % binwidth: the size of the time bins used to sum the neural
-            %           activity. Default is 1ms if not specified.
-            % minTime:  time to start the psth. Default is the minTime of
-            %           the nstCollObj.
-            % maxTime:  time to end the psth. Degault to maxTime of
-            %           nstCollObj.
-            if(nargin<5)
-                maxTime=nstCollObj.maxTime;
-            end
-            if(nargin<4)
-                minTime=nstCollObj.minTime;
-            end
-            if(nargin<3 || isempty(selectorArray))
-                if(nstCollObj.isNeuronMaskSet)
-                    selectorArray = nstCollObj.getIndFromMask;
-                else
-                    selectorArray = 1:nstCollObj.numSpikeTrains;
-                end
-            end
-            if(nargin<2)
-                binwidth=.100; %100ms
-            end
-            time = minTime:binwidth:maxTime;
-            psthData=zeros(1,length(time));
-                %dataMat = nstCollObj.dataToMatrix(nstCollObj,selectorArray,binwidth,minTime,maxTime);
-            for i=1:length(selectorArray)    
-                spikeTimes = nstCollObj.getNST(selectorArray(i)).getSpikeTimes;
-                if(~isempty(spikeTimes))
-                    psthData = psthData+histc(spikeTimes,time);
-                end
-            end
-            psthData = psthData./binwidth;
-            psthData = psthData/length(selectorArray);
-                %due to how histc works add the last observation to the
-                %previous one;
-
-            bp = defaultParams;
-            bp.prior_id = 'POISSON';
-            bp.dparams = 4;
-  
-  
-            numTrials = length(selectorArray);
-            fit = barsP(psthData,[minTime maxTime],numTrials);
-            psthSignal = SignalObj(time, [fit.mode fit.mean fit.confBands], 'PSTH_{bars}','time','s','Hz',{'mode','mean','ciLower','ciUpper'});
-
-        end
-
-        
-        
-        function [xK,WK, Qhat,gammahat,logll,fitResults] = ssglm(nstCollObj,windowTimes,numBasis,numVarEstIter,fitType)
-            if(nargin<5 || isempty(fitType))
-               fitType='poisson';%'binomial'; 
-            end
-            if(nargin<4 || isempty(numVarEstIter))
-                numVarEstIter=10;    
-            end
-            if(nargin<3 || isempty(numBasis))
-                basisWidth=.02;
-                numBasis = (nstCollObj.maxTime-nstCollObj.minTime)./basisWidth;
-                
-            end
-            if(nargin<2)
-               windowTimes = []; 
-            end
-
-
-
-            
-            
-
-
-
-            dN=nstCollObj.dataToMatrix';
-            dN(dN>1)=1;
-            basisWidth=(nstCollObj.maxTime-nstCollObj.minTime)/numBasis;
-            [~, ~, psthResult] =nstCollObj.psthGLM(basisWidth,windowTimes,fitType);
-            gamma0=psthResult.getHistCoeffs';%+.1*randn(size(histCoeffs));
-            gamma0(isnan(gamma0))=-5;
-            x0=psthResult.getCoeffs;
-
-            
-            Q0 = nstCollObj.estimateVarianceAcrossTrials(numBasis,windowTimes,numVarEstIter,fitType);
-
-            if(any(diag(Q0)==0))
-                Q0=Q0+0.001*diag(rand(numBasis,1));
-            end
-            A=eye(numBasis,numBasis);
-%             fitType='poisson';
-            delta = 1/nstCollObj.sampleRate;
-            [xK,WK, Qhat,gammahat,logll]=DecodingAlgortihms.PPSS_EM(A,Q0,x0,dN,fitType,delta,gamma0,windowTimes, numBasis);
-
-             minTime=nstCollObj.minTime; maxTime = nstCollObj.maxTime;
-             if(~isempty(numBasis))
-                basisWidth = (maxTime-minTime)/numBasis;
-                sampleRate=1/delta;
-                unitPulseBasis=nstCollObj.generateUnitImpulseBasis(basisWidth,minTime,maxTime,sampleRate);
-                basisMat = unitPulseBasis.data;
-             end
-
-            nCopy = nstCollObj.toSpikeTrain;
-             
-
-            histObj = History(windowTimes);
-            cnt=1; [K,N]=size(dN);
-            R=size(xK,1);
-%             R=numBasis;
-            clear beta otherLabels;
-            lambdaData=[];
-            nst=nstCollObj.nstrain;
-            for k=1:K
-                Hk{k}=histObj.computeHistory(nst{k}).dataToMatrix';
-                
-                stimK=basisMat*xK(:,k);
-
-                histEffect=exp(gammahat(end,:)*Hk{k})';
-                stimEffect=exp(stimK);
-                lambdaDelta = histEffect.*stimEffect;
-                
-                lambdaData = [lambdaData;lambdaDelta/delta];
-                
-                for r=1:R
-                    otherLabels{cnt} = ['b_{' num2str(r) ',' num2str(k) '}'];
-                    beta(cnt) = xK(r,k);
-                    cnt=cnt+1;
-                    
-                end
-            end
-            lambdaTime = minTime:delta:(length(lambdaData)-1)*delta;
-            nCopy.setMaxTime(max(lambdaTime));
-            nCopy.setMinTime(min(lambdaTime));
-%             otherLabels  = tObj.getLabelsFromMask(neuronNumber);
-            numLabels = length(otherLabels);
-            histLabels  = histObj.computeHistory(nst{1}).getCovLabelsFromMask;
-            otherLabels((numLabels+1):(numLabels+length(histLabels)))=histLabels;
-            clear labels distrib stats b XvalData XvalTime;
-            labels{1}  = otherLabels; % Labels change depending on presence/absense of History or ensCovHist
-            numHist = length(histObj.windowTimes)-1;
-%             histObj = tObj.history;
-            ensHistObj = [];
-%             [lambdaTemp, bTemp, devTemp, statsTemp,AICTemp,BICTemp,distribTemp] = Analysis.GLMFit(tObj,neuronNumber,i,Algorithm);
-           lambdaIndexStr=1;
-                lambda=Covariate(lambdaTime,lambdaData,...
-                       '\Lambda(t)','time',...
-                       's','Hz',strcat('\lambda_{',lambdaIndexStr,'}'));
-                AIC = 2*length(otherLabels)-2*logll(end);
-                BIC = -2*logll(end)+length(otherLabels)*log(length(lambdaData));
-                statsTemp{1}=[];
-                dev=-2*logll(end);
-% lambda{i} = lambdaTemp; 
-            b{1} = [beta';gammahat(end,:)']; 
-            stats{1} = statsTemp;
-%             dev(i) = devTemp;  
-%             AIC(i)= AICTemp; 
-%             BIC(i)= BICTemp;
-
-            distrib{1} =fitType;
-            currSpikes=nst;%nspikeColl.getNST(tObj.getNeuronIndFromName(neuronNames));
-            for n=1:length(currSpikes)
-                currSpikes{n} = currSpikes{n}.nstCopy;
-                currSpikes{n}.setName(nCopy.name);
-            end
-            XvalData{1} = [];
-            XvalTime{1} = [];
-            spikeTraining = currSpikes;
-
-                        
-            fitResults=FitResult(nCopy,labels,numHist,histObj,ensHistObj,lambda,b, dev, stats,AIC,BIC,configColl,XvalData,XvalTime,distrib);
-            DTCorrection=1;
-            makePlot=0;
-            Analysis.KSPlot(fitResults,DTCorrection,makePlot);
-            Analysis.plotInvGausTrans(fitResults,makePlot);
-            Analysis.plotFitResidual(fitResults,[],makePlot);
-                %fitResults.computePlotParams;
-            
-        
-            
-        end
-        
-        
-        function [psth, histSignal, psthResult] = psthGLM(nstCollObj, basisWidth,history,fitType,selectorArray,minTime,maxTime,sampleRate)
-            if(nargin<8)
-                sampleRate = 1/basisWidth;
-            end
-            if(nargin<7 || isempty(maxTime))
-                maxTime=nstCollObj.maxTime;
-            end
-            if(nargin<6 || isempty(minTime))
-                minTime=nstCollObj.minTime;
-            end
-            if(nargin<5 || isempty(selectorArray))
-                if(nstCollObj.isNeuronMaskSet)
-                    selectorArray = nstCollObj.getIndFromMask;
-                else
-                    selectorArray = 1:nstCollObj.numSpikeTrains;
-                end
-            end
-            if(nargin<4 ||isempty(fitType))
-               fitType = 'poisson'; %'binomial';
-            end
-                
-            if(nargin<3)
-                history =[];
-            end
-            
-            if(nargin<2)
-                basisWidth = .100; %100ms
-                
-            end
-            numBasis=ceil((maxTime-minTime)/basisWidth); 
-            alphaVal = .05;
-            unitPulseBasis=nstColl.generateUnitImpulseBasis(basisWidth,minTime,maxTime,sampleRate);
-
-            cc = CovColl({unitPulseBasis});
-            trial = Trial(nstCollObj,cc);
-            trial.setMinTime(minTime);
-            trial.setMaxTime(maxTime);
-%             for i=1:trial.nspikeColl.numSpikeTrains
-%                 if(i==1)
-%                     Y=num
-%                 
-   
-            clear c;
-            selfHist = history ; NeighborHist = []; sampleRate = nstCollObj.sampleRate; 
-            LabelSelect = cell(1,unitPulseBasis.dimension+1);
-            LabelSelect{1} = unitPulseBasis.name;
-            LabelSelect(2:end) = unitPulseBasis.dataLabels(1:end);
-            tc{1} = TrialConfig({LabelSelect},sampleRate,selfHist,NeighborHist); 
-            if(~isempty(selfHist))
-                tc{1}.setName('GLM-PSTH+Hist');
-            else
-                tc{1}.setName('GLM-PSTH');
-            end
-            cfgColl= ConfigColl(tc);
-            warning off;
-            
-            if(strcmp(fitType,'poisson'))
-                Algorithm='GLM';
-            else
-                Algorithm='BNLRCG';
-            end
-            
-            batchMode =1;
-            psthResult = Analysis.RunAnalysisForAllNeurons(trial,cfgColl,0,Algorithm,[],batchMode);
-%             cfgColl.setConfig(trial,1);
-%             for i=1:trial.nspikeColl.numSpikeTrains
-%                 if(i==1)
-%                     Y=trial.getSpikeVector(i);
-%                     X=trial.getDesignMatrix(i);
-%                 else
-%                     Y=[Y;trial.getSpikeVector(i)];
-%                     X=[X;trial.getDesignMatrix(i)];
-%                 end
-%             end
-%             
-% %                       y=tObj.getSpikeVector(neuronNumber);
-% %             X=tObj.getDesignMatrix(neuronNumber);
-% 
-%             
-%              distribution = 'poisson';
-%              linkfunction = 'log';
-%             
-%              [bVals,dev,stats] = glmfit(X,Y,distribution, 'link', linkfunction,'constant','off');
-
-            bVals = psthResult.b{1};
-            stats = psthResult.stats{1};
-            histVals = bVals(unitPulseBasis.dimension+1:end);
-            statsHist.se = stats.se(unitPulseBasis.dimension+1:end);
-            bVals=bVals(1:unitPulseBasis.dimension);
-            statsBVals.se = stats.se(1:unitPulseBasis.dimension);
-                
-            % Could do multinomial fit here but not at this time...
-%                 X=unitPulseBasis.data;
-%                 Y=nstCollObj.dataToMatrix;
-%                 [B,dev,stats]=mnrfit(X,Y);
-            
-            
-%             results = Analysis.RunAnalysisForAllNeurons(trial,cfgColl,0);
-%             warning on;
-%             bVals = zeros(unitPulseBasis.dimension,length(results));
-%             for i=1:length(results)
-%                bVals(:,i) = results{i}.b{1}; 
-%             end
-            if(strcmp(fitType,'poisson'))
-                expbVals = exp(bVals);
-                expHistVals=exp(histVals);
-            else
-                expbVals = exp(bVals)./(1+exp(bVals));
-                expHistVals = exp(histVals)./(1+exp(histVals));
-            end
-            
-            unitPulseBasis=nstColl.generateUnitImpulseBasis(basisWidth,minTime,maxTime,sampleRate);
-            psthData=(unitPulseBasis.data*expbVals)*(nstCollObj.sampleRate); % in Hz
-%             psthData=(expbVals)*(nstCollObj.sampleRate); % in Hz
-            %Remove Outliers%
-            psthData(or(isnan(psthData),isinf(psthData)))=0;
-%             modeVals = repmat(mode(psthData,2),[1 size(psthData,2)]);
-            
-%             psthData(psthData>nstCollObj.sampleRate*nstCollObj.numSpikeTrains)=0;
-%           psthData=psthData*(basisWidth); %counts
-            windowTimes = minTime:basisWidth:maxTime;
-            
-            if(~any(windowTimes==maxTime))
-                windowTimes=[windowTimes, maxTime];
-            end
-            
-            time = (windowTimes(2:end)+windowTimes(1:end-1))/2;
-                       
-            psth = Covariate(unitPulseBasis.time, psthData, 'PSTH_{glm}','time','s','Hz');
-            
-            
-            
-            mu=bVals;
-            s=statsBVals.se;
-            Mc=1000;
-            for c=1:Mc
-                z=normrnd(0,1,length(s),1);
-                xKDraw(:,c)=mu+(s.*z);
-            end
-            if(strcmp(fitType,'poisson'))
-%                 lower=logninv(alphaVal2/2,mu,s);
-%                 lower=(unitPulseBasis.data*lower)*(nstCollObj.sampleRate); % in Hz
-%                 upper=logninv(alphaVal2/2,mu,s);
-%                 upper=(unitPulseBasis.data*upper)*(nstCollObj.sampleRate); % in Hz
-            
-                lambdaDraw=exp(xKDraw)*(nstCollObj.sampleRate);
-                
-                
-            else %need to implement for binomial case
-                lambdaDraw=exp(xKDraw)./(1+exp(xKDraw))*(nstCollObj.sampleRate);
-                
-            end
-            lambdaDraw(isinf(lambdaDraw))=0;
-            for k=1:length(s)
-              [f,x] = ecdf(squeeze(lambdaDraw(k,:)));
-              CIs(k,1) = x(find(f(1-alphaVal/2),1,'first'));
-            end
-           
-%                 lower=logninv(0.025,mu,s);
-            lower=(unitPulseBasis.data*CIs(:,1)); % in Hz
-%                 upper=logninv(0.975,mu,s);
-            upper=(unitPulseBasis.data*CIs(:,2)); % in Hz
-  
-            ciPSTHGLM = ConfidenceInterval(unitPulseBasis.time,[lower,upper],'CI_{psth_GLM}',psth.xlabelval,psth.xunits,psth.yunits);
-            psth.setConfInterval(ciPSTHGLM);
-            
-            
-            
-            
-          
-            histTime=0:0.001:max(selfHist);
-            if(~isempty(histTime))
-                for i=1:length(selfHist)-1;
-                    if(i==(length(selfHist)-1))
-                        col = and(histTime>=selfHist(i),histTime<=selfHist(i+1))';
-                    else
-                        col = and(histTime>=selfHist(i),histTime(1-alphaVal/2),1,'first'));
-                end
-                lowerH=(basisMat*CIsH(:,1)); % in Hz
-                upperH=(basisMat*CIsH(:,2)); % in Hz
-                
-                ciPSTHGLMHist = ConfidenceInterval(histTime,[lowerH,upperH],'CI_{psth_GLMHIST}',psth.xlabelval,psth.xunits,psth.yunits);
-                histSignal.setConfInterval(ciPSTHGLMHist);
-            else
-                histSignal = [];
-            end
-            
-%             psth.setMinTime(minTime);
-%             psth.setMaxTime(maxTime);
-        end
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        %Plotting Functions
-        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-        function handle=plot(nstCollObj,selectorArray, minTime, maxTime,handle,reverseOrderPlot)
-            if(nargin<6 || isempty(reverseOrderPlot))
-                reverseOrderPlot =0;
-            end
-            if(nargin<5 || isempty(handle))
-                handle = gca;
-            end
-            if(nargin<4 || isempty(maxTime))
-                maxTime=nstCollObj.maxTime;
-            end
-            if(nargin<3 || isempty(minTime))
-                minTime=nstCollObj.minTime;
-            end
-            if(nargin<2 || isempty(selectorArray))
-                if(nstCollObj.isNeuronMaskSet)
-                    selectorArray = nstCollObj.getIndFromMask;
-                else
-                    selectorArray = 1:nstCollObj.numSpikeTrains;
-                end
-            end
-            
-            %plotHandle = figure(handle);
-            dHeight = 1;
-            yOffset = 0:1:length(selectorArray)-1;
-            yOffset = yOffset + dHeight/2;
-
-            if(reverseOrderPlot==0)
-                for i=1:length(selectorArray)
-                    currentObj = nstCollObj.getNST(selectorArray(i));
-                    currentObj.plot(dHeight, yOffset(i), handle); hold on;
-                    yticklabels{i} = currentObj.name;
-                    if(strcmp(yticklabels{i},''));
-                        yticklabels{i} = num2str(selectorArray(i));
-                    end
-                end
-            else
-                for i=1:length(selectorArray)
-                    currentObj = nstCollObj.getNST(selectorArray(i));
-                    currentObj.plot(dHeight, yOffset(end-(i-1)), handle); hold on;
-                    yticklabels{i} = currentObj.name;
-                    if(strcmp(yticklabels{i},''));
-                        yticklabels{i} = num2str(selectorArray(i));
-                    end
-                end
-            end
-            xlabel('$$ time [s] $$','Interpreter','latex');            
-            set(gca,'YTick',yOffset);
-            set(gca,'YTickLabel',yticklabels);
-            axis tight;
-            v=axis;
-%             minTime
-%             maxTime
-%           
-            if(minTime~=maxTime)
-             axis([minTime,maxTime,v(3),v(4)]);
-            end
-            handle=gca;
-
-%             plotHandle = figure(handle);
-%             binwidth = max(nstCollObj.getMaxBinSizeBinary,.001);
-%             nMat=nstCollObj.dataToMatrix(selectorArray,binwidth,minTime,maxTime);
-% %             time = nstCollObj.minTime:(1/nstCollObj.sampleRate):nstCollObj.maxTime;
-%             nMat(nMat>1)=1;
-%             nMat = ~nMat;
-%             imagesc(flipud(nMat'));
-%             colormap(gray);
-%             xt=get(gca,'xtick')*binwidth;
-%             xtStr= num2str(xt');
-%             set(gca,'xtickLabel',xtStr);
-%             
-%             for i=1:length(selectorArray)
-%                currentObj = nstCollObj.getNST(selectorArray(i));
-%                yticklabels{i} = currentObj.name;
-%                if(strcmp(yticklabels{i},''));
-%                     yticklabels{i} = num2str(selectorArray(i));
-%                end
-%             end
-%             set(gca,'YTick',selectorArray,'YTickLabel',fliplr(yticklabels));
-%             xlabel('$$ time [s] $$','Interpreter','latex');       
-
-
-        end
-   
-        function minISIs = getMinISIs(nstCollObj, selectorArray, minTime,maxTime)
-            if(nargin<4 || isempty(maxTime))
-                maxTime=nstCollObj.maxTime;
-            end
-            if(nargin<3 || isempty(minTime))
-                minTime=nstCollObj.minTime;
-            end
-            if(nargin<2 || isempty(selectorArray))
-                if(nstCollObj.isNeuronMaskSet)
-                    selectorArray = nstCollObj.getIndFromMask;
-                else
-                    selectorArray = 1:nstCollObj.numSpikeTrains;
-                end
-            end
-             
-            ISIs = nstCollObj.getISIs(selectorArray, minTime, maxTime);
-            minISIs = zeros(1,length(selectorArray));
-            for i=1:length(ISIs)
-               temp = min(ISIs{i});
-               if(isempty(temp))
-                    minISIs(i)=0;
-               else
-                    minISIs(i) = min(ISIs{i}); 
-               end
-            end
-        end
-        
-        function ISIs=getISIs(nstCollObj,selectorArray,minTime,maxTime)
-            if(nargin<4 || isempty(maxTime))
-                maxTime=nstCollObj.maxTime;
-            end
-            if(nargin<3 || isempty(minTime))
-                minTime=nstCollObj.minTime;
-            end
-            if(nargin<2 || isempty(selectorArray))
-                if(nstCollObj.isNeuronMaskSet)
-                    selectorArray = nstCollObj.getIndFromMask;
-                else
-                    selectorArray = 1:nstCollObj.numSpikeTrains;
-                end
-            end
-            
-            
-            for i=1:length(selectorArray)
-                currentObj = nstCollObj.getNST(selectorArray(i));
-                ISIs{i} = currentObj.getISIs(minTime,maxTime);
-               
-            end
-     
-        
-        end
-        
-        function plotISIHistogram(nstCollObj,selectorArray, minTime, maxTime,handle)
-            if(nargin<5 || isempty(handle))
-                handle = gca;
-            end
-            if(nargin<4 || isempty(maxTime))
-                maxTime=nstCollObj.maxTime;
-            end
-            if(nargin<3 || isempty(minTime))
-                minTime=nstCollObj.minTime;
-            end
-            if(nargin<2 || isempty(selectorArray))
-                if(nstCollObj.isNeuronMaskSet)
-                    selectorArray = nstCollObj.getIndFromMask;
-                else
-                    selectorArray = 1:nstCollObj.numSpikeTrains;
-                end
-            end
-            
-                        
-            f=factor(length(selectorArray));
-            
-            for i=1:length(selectorArray)
-                currentObj = nstCollObj.getNST(selectorArray(i));
-                if(length(f)==1)
-                    subplot(1,f,i);
-                else
-                    subplot(f(1),prod(f(2:end)),i);
-                end
-                currentObj.plotISIHistogram(minTime,maxTime); %hold on;
-                yticklabels{i} = currentObj.name;
-                if(strcmp(yticklabels{i},''));
-                    yticklabels{i} = num2str(selectorArray(i));
-                end
-            end
-            %xlabel('$$ time [s] $$','Interpreter','latex');            
-            %set(gca,'YTick',yOffset);
-            %set(gca,'YTickLabel',yticklabels);
-            %axis tight;
-            v=axis;
-%             minTime
-%             maxTime
-%             
-            axis([minTime,maxTime,v(3),v(4)]);
-        end
-        
-        function plotExponentialFit(nstCollObj,selectorArray, minTime, maxTime,numBins,handle)
-            if(nargin<6)
-                handle = gca;
-            end
-            if(nargin<5 || isempty(numBins))
-                numBins =[];
-            end
-            if(nargin<4)
-                maxTime=nstCollObj.maxTime;
-            end
-            if(nargin<3)
-                minTime=nstCollObj.minTime;
-            end
-            if(nargin<2)
-                if(nstCollObj.isNeuronMaskSet)
-                    selectorArray = nstCollObj.getIndFromMask;
-                else
-                    selectorArray = 1:nstCollObj.numSpikeTrains;
-                end
-            end
-            
-                        
-            for i=1:length(selectorArray)
-                currentObj = nstCollObj.getNST(selectorArray(i));
-                
-                currentObj.plotExponentialFit(minTime,maxTime,numBins); %hold on;
-                yticklabels{i} = currentObj.name;
-                if(strcmp(yticklabels{i},''));
-                    yticklabels{i} = num2str(selectorArray(i));
-                end
-            end
-            %xlabel('$$ time [s] $$','Interpreter','latex');            
-            %set(gca,'YTick',yOffset);
-            %set(gca,'YTickLabel',yticklabels);
-            %axis tight;
-            %v=axis;
-%             minTime
-%             maxTime
-%             
-            %axis([minTime,maxTime,v(3),v(4)]);
-        end
-        function varEst = estimateVarianceAcrossTrials(nstCollObj,numBasis,windowTimes,numIter,fitType)
-            %returns a estimate of the variance within each basis
-            if(nargin<5 || isempty(fitType))
-               fitType = 'poisson'; 
-            end
-            if(nargin<4 || isempty(numIter))
-                numIter=20;
-            end
-            if(nargin<3 || isempty(windowTimes))
-                windowTimes = [];
-            end
-            if(nargin<2 ||isempty(numBasis))
-                numBasis = 20;
-            end
-
-            echo off;
-            coeffs = zeros(numBasis,numIter);
-            numRealizations = nstCollObj.numSpikeTrains;
-            basisWidth = (nstCollObj.maxTime - nstCollObj.minTime)./numBasis;
-            sumNumber=numRealizations/2-1;
-            delta = 1/nstCollObj.sampleRate;
-            minTime = nstCollObj.minTime;
-            maxTime = nstCollObj.maxTime;
-            
-
-            for i=1:min([numIter/2 sumNumber])
-
-                spikeCollTemp=nstColl(nstCollObj.getNST(i:i+sumNumber));
-
-
-                spikeCollTemp.resample(1/delta);
-                spikeCollTemp.setMaxTime(maxTime);
-                spikeCollTemp.setMinTime(minTime);
-                [~, ~, psthResultT] =spikeCollTemp.psthGLM(basisWidth,windowTimes,fitType);
-                coeffs(:,i)=psthResultT.getCoeffs;
-            end
-            for i=numRealizations:-1:(numRealizations-min([numIter/2 sumNumber])+1)
-                spikeCollTemp=nstColl(nstCollObj.getNST(i:-1:i-sumNumber));
-
-
-                spikeCollTemp.resample(1/delta);
-                spikeCollTemp.setMaxTime(maxTime);
-                spikeCollTemp.setMinTime(minTime);
-                [~, ~, psthResultT] =spikeCollTemp.psthGLM(basisWidth,windowTimes,fitType);
-                coeffs(:,i)=psthResultT.getCoeffs;
-            end 
-            
-            %Remove zero columns
-            for i=1:size(coeffs,1)
-                CoeffsTemp(i,:) = coeffs(i,coeffs(i,:)~=0);
-            end
-            
-            coeffs=CoeffsTemp;
-            NTerms=4;A=1; B=ones(1,NTerms)./NTerms;
-            coeffs(isnan(coeffs))=0;
-%             coeffs(exp(coeffs)/delta>10)=log(10*delta); %dont allow for really large coeffs
-            if(size(coeffs',1)>3*NTerms)
-                fcoeffs = filtfilt(B,A,coeffs')';
-            else
-                fcoeffs = coeffs;
-            end
-            
-            varEst=nanvar(diff(fcoeffs,[],2),[],2);
-
-%             varEst(varEst>.001)=0.0001; %avoid large estimates of the sample variance
-
-            varEst=diag(varEst);
-            echo on;
-        end
-        function windowedSpikeTimes=getSpikeTimes(nstCollObj, minTime, maxTime)
-            if(nargin<3 || isempty(maxTime))
-                maxTime=nstCollObj.maxTime;
-            end
-            if(nargin<2 || isempty(minTime))
-                minTime=nstCollObj.minTime;
-            end
-            
-            ind = nstCollObj.getIndFromMask;
-            windowedSpikeTimes=cell(length(ind),1);
-            for i=ind
-                if(i==1)
-                    count=1;
-                end
-                currSpike = nstCollObj.getNST(i);
-                windowedSpikeTimes{count} = currSpike.getSpikeTimes;
-                count=count+1;
-            end
-        end
-        
-        function structure = toStructure(nstCollObj)
-            fnames = fieldnames(nstCollObj);
-            nstCollObj.resetMask; %otherwise masked data will not get saved!!
-            for i=1:length(fnames)
-                currObj = nstCollObj.(fnames{i});
-                if(isa(currObj,'double')||isa(currObj,'cell')||isa(currObj,'logical'))
-                    if(strcmp(fnames{i},'nstrain'))
-                        for j=1:nstCollObj.numSpikeTrains
-                            structure.(fnames{i}){j} = nstCollObj.(fnames{i}){j}.toStructure;
-                        end
-                    else
-                        structure.(fnames{i}) =  currObj;
-                    end
-                end
-            end
-        end
-    end
-    methods (Static)
-        function nstCollObj = fromStructure(structure)
-            nst = cell(1,structure.numSpikeTrains);
-            for i=1:structure.numSpikeTrains;
-                nst{i} = nspikeTrain.fromStructure(structure.nstrain{i});
-            end
-            nstCollObj = nstColl(nst);
-            nstCollObj.setMinTime(structure.minTime);
-            nstCollObj.setMaxTime(structure.maxTime);
-            nstCollObj.setNeighbors(structure.neighbors);
-        end
-        function unitPulseBasis=generateUnitImpulseBasis(basisWidth,minTime,maxTime,sampleRate)
-            % Samplerate determines number of samples per second for the
-            % unit pulse functions. If basisWidth is larger than the sample
-            % rate of nstCollObj, when a trial is formed to obtain the GLM
-            % psth, the up-sampled pulses will no longer be square. Better
-            % to upsample the spikeTrain instead.
-            if(nargin<5)
-                sampleRate=1000;
-            end
-             
-            windowTimes = minTime:basisWidth:(maxTime);
-            
-            
-            if(~any(windowTimes==maxTime))
-                windowTimes=[windowTimes, maxTime];
-            end
-            numBasis=length(windowTimes)-1;   
-%             timeVec = (minTime:(1/nstCollObj.sampleRate):maxTime)';
-            timeVec = (minTime:(1/sampleRate):maxTime)';
-            dataMat = zeros(length(timeVec),length(windowTimes)-1);
-            
-            for i=1:length(windowTimes)-1
-               dataMat(:,i) = and(timeVec>=(windowTimes(i)),timeVec=(windowTimes(i)),timeVec<=windowTimes(i+1)); 
-               else
-                  dataMat(:,i) = and(timeVec>=(windowTimes(i)),timeVec=nstCollObj.maxTime)
-                nstCollObj.setMaxTime(nst.maxTime);
-            else
-                nst.setMaxTime(nstCollObj.maxTime);
-            end
-        end
-        
-      
-        
-    end
-    
-end
-
diff --git a/nstat/ConfidenceInterval.py b/nstat/ConfidenceInterval.py
new file mode 100644
index 00000000..eba47603
--- /dev/null
+++ b/nstat/ConfidenceInterval.py
@@ -0,0 +1,13 @@
+from __future__ import annotations
+
+from ._compat import warn_deprecated_adapter
+from .confidence_interval import ConfidenceInterval as _ConfidenceInterval
+
+
+class ConfidenceInterval(_ConfidenceInterval):
+    def __init__(self, *args, **kwargs) -> None:
+        warn_deprecated_adapter("nstat.ConfidenceInterval.ConfidenceInterval", "nstat.confidence_interval.ConfidenceInterval")
+        super().__init__(*args, **kwargs)
+
+
+__all__ = ["ConfidenceInterval"]
diff --git a/nstat/ConfigColl.py b/nstat/ConfigColl.py
new file mode 100644
index 00000000..ddeef33d
--- /dev/null
+++ b/nstat/ConfigColl.py
@@ -0,0 +1,13 @@
+from __future__ import annotations
+
+from ._compat import warn_deprecated_adapter
+from .trial import ConfigCollection
+
+
+class ConfigColl(ConfigCollection):
+    def __init__(self, *args, **kwargs) -> None:
+        warn_deprecated_adapter("nstat.ConfigColl.ConfigColl", "nstat.trial.ConfigCollection")
+        super().__init__(*args, **kwargs)
+
+
+__all__ = ["ConfigColl"]
diff --git a/nstat/CovColl.py b/nstat/CovColl.py
new file mode 100644
index 00000000..76b4ff93
--- /dev/null
+++ b/nstat/CovColl.py
@@ -0,0 +1,13 @@
+from __future__ import annotations
+
+from ._compat import warn_deprecated_adapter
+from .trial import CovariateCollection
+
+
+class CovColl(CovariateCollection):
+    def __init__(self, *args, **kwargs) -> None:
+        warn_deprecated_adapter("nstat.CovColl.CovColl", "nstat.trial.CovariateCollection")
+        super().__init__(*args, **kwargs)
+
+
+__all__ = ["CovColl"]
diff --git a/nstat/Covariate.py b/nstat/Covariate.py
new file mode 100644
index 00000000..e04d6825
--- /dev/null
+++ b/nstat/Covariate.py
@@ -0,0 +1,13 @@
+from __future__ import annotations
+
+from ._compat import warn_deprecated_adapter
+from .signal import Covariate as _Covariate
+
+
+class Covariate(_Covariate):
+    def __init__(self, *args, **kwargs) -> None:
+        warn_deprecated_adapter("nstat.Covariate.Covariate", "nstat.signal.Covariate")
+        super().__init__(*args, **kwargs)
+
+
+__all__ = ["Covariate"]
diff --git a/nstat/DecodingAlgorithms.py b/nstat/DecodingAlgorithms.py
new file mode 100644
index 00000000..0cc8eb78
--- /dev/null
+++ b/nstat/DecodingAlgorithms.py
@@ -0,0 +1,13 @@
+from __future__ import annotations
+
+from ._compat import warn_deprecated_adapter
+from .decoding_algorithms import DecodingAlgorithms as _DecodingAlgorithms
+
+
+class DecodingAlgorithms(_DecodingAlgorithms):
+    def __init__(self, *args, **kwargs) -> None:
+        warn_deprecated_adapter("nstat.DecodingAlgorithms.DecodingAlgorithms", "nstat.decoding.DecoderSuite")
+        super().__init__(*args, **kwargs)
+
+
+__all__ = ["DecodingAlgorithms"]
diff --git a/nstat/FitResSummary.py b/nstat/FitResSummary.py
new file mode 100644
index 00000000..7305bbb6
--- /dev/null
+++ b/nstat/FitResSummary.py
@@ -0,0 +1,13 @@
+from __future__ import annotations
+
+from ._compat import warn_deprecated_adapter
+from .fit import FitResSummary as _FitResSummary
+
+
+class FitResSummary(_FitResSummary):
+    def __init__(self, *args, **kwargs) -> None:
+        warn_deprecated_adapter("nstat.FitResSummary.FitResSummary", "nstat.fit.FitSummary")
+        super().__init__(*args, **kwargs)
+
+
+__all__ = ["FitResSummary"]
diff --git a/nstat/FitResult.py b/nstat/FitResult.py
new file mode 100644
index 00000000..fb4dc3d0
--- /dev/null
+++ b/nstat/FitResult.py
@@ -0,0 +1,13 @@
+from __future__ import annotations
+
+from ._compat import warn_deprecated_adapter
+from .fit import FitResult as _FitResult
+
+
+class FitResult(_FitResult):
+    def __init__(self, *args, **kwargs) -> None:
+        warn_deprecated_adapter("nstat.FitResult.FitResult", "nstat.fit.FitResult")
+        super().__init__(*args, **kwargs)
+
+
+__all__ = ["FitResult"]
diff --git a/nstat/SignalObj.py b/nstat/SignalObj.py
new file mode 100644
index 00000000..32e333a3
--- /dev/null
+++ b/nstat/SignalObj.py
@@ -0,0 +1,13 @@
+from __future__ import annotations
+
+from ._compat import warn_deprecated_adapter
+from .signal import Signal
+
+
+class SignalObj(Signal):
+    def __init__(self, *args, **kwargs) -> None:
+        warn_deprecated_adapter("nstat.SignalObj.SignalObj", "nstat.signal.Signal")
+        super().__init__(*args, **kwargs)
+
+
+__all__ = ["SignalObj"]
diff --git a/nstat/TrialConfig.py b/nstat/TrialConfig.py
new file mode 100644
index 00000000..a110e4c6
--- /dev/null
+++ b/nstat/TrialConfig.py
@@ -0,0 +1,13 @@
+from __future__ import annotations
+
+from ._compat import warn_deprecated_adapter
+from .trial import TrialConfig as _TrialConfig
+
+
+class TrialConfig(_TrialConfig):
+    def __init__(self, *args, **kwargs) -> None:
+        warn_deprecated_adapter("nstat.TrialConfig.TrialConfig", "nstat.trial.TrialConfig")
+        super().__init__(*args, **kwargs)
+
+
+__all__ = ["TrialConfig"]
diff --git a/nstat/__init__.py b/nstat/__init__.py
new file mode 100644
index 00000000..57e45779
--- /dev/null
+++ b/nstat/__init__.py
@@ -0,0 +1,68 @@
+from .ConfidenceInterval import ConfidenceInterval
+from .ConfigColl import ConfigColl
+from .CovColl import CovColl
+from .SignalObj import SignalObj
+from .analysis import Analysis, psth
+from .cif import CIF, CIFModel
+from .datasets import get_dataset_path, list_datasets, verify_checksums
+from .decoding import DecoderSuite
+from .decoding_algorithms import DecodingAlgorithms
+from .errors import DataNotFoundError, ParityValidationError, UnsupportedWorkflowError
+from .fit import FitResSummary, FitResult, FitSummary
+from .glm import PoissonGLMResult, fit_poisson_glm
+from .history import History, HistoryBasis
+from .paper_examples_full import run_full_paper_examples
+from .signal import Covariate, Signal
+from .simulation import simulate_poisson_from_rate
+from .simulators import (
+    NetworkSimulationResult,
+    PointProcessSimulation,
+    simulate_point_process,
+    simulate_two_neuron_network,
+)
+from .spikes import SpikeTrain, SpikeTrainCollection
+from .trial import ConfigCollection, CovariateCollection, Trial, TrialConfig
+from .nspikeTrain import nspikeTrain
+from .nstColl import nstColl
+
+__all__ = [
+    "Analysis",
+    "CIF",
+    "CIFModel",
+    "ConfidenceInterval",
+    "ConfigColl",
+    "ConfigCollection",
+    "Covariate",
+    "CovColl",
+    "CovariateCollection",
+    "DataNotFoundError",
+    "DecoderSuite",
+    "DecodingAlgorithms",
+    "FitResSummary",
+    "FitResult",
+    "FitSummary",
+    "History",
+    "HistoryBasis",
+    "NetworkSimulationResult",
+    "ParityValidationError",
+    "PointProcessSimulation",
+    "PoissonGLMResult",
+    "SignalObj",
+    "Signal",
+    "SpikeTrain",
+    "SpikeTrainCollection",
+    "Trial",
+    "TrialConfig",
+    "UnsupportedWorkflowError",
+    "fit_poisson_glm",
+    "get_dataset_path",
+    "list_datasets",
+    "psth",
+    "run_full_paper_examples",
+    "simulate_point_process",
+    "simulate_poisson_from_rate",
+    "simulate_two_neuron_network",
+    "nspikeTrain",
+    "nstColl",
+    "verify_checksums",
+]
diff --git a/nstat/_compat.py b/nstat/_compat.py
new file mode 100644
index 00000000..6d541ab1
--- /dev/null
+++ b/nstat/_compat.py
@@ -0,0 +1,11 @@
+from __future__ import annotations
+
+import warnings
+
+
+def warn_deprecated_adapter(old: str, new: str) -> None:
+    warnings.warn(
+        f"{old} is deprecated and will be removed in a future major release; use {new} instead.",
+        DeprecationWarning,
+        stacklevel=3,
+    )
diff --git a/nstat/analysis.py b/nstat/analysis.py
new file mode 100644
index 00000000..0f581c56
--- /dev/null
+++ b/nstat/analysis.py
@@ -0,0 +1,120 @@
+from __future__ import annotations
+
+from typing import Sequence
+
+import numpy as np
+
+from .fit import FitResult, _SingleFit
+from .glm import fit_poisson_glm
+from .signal import Covariate
+from .trial import ConfigCollection, Trial
+
+
+def psth(spike_trains: Sequence[object], bin_edges: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
+    edges = np.asarray(bin_edges, dtype=float)
+    if edges.ndim != 1 or edges.size < 2:
+        raise ValueError("bin_edges must be 1D and length >= 2")
+
+    counts = np.zeros(edges.size - 1, dtype=float)
+    if len(spike_trains) == 0:
+        return counts.copy(), counts
+
+    for tr in spike_trains:
+        spikes = np.asarray(getattr(tr, "spikeTimes"), dtype=float).reshape(-1)
+        c, _ = np.histogram(spikes, bins=edges)
+        counts += c
+
+    widths = np.diff(edges)
+    mean_rate_hz = counts / (len(spike_trains) * widths)
+    return mean_rate_hz, counts
+
+
+class Analysis:
+    """Canonical analysis entry points preserving the paper's workflow semantics."""
+
+    @staticmethod
+    def psth(spike_trains: Sequence[object], bin_edges: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
+        return psth(spike_trains, bin_edges)
+
+    @staticmethod
+    def run_analysis_for_neuron(
+        trial: Trial,
+        neuron_index: int,
+        config_collection: ConfigCollection,
+        *,
+        l2: float = 1e-6,
+        max_iter: int = 120,
+    ) -> FitResult:
+        time, x_all, labels = trial.get_covariate_matrix()
+        spike_train = trial.spike_collection.get_nst(neuron_index)
+
+        dt = float(np.median(np.diff(time))) if time.shape[0] > 1 else 1.0
+        edges = np.concatenate([time, [time[-1] + dt]])
+        y = spike_train.to_binned_counts(edges)
+        offset = np.full(y.shape[0], np.log(max(dt, 1e-12)), dtype=float)
+
+        fits: list[_SingleFit] = []
+        for idx, cfg in enumerate(config_collection.configs, start=1):
+            names = cfg.covariate_names
+            if names:
+                cols = [i for i, lab in enumerate(labels) if lab in set(names)]
+                x = x_all[:, cols] if cols else np.zeros((x_all.shape[0], 0), dtype=float)
+            else:
+                x = x_all
+
+            glm_res = fit_poisson_glm(x, y, offset=offset, l2=l2, max_iter=max_iter)
+            n_params = x.shape[1] + 1
+            aic = 2.0 * n_params - 2.0 * glm_res.log_likelihood
+            bic = np.log(max(y.shape[0], 1)) * n_params - 2.0 * glm_res.log_likelihood
+            fit_name = cfg.name if cfg.name else f"Fit {idx}"
+            fits.append(
+                _SingleFit(
+                    name=fit_name,
+                    coefficients=np.asarray(glm_res.coefficients, dtype=float),
+                    intercept=float(glm_res.intercept),
+                    log_likelihood=float(glm_res.log_likelihood),
+                    aic=float(aic),
+                    bic=float(bic),
+                )
+            )
+
+        if x_all.shape[1] == 0:
+            x_for_rate = np.zeros((y.shape[0], 0), dtype=float)
+        else:
+            x_for_rate = x_all
+        rate = fit_poisson_glm(x_for_rate, y, offset=offset, l2=l2, max_iter=max_iter).predict_rate(x_for_rate, offset=offset)
+        lambda_signal = Covariate(time, rate, "lambda", "time", "s", "spikes/sec", ["lambda"])
+        return FitResult(spike_train, lambda_signal, fits)
+
+    @staticmethod
+    def run_analysis_for_all_neurons(
+        trial: Trial,
+        config_collection: ConfigCollection,
+        *,
+        l2: float = 1e-6,
+        max_iter: int = 120,
+    ) -> list[FitResult]:
+        out: list[FitResult] = []
+        for i in range(trial.spike_collection.num_spike_trains):
+            out.append(
+                Analysis.run_analysis_for_neuron(
+                    trial,
+                    i,
+                    config_collection,
+                    l2=l2,
+                    max_iter=max_iter,
+                )
+            )
+        return out
+
+    # MATLAB-compatible method names.
+    @staticmethod
+    def RunAnalysisForNeuron(tObj: Trial, neuronNumber: int, configColl: ConfigCollection):
+        return Analysis.run_analysis_for_neuron(tObj, neuronNumber - 1, configColl)
+
+    @staticmethod
+    def RunAnalysisForAllNeurons(tObj: Trial, configs: ConfigCollection, *_):
+        return Analysis.run_analysis_for_all_neurons(tObj, configs)
+
+
+__all__ = ["Analysis", "psth"]
diff --git a/nstat/cif.py b/nstat/cif.py
new file mode 100644
index 00000000..8b64b0ab
--- /dev/null
+++ b/nstat/cif.py
@@ -0,0 +1,77 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import numpy as np
+
+from .signal import Covariate
+from .simulation import simulate_poisson_from_rate
+from .trial import SpikeTrainCollection
+
+
+@dataclass
+class CIFModel:
+    """Conditional intensity function abstraction used by standalone workflows."""
+
+    time: np.ndarray
+    rate_hz: np.ndarray
+    name: str = "lambda"
+
+    def __post_init__(self) -> None:
+        self.time = np.asarray(self.time, dtype=float).reshape(-1)
+        self.rate_hz = np.asarray(self.rate_hz, dtype=float).reshape(-1)
+        if self.time.shape[0] != self.rate_hz.shape[0]:
+            raise ValueError("time and rate_hz length mismatch")
+
+    def to_covariate(self) -> Covariate:
+        return Covariate(self.time, self.rate_hz, self.name, "time", "s", "spikes/sec", [self.name])
+
+    def simulate(self, num_realizations: int = 1, *, seed: int | None = None) -> SpikeTrainCollection:
+        if num_realizations < 1:
+            raise ValueError("num_realizations must be >= 1")
+        rng = np.random.default_rng(seed)
+        trains = []
+        for i in range(num_realizations):
+            st = simulate_poisson_from_rate(self.time, self.rate_hz, rng=rng)
+            st.setName(str(i + 1))
+            trains.append(st)
+        return SpikeTrainCollection(trains)
+
+    @classmethod
+    def from_linear_terms(
+        cls,
+        time: np.ndarray,
+        intercept: float,
+        coefficients: np.ndarray,
+        design_matrix: np.ndarray,
+        dt: float,
+        name: str = "lambda",
+    ) -> "CIFModel":
+        eta = intercept + np.asarray(design_matrix, dtype=float) @ np.asarray(coefficients, dtype=float)
+        p = np.exp(np.clip(eta, -20.0, 20.0))
+        p = p / (1.0 + p)
+        rate = p / max(float(dt), 1e-12)
+        return cls(np.asarray(time, dtype=float).reshape(-1), rate, name)
+
+
+class CIF:
+    """MATLAB-compatible CIF static API wrapper."""
+
+    @staticmethod
+    def simulateCIFByThinningFromLambda(lambda_covariate: Covariate, numRealizations: int = 1) -> SpikeTrainCollection:
+        model = CIFModel(lambda_covariate.time, lambda_covariate.data[:, 0], getattr(lambda_covariate, "name", "lambda"))
+        return model.simulate(num_realizations=numRealizations)
+
+    @staticmethod
+    def from_linear_terms(
+        time: np.ndarray,
+        intercept: float,
+        coefficients: np.ndarray,
+        design_matrix: np.ndarray,
+        dt: float,
+        name: str = "lambda",
+    ) -> Covariate:
+        return CIFModel.from_linear_terms(time, intercept, coefficients, design_matrix, dt, name).to_covariate()
+
+
+__all__ = ["CIFModel", "CIF"]
diff --git a/nstat/confidence_interval.py b/nstat/confidence_interval.py
new file mode 100644
index 00000000..0da57c2d
--- /dev/null
+++ b/nstat/confidence_interval.py
@@ -0,0 +1,34 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import numpy as np
+
+
+@dataclass
+class ConfidenceInterval:
+    time: np.ndarray
+    bounds: np.ndarray
+    color: str = "b"
+
+    def __init__(self, time, bounds, color: str = "b") -> None:
+        t = np.asarray(time, dtype=float).reshape(-1)
+        b = np.asarray(bounds, dtype=float)
+        if b.ndim != 2 or b.shape[1] != 2:
+            raise ValueError("bounds must have shape (n, 2)")
+        if b.shape[0] != t.shape[0]:
+            raise ValueError("bounds rows must match time length")
+        self.time = t
+        self.bounds = b
+        self.color = color
+
+    @property
+    def lower(self) -> np.ndarray:
+        return self.bounds[:, 0]
+
+    @property
+    def upper(self) -> np.ndarray:
+        return self.bounds[:, 1]
+
+    def setColor(self, color: str) -> None:
+        self.color = str(color)
diff --git a/nstat/core.py b/nstat/core.py
new file mode 100644
index 00000000..a1836b1a
--- /dev/null
+++ b/nstat/core.py
@@ -0,0 +1,294 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Iterable, Sequence
+
+import numpy as np
+
+
+def _as_1d_float(values: Sequence[float] | np.ndarray, name: str) -> np.ndarray:
+    array = np.asarray(values, dtype=float).reshape(-1)
+    if array.size == 0:
+        raise ValueError(f"{name} must be non-empty.")
+    return array
+
+
+class SignalObj:
+    """Python approximation of nSTAT SignalObj.
+
+    The class stores a time vector and one or more aligned signal channels.
+    """
+
+    def __init__(
+        self,
+        time: Sequence[float],
+        data: Sequence[float] | Sequence[Sequence[float]] | np.ndarray,
+        name: str = "signal",
+        xlabel: str = "time",
+        xunits: str = "s",
+        yunits: str = "",
+        data_labels: Sequence[str] | None = None,
+    ) -> None:
+        t = _as_1d_float(time, "time")
+        if np.any(np.diff(t) <= 0):
+            raise ValueError("time must be strictly increasing.")
+
+        x = np.asarray(data, dtype=float)
+        if x.ndim == 1:
+            x = x[:, None]
+        if x.shape[0] != t.shape[0]:
+            raise ValueError("data must have same first dimension as time.")
+
+        self.time = t
+        self.data = x
+        self.name = name
+        self.xlabelval = xlabel
+        self.xunits = xunits
+        self.yunits = yunits
+
+        if data_labels is None:
+            labels = [f"{name}_{k+1}" for k in range(self.data.shape[1])]
+        else:
+            labels = list(data_labels)
+            if len(labels) != self.data.shape[1]:
+                raise ValueError("data_labels length must match signal dimension.")
+        self.dataLabels = labels
+        self.conf_interval: tuple[np.ndarray, np.ndarray] | None = None
+
+    @property
+    def dimension(self) -> int:
+        return int(self.data.shape[1])
+
+    @property
+    def values(self) -> np.ndarray:
+        if self.dimension == 1:
+            return self.data[:, 0]
+        return self.data
+
+    @property
+    def units(self) -> str:
+        return self.yunits
+
+    @property
+    def sample_rate(self) -> float:
+        if self.time.shape[0] < 2:
+            return 0.0
+        dt = np.median(np.diff(self.time))
+        if dt <= 0:
+            return 0.0
+        return float(1.0 / dt)
+
+    def copySignal(self) -> "SignalObj":
+        out = SignalObj(
+            self.time.copy(),
+            self.data.copy(),
+            self.name,
+            self.xlabelval,
+            self.xunits,
+            self.yunits,
+            self.dataLabels,
+        )
+        out.conf_interval = None if self.conf_interval is None else (
+            self.conf_interval[0].copy(),
+            self.conf_interval[1].copy(),
+        )
+        return out
+
+    def setName(self, name: str) -> None:
+        self.name = str(name)
+
+    def setDataLabels(self, labels: Sequence[str]) -> None:
+        labels = list(labels)
+        if len(labels) != self.dimension:
+            raise ValueError("labels length must equal number of signal channels.")
+        self.dataLabels = labels
+
+    def setConfInterval(self, bounds: tuple[np.ndarray, np.ndarray]) -> None:
+        low, high = bounds
+        low = np.asarray(low, dtype=float)
+        high = np.asarray(high, dtype=float)
+        if low.shape[0] != self.time.shape[0] or high.shape[0] != self.time.shape[0]:
+            raise ValueError("confidence interval bounds must align with time.")
+        self.conf_interval = (low, high)
+
+    def getSubSignal(self, idx: int) -> "SignalObj":
+        if idx < 1 or idx > self.dimension:
+            raise IndexError("Signal index out of range. Indexing is 1-based.")
+        j = idx - 1
+        return SignalObj(
+            self.time,
+            self.data[:, j],
+            self.name,
+            self.xlabelval,
+            self.xunits,
+            self.yunits,
+            [self.dataLabels[j]],
+        )
+
+    def getSigInTimeWindow(self, t0: float, t1: float) -> "SignalObj":
+        mask = (self.time >= t0) & (self.time <= t1)
+        if not np.any(mask):
+            raise ValueError("Requested time window has no samples.")
+        return SignalObj(
+            self.time[mask],
+            self.data[mask, :],
+            self.name,
+            self.xlabelval,
+            self.xunits,
+            self.yunits,
+            self.dataLabels,
+        )
+
+    def merge(self, other: "SignalObj") -> "SignalObj":
+        if self.time.shape != other.time.shape or np.max(np.abs(self.time - other.time)) > 1e-9:
+            raise ValueError("Signals must share an identical time grid to merge.")
+        return SignalObj(
+            self.time,
+            np.column_stack([self.data, other.data]),
+            self.name,
+            self.xlabelval,
+            self.xunits,
+            self.yunits,
+            [*self.dataLabels, *other.dataLabels],
+        )
+
+    def resample(self, sample_rate: float) -> "SignalObj":
+        if sample_rate <= 0:
+            raise ValueError("sample_rate must be > 0.")
+        dt = 1.0 / float(sample_rate)
+        t_new = np.arange(self.time[0], self.time[-1] + 0.5 * dt, dt)
+        x_new = np.column_stack(
+            [np.interp(t_new, self.time, self.data[:, i]) for i in range(self.dimension)]
+        )
+        return SignalObj(
+            t_new,
+            x_new,
+            self.name,
+            self.xlabelval,
+            self.xunits,
+            self.yunits,
+            self.dataLabels,
+        )
+
+    @property
+    def derivative(self) -> "SignalObj":
+        dt = np.gradient(self.time)
+        deriv = np.column_stack([np.gradient(self.data[:, i], self.time) for i in range(self.dimension)])
+        # Avoid numerical noise spikes where dt is near 0.
+        deriv[~np.isfinite(deriv)] = 0.0
+        return SignalObj(
+            self.time,
+            deriv,
+            f"d/dt({self.name})",
+            self.xlabelval,
+            self.xunits,
+            self.yunits,
+            [f"d_{lbl}" for lbl in self.dataLabels],
+        )
+
+    def plot(self, *_, **__) -> None:
+        # Intentionally lightweight: plotting is handled in examples where needed.
+        return None
+
+
+class Covariate(SignalObj):
+    """MATLAB-compatible alias for SignalObj.
+
+    Accepts both MATLAB-style positional arguments and Pythonic keywords:
+    `Covariate(time=t, values=x, name='stim', units='a.u.')`.
+    """
+
+    def __init__(self, *args, **kwargs) -> None:
+        if "values" in kwargs and "data" not in kwargs:
+            kwargs["data"] = kwargs.pop("values")
+        if "units" in kwargs and "yunits" not in kwargs:
+            kwargs["yunits"] = kwargs.pop("units")
+        super().__init__(*args, **kwargs)
+
+
+@dataclass
+class nspikeTrain:
+    """Python approximation of MATLAB nspikeTrain."""
+
+    spikeTimes: np.ndarray
+    name: str = ""
+    binwidth: float = 0.001
+    minTime: float | None = None
+    maxTime: float | None = None
+
+    def __post_init__(self) -> None:
+        spikes = np.asarray(self.spikeTimes, dtype=float).reshape(-1)
+        spikes = np.sort(spikes)
+        self.spikeTimes = spikes
+
+        if self.minTime is None:
+            self.minTime = float(spikes[0]) if spikes.size else 0.0
+        if self.maxTime is None:
+            self.maxTime = float(spikes[-1]) if spikes.size else self.minTime
+
+        self.minTime = float(self.minTime)
+        self.maxTime = float(self.maxTime)
+        self.sampleRate = float(1.0 / self.binwidth)
+
+    @property
+    def times(self) -> np.ndarray:
+        return self.spikeTimes
+
+    @property
+    def n_spikes(self) -> int:
+        return int(self.spikeTimes.shape[0])
+
+    @property
+    def duration(self) -> float:
+        return float(self.maxTime - self.minTime)
+
+    @property
+    def firing_rate_hz(self) -> float:
+        d = self.duration
+        if d <= 0:
+            return 0.0
+        return float(self.n_spikes / d)
+
+    def setName(self, name: str) -> None:
+        self.name = str(name)
+
+    def setMinTime(self, value: float) -> None:
+        self.minTime = float(value)
+
+    def setMaxTime(self, value: float) -> None:
+        self.maxTime = float(value)
+
+    def getISIs(self) -> np.ndarray:
+        if self.n_spikes < 2:
+            return np.array([], dtype=float)
+        return np.diff(self.spikeTimes)
+
+    def getSigRep(
+        self,
+        binwidth: float | None = None,
+        minTime: float | None = None,
+        maxTime: float | None = None,
+    ) -> SignalObj:
+        bw = self.binwidth if binwidth is None else float(binwidth)
+        t0 = self.minTime if minTime is None else float(minTime)
+        t1 = self.maxTime if maxTime is None else float(maxTime)
+        if bw <= 0:
+            raise ValueError("binwidth must be > 0")
+        if t1 < t0:
+            raise ValueError("maxTime must be >= minTime")
+
+        edges = np.arange(t0, t1 + 1.5 * bw, bw)
+        if edges.shape[0] < 2:
+            edges = np.array([t0, t0 + bw], dtype=float)
+        counts, _ = np.histogram(self.spikeTimes, bins=edges)
+        centers = edges[:-1] + 0.5 * bw
+        return SignalObj(centers, counts.astype(float), self.name or "spikes", "time", "s", "count", ["counts"])
+
+    def to_binned_counts(self, bin_edges: Sequence[float]) -> np.ndarray:
+        edges = np.asarray(bin_edges, dtype=float).reshape(-1)
+        counts, _ = np.histogram(self.spikeTimes, bins=edges)
+        return counts.astype(float)
+
+
+# Backward-compatible alias used by earlier Python scaffolding.
+SpikeTrain = nspikeTrain
diff --git a/nstat/data/__init__.py b/nstat/data/__init__.py
new file mode 100644
index 00000000..aade6388
--- /dev/null
+++ b/nstat/data/__init__.py
@@ -0,0 +1 @@
+"""Package data used by nSTAT runtime helpers."""
diff --git a/nstat/data/manifest.json b/nstat/data/manifest.json
new file mode 100644
index 00000000..0f24741a
--- /dev/null
+++ b/nstat/data/manifest.json
@@ -0,0 +1,33 @@
+{
+  "datasets": {
+    "mepcs_epsc2": {
+      "path": "data/mEPSCs/epsc2.txt",
+      "sha256": "65a130b7af4bc34eeaf943da76df6ebf9ba0ae9720eb98b6813f9f44a43ff435"
+    },
+    "mepcs_washout1": {
+      "path": "data/mEPSCs/washout1.txt",
+      "sha256": "4791531b54dd3f98c8cf756bd253d61d09113338b0dbe98ed09ef2df2d18e00e"
+    },
+    "mepcs_washout2": {
+      "path": "data/mEPSCs/washout2.txt",
+      "sha256": "ab35f26d4bccc48d2dc91e5007ba64d2527891666d2653e0a6118e397a4985fa"
+    },
+    "explicit_stimulus_dir3_neuron1_stim2_train": {
+      "path": "data/Explicit Stimulus/Dir3/Neuron1/Stim2/trngdataBis.mat",
+      "sha256": "f4b4299a1e977db37bab8a11d107b6d2a73541d3e5bb017ab68b1d9885def3f2"
+    },
+    "ssglm_example": {
+      "path": "data/SSGLMExampleData.mat",
+      "sha256": "fc1d4730267b49e3af534f6572b28ce1ba746708a49a1e4f1e8fb082cdabc360"
+    },
+    "place_cell_animal1": {
+      "path": "data/Place Cells/PlaceCellDataAnimal1.mat",
+      "sha256": "8806ab38c62a04ee1bec9cabab907a8f9fa3d66e0799fa09de8acd01789fc77b"
+    },
+    "hybrid_filter_example": {
+      "path": "helpfiles/paperHybridFilterExample.mat",
+      "sha256": "0a9941cc9cf564f1aaffdcd6dac766ada1f514926b610949bf0545c1b1bf401d"
+    }
+  },
+  "notes": "Core offline datasets required by canonical paper/help workflows."
+}
\ No newline at end of file
diff --git a/nstat/datasets.py b/nstat/datasets.py
new file mode 100644
index 00000000..f4dfd138
--- /dev/null
+++ b/nstat/datasets.py
@@ -0,0 +1,65 @@
+from __future__ import annotations
+
+import hashlib
+import json
+from pathlib import Path
+
+from .errors import DataNotFoundError
+
+MANIFEST_PATH = Path(__file__).resolve().parent / "data" / "manifest.json"
+
+
+def _repo_root() -> Path:
+    cur = Path(__file__).resolve()
+    for candidate in [cur, *cur.parents]:
+        if (candidate / "data").exists() and (candidate / "nstat" / "data" / "manifest.json").exists():
+            return candidate
+    raise RuntimeError("Could not locate nSTAT repository root from installed package path.")
+
+
+def _load_manifest() -> dict[str, dict[str, str]]:
+    if not MANIFEST_PATH.exists():
+        raise DataNotFoundError(f"Dataset manifest not found: {MANIFEST_PATH}")
+    payload = json.loads(MANIFEST_PATH.read_text(encoding="utf-8"))
+    entries = payload.get("datasets", {})
+    if not isinstance(entries, dict):
+        raise ValueError("Invalid dataset manifest format; 'datasets' must be a mapping")
+    return entries
+
+
+def _sha256(path: Path) -> str:
+    h = hashlib.sha256()
+    with path.open("rb") as f:
+        for chunk in iter(lambda: f.read(1024 * 1024), b""):
+            h.update(chunk)
+    return h.hexdigest()
+
+
+def list_datasets() -> list[str]:
+    return sorted(_load_manifest().keys())
+
+
+def get_dataset_path(name: str) -> Path:
+    entries = _load_manifest()
+    if name not in entries:
+        raise DataNotFoundError(f"Unknown dataset '{name}'. Available: {', '.join(sorted(entries))}")
+
+    rel = entries[name]["path"]
+    path = _repo_root() / rel
+    if not path.exists():
+        raise DataNotFoundError(f"Dataset '{name}' not found at expected path: {path}")
+    return path
+
+
+def verify_checksums() -> dict[str, bool]:
+    entries = _load_manifest()
+    root = _repo_root()
+    result: dict[str, bool] = {}
+    for name, item in entries.items():
+        path = root / item["path"]
+        expected = item.get("sha256", "")
+        if not path.exists() or not expected:
+            result[name] = False
+            continue
+        result[name] = _sha256(path) == expected
+    return result
diff --git a/nstat/decoding.py b/nstat/decoding.py
new file mode 100644
index 00000000..07ee86d3
--- /dev/null
+++ b/nstat/decoding.py
@@ -0,0 +1,58 @@
+from __future__ import annotations
+
+import numpy as np
+
+from .decoding_algorithms import DecodingAlgorithms
+
+
+class DecoderSuite:
+    """Canonical decoding API for the Python nSTAT package."""
+
+    @staticmethod
+    def linear(spike_counts: np.ndarray, stimulus: np.ndarray) -> dict[str, np.ndarray]:
+        return DecodingAlgorithms.linear_decode(spike_counts, stimulus)
+
+    @staticmethod
+    def kalman(
+        observations: np.ndarray,
+        transition: np.ndarray,
+        observation_matrix: np.ndarray,
+        q_cov: np.ndarray,
+        r_cov: np.ndarray,
+        x0: np.ndarray,
+        p0: np.ndarray,
+    ) -> dict[str, np.ndarray]:
+        """Basic linear Kalman filter used for standalone decoding workflows."""
+        y = np.asarray(observations, dtype=float)
+        a = np.asarray(transition, dtype=float)
+        h = np.asarray(observation_matrix, dtype=float)
+        q = np.asarray(q_cov, dtype=float)
+        r = np.asarray(r_cov, dtype=float)
+        x_prev = np.asarray(x0, dtype=float).reshape(-1)
+        p_prev = np.asarray(p0, dtype=float)
+
+        n_t = y.shape[0]
+        n_x = x_prev.shape[0]
+        xs = np.zeros((n_t, n_x), dtype=float)
+        ps = np.zeros((n_t, n_x, n_x), dtype=float)
+
+        for t in range(n_t):
+            x_pred = a @ x_prev
+            p_pred = a @ p_prev @ a.T + q
+
+            innovation = y[t] - h @ x_pred
+            s_cov = h @ p_pred @ h.T + r
+            k_gain = p_pred @ h.T @ np.linalg.pinv(s_cov)
+
+            x_post = x_pred + k_gain @ innovation
+            p_post = (np.eye(n_x) - k_gain @ h) @ p_pred
+
+            xs[t] = x_post
+            ps[t] = p_post
+            x_prev = x_post
+            p_prev = p_post
+
+        return {"state": xs, "cov": ps}
+
+
+__all__ = ["DecoderSuite"]
diff --git a/nstat/decoding_algorithms.py b/nstat/decoding_algorithms.py
new file mode 100644
index 00000000..f302ce21
--- /dev/null
+++ b/nstat/decoding_algorithms.py
@@ -0,0 +1,70 @@
+from __future__ import annotations
+
+import numpy as np
+
+
+class DecodingAlgorithms:
+    @staticmethod
+    def linear_decode(spike_counts: np.ndarray, stimulus: np.ndarray) -> dict[str, np.ndarray]:
+        x = np.asarray(spike_counts, dtype=float)
+        y = np.asarray(stimulus, dtype=float).reshape(-1)
+        if x.ndim == 1:
+            x = x[:, None]
+        if x.shape[0] != y.shape[0]:
+            raise ValueError("spike_counts and stimulus must align")
+
+        x_aug = np.column_stack([np.ones(x.shape[0]), x])
+        beta, *_ = np.linalg.lstsq(x_aug, y, rcond=None)
+        y_hat = x_aug @ beta
+        resid = y - y_hat
+        sigma = float(np.std(resid))
+        ci = np.column_stack([y_hat - 1.96 * sigma, y_hat + 1.96 * sigma])
+        return {"coefficients": beta, "decoded": y_hat, "residual": resid, "ci": ci}
+
+    @staticmethod
+    def kalman_filter(
+        observations: np.ndarray,
+        transition: np.ndarray,
+        observation_matrix: np.ndarray,
+        q_cov: np.ndarray,
+        r_cov: np.ndarray,
+        x0: np.ndarray,
+        p0: np.ndarray,
+    ) -> dict[str, np.ndarray]:
+        y = np.asarray(observations, dtype=float)
+        a = np.asarray(transition, dtype=float)
+        h = np.asarray(observation_matrix, dtype=float)
+        q = np.asarray(q_cov, dtype=float)
+        r = np.asarray(r_cov, dtype=float)
+        x_prev = np.asarray(x0, dtype=float).reshape(-1)
+        p_prev = np.asarray(p0, dtype=float)
+
+        n_t = y.shape[0]
+        n_x = x_prev.shape[0]
+        xs = np.zeros((n_t, n_x), dtype=float)
+        ps = np.zeros((n_t, n_x, n_x), dtype=float)
+
+        for t in range(n_t):
+            x_pred = a @ x_prev
+            p_pred = a @ p_prev @ a.T + q
+
+            innovation = y[t] - h @ x_pred
+            s_cov = h @ p_pred @ h.T + r
+            k_gain = p_pred @ h.T @ np.linalg.pinv(s_cov)
+
+            x_post = x_pred + k_gain @ innovation
+            p_post = (np.eye(n_x) - k_gain @ h) @ p_pred
+
+            xs[t] = x_post
+            ps[t] = p_post
+            x_prev = x_post
+            p_prev = p_post
+
+        return {"state": xs, "cov": ps}
+
+    # MATLAB-style API aliases.
+    PPDecodeFilterLinear = kalman_filter
+    PPDecodeFilter = kalman_filter
+
+
+__all__ = ["DecodingAlgorithms"]
diff --git a/nstat/errors.py b/nstat/errors.py
new file mode 100644
index 00000000..4ada5867
--- /dev/null
+++ b/nstat/errors.py
@@ -0,0 +1,17 @@
+from __future__ import annotations
+
+
+class NSTATError(Exception):
+    """Base exception type for the Python nSTAT package."""
+
+
+class DataNotFoundError(NSTATError, FileNotFoundError):
+    """Raised when a required dataset is missing from the local checkout."""
+
+
+class ParityValidationError(NSTATError):
+    """Raised when MATLAB/Python parity validation fails."""
+
+
+class UnsupportedWorkflowError(NSTATError, NotImplementedError):
+    """Raised when a legacy workflow has not yet been ported."""
diff --git a/nstat/events.py b/nstat/events.py
new file mode 100644
index 00000000..969b99a0
--- /dev/null
+++ b/nstat/events.py
@@ -0,0 +1,32 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any
+
+import numpy as np
+
+
+@dataclass
+class Events:
+    event_times: np.ndarray
+    labels: list[str] | None = None
+
+    def __init__(self, event_times, labels=None) -> None:
+        self.event_times = np.asarray(event_times, dtype=float).reshape(-1)
+        self.labels = None if labels is None else list(labels)
+
+    def toStructure(self) -> dict[str, Any]:
+        return {
+            "event_times": self.event_times.tolist(),
+            "labels": list(self.labels) if self.labels is not None else None,
+        }
+
+    @staticmethod
+    def fromStructure(structure: dict[str, Any]) -> "Events":
+        return Events(structure.get("event_times", []), labels=structure.get("labels"))
+
+    def plot(self, *_, **__) -> None:
+        return None
+
+
+__all__ = ["Events"]
diff --git a/nstat/fit.py b/nstat/fit.py
new file mode 100644
index 00000000..ad6021b4
--- /dev/null
+++ b/nstat/fit.py
@@ -0,0 +1,211 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any, Iterable
+
+import numpy as np
+
+from .core import nspikeTrain
+from .signal import Covariate
+
+
+@dataclass
+class _SingleFit:
+    name: str
+    coefficients: np.ndarray
+    intercept: float
+    log_likelihood: float
+    aic: float
+    bic: float
+
+
+class FitResult:
+    """Simplified Python FitResult compatible with nSTAT workflows."""
+
+    def __init__(
+        self,
+        neuralSpikeTrain: nspikeTrain,
+        lambda_signal: Covariate,
+        fits: list[_SingleFit],
+    ) -> None:
+        self.neuralSpikeTrain = neuralSpikeTrain
+        self.lambda_signal = lambda_signal
+        self.fits = fits
+        self.numResults = len(fits)
+        self.AIC = np.asarray([f.aic for f in fits], dtype=float)
+        self.BIC = np.asarray([f.bic for f in fits], dtype=float)
+        self.logLL = np.asarray([f.log_likelihood for f in fits], dtype=float)
+        self.KSStats = np.zeros((self.numResults, 1), dtype=float)
+        self.configNames = [f.name for f in fits]
+        self.lambda_ = lambda_signal
+
+    @property
+    def lambdaSignal(self) -> Covariate:
+        return self.lambda_signal
+
+    @property
+    def lambda_sig(self) -> Covariate:
+        return self.lambda_signal
+
+    @property
+    def lambdaCov(self) -> Covariate:
+        return self.lambda_signal
+
+    @property
+    def lambdaObj(self) -> Covariate:
+        return self.lambda_signal
+
+    @property
+    def lambda_data(self) -> np.ndarray:
+        return self.lambda_signal.data
+
+    @property
+    def lambda_values(self) -> np.ndarray:
+        return self.lambda_signal.data
+
+    @property
+    def lambda_time(self) -> np.ndarray:
+        return self.lambda_signal.time
+
+    @property
+    def lambda_rate(self) -> np.ndarray:
+        return self.lambda_signal.data
+
+    @property
+    def lambda_model(self) -> Covariate:
+        return self.lambda_signal
+
+    @property
+    def lambda_result(self) -> Covariate:
+        return self.lambda_signal
+
+    @property
+    def lambda_(self) -> Covariate:
+        return self.lambda_signal
+
+    @lambda_.setter
+    def lambda_(self, value: Covariate) -> None:
+        self.lambda_signal = value
+
+    def getCoeffs(self, fit_num: int = 1) -> np.ndarray:
+        return self.fits[fit_num - 1].coefficients.copy()
+
+    def getHistCoeffs(self, fit_num: int = 1) -> np.ndarray:
+        return np.array([], dtype=float)
+
+    def mergeResults(self, other: "FitResult") -> "FitResult":
+        merged_fits = [*self.fits, *other.fits]
+        merged_lambda = self.lambda_signal.merge(other.lambda_signal)
+        out = FitResult(self.neuralSpikeTrain, merged_lambda, merged_fits)
+        return out
+
+    def plotResults(self, *_, **__) -> None:
+        return None
+
+    def KSPlot(self, *_, **__) -> None:
+        return None
+
+    def plotResidual(self, *_, **__) -> None:
+        return None
+
+    def plotInvGausTrans(self, *_, **__) -> None:
+        return None
+
+    def plotSeqCorr(self, *_, **__) -> None:
+        return None
+
+    def plotCoeffs(self, *_, **__) -> None:
+        return None
+
+    @property
+    def lambda_obj(self) -> Covariate:
+        return self.lambda_signal
+
+    def toStructure(self) -> dict[str, Any]:
+        return {
+            "fits": [
+                {
+                    "name": f.name,
+                    "coefficients": f.coefficients.tolist(),
+                    "intercept": f.intercept,
+                    "log_likelihood": f.log_likelihood,
+                    "aic": f.aic,
+                    "bic": f.bic,
+                }
+                for f in self.fits
+            ],
+            "lambda_time": self.lambda_signal.time.tolist(),
+            "lambda_data": self.lambda_signal.data.tolist(),
+            "neural_spike_times": self.neuralSpikeTrain.spikeTimes.tolist(),
+            "neural_name": self.neuralSpikeTrain.name,
+            "neural_min_time": self.neuralSpikeTrain.minTime,
+            "neural_max_time": self.neuralSpikeTrain.maxTime,
+        }
+
+    @staticmethod
+    def fromStructure(structure: dict[str, Any]) -> "FitResult":
+        train = nspikeTrain(
+            structure["neural_spike_times"],
+            name=structure.get("neural_name", ""),
+            minTime=structure.get("neural_min_time"),
+            maxTime=structure.get("neural_max_time"),
+        )
+        lam = Covariate(
+            structure["lambda_time"],
+            np.asarray(structure["lambda_data"], dtype=float),
+            "lambda",
+            "time",
+            "s",
+            "spikes/sec",
+        )
+        fits = []
+        for f in structure["fits"]:
+            fits.append(
+                _SingleFit(
+                    name=f["name"],
+                    coefficients=np.asarray(f["coefficients"], dtype=float),
+                    intercept=float(f["intercept"]),
+                    log_likelihood=float(f["log_likelihood"]),
+                    aic=float(f["aic"]),
+                    bic=float(f["bic"]),
+                )
+            )
+        return FitResult(train, lam, fits)
+
+
+class FitSummary:
+    """Cross-fit summary statistics for one or more FitResult objects."""
+
+    def __init__(self, fit_results: FitResult | Iterable[FitResult]) -> None:
+        if isinstance(fit_results, FitResult):
+            self.fit_results = [fit_results]
+        else:
+            self.fit_results = list(fit_results)
+            if not self.fit_results:
+                raise ValueError("FitSummary requires at least one FitResult")
+
+        aic = np.vstack([fr.AIC for fr in self.fit_results])
+        bic = np.vstack([fr.BIC for fr in self.fit_results])
+        ks = np.vstack([fr.KSStats.reshape(1, -1) for fr in self.fit_results])
+        self.AIC = np.mean(aic, axis=0)
+        self.BIC = np.mean(bic, axis=0)
+        self.KSStats = np.column_stack([np.mean(ks, axis=0), np.std(ks, axis=0)])
+        self.numNeurons = len(self.fit_results)
+
+    def getDiffAIC(self, idx: int = 1) -> np.ndarray:
+        base = self.AIC[idx - 1]
+        return self.AIC - base
+
+    def getDiffBIC(self, idx: int = 1) -> np.ndarray:
+        base = self.BIC[idx - 1]
+        return self.BIC - base
+
+    def plotSummary(self, *_, **__) -> None:
+        return None
+
+
+class FitResSummary(FitSummary):
+    """MATLAB-compatible alias for FitSummary."""
+
+
+__all__ = ["FitResult", "FitSummary", "FitResSummary", "_SingleFit"]
diff --git a/python/nstat/glm.py b/nstat/glm.py
similarity index 64%
rename from python/nstat/glm.py
rename to nstat/glm.py
index 6af77f28..560521dd 100644
--- a/python/nstat/glm.py
+++ b/nstat/glm.py
@@ -15,53 +15,46 @@ class PoissonGLMResult:
     log_likelihood: float
 
     def predict_rate(
-        self, x: Sequence[Sequence[float]], offset: Sequence[float] | None = None
+        self, x: Sequence[Sequence[float]] | Sequence[float] | np.ndarray, offset: Sequence[float] | np.ndarray | None = None
     ) -> np.ndarray:
         x_arr = np.asarray(x, dtype=float)
         if x_arr.ndim == 1:
             x_arr = x_arr[:, None]
         eta = self.intercept + x_arr @ self.coefficients
         if offset is not None:
-            offset_arr = np.asarray(offset, dtype=float).reshape(-1)
-            if offset_arr.shape[0] != x_arr.shape[0]:
-                raise ValueError("offset must match the number of rows in x.")
-            eta = eta + offset_arr
+            eta = eta + np.asarray(offset, dtype=float).reshape(-1)
         return np.exp(np.clip(eta, -20.0, 20.0))
 
 
 def fit_poisson_glm(
-    x: Sequence[Sequence[float]] | Sequence[float],
-    y: Sequence[float],
+    x: Sequence[Sequence[float]] | Sequence[float] | np.ndarray,
+    y: Sequence[float] | np.ndarray,
     *,
-    offset: Sequence[float] | None = None,
+    offset: Sequence[float] | np.ndarray | None = None,
     l2: float = 1e-6,
-    max_iter: int = 100,
+    max_iter: int = 120,
     tol: float = 1e-8,
 ) -> PoissonGLMResult:
-    """Fit a Poisson GLM with a log link using Newton updates."""
-
     x_arr = np.asarray(x, dtype=float)
     y_arr = np.asarray(y, dtype=float).reshape(-1)
-
     if x_arr.ndim == 1:
         x_arr = x_arr[:, None]
     if x_arr.shape[0] != y_arr.shape[0]:
-        raise ValueError("x and y must have the same number of rows.")
-    if np.any(y_arr < 0):
-        raise ValueError("y must be non-negative counts.")
+        raise ValueError("x and y must have same row count")
+
     if offset is None:
-        offset_arr = np.zeros_like(y_arr, dtype=float)
+        offset_arr = np.zeros_like(y_arr)
     else:
         offset_arr = np.asarray(offset, dtype=float).reshape(-1)
         if offset_arr.shape[0] != y_arr.shape[0]:
-            raise ValueError("offset must have the same number of rows as y.")
+            raise ValueError("offset size mismatch")
 
     n_samples, n_features = x_arr.shape
     x_aug = np.column_stack([np.ones(n_samples), x_arr])
     beta = np.zeros(n_features + 1, dtype=float)
 
-    eye = np.eye(n_features + 1, dtype=float)
-    eye[0, 0] = 0.0  # do not regularize intercept
+    eye = np.eye(n_features + 1)
+    eye[0, 0] = 0.0
 
     converged = False
     n_iter = 0
@@ -70,12 +63,11 @@ def fit_poisson_glm(
         lam = np.exp(np.clip(eta, -20.0, 20.0))
 
         grad = x_aug.T @ (y_arr - lam) - l2 * (eye @ beta)
-        hessian_pos = x_aug.T @ (lam[:, None] * x_aug) + l2 * eye
-
+        hess_pos = x_aug.T @ (lam[:, None] * x_aug) + l2 * eye
         try:
-            step = np.linalg.solve(hessian_pos, grad)
+            step = np.linalg.solve(hess_pos, grad)
         except np.linalg.LinAlgError:
-            step = np.linalg.lstsq(hessian_pos, grad, rcond=None)[0]
+            step = np.linalg.lstsq(hess_pos, grad, rcond=None)[0]
 
         beta_next = beta + step
         if np.linalg.norm(beta_next - beta, ord=2) < tol:
diff --git a/nstat/history.py b/nstat/history.py
new file mode 100644
index 00000000..efdb575b
--- /dev/null
+++ b/nstat/history.py
@@ -0,0 +1,49 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import numpy as np
+
+from .signal import Covariate
+
+
+@dataclass
+class HistoryBasis:
+    """Spike-history basis using lagged spike-count regressors."""
+
+    lags: np.ndarray
+    name: str = "History"
+
+    def __init__(self, lags, name: str = "History") -> None:
+        arr = np.asarray(lags, dtype=int).reshape(-1)
+        if arr.size == 0:
+            raise ValueError("lags must be non-empty")
+        if np.any(arr <= 0):
+            raise ValueError("lags must be strictly positive")
+        self.lags = np.unique(arr)
+        self.name = name
+
+    def design_matrix(self, spike_indicator: np.ndarray) -> np.ndarray:
+        y = np.asarray(spike_indicator, dtype=float).reshape(-1)
+        x = np.zeros((y.shape[0], self.lags.shape[0]), dtype=float)
+        for j, lag in enumerate(self.lags):
+            x[lag:, j] = y[:-lag]
+        return x
+
+    def compute_history(self, spike_indicator: np.ndarray, time: np.ndarray) -> Covariate:
+        x = self.design_matrix(spike_indicator)
+        labels = [f"hist_lag_{int(l)}" for l in self.lags]
+        return Covariate(time, x, self.name, "time", "s", "count", labels)
+
+    # MATLAB-compatible method names.
+    def computeHistory(self, nst) -> Covariate:
+        y = np.asarray(getattr(nst, "getSigRep")().data[:, 0], dtype=float)
+        t = np.asarray(getattr(nst, "getSigRep")().time, dtype=float)
+        return self.compute_history(y, t)
+
+
+# Backward-compatible alias.
+History = HistoryBasis
+
+
+__all__ = ["HistoryBasis", "History"]
diff --git a/nstat/nspikeTrain.py b/nstat/nspikeTrain.py
new file mode 100644
index 00000000..f6e54d8a
--- /dev/null
+++ b/nstat/nspikeTrain.py
@@ -0,0 +1,13 @@
+from __future__ import annotations
+
+from ._compat import warn_deprecated_adapter
+from .spikes import SpikeTrain
+
+
+class nspikeTrain(SpikeTrain):
+    def __init__(self, *args, **kwargs) -> None:
+        warn_deprecated_adapter("nstat.nspikeTrain.nspikeTrain", "nstat.spikes.SpikeTrain")
+        super().__init__(*args, **kwargs)
+
+
+__all__ = ["nspikeTrain"]
diff --git a/nstat/nstColl.py b/nstat/nstColl.py
new file mode 100644
index 00000000..1e1cb96a
--- /dev/null
+++ b/nstat/nstColl.py
@@ -0,0 +1,13 @@
+from __future__ import annotations
+
+from ._compat import warn_deprecated_adapter
+from .spikes import SpikeTrainCollection
+
+
+class nstColl(SpikeTrainCollection):
+    def __init__(self, *args, **kwargs) -> None:
+        warn_deprecated_adapter("nstat.nstColl.nstColl", "nstat.spikes.SpikeTrainCollection")
+        super().__init__(*args, **kwargs)
+
+
+__all__ = ["nstColl"]
diff --git a/nstat/nstat_install.py b/nstat/nstat_install.py
new file mode 100644
index 00000000..d34dd7b6
--- /dev/null
+++ b/nstat/nstat_install.py
@@ -0,0 +1,8 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+
+def nSTAT_Install() -> Path:
+    """Return Python package root path (MATLAB nSTAT_Install analogue)."""
+    return Path(__file__).resolve().parents[1]
diff --git a/nstat/paper_examples.py b/nstat/paper_examples.py
new file mode 100644
index 00000000..7c213d22
--- /dev/null
+++ b/nstat/paper_examples.py
@@ -0,0 +1,464 @@
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+from scipy.io import loadmat
+
+from .analysis import psth
+from .decoding_algorithms import DecodingAlgorithms
+from .glm import fit_poisson_glm
+from .simulation import simulate_poisson_from_rate
+
+
+Summary = dict[str, float]
+Payload = dict[str, Any]
+Results = dict[str, Summary]
+PlotPayloads = dict[str, Payload]
+
+
+def _default_repo_root() -> Path:
+    cur = Path(__file__).resolve()
+    for candidate in [cur, *cur.parents]:
+        if (candidate / "nstat").exists() and (candidate / "data").exists():
+            return candidate
+    return cur.parents[1]
+
+
+def _aic_bic(log_likelihood: float, n_obs: int, n_params: int) -> tuple[float, float]:
+    aic = 2.0 * n_params - 2.0 * log_likelihood
+    bic = np.log(max(n_obs, 1)) * n_params - 2.0 * log_likelihood
+    return float(aic), float(bic)
+
+
+def _history_matrix(y: np.ndarray, lags: tuple[int, ...]) -> np.ndarray:
+    x = np.zeros((y.shape[0], len(lags)), dtype=float)
+    for j, lag in enumerate(lags):
+        x[lag:, j] = y[:-lag]
+    return x
+
+
+def _bin_mean(values: np.ndarray, samples_per_bin: int) -> np.ndarray:
+    n_bins = values.shape[0] // samples_per_bin
+    if n_bins < 1:
+        return np.asarray([], dtype=float)
+    trimmed = values[: n_bins * samples_per_bin]
+    return trimmed.reshape(n_bins, samples_per_bin).mean(axis=1)
+
+
+def _bin_sum(values: np.ndarray, samples_per_bin: int) -> np.ndarray:
+    n_bins = values.shape[0] // samples_per_bin
+    if n_bins < 1:
+        return np.asarray([], dtype=float)
+    trimmed = values[: n_bins * samples_per_bin]
+    return trimmed.reshape(n_bins, samples_per_bin).sum(axis=1)
+
+
+def run_experiment2(data_dir: Path, *, return_payload: bool = False) -> Summary | tuple[Summary, Payload]:
+    mat_path = data_dir / "Explicit Stimulus" / "Dir3" / "Neuron1" / "Stim2" / "trngdataBis.mat"
+    d = loadmat(mat_path, squeeze_me=True, struct_as_record=False)
+
+    stim_raw = np.asarray(d["t"], dtype=float).reshape(-1)
+    y = np.asarray(d["y"], dtype=float).reshape(-1)
+
+    dt = 0.001
+    stim = stim_raw / 10.0
+    stim_vel = np.gradient(stim, dt)
+    hist = _history_matrix(y, lags=(1, 2, 3, 4, 5))
+
+    x1 = np.zeros((y.shape[0], 0), dtype=float)
+    x2 = np.column_stack([stim, stim_vel])
+    x3 = np.column_stack([stim, stim_vel, hist])
+    offset = np.full(y.shape[0], np.log(dt), dtype=float)
+
+    m1 = fit_poisson_glm(x1, y, offset=offset)
+    m2 = fit_poisson_glm(x2, y, offset=offset)
+    m3 = fit_poisson_glm(x3, y, offset=offset)
+
+    aic1, bic1 = _aic_bic(m1.log_likelihood, y.shape[0], 1)
+    aic2, bic2 = _aic_bic(m2.log_likelihood, y.shape[0], 3)
+    aic3, bic3 = _aic_bic(m3.log_likelihood, y.shape[0], 8)
+
+    summary: Summary = {
+        "n_samples": float(y.shape[0]),
+        "model1_aic": aic1,
+        "model2_aic": aic2,
+        "model3_aic": aic3,
+        "model1_bic": bic1,
+        "model2_bic": bic2,
+        "model3_bic": bic3,
+    }
+    if not return_payload:
+        return summary
+
+    rate1_hz = m1.predict_rate(x1, offset=offset)
+    rate2_hz = m2.predict_rate(x2, offset=offset)
+    rate3_hz = m3.predict_rate(x3, offset=offset)
+
+    samples_per_bin = 50  # 50 ms bins.
+    t_binned = np.arange(y.shape[0] // samples_per_bin, dtype=float) * dt * samples_per_bin
+    obs_rate_hz = _bin_sum(y, samples_per_bin) / (dt * samples_per_bin)
+    stim_binned = _bin_mean(stim, samples_per_bin)
+    rate1_binned_hz = _bin_mean(rate1_hz, samples_per_bin)
+    rate2_binned_hz = _bin_mean(rate2_hz, samples_per_bin)
+    rate3_binned_hz = _bin_mean(rate3_hz, samples_per_bin)
+
+    payload: Payload = {
+        "time_binned_s": t_binned,
+        "stimulus_binned": stim_binned,
+        "obs_rate_hz": obs_rate_hz,
+        "rate1_binned_hz": rate1_binned_hz,
+        "rate2_binned_hz": rate2_binned_hz,
+        "rate3_binned_hz": rate3_binned_hz,
+        "aic": np.asarray([aic1, aic2, aic3], dtype=float),
+        "bic": np.asarray([bic1, bic2, bic3], dtype=float),
+    }
+    return summary, payload
+
+
+def run_experiment3(seed: int = 7, *, return_payload: bool = False) -> Summary | tuple[Summary, Payload]:
+    rng = np.random.default_rng(seed)
+    dt = 0.001
+    tmax = 1.0
+    time = np.arange(0.0, tmax + dt, dt)
+
+    f = 2.0
+    mu = -3.0
+    linear = np.sin(2.0 * np.pi * f * time) + mu
+    p = np.exp(linear)
+    p = p / (1.0 + p)
+    rate_hz = p / dt
+
+    trains = [simulate_poisson_from_rate(time, rate_hz, rng=rng) for _ in range(20)]
+    bin_edges = np.arange(0.0, tmax + 0.05, 0.05)
+    psth_rate_hz, counts = psth(trains, bin_edges)
+
+    summary: Summary = {
+        "num_trials": float(len(trains)),
+        "psth_peak_hz": float(np.max(psth_rate_hz)),
+        "psth_mean_hz": float(np.mean(psth_rate_hz)),
+        "total_spikes": float(np.sum(counts)),
+    }
+    if not return_payload:
+        return summary
+
+    payload: Payload = {
+        "time_s": time,
+        "true_rate_hz": rate_hz,
+        "psth_bin_centers_s": 0.5 * (bin_edges[:-1] + bin_edges[1:]),
+        "psth_rate_hz": psth_rate_hz,
+        "raster_spike_times": [np.asarray(train.spikeTimes, dtype=float) for train in trains],
+    }
+    return summary, payload
+
+
+def _spike_indicator_from_times(time: np.ndarray, spike_times: np.ndarray) -> np.ndarray:
+    y = np.zeros(time.shape[0], dtype=float)
+    idx = np.searchsorted(time, spike_times, side="left")
+    idx = idx[(idx >= 0) & (idx < time.shape[0])]
+    if idx.size:
+        y[idx] = 1.0
+    return y
+
+
+def _zernike_like_basis(x: np.ndarray, y: np.ndarray) -> np.ndarray:
+    theta = np.arctan2(y, x)
+    r = np.sqrt(x * x + y * y)
+    return np.column_stack(
+        [
+            np.ones_like(r),
+            r,
+            r**2,
+            np.cos(theta),
+            np.sin(theta),
+            r * np.cos(theta),
+            r * np.sin(theta),
+            r**2 * np.cos(2.0 * theta),
+            r**2 * np.sin(2.0 * theta),
+            r**3,
+        ]
+    )
+
+
+def run_experiment4(data_dir: Path, *, return_payload: bool = False) -> Summary | tuple[Summary, Payload]:
+    mat_path = data_dir / "Place Cells" / "PlaceCellDataAnimal1.mat"
+    d = loadmat(mat_path, squeeze_me=True, struct_as_record=False)
+
+    x = np.asarray(d["x"], dtype=float).reshape(-1)
+    y = np.asarray(d["y"], dtype=float).reshape(-1)
+    time = np.asarray(d["time"], dtype=float).reshape(-1)
+    neurons = np.asarray(d["neuron"], dtype=object).reshape(-1)
+
+    dt = float(np.median(np.diff(time)))
+    offset = np.full(time.shape[0], np.log(max(dt, 1e-12)), dtype=float)
+
+    x_gauss = np.column_stack([x, y, x * x, y * y, x * y])
+    x_zern = _zernike_like_basis(x, y)
+
+    n_eval = int(min(8, neurons.shape[0]))
+    delta_aic = []
+    delta_bic = []
+    for i in range(n_eval):
+        spike_times = np.asarray(neurons[i].spikeTimes, dtype=float).reshape(-1)
+        y_spike = _spike_indicator_from_times(time, spike_times)
+
+        m_g = fit_poisson_glm(x_gauss, y_spike, offset=offset)
+        m_z = fit_poisson_glm(x_zern, y_spike, offset=offset)
+
+        aic_g, bic_g = _aic_bic(m_g.log_likelihood, y_spike.shape[0], x_gauss.shape[1] + 1)
+        aic_z, bic_z = _aic_bic(m_z.log_likelihood, y_spike.shape[0], x_zern.shape[1] + 1)
+        delta_aic.append(aic_g - aic_z)
+        delta_bic.append(bic_g - bic_z)
+
+    summary: Summary = {
+        "num_cells_fit": float(n_eval),
+        "mean_delta_aic_gaussian_minus_zernike": float(np.mean(delta_aic)),
+        "mean_delta_bic_gaussian_minus_zernike": float(np.mean(delta_bic)),
+    }
+    if not return_payload:
+        return summary
+
+    first_cell_spikes = np.asarray(neurons[0].spikeTimes, dtype=float).reshape(-1)
+    payload: Payload = {
+        "time_s": time,
+        "x_pos": x,
+        "y_pos": y,
+        "first_cell_spike_times_s": first_cell_spikes,
+        "delta_aic": np.asarray(delta_aic, dtype=float),
+        "delta_bic": np.asarray(delta_bic, dtype=float),
+    }
+    return summary, payload
+
+
+def run_experiment5(seed: int = 11, *, return_payload: bool = False) -> Summary | tuple[Summary, Payload]:
+    rng = np.random.default_rng(seed)
+
+    dt = 0.001
+    time = np.arange(0.0, 1.0 + dt, dt)
+    stim = np.sin(2.0 * np.pi * 2.0 * time)
+
+    n_cells = 20
+    spikes = np.zeros((time.shape[0], n_cells), dtype=float)
+    for i in range(n_cells):
+        b1 = rng.normal(1.0, 0.5)
+        b0 = np.log(10.0 * dt) + rng.normal(0.0, 0.3)
+        eta = b1 * stim + b0
+        p = np.exp(eta)
+        p = p / (1.0 + p)
+        spikes[:, i] = (rng.random(time.shape[0]) < p).astype(float)
+
+    decoded = DecodingAlgorithms.linear_decode(spikes, stim)
+    rmse = float(np.sqrt(np.mean((decoded["decoded"] - stim) ** 2)))
+
+    summary: Summary = {
+        "num_cells": float(n_cells),
+        "decode_rmse": rmse,
+    }
+    if not return_payload:
+        return summary
+
+    payload: Payload = {
+        "time_s": time,
+        "stimulus": stim,
+        "decoded": np.asarray(decoded["decoded"], dtype=float),
+        "ci_low": np.asarray(decoded["ci"][:, 0], dtype=float),
+        "ci_high": np.asarray(decoded["ci"][:, 1], dtype=float),
+    }
+    return summary, payload
+
+
+def run_paper_examples(
+    repo_root: Path, *, return_plot_data: bool = False
+) -> Results | tuple[Results, PlotPayloads]:
+    data_dir = repo_root / "data"
+    if not data_dir.exists():
+        raise FileNotFoundError(f"Could not locate data directory: {data_dir}")
+
+    if not return_plot_data:
+        return {
+            "experiment2": run_experiment2(data_dir),  # type: ignore[arg-type]
+            "experiment3": run_experiment3(),
+            "experiment4": run_experiment4(data_dir),  # type: ignore[arg-type]
+            "experiment5": run_experiment5(),
+        }
+
+    exp2_summary, exp2_payload = run_experiment2(data_dir, return_payload=True)  # type: ignore[misc]
+    exp3_summary, exp3_payload = run_experiment3(return_payload=True)  # type: ignore[misc]
+    exp4_summary, exp4_payload = run_experiment4(data_dir, return_payload=True)  # type: ignore[misc]
+    exp5_summary, exp5_payload = run_experiment5(return_payload=True)  # type: ignore[misc]
+
+    results: Results = {
+        "experiment2": exp2_summary,
+        "experiment3": exp3_summary,
+        "experiment4": exp4_summary,
+        "experiment5": exp5_summary,
+    }
+    plot_payloads: PlotPayloads = {
+        "experiment2": exp2_payload,
+        "experiment3": exp3_payload,
+        "experiment4": exp4_payload,
+        "experiment5": exp5_payload,
+    }
+    return results, plot_payloads
+
+
+def _save_paper_example_plots(plot_payloads: PlotPayloads, plots_dir: Path) -> list[Path]:
+    import matplotlib
+
+    matplotlib.use("Agg")
+    import matplotlib.pyplot as plt
+
+    plots_dir.mkdir(parents=True, exist_ok=True)
+    saved_paths: list[Path] = []
+
+    # Experiment 2: explicit stimulus + model comparison.
+    e2 = plot_payloads["experiment2"]
+    fig, (ax_rate, ax_metrics) = plt.subplots(2, 1, figsize=(11, 8), constrained_layout=True)
+    ax_rate.plot(e2["time_binned_s"], e2["obs_rate_hz"], label="Observed spike rate", color="tab:blue", lw=1.5)
+    ax_rate.plot(e2["time_binned_s"], e2["rate1_binned_hz"], label="Model 1 rate", color="tab:orange", lw=1.2)
+    ax_rate.plot(e2["time_binned_s"], e2["rate2_binned_hz"], label="Model 2 rate", color="tab:green", lw=1.2)
+    ax_rate.plot(e2["time_binned_s"], e2["rate3_binned_hz"], label="Model 3 rate", color="tab:red", lw=1.2)
+    ax_rate.set_title("Experiment 2: Stimulus and GLM Rate Fits")
+    ax_rate.set_xlabel("Time (s)")
+    ax_rate.set_ylabel("Rate (Hz)")
+    ax_rate.grid(alpha=0.3)
+
+    ax_stim = ax_rate.twinx()
+    ax_stim.plot(e2["time_binned_s"], e2["stimulus_binned"], color="black", alpha=0.25, lw=1.0, label="Stimulus")
+    ax_stim.set_ylabel("Stimulus (a.u.)")
+
+    handles1, labels1 = ax_rate.get_legend_handles_labels()
+    handles2, labels2 = ax_stim.get_legend_handles_labels()
+    ax_rate.legend(handles1 + handles2, labels1 + labels2, loc="upper right", fontsize=8)
+
+    xloc = np.arange(3)
+    ax_metrics.bar(xloc - 0.175, e2["aic"], width=0.35, label="AIC", color="tab:purple")
+    ax_metrics.bar(xloc + 0.175, e2["bic"], width=0.35, label="BIC", color="tab:brown")
+    ax_metrics.set_xticks(xloc, ["Model 1", "Model 2", "Model 3"])
+    ax_metrics.set_ylabel("Information Criterion")
+    ax_metrics.set_title("Experiment 2: Model Comparison")
+    ax_metrics.grid(alpha=0.3, axis="y")
+    ax_metrics.legend()
+
+    out = plots_dir / "experiment2_stimulus_glm_comparison.png"
+    fig.savefig(out, dpi=180)
+    plt.close(fig)
+    saved_paths.append(out)
+
+    # Experiment 3: true CIF and PSTH with raster.
+    e3 = plot_payloads["experiment3"]
+    fig, (ax_rate, ax_raster) = plt.subplots(2, 1, figsize=(11, 8), constrained_layout=True)
+    ax_rate.plot(e3["time_s"], e3["true_rate_hz"], color="tab:gray", lw=1.5, label="True rate")
+    ax_rate.step(
+        e3["psth_bin_centers_s"],
+        e3["psth_rate_hz"],
+        where="mid",
+        color="tab:blue",
+        lw=2.0,
+        label="Estimated PSTH",
+    )
+    ax_rate.set_title("Experiment 3: Simulated CIF and Estimated PSTH")
+    ax_rate.set_xlabel("Time (s)")
+    ax_rate.set_ylabel("Rate (Hz)")
+    ax_rate.grid(alpha=0.3)
+    ax_rate.legend(loc="upper right")
+
+    n_show = min(10, len(e3["raster_spike_times"]))
+    for row, spikes in enumerate(e3["raster_spike_times"][:n_show], start=1):
+        if len(spikes) > 0:
+            ax_raster.vlines(spikes, row - 0.4, row + 0.4, color="black", lw=0.6)
+    ax_raster.set_ylim(0.5, n_show + 0.5)
+    ax_raster.set_title("Experiment 3: Spike Raster (first 10 trials)")
+    ax_raster.set_xlabel("Time (s)")
+    ax_raster.set_ylabel("Trial")
+    ax_raster.grid(alpha=0.2)
+
+    out = plots_dir / "experiment3_psth_and_raster.png"
+    fig.savefig(out, dpi=180)
+    plt.close(fig)
+    saved_paths.append(out)
+
+    # Experiment 4: trajectory and model deltas.
+    e4 = plot_payloads["experiment4"]
+    fig, (ax_traj, ax_delta) = plt.subplots(1, 2, figsize=(13, 5.5), constrained_layout=True)
+    ax_traj.plot(e4["x_pos"], e4["y_pos"], color="tab:blue", alpha=0.45, lw=0.8, label="Trajectory")
+    spike_x = np.interp(e4["first_cell_spike_times_s"], e4["time_s"], e4["x_pos"])
+    spike_y = np.interp(e4["first_cell_spike_times_s"], e4["time_s"], e4["y_pos"])
+    ax_traj.scatter(spike_x, spike_y, s=8, color="tab:red", alpha=0.6, label="Cell 1 spikes")
+    ax_traj.set_title("Experiment 4: Place Trajectory and Cell 1 Spikes")
+    ax_traj.set_xlabel("X position")
+    ax_traj.set_ylabel("Y position")
+    ax_traj.set_aspect("equal", adjustable="box")
+    ax_traj.grid(alpha=0.3)
+    ax_traj.legend(loc="upper right", fontsize=8)
+
+    cells = np.arange(1, len(e4["delta_aic"]) + 1)
+    ax_delta.plot(cells, e4["delta_aic"], marker="o", lw=1.5, color="tab:purple", label="Delta AIC")
+    ax_delta.plot(cells, e4["delta_bic"], marker="s", lw=1.5, color="tab:green", label="Delta BIC")
+    ax_delta.axhline(0.0, color="black", lw=1.0, alpha=0.5)
+    ax_delta.set_title("Experiment 4: Gaussian - Zernike Model Delta")
+    ax_delta.set_xlabel("Cell index")
+    ax_delta.set_ylabel("Score difference")
+    ax_delta.grid(alpha=0.3)
+    ax_delta.legend(loc="upper right")
+
+    out = plots_dir / "experiment4_placecell_model_comparison.png"
+    fig.savefig(out, dpi=180)
+    plt.close(fig)
+    saved_paths.append(out)
+
+    # Experiment 5: decode quality with confidence bounds.
+    e5 = plot_payloads["experiment5"]
+    fig, ax = plt.subplots(1, 1, figsize=(11, 4.5), constrained_layout=True)
+    ax.plot(e5["time_s"], e5["stimulus"], color="tab:blue", lw=1.8, label="True stimulus")
+    ax.plot(e5["time_s"], e5["decoded"], color="tab:orange", lw=1.5, label="Decoded stimulus")
+    ax.fill_between(e5["time_s"], e5["ci_low"], e5["ci_high"], color="tab:orange", alpha=0.2, label="95% CI")
+    ax.set_title("Experiment 5: Linear Decoding of Simulated Stimulus")
+    ax.set_xlabel("Time (s)")
+    ax.set_ylabel("Stimulus (a.u.)")
+    ax.grid(alpha=0.3)
+    ax.legend(loc="upper right")
+
+    out = plots_dir / "experiment5_stimulus_decoding.png"
+    fig.savefig(out, dpi=180)
+    plt.close(fig)
+    saved_paths.append(out)
+
+    return saved_paths
+
+
+def main() -> int:
+    parser = argparse.ArgumentParser(description="Python nSTAT paper examples equivalent")
+    parser.add_argument("--repo-root", type=Path, default=_default_repo_root())
+    parser.add_argument("--no-plots", action="store_true", help="Run metrics only without generating plots")
+    parser.add_argument("--plots-dir", type=Path, default=None, help="Directory for generated PNG plots")
+    parser.add_argument("--output-json", type=Path, default=None)
+    args = parser.parse_args()
+
+    repo_root = args.repo_root.resolve()
+    default_plots_dir = repo_root / "plots" / "nstat_paper_examples"
+    plots_dir = (args.plots_dir or default_plots_dir).resolve()
+
+    if args.no_plots:
+        results = run_paper_examples(repo_root)
+        saved_plots: list[Path] = []
+    else:
+        results, payloads = run_paper_examples(repo_root, return_plot_data=True)
+        saved_plots = _save_paper_example_plots(payloads, plots_dir)
+
+    if args.output_json is not None:
+        args.output_json.write_text(json.dumps(results, indent=2), encoding="utf-8")
+
+    print(json.dumps(results, indent=2))
+    if saved_plots:
+        print("\nGenerated plots:")
+        for path in saved_plots:
+            print(str(path))
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())
diff --git a/nstat/paper_examples_full.py b/nstat/paper_examples_full.py
new file mode 100644
index 00000000..89501d86
--- /dev/null
+++ b/nstat/paper_examples_full.py
@@ -0,0 +1,460 @@
+from __future__ import annotations
+
+import argparse
+import json
+import os
+from pathlib import Path
+
+import numpy as np
+from scipy.io import loadmat
+
+from .analysis import psth
+from .decoding_algorithms import DecodingAlgorithms
+from .glm import fit_poisson_glm
+from .simulation import simulate_poisson_from_rate
+
+
+def _default_repo_root() -> Path:
+    cur = Path(__file__).resolve()
+    for candidate in [cur, *cur.parents]:
+        if (candidate / "nstat").exists() and (candidate / "data").exists():
+            return candidate
+    return cur.parents[1]
+
+
+def _allow_synthetic_data() -> bool:
+    return os.environ.get("NSTAT_ALLOW_SYNTHETIC_DATA", "").strip().lower() in {"1", "true", "yes", "on"}
+
+
+def _is_lfs_pointer(path: Path) -> bool:
+    try:
+        head = path.read_bytes()[:200]
+    except OSError:
+        return False
+    return head.startswith(b"version https://git-lfs.github.com/spec/v1")
+
+
+def _loadmat_checked(path: Path):
+    if path.exists() and not _is_lfs_pointer(path):
+        return loadmat(path, squeeze_me=True, struct_as_record=False)
+    if _allow_synthetic_data():
+        return None
+    if not path.exists():
+        raise FileNotFoundError(f"Missing MAT file: {path}")
+    if _is_lfs_pointer(path):
+        raise RuntimeError(
+            f"MAT file is a Git LFS pointer, not dataset content: {path}. "
+            "Fetch LFS assets or set NSTAT_ALLOW_SYNTHETIC_DATA=1 for synthetic CI fallback."
+        )
+    raise RuntimeError(f"Unable to load MAT file: {path}")
+
+
+def _aic_bic(log_likelihood: float, n_obs: int, n_params: int) -> tuple[float, float]:
+    aic = 2.0 * n_params - 2.0 * log_likelihood
+    bic = np.log(max(n_obs, 1)) * n_params - 2.0 * log_likelihood
+    return float(aic), float(bic)
+
+
+def _history_matrix(y: np.ndarray, lags: list[int]) -> np.ndarray:
+    out = np.zeros((y.shape[0], len(lags)), dtype=float)
+    for j, lag in enumerate(lags):
+        out[lag:, j] = y[:-lag]
+    return out
+
+
+def _load_mepsc_times_seconds(path: Path) -> np.ndarray:
+    arr = np.loadtxt(path, skiprows=1)
+    return np.asarray(arr[:, 1], dtype=float).reshape(-1) / 1000.0
+
+
+def _bin_spike_times(spikes: np.ndarray, t0: float, t1: float, dt: float) -> tuple[np.ndarray, np.ndarray]:
+    n_bins = int(np.floor((t1 - t0) / dt)) + 1
+    edges = t0 + np.arange(n_bins + 1, dtype=float) * dt
+    counts, _ = np.histogram(spikes, bins=edges)
+    return edges[:-1], counts.astype(float)
+
+
+def run_experiment1(data_dir: Path) -> dict[str, float]:
+    mepsc_dir = data_dir / "mEPSCs"
+    epsc2 = _load_mepsc_times_seconds(mepsc_dir / "epsc2.txt")
+    washout1 = _load_mepsc_times_seconds(mepsc_dir / "washout1.txt")
+    washout2 = _load_mepsc_times_seconds(mepsc_dir / "washout2.txt")
+
+    dt_const = 0.01
+    _, y_const = _bin_spike_times(epsc2, 0.0, float(np.max(epsc2)), dt_const)
+    off_const = np.full(y_const.shape[0], np.log(dt_const), dtype=float)
+    m_const = fit_poisson_glm(np.zeros((y_const.shape[0], 0), dtype=float), y_const, offset=off_const, max_iter=80)
+    aic_const, bic_const = _aic_bic(m_const.log_likelihood, y_const.shape[0], 1)
+
+    spikes = np.concatenate([260.0 + washout1, np.sort(washout2) + 745.0])
+    dt = 0.01
+    t, y = _bin_spike_times(spikes, 260.0, float(np.max(spikes)), dt)
+    off = np.full(y.shape[0], np.log(dt), dtype=float)
+
+    seg2 = ((t >= 495.0) & (t < 765.0)).astype(float)
+    seg3 = (t >= 765.0).astype(float)
+    x_piece = np.column_stack([seg2, seg3])
+    hist = _history_matrix(y, [1, 2, 3, 4, 5, 7, 10, 14, 20, 30])
+    x_piece_hist = np.column_stack([x_piece, hist])
+
+    m_piece = fit_poisson_glm(x_piece, y, offset=off, max_iter=100)
+    m_piece_hist = fit_poisson_glm(x_piece_hist, y, offset=off, max_iter=120)
+    aic_piece, bic_piece = _aic_bic(m_piece.log_likelihood, y.shape[0], x_piece.shape[1] + 1)
+    aic_piece_hist, bic_piece_hist = _aic_bic(m_piece_hist.log_likelihood, y.shape[0], x_piece_hist.shape[1] + 1)
+
+    return {
+        "const_condition_spikes": float(np.sum(y_const)),
+        "const_model_aic": aic_const,
+        "const_model_bic": bic_const,
+        "decreasing_condition_spikes": float(np.sum(y)),
+        "piecewise_model_aic": aic_piece,
+        "piecewise_model_bic": bic_piece,
+        "piecewise_history_model_aic": aic_piece_hist,
+        "piecewise_history_model_bic": bic_piece_hist,
+        "dt_seconds": dt,
+    }
+
+
+def run_experiment2(data_dir: Path) -> dict[str, float]:
+    path = data_dir / "Explicit Stimulus" / "Dir3" / "Neuron1" / "Stim2" / "trngdataBis.mat"
+    d = _loadmat_checked(path)
+    if d is None:
+        rng = np.random.default_rng(2002)
+        n = 5000
+        t = np.linspace(0.0, 2.0 * np.pi, n, dtype=float)
+        stim_raw = np.sin(1.8 * t) + 0.25 * np.sin(0.4 * t + 0.2)
+        p = np.clip(0.015 + 0.02 * np.maximum(stim_raw, 0.0), 1e-4, 0.35)
+        y = (rng.random(n) < p).astype(float)
+    else:
+        stim_raw = np.asarray(d["t"], dtype=float).reshape(-1)
+        y = np.asarray(d["y"], dtype=float).reshape(-1)
+
+    dt = 0.001
+    stim = stim_raw / 10.0
+    stim_vel = np.gradient(stim, dt)
+    hist = _history_matrix(y, [1, 2, 3, 4, 5])
+
+    x1 = np.zeros((y.shape[0], 0), dtype=float)
+    x2 = np.column_stack([stim, stim_vel])
+    x3 = np.column_stack([stim, stim_vel, hist])
+    offset = np.full(y.shape[0], np.log(dt), dtype=float)
+
+    m1 = fit_poisson_glm(x1, y, offset=offset)
+    m2 = fit_poisson_glm(x2, y, offset=offset)
+    m3 = fit_poisson_glm(x3, y, offset=offset)
+
+    aic1, bic1 = _aic_bic(m1.log_likelihood, y.shape[0], 1)
+    aic2, bic2 = _aic_bic(m2.log_likelihood, y.shape[0], 3)
+    aic3, bic3 = _aic_bic(m3.log_likelihood, y.shape[0], 8)
+
+    return {
+        "n_samples": float(y.shape[0]),
+        "model1_aic": aic1,
+        "model2_aic": aic2,
+        "model3_aic": aic3,
+        "model1_bic": bic1,
+        "model2_bic": bic2,
+        "model3_bic": bic3,
+    }
+
+
+def run_experiment3(seed: int = 7) -> dict[str, float]:
+    rng = np.random.default_rng(seed)
+    dt = 0.001
+    tmax = 1.0
+    time = np.arange(0.0, tmax + dt, dt)
+
+    linear = np.sin(2.0 * np.pi * 2.0 * time) - 3.0
+    p = np.exp(linear)
+    p = p / (1.0 + p)
+    rate_hz = p / dt
+
+    trains = [simulate_poisson_from_rate(time, rate_hz, rng=rng) for _ in range(20)]
+    edges = np.arange(0.0, tmax + 0.05, 0.05)
+    psth_rate_hz, counts = psth(trains, edges)
+
+    return {
+        "num_trials": float(len(trains)),
+        "psth_peak_hz": float(np.max(psth_rate_hz)),
+        "psth_mean_hz": float(np.mean(psth_rate_hz)),
+        "total_spikes": float(np.sum(counts)),
+    }
+
+
+def run_experiment3b(data_dir: Path) -> dict[str, float]:
+    path = data_dir / "SSGLMExampleData.mat"
+    d = _loadmat_checked(path)
+    if d is None:
+        rng = np.random.default_rng(3003)
+        stimulus = rng.normal(0.0, 1.0, size=(15, 250))
+        xk = stimulus + rng.normal(0.0, 0.2, size=stimulus.shape)
+        ci_half = np.abs(rng.normal(0.35, 0.08, size=stimulus.shape))
+        stim_cis = np.stack([xk - ci_half, xk + ci_half], axis=-1)
+        qhat = np.abs(rng.normal(0.12, 0.03, size=stimulus.shape[0]))
+        gammahat = np.abs(rng.normal(0.08, 0.02, size=stimulus.shape[0]))
+        logll = float(-np.mean((xk - stimulus) ** 2) * stimulus.size)
+    else:
+        stimulus = np.asarray(d["stimulus"], dtype=float)
+        xk = np.asarray(d["xK"], dtype=float)
+        stim_cis = np.asarray(d["stimCIs"], dtype=float)
+        qhat = np.asarray(d["Qhat"], dtype=float).reshape(-1)
+        gammahat = np.asarray(d["gammahat"], dtype=float).reshape(-1)
+        logll = float(np.asarray(d["logll"], dtype=float).reshape(-1)[0])
+
+    coverage = np.mean((stimulus >= stim_cis[:, :, 0]) & (stimulus <= stim_cis[:, :, 1]))
+    rmse = np.sqrt(np.mean((xk - stimulus) ** 2))
+
+    return {
+        "num_trials": float(stimulus.shape[0]),
+        "num_time_bins": float(stimulus.shape[1]),
+        "state_rmse": float(rmse),
+        "ci_coverage": float(coverage),
+        "mean_qhat": float(np.mean(qhat)),
+        "mean_gammahat": float(np.mean(gammahat)),
+        "log_likelihood": logll,
+    }
+
+
+def _spike_indicator(time: np.ndarray, spike_times: np.ndarray) -> np.ndarray:
+    y = np.zeros(time.shape[0], dtype=float)
+    idx = np.searchsorted(time, spike_times, side="left")
+    idx = idx[(idx >= 0) & (idx < time.shape[0])]
+    if idx.size > 0:
+        y[idx] = 1.0
+    return y
+
+
+def _zernike_like_basis(x: np.ndarray, y: np.ndarray) -> np.ndarray:
+    theta = np.arctan2(y, x)
+    r = np.sqrt(x * x + y * y)
+    return np.column_stack([
+        np.ones_like(r),
+        r,
+        r**2,
+        np.cos(theta),
+        np.sin(theta),
+        r * np.cos(theta),
+        r * np.sin(theta),
+        r**2 * np.cos(2.0 * theta),
+        r**2 * np.sin(2.0 * theta),
+        r**3,
+    ])
+
+
+def run_experiment4(data_dir: Path) -> dict[str, float]:
+    path = data_dir / "Place Cells" / "PlaceCellDataAnimal1.mat"
+    d = _loadmat_checked(path)
+    if d is None:
+        rng = np.random.default_rng(4004)
+        time = np.linspace(0.0, 20.0, 2400, dtype=float)
+        x = 0.8 * np.sin(0.6 * time) + 0.2 * np.sin(1.7 * time + 0.5)
+        y = 0.7 * np.cos(0.5 * time + 0.3)
+        n_cells = 8
+        neurons = []
+        for _ in range(n_cells):
+            field = np.exp(-((x - rng.uniform(-0.5, 0.5)) ** 2 + (y - rng.uniform(-0.5, 0.5)) ** 2) / 0.2)
+            p = np.clip(0.001 + 0.03 * field, 1e-6, 0.25)
+            spikes = time[rng.random(time.shape[0]) < p]
+            neurons.append(type("N", (), {"spikeTimes": spikes})())
+        neurons = np.asarray(neurons, dtype=object)
+    else:
+        x = np.asarray(d["x"], dtype=float).reshape(-1)
+        y = np.asarray(d["y"], dtype=float).reshape(-1)
+        time = np.asarray(d["time"], dtype=float).reshape(-1)
+        neurons = np.asarray(d["neuron"], dtype=object).reshape(-1)
+
+    dt = float(np.median(np.diff(time)))
+    offset = np.full(time.shape[0], np.log(max(dt, 1e-12)), dtype=float)
+    x_gauss = np.column_stack([x, y, x * x, y * y, x * y])
+    x_zern = _zernike_like_basis(x, y)
+
+    d_aic = []
+    d_bic = []
+    n_eval = int(min(8, neurons.shape[0]))
+    for i in range(n_eval):
+        spike_times = np.asarray(neurons[i].spikeTimes, dtype=float).reshape(-1)
+        y_spike = _spike_indicator(time, spike_times)
+        mg = fit_poisson_glm(x_gauss, y_spike, offset=offset)
+        mz = fit_poisson_glm(x_zern, y_spike, offset=offset)
+        aicg, bicg = _aic_bic(mg.log_likelihood, y_spike.shape[0], x_gauss.shape[1] + 1)
+        aicz, bicz = _aic_bic(mz.log_likelihood, y_spike.shape[0], x_zern.shape[1] + 1)
+        d_aic.append(aicg - aicz)
+        d_bic.append(bicg - bicz)
+
+    return {
+        "num_cells_fit": float(n_eval),
+        "mean_delta_aic_gaussian_minus_zernike": float(np.mean(d_aic)),
+        "mean_delta_bic_gaussian_minus_zernike": float(np.mean(d_bic)),
+    }
+
+
+def run_experiment5(seed: int = 11, n_cells: int = 20) -> dict[str, float]:
+    rng = np.random.default_rng(seed)
+    dt = 0.001
+    time = np.arange(0.0, 1.0 + dt, dt)
+    stim = np.sin(2.0 * np.pi * 2.0 * time)
+
+    n_cells = int(n_cells)
+    if n_cells < 1:
+        raise ValueError("n_cells must be >= 1")
+    spikes = np.zeros((time.shape[0], n_cells), dtype=float)
+    for i in range(n_cells):
+        b1 = rng.normal(1.0, 0.5)
+        b0 = np.log(10.0 * dt) + rng.normal(0.0, 0.3)
+        eta = b1 * stim + b0
+        p = np.exp(eta)
+        p = p / (1.0 + p)
+        spikes[:, i] = (rng.random(time.shape[0]) < p).astype(float)
+
+    decoded = DecodingAlgorithms.linear_decode(spikes, stim)
+    rmse = float(np.sqrt(np.mean((decoded["decoded"] - stim) ** 2)))
+    return {"num_cells": float(n_cells), "decode_rmse": rmse}
+
+
+def run_experiment5b(seed: int = 19, n_cells: int = 30) -> dict[str, float]:
+    rng = np.random.default_rng(seed)
+
+    dt = 0.01
+    time = np.arange(0.0, 20.0 + dt, dt)
+    x_true = 0.25 * np.sin(2.0 * np.pi * 0.15 * time)
+    y_true = 0.20 * np.cos(2.0 * np.pi * 0.10 * time)
+    vx = np.gradient(x_true, dt)
+    vy = np.gradient(y_true, dt)
+
+    n_cells = int(n_cells)
+    if n_cells < 1:
+        raise ValueError("n_cells must be >= 1")
+    spikes = np.zeros((time.shape[0], n_cells), dtype=float)
+    for i in range(n_cells):
+        wx = rng.normal(0.0, 1.0)
+        wy = rng.normal(0.0, 1.0)
+        b0 = -3.0 + rng.normal(0.0, 0.2)
+        eta = b0 + 3.0 * wx * vx + 3.0 * wy * vy
+        p = 1.0 / (1.0 + np.exp(-np.clip(eta, -20.0, 20.0)))
+        spikes[:, i] = (rng.random(time.shape[0]) < p).astype(float)
+
+    dx = DecodingAlgorithms.linear_decode(spikes, x_true)["decoded"]
+    dy = DecodingAlgorithms.linear_decode(spikes, y_true)["decoded"]
+    return {
+        "num_cells": float(n_cells),
+        "num_samples": float(time.shape[0]),
+        "decode_rmse_x": float(np.sqrt(np.mean((dx - x_true) ** 2))),
+        "decode_rmse_y": float(np.sqrt(np.mean((dy - y_true) ** 2))),
+    }
+
+
+def _simulate_hybrid_spikes(x: np.ndarray, mstate: np.ndarray, dt: float, n_cells: int, seed: int):
+    rng = np.random.default_rng(seed)
+    vx = x[2, :]
+    vy = x[3, :]
+    wvx = rng.normal(0.0, 1.0, size=n_cells)
+    wvy = rng.normal(0.0, 1.0, size=n_cells)
+    b1 = rng.normal(-3.8, 0.2, size=n_cells)
+    b2 = rng.normal(-2.8, 0.2, size=n_cells)
+
+    spikes = np.zeros((x.shape[1], n_cells), dtype=float)
+    for t in range(x.shape[1]):
+        base = b1 if int(mstate[t]) == 1 else b2
+        eta = base + 1.2 * wvx * vx[t] + 1.2 * wvy * vy[t]
+        lam = np.exp(np.clip(eta, -15.0, 15.0))
+        p = 1.0 - np.exp(-lam * dt)
+        spikes[t, :] = (rng.random(n_cells) < p).astype(float)
+    return spikes, wvx, wvy, b1, b2
+
+
+def _hybrid_state_filter(spikes: np.ndarray, x: np.ndarray, dt: float, p_ij: np.ndarray, wvx: np.ndarray, wvy: np.ndarray, b1: np.ndarray, b2: np.ndarray) -> np.ndarray:
+    n_t, _ = spikes.shape
+    post = np.zeros((n_t, 2), dtype=float)
+    post[0, :] = [0.5, 0.5]
+    vx = x[2, :]
+    vy = x[3, :]
+
+    for t in range(1, n_t):
+        eta1 = b1 + 1.2 * wvx * vx[t] + 1.2 * wvy * vy[t]
+        eta2 = b2 + 1.2 * wvx * vx[t] + 1.2 * wvy * vy[t]
+        p1 = np.clip(1.0 - np.exp(-np.exp(np.clip(eta1, -15.0, 15.0)) * dt), 1e-6, 1.0 - 1e-6)
+        p2 = np.clip(1.0 - np.exp(-np.exp(np.clip(eta2, -15.0, 15.0)) * dt), 1e-6, 1.0 - 1e-6)
+        k = spikes[t, :]
+        ll1 = np.sum(k * np.log(p1) + (1.0 - k) * np.log(1.0 - p1))
+        ll2 = np.sum(k * np.log(p2) + (1.0 - k) * np.log(1.0 - p2))
+        pred0 = max(post[t - 1, 0] * p_ij[0, 0] + post[t - 1, 1] * p_ij[1, 0], 1e-15)
+        pred1 = max(post[t - 1, 0] * p_ij[0, 1] + post[t - 1, 1] * p_ij[1, 1], 1e-15)
+        logs = np.array([np.log(pred0) + ll1, np.log(pred1) + ll2], dtype=float)
+        logs = logs - np.max(logs)
+        un = np.exp(logs)
+        post[t, :] = un / np.sum(un)
+    return post
+
+
+def run_experiment6(repo_root: Path, seed: int = 37) -> dict[str, float]:
+    path = repo_root / "helpfiles" / "paperHybridFilterExample.mat"
+    d = _loadmat_checked(path)
+    if d is None:
+        rng = np.random.default_rng(seed)
+        dt = 0.01
+        t = np.arange(0.0, 30.0, dt, dtype=float)
+        x_pos = 0.3 * np.sin(0.2 * t)
+        y_pos = 0.25 * np.cos(0.15 * t)
+        x_vel = np.gradient(x_pos, dt)
+        y_vel = np.gradient(y_pos, dt)
+        x = np.vstack([x_pos, y_pos, x_vel, y_vel])
+        mstate = np.where(np.sin(0.05 * t + 0.4) > 0.0, 1, 2).astype(int)
+        # Add mild stochasticity so state filter is non-trivial.
+        flip = rng.random(t.shape[0]) < 0.02
+        mstate[flip] = 3 - mstate[flip]
+        p_ij = np.array([[0.985, 0.015], [0.02, 0.98]], dtype=float)
+    else:
+        x = np.asarray(d["X"], dtype=float)
+        mstate = np.asarray(d["mstate"], dtype=int).reshape(-1)
+        p_ij = np.asarray(d["p_ij"], dtype=float)
+        dt = float(np.asarray(d["delta"], dtype=float).reshape(-1)[0])
+
+    n_cells = 24
+    spikes, wvx, wvy, b1, b2 = _simulate_hybrid_spikes(x, mstate, dt, n_cells=n_cells, seed=seed)
+    post = _hybrid_state_filter(spikes, x, dt, p_ij, wvx, wvy, b1, b2)
+    state_hat = np.argmax(post, axis=1) + 1
+    state_acc = np.mean(state_hat == mstate)
+
+    dx = DecodingAlgorithms.linear_decode(spikes, x[0, :])["decoded"]
+    dy = DecodingAlgorithms.linear_decode(spikes, x[1, :])["decoded"]
+    return {
+        "num_samples": float(x.shape[1]),
+        "num_cells": float(n_cells),
+        "state_accuracy": float(state_acc),
+        "decode_rmse_x": float(np.sqrt(np.mean((dx - x[0, :]) ** 2))),
+        "decode_rmse_y": float(np.sqrt(np.mean((dy - x[1, :]) ** 2))),
+    }
+
+
+def run_full_paper_examples(repo_root: Path) -> dict[str, dict[str, float]]:
+    data_dir = repo_root / "data"
+    if not data_dir.exists():
+        raise FileNotFoundError(f"Could not locate data directory: {data_dir}")
+
+    return {
+        "experiment1": run_experiment1(data_dir),
+        "experiment2": run_experiment2(data_dir),
+        "experiment3": run_experiment3(),
+        "experiment3b": run_experiment3b(data_dir),
+        "experiment4": run_experiment4(data_dir),
+        "experiment5": run_experiment5(),
+        "experiment5b": run_experiment5b(),
+        "experiment6": run_experiment6(repo_root),
+    }
+
+
+def main() -> int:
+    parser = argparse.ArgumentParser(description="Native Python approximation of nSTATPaperExamples.m")
+    parser.add_argument("--repo-root", type=Path, default=_default_repo_root())
+    parser.add_argument("--output-json", type=Path, default=None)
+    args = parser.parse_args()
+
+    results = run_full_paper_examples(args.repo_root.resolve())
+    if args.output_json is not None:
+        args.output_json.write_text(json.dumps(results, indent=2), encoding="utf-8")
+    print(json.dumps(results, indent=2))
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())
diff --git a/nstat/signal.py b/nstat/signal.py
new file mode 100644
index 00000000..11be2dc4
--- /dev/null
+++ b/nstat/signal.py
@@ -0,0 +1,88 @@
+from __future__ import annotations
+
+from typing import Sequence
+
+import numpy as np
+
+from .core import Covariate as _LegacyCovariate
+from .core import SignalObj as _LegacySignalObj
+
+
+class Signal(_LegacySignalObj):
+    """Canonical Pythonic signal abstraction for nSTAT."""
+
+    def copy(self) -> "Signal":
+        copied = self.copySignal()
+        return Signal(
+            copied.time,
+            copied.data,
+            copied.name,
+            copied.xlabelval,
+            copied.xunits,
+            copied.yunits,
+            copied.dataLabels,
+        )
+
+    def sub_signal(self, index: int) -> "Signal":
+        """Return one channel as a new signal.
+
+        Uses zero-based indexing in Python, unlike MATLAB's one-based indexing.
+        """
+        if index < 0 or index >= self.dimension:
+            raise IndexError("Signal channel index out of range.")
+        out = self.getSubSignal(index + 1)
+        return Signal(
+            out.time,
+            out.data,
+            out.name,
+            out.xlabelval,
+            out.xunits,
+            out.yunits,
+            out.dataLabels,
+        )
+
+    def window(self, start: float, stop: float) -> "Signal":
+        out = self.getSigInTimeWindow(start, stop)
+        return Signal(
+            out.time,
+            out.data,
+            out.name,
+            out.xlabelval,
+            out.xunits,
+            out.yunits,
+            out.dataLabels,
+        )
+
+    def as_array(self) -> np.ndarray:
+        return np.asarray(self.data, dtype=float)
+
+
+class Covariate(_LegacyCovariate):
+    """Canonical covariate type for model design matrices."""
+
+    def standardize(self) -> "Covariate":
+        data = np.asarray(self.data, dtype=float)
+        mu = np.mean(data, axis=0, keepdims=True)
+        sigma = np.std(data, axis=0, keepdims=True)
+        sigma[sigma == 0.0] = 1.0
+        z = (data - mu) / sigma
+        return Covariate(
+            self.time,
+            z,
+            self.name,
+            self.xlabelval,
+            self.xunits,
+            self.yunits,
+            self.dataLabels,
+        )
+
+    @classmethod
+    def from_values(
+        cls,
+        time: Sequence[float],
+        values: Sequence[float] | Sequence[Sequence[float]] | np.ndarray,
+        *,
+        name: str = "covariate",
+        units: str = "",
+    ) -> "Covariate":
+        return cls(time=time, values=values, name=name, units=units)
diff --git a/nstat/simulation.py b/nstat/simulation.py
new file mode 100644
index 00000000..863bd604
--- /dev/null
+++ b/nstat/simulation.py
@@ -0,0 +1,35 @@
+from __future__ import annotations
+
+import numpy as np
+
+from .core import nspikeTrain
+
+
+# Backward-compatible alias used by earlier Python code.
+SpikeTrain = nspikeTrain
+
+
+def simulate_poisson_from_rate(
+    time: np.ndarray,
+    rate_hz: np.ndarray,
+    rng: np.random.Generator | None = None,
+) -> nspikeTrain:
+    t = np.asarray(time, dtype=float).reshape(-1)
+    r = np.asarray(rate_hz, dtype=float).reshape(-1)
+    if t.shape[0] != r.shape[0]:
+        raise ValueError("time and rate_hz length mismatch")
+    if t.shape[0] < 2:
+        return nspikeTrain(np.asarray([], dtype=float))
+
+    if rng is None:
+        rng = np.random.default_rng()
+
+    dt = np.diff(t)
+    dt = np.concatenate([dt, [dt[-1]]])
+    p = 1.0 - np.exp(-np.clip(r, 0.0, np.inf) * dt)
+    p = np.clip(p, 0.0, 1.0)
+    keep = rng.random(t.shape[0]) < p
+    return nspikeTrain(spikeTimes=t[keep])
+
+
+__all__ = ["SpikeTrain", "simulate_poisson_from_rate"]
diff --git a/nstat/simulators.py b/nstat/simulators.py
new file mode 100644
index 00000000..fb88990b
--- /dev/null
+++ b/nstat/simulators.py
@@ -0,0 +1,73 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import numpy as np
+
+from .spikes import SpikeTrain, SpikeTrainCollection
+
+
+@dataclass
+class PointProcessSimulation:
+    time: np.ndarray
+    rate_hz: np.ndarray
+    spikes: SpikeTrain
+
+
+@dataclass
+class NetworkSimulationResult:
+    time: np.ndarray
+    latent_drive: np.ndarray
+    spikes: SpikeTrainCollection
+
+
+def simulate_point_process(time: np.ndarray, rate_hz: np.ndarray, *, seed: int | None = None) -> PointProcessSimulation:
+    t = np.asarray(time, dtype=float).reshape(-1)
+    r = np.asarray(rate_hz, dtype=float).reshape(-1)
+    if t.shape[0] != r.shape[0]:
+        raise ValueError("time and rate_hz length mismatch")
+    if t.shape[0] < 2:
+        return PointProcessSimulation(t, r, SpikeTrain(np.array([], dtype=float)))
+
+    dt = np.diff(t)
+    dt = np.concatenate([dt, [dt[-1]]])
+    p = 1.0 - np.exp(-np.clip(r, 0.0, np.inf) * dt)
+    p = np.clip(p, 0.0, 1.0)
+
+    rng = np.random.default_rng(seed)
+    keep = rng.random(t.shape[0]) < p
+    return PointProcessSimulation(t, r, SpikeTrain(t[keep]))
+
+
+def simulate_two_neuron_network(
+    duration_s: float = 2.0,
+    dt: float = 0.001,
+    base_rate_hz: float = 8.0,
+    coupling: float = 1.2,
+    seed: int | None = 13,
+) -> NetworkSimulationResult:
+    """Standalone Python replacement for Simulink-style 2-neuron network examples."""
+    if duration_s <= 0 or dt <= 0:
+        raise ValueError("duration_s and dt must be > 0")
+
+    time = np.arange(0.0, duration_s + dt, dt)
+    drive = np.sin(2.0 * np.pi * 2.0 * time)
+
+    rng = np.random.default_rng(seed)
+    spikes = np.zeros((time.shape[0], 2), dtype=float)
+    for i in range(1, time.shape[0]):
+        prev = spikes[i - 1]
+        eta1 = np.log(base_rate_hz * dt) + 1.5 * drive[i] + coupling * (prev[1] - 0.1)
+        eta2 = np.log(base_rate_hz * dt) - 1.5 * drive[i] + coupling * (prev[0] - 0.1)
+        p1 = 1.0 / (1.0 + np.exp(-np.clip(eta1, -20.0, 20.0)))
+        p2 = 1.0 / (1.0 + np.exp(-np.clip(eta2, -20.0, 20.0)))
+        spikes[i, 0] = 1.0 if rng.random() < p1 else 0.0
+        spikes[i, 1] = 1.0 if rng.random() < p2 else 0.0
+
+    t1 = time[spikes[:, 0] > 0.5]
+    t2 = time[spikes[:, 1] > 0.5]
+    coll = SpikeTrainCollection([SpikeTrain(t1, name="neuron_1"), SpikeTrain(t2, name="neuron_2")])
+    return NetworkSimulationResult(time=time, latent_drive=drive, spikes=coll)
+
+
+__all__ = ["PointProcessSimulation", "NetworkSimulationResult", "simulate_point_process", "simulate_two_neuron_network"]
diff --git a/nstat/spikes.py b/nstat/spikes.py
new file mode 100644
index 00000000..1670c0f1
--- /dev/null
+++ b/nstat/spikes.py
@@ -0,0 +1,37 @@
+from __future__ import annotations
+
+from typing import Sequence
+
+import numpy as np
+
+from .core import nspikeTrain as _LegacySpikeTrain
+from .simulation import simulate_poisson_from_rate
+from .trial import nstColl as _LegacySpikeTrainCollection
+
+
+class SpikeTrain(_LegacySpikeTrain):
+    """Canonical spike train type for point-process analyses."""
+
+    def inter_spike_intervals(self) -> np.ndarray:
+        return self.getISIs()
+
+    def to_counts(self, bin_edges: Sequence[float]) -> np.ndarray:
+        return self.to_binned_counts(bin_edges)
+
+
+class SpikeTrainCollection(_LegacySpikeTrainCollection):
+    """Collection of aligned spike trains for ensemble analyses."""
+
+    def __iter__(self):
+        for i in range(1, self.numSpikeTrains + 1):
+            yield self.getNST(i)
+
+    def to_matrix(self, bin_edges: Sequence[float]) -> np.ndarray:
+        edges = np.asarray(bin_edges, dtype=float).reshape(-1)
+        if edges.ndim != 1 or edges.size < 2:
+            raise ValueError("bin_edges must be a 1D array with at least two entries")
+        rows = [np.asarray(train.to_binned_counts(edges), dtype=float) for train in self]
+        return np.vstack(rows)
+
+
+__all__ = ["SpikeTrain", "SpikeTrainCollection", "simulate_poisson_from_rate"]
diff --git a/nstat/trial.py b/nstat/trial.py
new file mode 100644
index 00000000..8b336367
--- /dev/null
+++ b/nstat/trial.py
@@ -0,0 +1,266 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Iterable, Sequence
+
+import numpy as np
+
+from .core import nspikeTrain
+from .events import Events
+from .signal import Covariate
+
+
+class CovariateCollection:
+    def __init__(self, covariates: Sequence[Covariate] | None = None) -> None:
+        self.covariates = list(covariates or [])
+
+    @property
+    def names(self) -> list[str]:
+        return [cov.name for cov in self.covariates]
+
+    def add(self, covariate: Covariate) -> None:
+        self.covariates.append(covariate)
+
+    def addCovariate(self, covariate: Covariate) -> None:
+        self.add(covariate)
+
+    def addToColl(self, covariate: Covariate) -> None:
+        self.add(covariate)
+
+    def get(self, name: str) -> Covariate:
+        for cov in self.covariates:
+            if cov.name == name:
+                return cov
+        raise KeyError(f"Covariate '{name}' not found")
+
+    def getCov(self, name: str) -> Covariate:
+        return self.get(name)
+
+    def dataToMatrix(self, names: Sequence[str] | None = None) -> tuple[np.ndarray, np.ndarray, list[str]]:
+        if not self.covariates:
+            raise ValueError("CovariateCollection is empty")
+        selected = self.covariates
+        if names is not None:
+            keep = set(names)
+            selected = [cov for cov in self.covariates if cov.name in keep]
+            if not selected:
+                raise ValueError("No covariates matched requested names")
+
+        base_time = selected[0].time
+        x_parts: list[np.ndarray] = []
+        labels: list[str] = []
+        for cov in selected:
+            if cov.time.shape != base_time.shape or np.max(np.abs(cov.time - base_time)) > 1e-9:
+                raise ValueError("All covariates must share the same time grid")
+            x_parts.append(np.asarray(cov.data, dtype=float))
+            labels.extend(cov.dataLabels)
+        return base_time, np.hstack(x_parts), labels
+
+
+class SpikeTrainCollection:
+    def __init__(self, trains: Sequence[nspikeTrain] | nspikeTrain) -> None:
+        if isinstance(trains, nspikeTrain):
+            trains = [trains]
+        self._trains = list(trains)
+        if len(self._trains) == 0:
+            raise ValueError("SpikeTrainCollection requires at least one spike train")
+
+        self.minTime = float(min(s.minTime for s in self._trains))
+        self.maxTime = float(max(s.maxTime for s in self._trains))
+        rates = [s.sampleRate for s in self._trains if s.sampleRate > 0]
+        self.sampleRate = float(np.median(rates)) if rates else 1000.0
+
+    @property
+    def num_spike_trains(self) -> int:
+        return len(self._trains)
+
+    @property
+    def numSpikeTrains(self) -> int:
+        return self.num_spike_trains
+
+    def __iter__(self):
+        for tr in self._trains:
+            yield tr
+
+    def get_nst(self, idx: int) -> nspikeTrain:
+        if idx < 0 or idx >= len(self._trains):
+            raise IndexError("SpikeTrainCollection index out of bounds (0-based indexing).")
+        return self._trains[idx]
+
+    def getNST(self, idx: int) -> nspikeTrain:
+        if idx < 1 or idx > len(self._trains):
+            raise IndexError("nstColl index out of bounds (1-based indexing).")
+        return self._trains[idx - 1]
+
+    def setMinTime(self, value: float) -> None:
+        self.minTime = float(value)
+
+    def setMaxTime(self, value: float) -> None:
+        self.maxTime = float(value)
+
+    def dataToMatrix(self, bin_edges: Sequence[float]) -> np.ndarray:
+        edges = np.asarray(bin_edges, dtype=float).reshape(-1)
+        if edges.ndim != 1 or edges.size < 2:
+            raise ValueError("bin_edges must be a 1D array with at least two points")
+        rows = [np.asarray(spk.to_binned_counts(edges), dtype=float) for spk in self._trains]
+        return np.vstack(rows)
+
+    def plot(self, *_, **__) -> None:
+        return None
+
+    def psth(self, binwidth: float) -> Covariate:
+        if binwidth <= 0:
+            raise ValueError("binwidth must be > 0")
+        min_time = float(self.minTime)
+        max_time = float(self.maxTime)
+        if max_time < min_time:
+            raise ValueError("maxTime must be >= minTime")
+
+        # Match MATLAB nstColl.psth edge construction:
+        #   windowTimes = minTime:binwidth:maxTime;
+        #   if ~any(windowTimes==maxTime), append maxTime
+        span = max_time - min_time
+        n_full = int(np.floor((span / binwidth) + 1e-12))
+        window_times = min_time + np.arange(n_full + 1, dtype=float) * float(binwidth)
+        if window_times.size == 0:
+            window_times = np.array([min_time, max_time], dtype=float)
+        if window_times[-1] < max_time - 1e-12:
+            window_times = np.append(window_times, max_time)
+        elif window_times[-1] > max_time + 1e-12:
+            window_times[-1] = max_time
+        if window_times.size < 2:
+            window_times = np.array([min_time, max_time], dtype=float)
+            if window_times[1] <= window_times[0]:
+                window_times[1] = window_times[0] + float(binwidth)
+
+        # MATLAB histc-like counting produces one extra terminal bin for x==max;
+        # nstColl.psth discards that final bin before normalizing.
+        psth_hist = np.zeros(window_times.size, dtype=float)
+        for spk in self._trains:
+            spikes = np.asarray(spk.spikeTimes, dtype=float).reshape(-1)
+            if spikes.size == 0:
+                continue
+            valid = np.isfinite(spikes) & (spikes >= window_times[0]) & (spikes <= window_times[-1])
+            if not np.any(valid):
+                continue
+            idx = np.searchsorted(window_times, spikes[valid], side="right") - 1
+            idx = np.clip(idx, 0, window_times.size - 1)
+            psth_hist += np.bincount(idx, minlength=window_times.size).astype(float)
+
+        rate = psth_hist[:-1] / binwidth / float(len(self._trains))
+        centers = (window_times[1:] + window_times[:-1]) * 0.5
+        return Covariate(centers, rate, "PSTH", "time", "s", "spikes/sec", ["psth"])
+
+    def psthGLM(self, binwidth: float):
+        psth_signal = self.psth(binwidth)
+        return psth_signal, None, None
+
+
+@dataclass
+class TrialConfig:
+    covMask: Sequence[Sequence[str]] | Sequence[str]
+    sampleRate: float
+    history: object | None = None
+    ensCovHist: object | None = None
+    covLag: object | None = None
+    name: str = ""
+
+    def setName(self, name: str) -> None:
+        self.name = str(name)
+
+    @property
+    def covariate_names(self) -> list[str]:
+        if not self.covMask:
+            return []
+        names: list[str] = []
+        for item in self.covMask:
+            if isinstance(item, str):
+                names.append(item)
+            else:
+                names.extend([str(v) for v in item])
+        return names
+
+
+class ConfigCollection:
+    def __init__(self, configs: Sequence[TrialConfig] | None = None) -> None:
+        self.configs: list[TrialConfig] = list(configs or [])
+
+    @property
+    def numConfigs(self) -> int:
+        return len(self.configs)
+
+    @property
+    def configArray(self) -> list[TrialConfig]:
+        return self.configs
+
+    def add_config(self, cfg: TrialConfig) -> None:
+        self.configs.append(cfg)
+
+    def addConfig(self, cfg: TrialConfig) -> None:
+        self.add_config(cfg)
+
+    def get_config(self, idx: int) -> TrialConfig:
+        if idx < 0 or idx >= len(self.configs):
+            raise IndexError("ConfigCollection index out of bounds (0-based indexing).")
+        return self.configs[idx]
+
+    def getConfig(self, idx: int) -> TrialConfig:
+        return self.configs[idx - 1]
+
+    def getConfigNames(self, index: Sequence[int] | None = None) -> list[str]:
+        if index is None:
+            index = list(range(1, self.numConfigs + 1))
+        out: list[str] = []
+        for i in index:
+            cfg = self.configs[i - 1]
+            out.append(cfg.name if cfg.name else f"Fit {i}")
+        return out
+
+
+class Trial:
+    def __init__(
+        self,
+        spike_collection: SpikeTrainCollection | None = None,
+        covariate_collection: CovariateCollection | None = None,
+        events: Events | None = None,
+        *,
+        spikeColl: SpikeTrainCollection | None = None,
+        covarColl: CovariateCollection | None = None,
+    ) -> None:
+        self.spike_collection = spike_collection if spike_collection is not None else spikeColl
+        self.covariate_collection = covariate_collection if covariate_collection is not None else covarColl
+        if self.spike_collection is None or self.covariate_collection is None:
+            raise ValueError("Trial requires both spike_collection and covariate_collection")
+        self.events = events
+
+    @property
+    def spikeColl(self) -> SpikeTrainCollection:
+        return self.spike_collection
+
+    @property
+    def covarColl(self) -> CovariateCollection:
+        return self.covariate_collection
+
+    def get_covariate_matrix(self, selected_covariates: Sequence[str] | None = None) -> tuple[np.ndarray, np.ndarray, list[str]]:
+        return self.covariate_collection.dataToMatrix(selected_covariates)
+
+    def getSpikeVector(self, bin_edges: Sequence[float], neuron_index: int = 1) -> np.ndarray:
+        return self.spike_collection.getNST(neuron_index).to_binned_counts(bin_edges)
+
+
+# Backward-compatible MATLAB-style aliases.
+CovColl = CovariateCollection
+nstColl = SpikeTrainCollection
+ConfigColl = ConfigCollection
+
+
+__all__ = [
+    "CovariateCollection",
+    "SpikeTrainCollection",
+    "TrialConfig",
+    "ConfigCollection",
+    "Trial",
+    "CovColl",
+    "nstColl",
+    "ConfigColl",
+]
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 00000000..9356a4c9
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,35 @@
+[build-system]
+requires = ["setuptools>=68", "wheel"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "nstat-toolbox"
+version = "0.1.0"
+description = "Python port of the nSTAT toolbox"
+readme = "README.md"
+requires-python = ">=3.10"
+authors = [
+  { name = "Cajigas Lab" }
+]
+dependencies = [
+  "numpy>=1.24",
+  "scipy>=1.10",
+  "matplotlib>=3.7"
+]
+
+[project.optional-dependencies]
+dev = [
+  "pytest>=8.0",
+  "nbformat>=5.9",
+  "sphinx>=7.0",
+]
+
+[tool.setuptools.packages.find]
+where = ["."]
+include = ["nstat*"]
+
+[tool.setuptools.package-data]
+"nstat.data" = ["manifest.json"]
+
+[project.scripts]
+nstat-paper-examples = "nstat.paper_examples:main"
diff --git a/python/examples/README.md b/python/examples/README.md
deleted file mode 100644
index fe1179c3..00000000
--- a/python/examples/README.md
+++ /dev/null
@@ -1,12 +0,0 @@
-# Python nSTAT Examples
-
-Run examples from repository root:
-
-```bash
-python3 python/examples/basic_data_workflow.py
-python3 python/examples/simulate_population_psth.py
-python3 python/examples/fit_poisson_glm.py
-```
-
-These examples use the lightweight `python/nstat` starter package in this branch.
-
diff --git a/python/nstat/__init__.py b/python/nstat/__init__.py
deleted file mode 100644
index f29d8d49..00000000
--- a/python/nstat/__init__.py
+++ /dev/null
@@ -1,22 +0,0 @@
-"""Minimal Python nSTAT starter toolkit.
-
-This package is a small, dependency-light foundation for Python examples
-while the full nSTAT port is under development.
-"""
-
-from .analysis import psth, spike_indicator
-from .core import Covariate, SpikeTrain
-from .glm import PoissonGLMResult, fit_poisson_glm
-from .simulation import simulate_cif_from_stimulus, simulate_poisson_from_rate
-
-__all__ = [
-    "Covariate",
-    "SpikeTrain",
-    "psth",
-    "spike_indicator",
-    "PoissonGLMResult",
-    "fit_poisson_glm",
-    "simulate_poisson_from_rate",
-    "simulate_cif_from_stimulus",
-]
-
diff --git a/python/nstat/analysis.py b/python/nstat/analysis.py
deleted file mode 100644
index 2dbfbb72..00000000
--- a/python/nstat/analysis.py
+++ /dev/null
@@ -1,42 +0,0 @@
-from __future__ import annotations
-
-from typing import Sequence
-
-import numpy as np
-
-from .core import SpikeTrain
-
-
-def spike_indicator(spike_train: SpikeTrain, time: Sequence[float]) -> np.ndarray:
-    """Convert spike times to a binary per-sample indicator on a time grid."""
-
-    t = np.asarray(time, dtype=float).reshape(-1)
-    if t.size < 2:
-        raise ValueError("time must include at least two samples.")
-    if np.any(np.diff(t) <= 0):
-        raise ValueError("time must be strictly increasing.")
-
-    dt = np.diff(t)
-    edges = np.concatenate([t, [t[-1] + dt[-1]]])
-    counts = spike_train.to_binned_counts(edges)
-    return (counts > 0).astype(float)
-
-
-def psth(
-    spike_trains: Sequence[SpikeTrain], bin_edges: Sequence[float]
-) -> tuple[np.ndarray, np.ndarray]:
-    """Compute per-bin mean firing rate (PSTH) across trials."""
-
-    if len(spike_trains) == 0:
-        raise ValueError("spike_trains must contain at least one trial.")
-
-    edges = np.asarray(bin_edges, dtype=float).reshape(-1)
-    if edges.size < 2:
-        raise ValueError("bin_edges must contain at least 2 values.")
-    if np.any(np.diff(edges) <= 0):
-        raise ValueError("bin_edges must be strictly increasing.")
-
-    counts = np.vstack([trial.to_binned_counts(edges) for trial in spike_trains])
-    mean_rate_hz = counts.mean(axis=0) / np.diff(edges)
-    return mean_rate_hz, counts
-
diff --git a/python/nstat/core.py b/python/nstat/core.py
deleted file mode 100644
index 1657421e..00000000
--- a/python/nstat/core.py
+++ /dev/null
@@ -1,89 +0,0 @@
-from __future__ import annotations
-
-from dataclasses import dataclass
-from typing import Sequence
-
-import numpy as np
-
-
-def _as_1d_float(values: Sequence[float], name: str) -> np.ndarray:
-    array = np.asarray(values, dtype=float).reshape(-1)
-    if array.size == 0:
-        raise ValueError(f"{name} must be non-empty.")
-    return array
-
-
-@dataclass(frozen=True)
-class Covariate:
-    """Time-aligned covariate signal."""
-
-    time: np.ndarray
-    values: np.ndarray
-    name: str = "covariate"
-    units: str = ""
-
-    def __post_init__(self) -> None:
-        time = _as_1d_float(self.time, "time")
-        values = _as_1d_float(self.values, "values")
-        if time.shape[0] != values.shape[0]:
-            raise ValueError("time and values must have identical length.")
-        if np.any(np.diff(time) <= 0):
-            raise ValueError("time must be strictly increasing.")
-        object.__setattr__(self, "time", time)
-        object.__setattr__(self, "values", values)
-
-
-@dataclass(frozen=True)
-class SpikeTrain:
-    """Container for spike times in seconds."""
-
-    times: np.ndarray
-    t_start: float = 0.0
-    t_stop: float | None = None
-
-    def __post_init__(self) -> None:
-        times = np.asarray(self.times, dtype=float).reshape(-1)
-        if times.size:
-            times = np.sort(times)
-            if np.any(np.diff(times) < 0):
-                raise ValueError("spike times must be monotonic.")
-            t_start = float(min(self.t_start, times[0]))
-            t_stop = float(times[-1] if self.t_stop is None else self.t_stop)
-            if t_stop < t_start:
-                raise ValueError("t_stop must be >= t_start.")
-        else:
-            t_start = float(self.t_start)
-            t_stop = float(self.t_start if self.t_stop is None else self.t_stop)
-        object.__setattr__(self, "times", times)
-        object.__setattr__(self, "t_start", t_start)
-        object.__setattr__(self, "t_stop", t_stop)
-
-    @property
-    def n_spikes(self) -> int:
-        return int(self.times.shape[0])
-
-    @property
-    def duration(self) -> float:
-        return float(self.t_stop - self.t_start)
-
-    @property
-    def firing_rate_hz(self) -> float:
-        duration = self.duration
-        if duration <= 0:
-            return 0.0
-        return float(self.n_spikes / duration)
-
-    def interspike_intervals(self) -> np.ndarray:
-        if self.n_spikes < 2:
-            return np.array([], dtype=float)
-        return np.diff(self.times)
-
-    def to_binned_counts(self, bin_edges: Sequence[float]) -> np.ndarray:
-        edges = np.asarray(bin_edges, dtype=float).reshape(-1)
-        if edges.size < 2:
-            raise ValueError("bin_edges must contain at least 2 values.")
-        if np.any(np.diff(edges) <= 0):
-            raise ValueError("bin_edges must be strictly increasing.")
-        counts, _ = np.histogram(self.times, bins=edges)
-        return counts.astype(float)
-
diff --git a/python/nstat/simulation.py b/python/nstat/simulation.py
deleted file mode 100644
index 377d035c..00000000
--- a/python/nstat/simulation.py
+++ /dev/null
@@ -1,68 +0,0 @@
-from __future__ import annotations
-
-from typing import Sequence
-
-import numpy as np
-
-from .core import SpikeTrain
-
-
-def _validate_time_and_rate(
-    time: Sequence[float], rate_hz: Sequence[float]
-) -> tuple[np.ndarray, np.ndarray]:
-    time_arr = np.asarray(time, dtype=float).reshape(-1)
-    rate_arr = np.asarray(rate_hz, dtype=float).reshape(-1)
-    if time_arr.size == 0 or rate_arr.size == 0:
-        raise ValueError("time and rate_hz must be non-empty.")
-    if time_arr.shape[0] != rate_arr.shape[0]:
-        raise ValueError("time and rate_hz must have identical length.")
-    if np.any(np.diff(time_arr) <= 0):
-        raise ValueError("time must be strictly increasing.")
-    if np.any(rate_arr < 0):
-        raise ValueError("rate_hz must be non-negative.")
-    return time_arr, rate_arr
-
-
-def simulate_poisson_from_rate(
-    time: Sequence[float], rate_hz: Sequence[float], rng: np.random.Generator | None = None
-) -> SpikeTrain:
-    """Simulate spikes from an inhomogeneous Poisson process.
-
-    This uses one Bernoulli draw per sample with p = 1 - exp(-rate * dt),
-    which is accurate for fine time grids.
-    """
-
-    if rng is None:
-        rng = np.random.default_rng()
-    time_arr, rate_arr = _validate_time_and_rate(time, rate_hz)
-
-    dt = np.diff(time_arr)
-    dt_per_sample = np.empty_like(time_arr)
-    dt_per_sample[0] = dt[0]
-    dt_per_sample[1:] = dt
-
-    p_spike = 1.0 - np.exp(-rate_arr * dt_per_sample)
-    p_spike = np.clip(p_spike, 0.0, 1.0)
-    spikes = rng.random(time_arr.shape[0]) < p_spike
-    return SpikeTrain(time_arr[spikes], t_start=time_arr[0], t_stop=time_arr[-1])
-
-
-def simulate_cif_from_stimulus(
-    time: Sequence[float],
-    stimulus: Sequence[float],
-    beta0: float = -3.0,
-    beta1: float = 1.0,
-    rng: np.random.Generator | None = None,
-) -> tuple[SpikeTrain, np.ndarray, np.ndarray]:
-    """Simulate a simple CIF model: lambda(t) = exp(beta0 + beta1 * stimulus)."""
-
-    stim_arr = np.asarray(stimulus, dtype=float).reshape(-1)
-    time_arr = np.asarray(time, dtype=float).reshape(-1)
-    if stim_arr.shape[0] != time_arr.shape[0]:
-        raise ValueError("stimulus and time must have identical length.")
-
-    linear_predictor = beta0 + beta1 * stim_arr
-    rate_hz = np.exp(np.clip(linear_predictor, -20.0, 20.0))
-    spike_train = simulate_poisson_from_rate(time_arr, rate_hz, rng=rng)
-    return spike_train, rate_hz, linear_predictor
-
diff --git a/reports/examples_notebook_verification.json b/reports/examples_notebook_verification.json
new file mode 100644
index 00000000..eb50065b
--- /dev/null
+++ b/reports/examples_notebook_verification.json
@@ -0,0 +1,458 @@
+{
+  "summary": {
+    "total_examples": 25,
+    "python_modules_ok": 25,
+    "notebooks_ok": 25,
+    "topic_alignment_ok": 25
+  },
+  "rows": [
+    {
+      "example": "SignalObjExamples",
+      "title": "Using the SignalObj Class",
+      "matlab_target": "SignalObjExamples.html",
+      "python_module_ok": true,
+      "python_module_error": "",
+      "python_output_keys": [
+        "dimension",
+        "parity",
+        "sample_rate",
+        "topic"
+      ],
+      "notebook_ok": true,
+      "notebook_error": "",
+      "notebook_code_cells": 3,
+      "topic_alignment_ok": true
+    },
+    {
+      "example": "CovariateExamples",
+      "title": "Using the Covariate Class",
+      "matlab_target": "CovariateExamples.html",
+      "python_module_ok": true,
+      "python_module_error": "",
+      "python_output_keys": [
+        "mean",
+        "parity",
+        "std",
+        "topic"
+      ],
+      "notebook_ok": true,
+      "notebook_error": "",
+      "notebook_code_cells": 3,
+      "topic_alignment_ok": true
+    },
+    {
+      "example": "CovCollExamples",
+      "title": "Using the CovColl Class",
+      "matlab_target": "CovCollExamples.html",
+      "python_module_ok": true,
+      "python_module_error": "",
+      "python_output_keys": [
+        "labels",
+        "matrix_shape",
+        "parity",
+        "topic"
+      ],
+      "notebook_ok": true,
+      "notebook_error": "",
+      "notebook_code_cells": 3,
+      "topic_alignment_ok": true
+    },
+    {
+      "example": "nSpikeTrainExamples",
+      "title": "Using the nSpikeTrain Class",
+      "matlab_target": "nSpikeTrainExamples.html",
+      "python_module_ok": true,
+      "python_module_error": "",
+      "python_output_keys": [
+        "n_spikes",
+        "parity",
+        "rate_hz",
+        "topic"
+      ],
+      "notebook_ok": true,
+      "notebook_error": "",
+      "notebook_code_cells": 3,
+      "topic_alignment_ok": true
+    },
+    {
+      "example": "nstCollExamples",
+      "title": "Using the nstColl Class",
+      "matlab_target": "nstCollExamples.html",
+      "python_module_ok": true,
+      "python_module_error": "",
+      "python_output_keys": [
+        "num_trains",
+        "parity",
+        "psth_points",
+        "topic"
+      ],
+      "notebook_ok": true,
+      "notebook_error": "",
+      "notebook_code_cells": 3,
+      "topic_alignment_ok": true
+    },
+    {
+      "example": "EventsExamples",
+      "title": "Using the Events Class",
+      "matlab_target": "EventsExamples.html",
+      "python_module_ok": true,
+      "python_module_error": "",
+      "python_output_keys": [
+        "n_events",
+        "parity",
+        "topic"
+      ],
+      "notebook_ok": true,
+      "notebook_error": "",
+      "notebook_code_cells": 3,
+      "topic_alignment_ok": true
+    },
+    {
+      "example": "HistoryExamples",
+      "title": "Using the History Class",
+      "matlab_target": "HistoryExamples.html",
+      "python_module_ok": true,
+      "python_module_error": "",
+      "python_output_keys": [
+        "design_shape",
+        "lags",
+        "parity",
+        "topic"
+      ],
+      "notebook_ok": true,
+      "notebook_error": "",
+      "notebook_code_cells": 3,
+      "topic_alignment_ok": true
+    },
+    {
+      "example": "TrialExamples",
+      "title": "Using the Trial Class",
+      "matlab_target": "TrialExamples.html",
+      "python_module_ok": true,
+      "python_module_error": "",
+      "python_output_keys": [
+        "covariate_rows",
+        "neurons",
+        "parity",
+        "topic"
+      ],
+      "notebook_ok": true,
+      "notebook_error": "",
+      "notebook_code_cells": 3,
+      "topic_alignment_ok": true
+    },
+    {
+      "example": "TrialConfigExamples",
+      "title": "Using the TrialConfig Class",
+      "matlab_target": "TrialConfigExamples.html",
+      "python_module_ok": true,
+      "python_module_error": "",
+      "python_output_keys": [
+        "covariates",
+        "parity",
+        "sample_rate",
+        "topic"
+      ],
+      "notebook_ok": true,
+      "notebook_error": "",
+      "notebook_code_cells": 3,
+      "topic_alignment_ok": true
+    },
+    {
+      "example": "ConfigCollExamples",
+      "title": "Using the ConfigColl Class",
+      "matlab_target": "ConfigCollExamples.html",
+      "python_module_ok": true,
+      "python_module_error": "",
+      "python_output_keys": [
+        "names",
+        "num_configs",
+        "parity",
+        "topic"
+      ],
+      "notebook_ok": true,
+      "notebook_error": "",
+      "notebook_code_cells": 3,
+      "topic_alignment_ok": true
+    },
+    {
+      "example": "AnalysisExamples",
+      "title": "Using the Analysis Class",
+      "matlab_target": "AnalysisExamples.html",
+      "python_module_ok": true,
+      "python_module_error": "",
+      "python_output_keys": [
+        "first_aic",
+        "num_results",
+        "parity",
+        "topic"
+      ],
+      "notebook_ok": true,
+      "notebook_error": "",
+      "notebook_code_cells": 3,
+      "topic_alignment_ok": true
+    },
+    {
+      "example": "FitResultExamples",
+      "title": "Using the FitResult Class",
+      "matlab_target": "FitResultExamples.html",
+      "python_module_ok": true,
+      "python_module_error": "",
+      "python_output_keys": [
+        "bic",
+        "coeffs",
+        "parity",
+        "topic"
+      ],
+      "notebook_ok": true,
+      "notebook_error": "",
+      "notebook_code_cells": 3,
+      "topic_alignment_ok": true
+    },
+    {
+      "example": "FitResSummaryExamples",
+      "title": "Using the FitResSummary Class",
+      "matlab_target": "FitResSummaryExamples.html",
+      "python_module_ok": true,
+      "python_module_error": "",
+      "python_output_keys": [
+        "mean_aic",
+        "mean_bic",
+        "parity",
+        "topic"
+      ],
+      "notebook_ok": true,
+      "notebook_error": "",
+      "notebook_code_cells": 3,
+      "topic_alignment_ok": true
+    },
+    {
+      "example": "PPThinning",
+      "title": "Point Process Simulation via Thinning",
+      "matlab_target": "PPThinning.html",
+      "python_module_ok": true,
+      "python_module_error": "",
+      "python_output_keys": [
+        "num_realizations",
+        "parity",
+        "topic"
+      ],
+      "notebook_ok": true,
+      "notebook_error": "",
+      "notebook_code_cells": 3,
+      "topic_alignment_ok": true
+    },
+    {
+      "example": "PSTHEstimation",
+      "title": "Example Data Analysis - Simulated Data - Computing a Peri-Stimulus Time Histogram (PSTH)",
+      "matlab_target": "PSTHEstimation.html",
+      "python_module_ok": true,
+      "python_module_error": "",
+      "python_output_keys": [
+        "num_realizations",
+        "parity",
+        "peak_rate",
+        "topic"
+      ],
+      "notebook_ok": true,
+      "notebook_error": "",
+      "notebook_code_cells": 3,
+      "topic_alignment_ok": true
+    },
+    {
+      "example": "ValidationDataSet",
+      "title": "Example Data Analysis - Simulated Constant (Piecewise Constant) Rate Poisson",
+      "matlab_target": "ValidationDataSet.html",
+      "python_module_ok": true,
+      "python_module_error": "",
+      "python_output_keys": [
+        "num_trials",
+        "parity",
+        "psth_mean_hz",
+        "psth_peak_hz",
+        "topic",
+        "total_spikes"
+      ],
+      "notebook_ok": true,
+      "notebook_error": "",
+      "notebook_code_cells": 3,
+      "topic_alignment_ok": true
+    },
+    {
+      "example": "mEPSCAnalysis",
+      "title": "Example Data Analysis - Miniature Excitatory Post-Synaptic Currents (mEPSCs)",
+      "matlab_target": "mEPSCAnalysis.html",
+      "python_module_ok": true,
+      "python_module_error": "",
+      "python_output_keys": [
+        "const_condition_spikes",
+        "const_model_aic",
+        "const_model_bic",
+        "decreasing_condition_spikes",
+        "dt_seconds",
+        "parity",
+        "piecewise_history_model_aic",
+        "piecewise_history_model_bic",
+        "piecewise_model_aic",
+        "piecewise_model_bic",
+        "topic"
+      ],
+      "notebook_ok": true,
+      "notebook_error": "",
+      "notebook_code_cells": 3,
+      "topic_alignment_ok": true
+    },
+    {
+      "example": "PPSimExample",
+      "title": "Example Data Analysis - Simulated Explicit Stimulus and History",
+      "matlab_target": "PPSimExample.html",
+      "python_module_ok": true,
+      "python_module_error": "",
+      "python_output_keys": [
+        "model1_aic",
+        "model1_bic",
+        "model2_aic",
+        "model2_bic",
+        "model3_aic",
+        "model3_bic",
+        "n_samples",
+        "parity",
+        "topic"
+      ],
+      "notebook_ok": true,
+      "notebook_error": "",
+      "notebook_code_cells": 3,
+      "topic_alignment_ok": true
+    },
+    {
+      "example": "ExplicitStimulusWhiskerData",
+      "title": "Example Data Analysis - Explicit Stimulus",
+      "matlab_target": "ExplicitStimulusWhiskerData.html",
+      "python_module_ok": true,
+      "python_module_error": "",
+      "python_output_keys": [
+        "model1_aic",
+        "model1_bic",
+        "model2_aic",
+        "model2_bic",
+        "model3_aic",
+        "model3_bic",
+        "n_samples",
+        "parity",
+        "topic"
+      ],
+      "notebook_ok": true,
+      "notebook_error": "",
+      "notebook_code_cells": 3,
+      "topic_alignment_ok": true
+    },
+    {
+      "example": "HippocampalPlaceCellExample",
+      "title": "Example Data Analysis - Hippocampal Place Cell Receptive Field Estimation",
+      "matlab_target": "HippocampalPlaceCellExample.html",
+      "python_module_ok": true,
+      "python_module_error": "",
+      "python_output_keys": [
+        "mean_delta_aic_gaussian_minus_zernike",
+        "mean_delta_bic_gaussian_minus_zernike",
+        "num_cells_fit",
+        "parity",
+        "topic"
+      ],
+      "notebook_ok": true,
+      "notebook_error": "",
+      "notebook_code_cells": 3,
+      "topic_alignment_ok": true
+    },
+    {
+      "example": "DecodingExample",
+      "title": "Example Data Analysis - Decoding Univariate Simulated Stimuli (No History Effect)",
+      "matlab_target": "DecodingExample.html",
+      "python_module_ok": true,
+      "python_module_error": "",
+      "python_output_keys": [
+        "decode_rmse",
+        "num_cells",
+        "parity",
+        "topic"
+      ],
+      "notebook_ok": true,
+      "notebook_error": "",
+      "notebook_code_cells": 3,
+      "topic_alignment_ok": true
+    },
+    {
+      "example": "DecodingExampleWithHist",
+      "title": "Example Data Analysis - Decoding Univariate Simulated Stimuli with and without History Effect",
+      "matlab_target": "DecodingExampleWithHist.html",
+      "python_module_ok": true,
+      "python_module_error": "",
+      "python_output_keys": [
+        "decode_rmse_x",
+        "decode_rmse_y",
+        "num_cells",
+        "num_samples",
+        "parity",
+        "topic"
+      ],
+      "notebook_ok": true,
+      "notebook_error": "",
+      "notebook_code_cells": 3,
+      "topic_alignment_ok": true
+    },
+    {
+      "example": "StimulusDecode2D",
+      "title": "Example Data Analysis - Decoding Bivariate Simulated Stimuli",
+      "matlab_target": "StimulusDecode2D.html",
+      "python_module_ok": true,
+      "python_module_error": "",
+      "python_output_keys": [
+        "decode_rmse_x",
+        "decode_rmse_y",
+        "num_cells",
+        "num_samples",
+        "parity",
+        "topic"
+      ],
+      "notebook_ok": true,
+      "notebook_error": "",
+      "notebook_code_cells": 3,
+      "topic_alignment_ok": true
+    },
+    {
+      "example": "NetworkTutorial",
+      "title": "Example Data Analysis - Two Neuron Network Simulation and Estimation of Ensemble Effect",
+      "matlab_target": "NetworkTutorial.html",
+      "python_module_ok": true,
+      "python_module_error": "",
+      "python_output_keys": [
+        "neuron_count",
+        "parity",
+        "psth_peak",
+        "samples",
+        "topic"
+      ],
+      "notebook_ok": true,
+      "notebook_error": "",
+      "notebook_code_cells": 3,
+      "topic_alignment_ok": true
+    },
+    {
+      "example": "nSTATPaperExamples",
+      "title": "nSTAT Paper Examples",
+      "matlab_target": "nSTATPaperExamples.html",
+      "python_module_ok": true,
+      "python_module_error": "",
+      "python_output_keys": [
+        "experiments",
+        "parity",
+        "summary",
+        "topic"
+      ],
+      "notebook_ok": true,
+      "notebook_error": "",
+      "notebook_code_cells": 3,
+      "topic_alignment_ok": true
+    }
+  ]
+}
\ No newline at end of file
diff --git a/reports/implemented_method_coverage.json b/reports/implemented_method_coverage.json
new file mode 100644
index 00000000..e1c36fbb
--- /dev/null
+++ b/reports/implemented_method_coverage.json
@@ -0,0 +1,30 @@
+{
+  "summary": {
+    "implemented_method_count": 34,
+    "smoke_covered_count": 34,
+    "missing_in_smoke_count": 0,
+    "extra_in_smoke_count": 0,
+    "implemented_class_count": 13,
+    "docs_class_covered_count": 13,
+    "missing_doc_class_count": 0
+  },
+  "missing_in_smoke": [],
+  "extra_in_smoke": [],
+  "doc_class_coverage": {
+    "Analysis": true,
+    "CIF": true,
+    "ConfidenceInterval": true,
+    "ConfigColl": true,
+    "CovColl": true,
+    "DecodingAlgorithms": true,
+    "Events": true,
+    "FitResSummary": true,
+    "FitResult": true,
+    "History": true,
+    "Trial": true,
+    "TrialConfig": true,
+    "nstColl": true
+  },
+  "missing_doc_classes": [],
+  "pass": true
+}
\ No newline at end of file
diff --git a/reports/matlab_smoke_input.json b/reports/matlab_smoke_input.json
new file mode 100644
index 00000000..ed8f7ec6
--- /dev/null
+++ b/reports/matlab_smoke_input.json
@@ -0,0 +1,172 @@
+[
+  {
+    "source": "helpfiles/AnalysisExamples.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/AnalysisExamples2.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/ClassDefinitions.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/ConfigCollExamples.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/CovCollExamples.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/CovariateExamples.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/DecodingExample.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/DecodingExampleWithHist.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/EventsExamples.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/Examples.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/ExplicitStimulusWhiskerData.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/FitResSummaryExamples.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/FitResultExamples.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/HippocampalPlaceCellExample.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/HistoryExamples.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/HybridFilterExample.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/NetworkTutorial.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/NeuralSpikeAnalysis_top.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/PPSimExample.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/PPThinning.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/PSTHEstimation.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/SignalObjExamples.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/StimulusDecode2D.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/TrialConfigExamples.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/TrialExamples.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/ValidationDataSet.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/mEPSCAnalysis.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/nSTATPaperExamples.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/nSpikeTrainExamples.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/nstCollExamples.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "helpfiles/temp.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/nearestSPD_demo.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "nSTAT_Install.m",
+    "kind": "script",
+    "function_name": ""
+  },
+  {
+    "source": "python/reports/matlab_smoke_runner.m",
+    "kind": "script",
+    "function_name": ""
+  }
+]
\ No newline at end of file
diff --git a/reports/matlab_smoke_runner.m b/reports/matlab_smoke_runner.m
new file mode 100644
index 00000000..643ddbf3
--- /dev/null
+++ b/reports/matlab_smoke_runner.m
@@ -0,0 +1,42 @@
+
+repo = '/Users/iahncajigas/Library/CloudStorage/Dropbox/Research/Matlab/nSTAT_currentRelease_Local';
+inFile = '/Users/iahncajigas/Library/CloudStorage/Dropbox/Research/Matlab/nSTAT_currentRelease_Local/python/reports/matlab_smoke_input.json';
+outFile = '/Users/iahncajigas/Library/CloudStorage/Dropbox/Research/Matlab/nSTAT_currentRelease_Local/python/reports/matlab_smoke_output.json';
+set(0,'DefaultFigureVisible','off');
+cfg = jsondecode(fileread(inFile));
+n = numel(cfg);
+res = repmat(struct('source','','ok',false,'message',''), n, 1);
+for i = 1:n
+    src = '';
+    kind = '';
+    fn = '';
+    if isfield(cfg(i), 'source')
+        src = char(cfg(i).source);
+    end
+    if isfield(cfg(i), 'kind')
+        kind = char(cfg(i).kind);
+    end
+    if isfield(cfg(i), 'function_name')
+        fn = char(cfg(i).function_name);
+    end
+    try
+        restoredefaultpath;
+        cd(repo);
+        addpath(genpath(repo),'-begin');
+        if strcmp(kind,'script')
+            run(fullfile(repo, src));
+        else
+            feval(fn);
+        end
+        res(i).ok = true;
+        res(i).message = 'ok';
+    catch ME
+        res(i).ok = false;
+        res(i).message = [ME.identifier ' | ' ME.message];
+    end
+    res(i).source = src;
+end
+fid = fopen(outFile,'w');
+fprintf(fid,'%s',jsonencode(res));
+fclose(fid);
+exit(0);
diff --git a/reports/method_parity_matrix.json b/reports/method_parity_matrix.json
new file mode 100644
index 00000000..228aca11
--- /dev/null
+++ b/reports/method_parity_matrix.json
@@ -0,0 +1,2897 @@
+{
+  "summary": {
+    "implemented": 34,
+    "planned": 428,
+    "intentionally_omitted": 39,
+    "total": 501
+  },
+  "implemented_methods": [
+    {
+      "matlab_class": "Analysis",
+      "matlab_method": "RunAnalysisForAllNeurons"
+    },
+    {
+      "matlab_class": "Analysis",
+      "matlab_method": "RunAnalysisForNeuron"
+    },
+    {
+      "matlab_class": "CIF",
+      "matlab_method": "simulateCIFByThinningFromLambda"
+    },
+    {
+      "matlab_class": "ConfidenceInterval",
+      "matlab_method": "setColor"
+    },
+    {
+      "matlab_class": "ConfigColl",
+      "matlab_method": "addConfig"
+    },
+    {
+      "matlab_class": "ConfigColl",
+      "matlab_method": "getConfig"
+    },
+    {
+      "matlab_class": "ConfigColl",
+      "matlab_method": "getConfigNames"
+    },
+    {
+      "matlab_class": "CovColl",
+      "matlab_method": "addToColl"
+    },
+    {
+      "matlab_class": "CovColl",
+      "matlab_method": "dataToMatrix"
+    },
+    {
+      "matlab_class": "CovColl",
+      "matlab_method": "getCov"
+    },
+    {
+      "matlab_class": "DecodingAlgorithms",
+      "matlab_method": "PPDecodeFilter"
+    },
+    {
+      "matlab_class": "DecodingAlgorithms",
+      "matlab_method": "PPDecodeFilterLinear"
+    },
+    {
+      "matlab_class": "DecodingAlgorithms",
+      "matlab_method": "kalman_filter"
+    },
+    {
+      "matlab_class": "Events",
+      "matlab_method": "fromStructure"
+    },
+    {
+      "matlab_class": "Events",
+      "matlab_method": "plot"
+    },
+    {
+      "matlab_class": "Events",
+      "matlab_method": "toStructure"
+    },
+    {
+      "matlab_class": "FitResSummary",
+      "matlab_method": "getDiffAIC"
+    },
+    {
+      "matlab_class": "FitResSummary",
+      "matlab_method": "getDiffBIC"
+    },
+    {
+      "matlab_class": "FitResSummary",
+      "matlab_method": "plotSummary"
+    },
+    {
+      "matlab_class": "FitResult",
+      "matlab_method": "KSPlot"
+    },
+    {
+      "matlab_class": "FitResult",
+      "matlab_method": "fromStructure"
+    },
+    {
+      "matlab_class": "FitResult",
+      "matlab_method": "getCoeffs"
+    },
+    {
+      "matlab_class": "FitResult",
+      "matlab_method": "getHistCoeffs"
+    },
+    {
+      "matlab_class": "FitResult",
+      "matlab_method": "mergeResults"
+    },
+    {
+      "matlab_class": "FitResult",
+      "matlab_method": "plotCoeffs"
+    },
+    {
+      "matlab_class": "FitResult",
+      "matlab_method": "plotInvGausTrans"
+    },
+    {
+      "matlab_class": "FitResult",
+      "matlab_method": "plotResidual"
+    },
+    {
+      "matlab_class": "FitResult",
+      "matlab_method": "plotResults"
+    },
+    {
+      "matlab_class": "FitResult",
+      "matlab_method": "plotSeqCorr"
+    },
+    {
+      "matlab_class": "FitResult",
+      "matlab_method": "toStructure"
+    },
+    {
+      "matlab_class": "History",
+      "matlab_method": "computeHistory"
+    },
+    {
+      "matlab_class": "Trial",
+      "matlab_method": "getSpikeVector"
+    },
+    {
+      "matlab_class": "TrialConfig",
+      "matlab_method": "setName"
+    },
+    {
+      "matlab_class": "nstColl",
+      "matlab_method": "dataToMatrix"
+    }
+  ],
+  "classes": [
+    {
+      "matlab_class": "SignalObj",
+      "matlab_source": "SignalObj.m",
+      "python_target": "nstat/signal.py",
+      "python_class": "Signal",
+      "python_methods": [
+        "as_array",
+        "copy",
+        "sub_signal",
+        "window"
+      ],
+      "methods": [
+        {
+          "matlab_method": "MTMspectrum",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "SignalObj",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "abs",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "alignTime",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "alignToMax",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "areDataLabelsEmpty",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "autocorrelation",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "cell2str",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "clearPlotProps",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "convertNamesToIndices",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "convertSigStructureToStructure",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "convertSimpleStructureToSigStructure",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "copySignal",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "crosscorrelation",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "ctranspose",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "dataToMatrix",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "dataToStructure",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "derivative",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "derivativeAt",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "filter",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "filtfilt",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "findGlobalPeak",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "findIndFromDataMask",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "findMaxima",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "findMinima",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "findNearestTimeIndex",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "findNearestTimeIndices",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "findPeaks",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getAvailableColor",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getData",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getIndexFromLabel",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getIndicesFromLabels",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getOrigDataSig",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getOriginalData",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getPlotProps",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getSigInTimeWindow",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getSubSignal",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getSubSignalFromInd",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getSubSignalFromNames",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getSubSignalsWithinNStd",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getTime",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getValueAt",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "integral",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "isLabelPresent",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "isMaskSet",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "ldivide",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "log",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "makeCompatible",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "max",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "mean",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "median",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "merge",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "min",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "minus",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "mode",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "mtimes",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "normWindowedSignal",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "periodogram",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "plot",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plotAllVariability",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plotPropsSet",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plotVariability",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plus",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "power",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "rdivide",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "resample",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "resampleMe",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "resetMask",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "restoreToOriginal",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setDataLabels",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setDataMask",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setMask",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setMaskByInd",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setMaskByLabels",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setMaxTime",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setMinTime",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setName",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setPlotProps",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setSampleRate",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setUnits",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setXUnits",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setXlabel",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setYLabel",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setYUnits",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setupPlots",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "shift",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "shiftMe",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "signalFromStruct",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "spectrogram",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "sqrt",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "std",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "times",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "transpose",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "uminus",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "uplus",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "windowedSignal",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "xcorr",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "xcov",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        }
+      ]
+    },
+    {
+      "matlab_class": "Covariate",
+      "matlab_source": "Covariate.m",
+      "python_target": "nstat/signal.py",
+      "python_class": "Covariate",
+      "python_methods": [
+        "from_values",
+        "standardize"
+      ],
+      "methods": [
+        {
+          "matlab_method": "Covariate",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "computeMeanPlusCI",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "copySignal",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "dataToStructure",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "filtfilt",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "fromStructure",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getSigRep",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getSubSignal",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "isConfIntervalSet",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "minus",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "plot",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plus",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setConfInterval",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "toStructure",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        }
+      ]
+    },
+    {
+      "matlab_class": "nspikeTrain",
+      "matlab_source": "nspikeTrain.m",
+      "python_target": "nstat/spikes.py",
+      "python_class": "SpikeTrain",
+      "python_methods": [
+        "inter_spike_intervals",
+        "to_counts"
+      ],
+      "methods": [
+        {
+          "matlab_method": "clearSigRep",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "computeRate",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "computeStatistics",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "fromStructure",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getFieldVal",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getISIs",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getLStatistic",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getMaxBinSizeBinary",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getMinISI",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getSigRep",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getSpikeTimes",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "isSigRepBinary",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "nspikeTrain",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "nstCopy",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "partitionNST",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "plot",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plotExponentialFit",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plotISIHistogram",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plotISISpectrumFunction",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plotJointISIHistogram",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plotProbPlot",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "resample",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "restoreToOriginal",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setMER",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setMaxTime",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setMinTime",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setName",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setSigRep",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "toStructure",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        }
+      ]
+    },
+    {
+      "matlab_class": "nstColl",
+      "matlab_source": "nstColl.m",
+      "python_target": "nstat/spikes.py",
+      "python_class": "SpikeTrainCollection",
+      "python_methods": [
+        "__iter__",
+        "to_matrix"
+      ],
+      "methods": [
+        {
+          "matlab_method": "BinarySigRep",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "addNeuronNamesToEnsCovColl",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "addSingleSpikeToColl",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "addToColl",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "areNeighborsSet",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "dataToMatrix",
+          "status": "implemented",
+          "rationale": "Implemented via Pythonic rename: to_matrix."
+        },
+        {
+          "matlab_method": "enforceSampleRate",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "ensureConsistancy",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "estimateVarianceAcrossTrials",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "findMaxSampleRate",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "fromStructure",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "generateUnitImpulseBasis",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getEnsembleNeuronCovariates",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getFieldVal",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getFirstSpikeTime",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getISIs",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getIndFromMask",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getIndFromMaskMinusOne",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getLastSpikeTime",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getMaxBinSizeBinary",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getMinISIs",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getNST",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getNSTFromName",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getNSTIndicesFromName",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getNSTnameFromInd",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getNSTnames",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getNeighbors",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getSpikeTimes",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getUniqueNSTnames",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "isNeuronMaskSet",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "isSigRepBinary",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "merge",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "nstColl",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "plot",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plotExponentialFit",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plotISIHistogram",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "psth",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "psthBars",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "psthGLM",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "resample",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "resetMask",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "restoreToOriginal",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setMask",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setMaxTime",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setMinTime",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setNeighbors",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setNeuronMask",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setNeuronMaskFromInd",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "shiftTime",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "ssglm",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "toSpikeTrain",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "toStructure",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "updateTimes",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        }
+      ]
+    },
+    {
+      "matlab_class": "CovColl",
+      "matlab_source": "CovColl.m",
+      "python_target": "nstat/trial.py",
+      "python_class": "CovariateCollection",
+      "python_methods": [
+        "__init__",
+        "add",
+        "addCovariate",
+        "addToColl",
+        "dataToMatrix",
+        "get",
+        "getCov",
+        "names"
+      ],
+      "methods": [
+        {
+          "matlab_method": "CovColl",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "addCovCellToColl",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "addCovCollection",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "addSingleCovToColl",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "addToColl",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "containsChars",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "copy",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "covIndFromSelector",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "dataToMatrix",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "dataToMatrixFromNames",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "dataToMatrixFromSel",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "dataToStructure",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "enforceSampleRate",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "findMaxTime",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "findMinTime",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "flattenCovMask",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "fromStructure",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "generateRemainingIndex",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "generateSelectorCell",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getAllCovLabels",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getCov",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "getCovDataMask",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getCovDimension",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getCovIndFromName",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getCovIndicesFromNames",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getCovLabelsFromMask",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getCovMaskFromSelector",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getSelectorFromMasks",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "isCovMaskSet",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "isCovPresent",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "isaSelectorCell",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "maskAwayAllExcept",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "maskAwayCov",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "maskAwayOnlyCov",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "nActCovar",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "numActCov",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "parseDataSelectorArray",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "plot",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "removeCovariate",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "removeFromColl",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "removeFromCollByIndices",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "resample",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "resetCovShift",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "resetMask",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "restoreToOriginal",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "restrictToTimeWindow",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setCovShift",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setMask",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setMasksFromSelector",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setMaxTime",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setMinTime",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setSampleRate",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "sumDimensions",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "toStructure",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "updateTimes",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        }
+      ]
+    },
+    {
+      "matlab_class": "TrialConfig",
+      "matlab_source": "TrialConfig.m",
+      "python_target": "nstat/trial.py",
+      "python_class": "TrialConfig",
+      "python_methods": [
+        "covariate_names",
+        "setName"
+      ],
+      "methods": [
+        {
+          "matlab_method": "TrialConfig",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "fromStructure",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getName",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setConfig",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setName",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "toStructure",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        }
+      ]
+    },
+    {
+      "matlab_class": "ConfigColl",
+      "matlab_source": "ConfigColl.m",
+      "python_target": "nstat/trial.py",
+      "python_class": "ConfigCollection",
+      "python_methods": [
+        "__init__",
+        "addConfig",
+        "add_config",
+        "configArray",
+        "getConfig",
+        "getConfigNames",
+        "get_config",
+        "numConfigs"
+      ],
+      "methods": [
+        {
+          "matlab_method": "ConfigColl",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "addConfig",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "fromStructure",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getConfig",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "getConfigNames",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "getSubsetConfigs",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setConfig",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setConfigNames",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "toStructure",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        }
+      ]
+    },
+    {
+      "matlab_class": "Trial",
+      "matlab_source": "Trial.m",
+      "python_target": "nstat/trial.py",
+      "python_class": "Trial",
+      "python_methods": [
+        "__init__",
+        "covarColl",
+        "getSpikeVector",
+        "get_covariate_matrix",
+        "spikeColl"
+      ],
+      "methods": [
+        {
+          "matlab_method": "Trial",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "addCov",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "findMaxSampleRate",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "findMaxTime",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "findMinSampleRate",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "findMinTime",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "flattenCovMask",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "flattenMask",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "fromStructure",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getAllCovLabels",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getAllLabels",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getCov",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getCovLabelsFromMask",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getCovSelectorFromMask",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getDesignMatrix",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getEnsCovLabels",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getEnsCovLabelsFromMask",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getEnsCovMatrix",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getEnsembleNeuronCovariates",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getEvents",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getHistForNeurons",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getHistLabels",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getHistMatrices",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getLabelsFromMask",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getNeuron",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getNeuronIndFromMask",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getNeuronIndFromName",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getNeuronNames",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getNeuronNeighbors",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getNumHist",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getNumUniqueNeurons",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getSpikeVector",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "getTrialPartition",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getUniqueNeuronNames",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "isCovMaskSet",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "isEnsCovHistSet",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "isHistSet",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "isMaskSet",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "isNeuronMaskSet",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "isSampleRateConsistent",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "makeConsistentSampleRate",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "makeConsistentTime",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "plot",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plotCovariates",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plotRaster",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "removeCov",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "resample",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "resampleEnsColl",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "resetCovMask",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "resetEnsCovMask",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "resetHistory",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "resetNeuronMask",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "restoreToOriginal",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setCovMask",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setEnsCovHist",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setEnsCovMask",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setHistory",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setMaxTime",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setMinTime",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setNeighbors",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setNeuronMask",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setSampleRate",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setTrialEvents",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setTrialPartition",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setTrialTimesFor",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "shiftCovariates",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "toStructure",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "updateTimePartitions",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        }
+      ]
+    },
+    {
+      "matlab_class": "History",
+      "matlab_source": "History.m",
+      "python_target": "nstat/history.py",
+      "python_class": "HistoryBasis",
+      "python_methods": [
+        "__init__",
+        "computeHistory",
+        "compute_history",
+        "design_matrix"
+      ],
+      "methods": [
+        {
+          "matlab_method": "History",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "computeHistory",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "computeNSTHistoryWindow",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "fromStructure",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "plot",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "setWindow",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "toFilter",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "toStructure",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        }
+      ]
+    },
+    {
+      "matlab_class": "Events",
+      "matlab_source": "Events.m",
+      "python_target": "nstat/events.py",
+      "python_class": "Events",
+      "python_methods": [
+        "__init__",
+        "fromStructure",
+        "plot",
+        "toStructure"
+      ],
+      "methods": [
+        {
+          "matlab_method": "Events",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "dsxy2figxy",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "fromStructure",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "plot",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "toStructure",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        }
+      ]
+    },
+    {
+      "matlab_class": "ConfidenceInterval",
+      "matlab_source": "ConfidenceInterval.m",
+      "python_target": "nstat/confidence_interval.py",
+      "python_class": "ConfidenceInterval",
+      "python_methods": [
+        "__init__",
+        "lower",
+        "setColor",
+        "upper"
+      ],
+      "methods": [
+        {
+          "matlab_method": "ConfidenceInterval",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "fromStructure",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "plot",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "setColor",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "setValue",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        }
+      ]
+    },
+    {
+      "matlab_class": "CIF",
+      "matlab_source": "CIF.m",
+      "python_target": "nstat/cif.py",
+      "python_class": "CIFModel",
+      "python_methods": [
+        "__post_init__",
+        "from_linear_terms",
+        "simulate",
+        "to_covariate"
+      ],
+      "methods": [
+        {
+          "matlab_method": "CIF",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "CIFCopy",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "evalFunctionWithVectorArgs",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "evalGradient",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "evalGradientLDGamma",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "evalGradientLog",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "evalGradientLogLDGamma",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "evalJacobian",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "evalJacobianLDGamma",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "evalJacobianLog",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "evalJacobianLogLDGamma",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "evalLDGamma",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "evalLambdaDelta",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "evalLogLDGamma",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "isSymBeta",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "resolveSimulinkModelName",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setHistory",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setSpikeTrain",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "simulateCIF",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "simulateCIFByThinning",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "simulateCIFByThinningFromLambda",
+          "status": "implemented",
+          "rationale": "Implemented via Pythonic rename: simulate."
+        }
+      ]
+    },
+    {
+      "matlab_class": "FitResult",
+      "matlab_source": "FitResult.m",
+      "python_target": "nstat/fit.py",
+      "python_class": "FitResult",
+      "python_methods": [
+        "KSPlot",
+        "__init__",
+        "fromStructure",
+        "getCoeffs",
+        "getHistCoeffs",
+        "lambdaCov",
+        "lambdaObj",
+        "lambdaSignal",
+        "lambda_",
+        "lambda_data",
+        "lambda_model",
+        "lambda_obj",
+        "lambda_rate",
+        "lambda_result",
+        "lambda_sig",
+        "lambda_time",
+        "lambda_values",
+        "mergeResults",
+        "plotCoeffs",
+        "plotInvGausTrans",
+        "plotResidual",
+        "plotResults",
+        "plotSeqCorr",
+        "toStructure"
+      ],
+      "methods": [
+        {
+          "matlab_method": "CellArrayToStructure",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "FitResult",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "KSPlot",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "addParamsToFit",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "computePlotParams",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "computeValLambda",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "evalLambda",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "fromStructure",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "getCoeffIndex",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getCoeffs",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "getHistCoeffs",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "getHistIndex",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getParam",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getPlotParams",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getSubsetFitResult",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getUniqueLabels",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "isValDataPresent",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "mapCovLabelsToUniqueLabels",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "mergeResults",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "plotCoeffs",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "plotCoeffsWithoutHistory",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plotHistCoeffs",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plotInvGausTrans",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "plotResidual",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "plotResults",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "plotSeqCorr",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "plotValidation",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "setFitResidual",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setInvGausStats",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setKSStats",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "setNeuronName",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "toStructure",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "xticklabel_rotate",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        }
+      ]
+    },
+    {
+      "matlab_class": "FitResSummary",
+      "matlab_source": "FitResSummary.m",
+      "python_target": "nstat/fit.py",
+      "python_class": "FitSummary",
+      "python_methods": [
+        "__init__",
+        "getDiffAIC",
+        "getDiffBIC",
+        "plotSummary"
+      ],
+      "methods": [
+        {
+          "matlab_method": "FitResSummary",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "binCoeffs",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "boxPlot",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "computeDiffMat",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "fromStructure",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getCoeffIndex",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getCoeffs",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getDiffAIC",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "getDiffBIC",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "getDifflogLL",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getHistCoeffs",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getHistIndex",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getSigCoeffs",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "getUniqueLabels",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "mapCovLabelsToUniqueLabels",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "plot2dCoeffSummary",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plot3dCoeffSummary",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plotAIC",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plotAllCoeffs",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plotBIC",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plotCoeffsWithoutHistory",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plotHistCoeffs",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plotIC",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plotKSSummary",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plotResidualSummary",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plotSummary",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "plotlogLL",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "setCoeffRange",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "toStructure",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "xticklabel_rotate",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        }
+      ]
+    },
+    {
+      "matlab_class": "Analysis",
+      "matlab_source": "Analysis.m",
+      "python_target": "nstat/analysis.py",
+      "python_class": "Analysis",
+      "python_methods": [
+        "RunAnalysisForAllNeurons",
+        "RunAnalysisForNeuron",
+        "psth",
+        "run_analysis_for_all_neurons",
+        "run_analysis_for_neuron"
+      ],
+      "methods": [
+        {
+          "matlab_method": "GLMFit",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "KSPlot",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "RunAnalysisForAllNeurons",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "RunAnalysisForNeuron",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "bnlrCG",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "compHistEnsCoeff",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "compHistEnsCoeffForAll",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "computeFitResidual",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "computeGrangerCausalityMatrix",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "computeHistLag",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "computeHistLagForAll",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "computeInvGausTrans",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "computeKSStats",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "computeNeighbors",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "fdr_bh",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "flatMaskCellToMat",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "ksdiscrete",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "plotCoeffs",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plotFitResidual",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plotInvGausTrans",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "plotSeqCorr",
+          "status": "intentionally_omitted",
+          "rationale": "Visualization helper is handled in notebooks/docs instead of core API."
+        },
+        {
+          "matlab_method": "spikeTrigAvg",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        }
+      ]
+    },
+    {
+      "matlab_class": "DecodingAlgorithms",
+      "matlab_source": "DecodingAlgorithms.m",
+      "python_target": "nstat/decoding_algorithms.py",
+      "python_class": "DecodingAlgorithms",
+      "python_methods": [
+        "kalman_filter",
+        "linear_decode"
+      ],
+      "methods": [
+        {
+          "matlab_method": "ComputeStimulusCIs",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "KF_ComputeParamStandardErrors",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "KF_EM",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "KF_EMCreateConstraints",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "KF_EStep",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "KF_MStep",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "PPDecodeFilter",
+          "status": "implemented",
+          "rationale": "Implemented via Pythonic rename: kalman_filter."
+        },
+        {
+          "matlab_method": "PPDecodeFilterLinear",
+          "status": "implemented",
+          "rationale": "Implemented via Pythonic rename: kalman_filter."
+        },
+        {
+          "matlab_method": "PPDecode_predict",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "PPDecode_update",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "PPDecode_updateLinear",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "PPHybridFilter",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "PPHybridFilterLinear",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "PPSS_EM",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "PPSS_EMFB",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "PPSS_EStep",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "PPSS_MStep",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "PP_ComputeParamStandardErrors",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "PP_EM",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "PP_EMCreateConstraints",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "PP_EStep",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "PP_MStep",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "PP_fixedIntervalSmoother",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "computeSpikeRateCIs",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "computeSpikeRateDiffCIs",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "estimateInfoMat",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "kalman_filter",
+          "status": "implemented",
+          "rationale": "Method name exists in canonical Python class."
+        },
+        {
+          "matlab_method": "kalman_fixedIntervalSmoother",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "kalman_predict",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "kalman_smoother",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "kalman_smootherFromFiltered",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "kalman_update",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "mPPCODecodeLinear",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "mPPCODecode_predict",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "mPPCODecode_update",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "mPPCO_ComputeParamStandardErrors",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "mPPCO_EM",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "mPPCO_EMCreateConstraints",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "mPPCO_EStep",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "mPPCO_MStep",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "mPPCO_fixedIntervalSmoother",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "prepareEMResults",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "ukf",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "ukf_sigmas",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        },
+        {
+          "matlab_method": "ukf_ut",
+          "status": "planned",
+          "rationale": "Not yet implemented in canonical class; tracked for incremental parity completion."
+        }
+      ]
+    }
+  ]
+}
\ No newline at end of file
diff --git a/reports/mfile_parity_report.json b/reports/mfile_parity_report.json
new file mode 100644
index 00000000..4912ffd8
--- /dev/null
+++ b/reports/mfile_parity_report.json
@@ -0,0 +1,593 @@
+{
+  "summary": {
+    "total_m_files": 58,
+    "python_ok": 58,
+    "python_runnable_ok": 33,
+    "matlab_runnable_ok": 24,
+    "runnable_parity_pass": 24,
+    "interface_only": 25,
+    "runnable_total": 33
+  },
+  "rows": [
+    {
+      "source": "Analysis.m",
+      "kind": "classdef",
+      "python_target": "python/matlab_port/Analysis.py",
+      "python_ok": true,
+      "python_message": "interface_checked",
+      "matlab_ok": null,
+      "matlab_message": "not_run",
+      "parity": "interface_only"
+    },
+    {
+      "source": "CIF.m",
+      "kind": "classdef",
+      "python_target": "python/matlab_port/CIF.py",
+      "python_ok": true,
+      "python_message": "interface_checked",
+      "matlab_ok": null,
+      "matlab_message": "not_run",
+      "parity": "interface_only"
+    },
+    {
+      "source": "ConfidenceInterval.m",
+      "kind": "classdef",
+      "python_target": "python/matlab_port/ConfidenceInterval.py",
+      "python_ok": true,
+      "python_message": "interface_checked",
+      "matlab_ok": null,
+      "matlab_message": "not_run",
+      "parity": "interface_only"
+    },
+    {
+      "source": "ConfigColl.m",
+      "kind": "classdef",
+      "python_target": "python/matlab_port/ConfigColl.py",
+      "python_ok": true,
+      "python_message": "interface_checked",
+      "matlab_ok": null,
+      "matlab_message": "not_run",
+      "parity": "interface_only"
+    },
+    {
+      "source": "CovColl.m",
+      "kind": "classdef",
+      "python_target": "python/matlab_port/CovColl.py",
+      "python_ok": true,
+      "python_message": "interface_checked",
+      "matlab_ok": null,
+      "matlab_message": "not_run",
+      "parity": "interface_only"
+    },
+    {
+      "source": "Covariate.m",
+      "kind": "classdef",
+      "python_target": "python/matlab_port/Covariate.py",
+      "python_ok": true,
+      "python_message": "interface_checked",
+      "matlab_ok": null,
+      "matlab_message": "not_run",
+      "parity": "interface_only"
+    },
+    {
+      "source": "DecodingAlgorithms.m",
+      "kind": "classdef",
+      "python_target": "python/matlab_port/DecodingAlgorithms.py",
+      "python_ok": true,
+      "python_message": "interface_checked",
+      "matlab_ok": null,
+      "matlab_message": "not_run",
+      "parity": "interface_only"
+    },
+    {
+      "source": "Events.m",
+      "kind": "classdef",
+      "python_target": "python/matlab_port/Events.py",
+      "python_ok": true,
+      "python_message": "interface_checked",
+      "matlab_ok": null,
+      "matlab_message": "not_run",
+      "parity": "interface_only"
+    },
+    {
+      "source": "FitResSummary.m",
+      "kind": "classdef",
+      "python_target": "python/matlab_port/FitResSummary.py",
+      "python_ok": true,
+      "python_message": "interface_checked",
+      "matlab_ok": null,
+      "matlab_message": "not_run",
+      "parity": "interface_only"
+    },
+    {
+      "source": "FitResult.m",
+      "kind": "classdef",
+      "python_target": "python/matlab_port/FitResult.py",
+      "python_ok": true,
+      "python_message": "interface_checked",
+      "matlab_ok": null,
+      "matlab_message": "not_run",
+      "parity": "interface_only"
+    },
+    {
+      "source": "History.m",
+      "kind": "classdef",
+      "python_target": "python/matlab_port/History.py",
+      "python_ok": true,
+      "python_message": "interface_checked",
+      "matlab_ok": null,
+      "matlab_message": "not_run",
+      "parity": "interface_only"
+    },
+    {
+      "source": "SignalObj.m",
+      "kind": "classdef",
+      "python_target": "python/matlab_port/SignalObj.py",
+      "python_ok": true,
+      "python_message": "interface_checked",
+      "matlab_ok": null,
+      "matlab_message": "not_run",
+      "parity": "interface_only"
+    },
+    {
+      "source": "Trial.m",
+      "kind": "classdef",
+      "python_target": "python/matlab_port/Trial.py",
+      "python_ok": true,
+      "python_message": "interface_checked",
+      "matlab_ok": null,
+      "matlab_message": "not_run",
+      "parity": "interface_only"
+    },
+    {
+      "source": "TrialConfig.m",
+      "kind": "classdef",
+      "python_target": "python/matlab_port/TrialConfig.py",
+      "python_ok": true,
+      "python_message": "interface_checked",
+      "matlab_ok": null,
+      "matlab_message": "not_run",
+      "parity": "interface_only"
+    },
+    {
+      "source": "data/Explicit Stimulus/GenCovMat.m",
+      "kind": "function_args",
+      "python_target": "python/matlab_port/data/Explicit Stimulus/GenCovMat.py",
+      "python_ok": true,
+      "python_message": "interface_checked",
+      "matlab_ok": null,
+      "matlab_message": "not_run",
+      "parity": "interface_only"
+    },
+    {
+      "source": "helpfiles/AnalysisExamples.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/AnalysisExamples.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": true,
+      "matlab_message": "ok",
+      "parity": "pass"
+    },
+    {
+      "source": "helpfiles/AnalysisExamples2.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/AnalysisExamples2.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": false,
+      "matlab_message": "Analyzing Configuration #1: Neuron #1CODEX_SMOKE_FAIL\nstats:glmfit:InputSizeMismatchX | Number of observations in X and Y must match.",
+      "parity": "fail"
+    },
+    {
+      "source": "helpfiles/ClassDefinitions.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/ClassDefinitions.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": true,
+      "matlab_message": "ok",
+      "parity": "pass"
+    },
+    {
+      "source": "helpfiles/ConfigCollExamples.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/ConfigCollExamples.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": true,
+      "matlab_message": "ok",
+      "parity": "pass"
+    },
+    {
+      "source": "helpfiles/CovCollExamples.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/CovCollExamples.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": true,
+      "matlab_message": "ok",
+      "parity": "pass"
+    },
+    {
+      "source": "helpfiles/CovariateExamples.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/CovariateExamples.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": true,
+      "matlab_message": "ok",
+      "parity": "pass"
+    },
+    {
+      "source": "helpfiles/DecodingExample.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/DecodingExample.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": false,
+      "matlab_message": "Analyzing Configuration #1: Neuron #1,2,3,4,5,6,7,8,9,10\nAnalyzing Configuration #2: Neuron #1,2,3,4,5,6,7,8,9,10\nCODEX_SMOKE_FAIL\nMATLAB:innerdim | Incorrect dimensions for matrix multiplication. Check that the number of columns in the first matrix matches the number of rows in the second matrix. To operate on each element of the matrix individually, use TIMES (.*) for elementwise multiplication.",
+      "parity": "fail"
+    },
+    {
+      "source": "helpfiles/DecodingExampleWithHist.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/DecodingExampleWithHist.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": false,
+      "matlab_message": "matlab_timeout",
+      "parity": "fail"
+    },
+    {
+      "source": "helpfiles/EventsExamples.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/EventsExamples.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": true,
+      "matlab_message": "ok",
+      "parity": "pass"
+    },
+    {
+      "source": "helpfiles/Examples.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/Examples.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": true,
+      "matlab_message": "ok",
+      "parity": "pass"
+    },
+    {
+      "source": "helpfiles/ExplicitStimulusWhiskerData.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/ExplicitStimulusWhiskerData.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": true,
+      "matlab_message": "ok",
+      "parity": "pass"
+    },
+    {
+      "source": "helpfiles/FitResSummaryExamples.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/FitResSummaryExamples.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": true,
+      "matlab_message": "ok",
+      "parity": "pass"
+    },
+    {
+      "source": "helpfiles/FitResult.m",
+      "kind": "classdef",
+      "python_target": "python/matlab_port/helpfiles/FitResult.py",
+      "python_ok": true,
+      "python_message": "interface_checked",
+      "matlab_ok": null,
+      "matlab_message": "not_run",
+      "parity": "interface_only"
+    },
+    {
+      "source": "helpfiles/FitResultExamples.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/FitResultExamples.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": true,
+      "matlab_message": "ok",
+      "parity": "pass"
+    },
+    {
+      "source": "helpfiles/HippocampalPlaceCellExample.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/HippocampalPlaceCellExample.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": false,
+      "matlab_message": "CODEX_SMOKE_FAIL\nMATLAB:pmaxsize | Requested array exceeds the maximum possible variable size.",
+      "parity": "fail"
+    },
+    {
+      "source": "helpfiles/HistoryExamples.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/HistoryExamples.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": true,
+      "matlab_message": "ok",
+      "parity": "pass"
+    },
+    {
+      "source": "helpfiles/HybridFilterExample.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/HybridFilterExample.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": true,
+      "matlab_message": "ok",
+      "parity": "pass"
+    },
+    {
+      "source": "helpfiles/NetworkTutorial.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/NetworkTutorial.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": true,
+      "matlab_message": "ok",
+      "parity": "pass"
+    },
+    {
+      "source": "helpfiles/NeuralSpikeAnalysis_top.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/NeuralSpikeAnalysis_top.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": true,
+      "matlab_message": "ok",
+      "parity": "pass"
+    },
+    {
+      "source": "helpfiles/PPSimExample.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/PPSimExample.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": true,
+      "matlab_message": "ok",
+      "parity": "pass"
+    },
+    {
+      "source": "helpfiles/PPThinning.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/PPThinning.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": true,
+      "matlab_message": "ok",
+      "parity": "pass"
+    },
+    {
+      "source": "helpfiles/PSTHEstimation.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/PSTHEstimation.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": true,
+      "matlab_message": "ok",
+      "parity": "pass"
+    },
+    {
+      "source": "helpfiles/SignalObjExamples.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/SignalObjExamples.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": false,
+      "matlab_message": "ans =\n        1001           1\nName successfully set \nCODEX_SMOKE_FAIL\nMATLAB:sizeDimensionsMustMatch | Arrays have incompatible sizes for this operation.",
+      "parity": "fail"
+    },
+    {
+      "source": "helpfiles/StimulusDecode2D.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/StimulusDecode2D.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": false,
+      "matlab_message": "CODEX_SMOKE_FAIL\nsymbolic:sym:sym:ArgumentMustBeVarnameOrNumber | Each character vector or string in input arguments must specify a variable or a number. To evaluate a character vector or a string representing symbolic expression, use 'str2sym'.",
+      "parity": "fail"
+    },
+    {
+      "source": "helpfiles/TrialConfigExamples.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/TrialConfigExamples.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": true,
+      "matlab_message": "ok",
+      "parity": "pass"
+    },
+    {
+      "source": "helpfiles/TrialExamples.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/TrialExamples.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": true,
+      "matlab_message": "ok",
+      "parity": "pass"
+    },
+    {
+      "source": "helpfiles/ValidationDataSet.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/ValidationDataSet.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": false,
+      "matlab_message": "lambda =\n    10\nmu =\n   -4.5951\nAnalyzing Configuration #1: Neuron #1CODEX_SMOKE_FAIL\nstats:glmfit:InputSizeMismatchX | Number of observations in X and Y must match.",
+      "parity": "fail"
+    },
+    {
+      "source": "helpfiles/mEPSCAnalysis.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/mEPSCAnalysis.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": true,
+      "matlab_message": "ok",
+      "parity": "pass"
+    },
+    {
+      "source": "helpfiles/nSTATPaperExamples.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/nSTATPaperExamples.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": false,
+      "matlab_message": "matlab_timeout",
+      "parity": "fail"
+    },
+    {
+      "source": "helpfiles/nSpikeTrainExamples.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/nSpikeTrainExamples.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": true,
+      "matlab_message": "ok",
+      "parity": "pass"
+    },
+    {
+      "source": "helpfiles/nstCollExamples.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/nstCollExamples.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": true,
+      "matlab_message": "ok",
+      "parity": "pass"
+    },
+    {
+      "source": "helpfiles/temp.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/helpfiles/temp.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": true,
+      "matlab_message": "ok",
+      "parity": "pass"
+    },
+    {
+      "source": "libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/nearestSPD.m",
+      "kind": "function_args",
+      "python_target": "python/matlab_port/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/nearestSPD.py",
+      "python_ok": true,
+      "python_message": "interface_checked",
+      "matlab_ok": null,
+      "matlab_message": "not_run",
+      "parity": "interface_only"
+    },
+    {
+      "source": "libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/nearestSPD_demo.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/libraries/NearestSymmetricPositiveDefinite/NearestSymmetricPositiveDefinite/nearestSPD_demo.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": false,
+      "matlab_message": "  Columns 15 through 21\n    0.3714    0.3922    0.6373    0.7147    0.8857    1.2443    1.3638\n  Columns 22 through 25\n    1.4439    1.5006    1.8153   13.0417\np =\n     3\nCODEX_SMOKE_FAIL\nMATLAB:UndefinedFunction | Undefined function 'nearest_posdef' for input arguments of type 'double'.",
+      "parity": "fail"
+    },
+    {
+      "source": "libraries/fixPSlinestyle.m",
+      "kind": "function_args",
+      "python_target": "python/matlab_port/libraries/fixPSlinestyle.py",
+      "python_ok": true,
+      "python_message": "interface_checked",
+      "matlab_ok": null,
+      "matlab_message": "not_run",
+      "parity": "interface_only"
+    },
+    {
+      "source": "libraries/rotateXLabels/rotateXLabels.m",
+      "kind": "function_args",
+      "python_target": "python/matlab_port/libraries/rotateXLabels/rotateXLabels.py",
+      "python_ok": true,
+      "python_message": "interface_checked",
+      "matlab_ok": null,
+      "matlab_message": "not_run",
+      "parity": "interface_only"
+    },
+    {
+      "source": "libraries/xticklabel_rotate.m",
+      "kind": "function_args",
+      "python_target": "python/matlab_port/libraries/xticklabel_rotate.py",
+      "python_ok": true,
+      "python_message": "interface_checked",
+      "matlab_ok": null,
+      "matlab_message": "not_run",
+      "parity": "interface_only"
+    },
+    {
+      "source": "libraries/zernike/zernfun.m",
+      "kind": "function_args",
+      "python_target": "python/matlab_port/libraries/zernike/zernfun.py",
+      "python_ok": true,
+      "python_message": "interface_checked",
+      "matlab_ok": null,
+      "matlab_message": "not_run",
+      "parity": "interface_only"
+    },
+    {
+      "source": "libraries/zernike/zernfun2.m",
+      "kind": "function_args",
+      "python_target": "python/matlab_port/libraries/zernike/zernfun2.py",
+      "python_ok": true,
+      "python_message": "interface_checked",
+      "matlab_ok": null,
+      "matlab_message": "not_run",
+      "parity": "interface_only"
+    },
+    {
+      "source": "libraries/zernike/zernpol.m",
+      "kind": "function_args",
+      "python_target": "python/matlab_port/libraries/zernike/zernpol.py",
+      "python_ok": true,
+      "python_message": "interface_checked",
+      "matlab_ok": null,
+      "matlab_message": "not_run",
+      "parity": "interface_only"
+    },
+    {
+      "source": "nSTAT_Install.m",
+      "kind": "script",
+      "python_target": "python/matlab_port/nSTAT_Install.py",
+      "python_ok": true,
+      "python_message": "run_ok",
+      "matlab_ok": true,
+      "matlab_message": "ok",
+      "parity": "pass"
+    },
+    {
+      "source": "nspikeTrain.m",
+      "kind": "classdef",
+      "python_target": "python/matlab_port/nspikeTrain.py",
+      "python_ok": true,
+      "python_message": "interface_checked",
+      "matlab_ok": null,
+      "matlab_message": "not_run",
+      "parity": "interface_only"
+    },
+    {
+      "source": "nstColl.m",
+      "kind": "classdef",
+      "python_target": "python/matlab_port/nstColl.py",
+      "python_ok": true,
+      "python_message": "interface_checked",
+      "matlab_ok": null,
+      "matlab_message": "not_run",
+      "parity": "interface_only"
+    }
+  ]
+}
\ No newline at end of file
diff --git a/reports/offline_standalone_verification.json b/reports/offline_standalone_verification.json
new file mode 100644
index 00000000..3b84256a
--- /dev/null
+++ b/reports/offline_standalone_verification.json
@@ -0,0 +1,69 @@
+{
+  "full_notebooks": false,
+  "steps": [
+    {
+      "cmd": [
+        "/Library/Developer/CommandLineTools/usr/bin/python3",
+        "-m",
+        "pip",
+        "install",
+        "--no-deps",
+        "./python",
+        "--target",
+        "/var/folders/tg/z6dfb8b13wg_h4f3v8whzpgh0000gn/T/nstat_offline_site_cwn3d943/site"
+      ],
+      "cwd": ".",
+      "returncode": 0,
+      "stdout": "Processing ./python\n  Installing build dependencies: started\n  Installing build dependencies: finished with status 'done'\n  Getting requirements to build wheel: started\n  Getting requirements to build wheel: finished with status 'done'\n    Preparing wheel metadata: started\n    Preparing wheel metadata: finished with status 'done'\nBuilding wheels for collected packages: UNKNOWN\n  Building wheel for UNKNOWN (PEP 517): started\n  Building wheel for UNKNOWN (PEP 517): finished with status 'done'\n  Created wheel for UNKNOWN: filename=UNKNOWN-0.0.0-py3-none-any.whl size=964 sha256=c90108beae5d6e47c6c92f0b9352de391932056a5d74b69c2720b860d3fce19c\n  Stored in directory: /private/var/folders/tg/z6dfb8b13wg_h4f3v8whzpgh0000gn/T/pip-ephem-wheel-cache-83_7ve9i/wheels/81/67/1b/46c5955793e14fd89065ce3e49006c6b43d36c440a1343a2c9\nSuccessfully built UNKNOWN\nInstalling collected packages: UNKNOWN\nSuccessfully installed UNKNOWN-0.0.0\n",
+      "stderr": "  DEPRECATION: A future pip version will change local packages to be built in-place without first copying to a temporary directory. We recommend you use --use-feature=in-tree-build to test your packages with this new behavior before it becomes the default.\n   pip 21.3 will remove support for this functionality. You can find discussion regarding this at https://github.com/pypa/pip/issues/7555.\n  WARNING: Value for prefixed-purelib does not match. Please report this to \n  distutils: /private/var/folders/tg/z6dfb8b13wg_h4f3v8whzpgh0000gn/T/pip-build-env-ff_yyb7u/normal/lib/python3.9/site-packages\n  sysconfig: /Library/Python/3.9/site-packages\n  WARNING: Value for prefixed-platlib does not match. Please report this to \n  distutils: /private/var/folders/tg/z6dfb8b13wg_h4f3v8whzpgh0000gn/T/pip-build-env-ff_yyb7u/normal/lib/python3.9/site-packages\n  sysconfig: /Library/Python/3.9/site-packages\n  WARNING: Additional context:\n  user = False\n  home = None\n  root = None\n  prefix = '/private/var/folders/tg/z6dfb8b13wg_h4f3v8whzpgh0000gn/T/pip-build-env-ff_yyb7u/normal'\n  WARNING: Value for prefixed-purelib does not match. Please report this to \n  distutils: /private/var/folders/tg/z6dfb8b13wg_h4f3v8whzpgh0000gn/T/pip-build-env-ff_yyb7u/overlay/lib/python3.9/site-packages\n  sysconfig: /Library/Python/3.9/site-packages\n  WARNING: Value for prefixed-platlib does not match. Please report this to \n  distutils: /private/var/folders/tg/z6dfb8b13wg_h4f3v8whzpgh0000gn/T/pip-build-env-ff_yyb7u/overlay/lib/python3.9/site-packages\n  sysconfig: /Library/Python/3.9/site-packages\n  WARNING: Additional context:\n  user = False\n  home = None\n  root = None\n  prefix = '/private/var/folders/tg/z6dfb8b13wg_h4f3v8whzpgh0000gn/T/pip-build-env-ff_yyb7u/overlay'\nWARNING: You are using pip version 21.2.4; however, version 26.0.1 is available.\nYou should consider upgrading via the '/Library/Developer/CommandLineTools/usr/bin/python3 -m pip install --upgrade pip' command.\n",
+      "ok": true
+    },
+    {
+      "cmd": [
+        "/Library/Developer/CommandLineTools/usr/bin/python3",
+        "-c",
+        "import json, pathlib, nstat; checks=nstat.verify_checksums(); print(json.dumps({'dataset_count': len(nstat.list_datasets()), 'checksum_all_true': all(checks.values()), 'nstat_path': str(pathlib.Path(nstat.__file__).resolve())}))"
+      ],
+      "cwd": ".",
+      "returncode": 1,
+      "stdout": "",
+      "stderr": "Traceback (most recent call last):\n  File \"\", line 1, in \nModuleNotFoundError: No module named 'nstat'\n",
+      "ok": false
+    },
+    {
+      "cmd": [
+        "/Library/Developer/CommandLineTools/usr/bin/python3",
+        "-c",
+        "import numpy as np; from nstat.signal import Signal; t=np.linspace(0.0,1.0,100); sig=Signal(t, np.column_stack([np.sin(t), np.cos(t)]), name='offline_check'); print(sig.dimension)"
+      ],
+      "cwd": ".",
+      "returncode": 1,
+      "stdout": "",
+      "stderr": "Traceback (most recent call last):\n  File \"\", line 1, in \nModuleNotFoundError: No module named 'nstat'\n",
+      "ok": false
+    },
+    {
+      "cmd": [
+        "/Library/Developer/CommandLineTools/usr/bin/python3",
+        "-c",
+        "import json, pathlib, nstat; checks=nstat.verify_checksums(); print(json.dumps({'dataset_count': len(nstat.list_datasets()), 'checksum_all_true': all(checks.values()), 'nstat_path': str(pathlib.Path(nstat.__file__).resolve())}))"
+      ],
+      "cwd": ".",
+      "returncode": 0,
+      "stdout": "{\"dataset_count\": 7, \"checksum_all_true\": true, \"nstat_path\": \"/Users/iahncajigas/Library/CloudStorage/Dropbox/Research/Matlab/nSTAT_currentRelease_Local/python/nstat/__init__.py\"}\n",
+      "stderr": "",
+      "ok": true
+    }
+  ],
+  "runtime_matlab_scan": {
+    "ok": true,
+    "hits": []
+  },
+  "target_install_ok": true,
+  "installed_runtime_ok": false,
+  "source_fallback_ok": true,
+  "notebook_checks_ok": true,
+  "install_mode": "source_fallback",
+  "pass_strict_target_install": false,
+  "pass": true
+}
\ No newline at end of file
diff --git a/reports/offline_standalone_verification_no_matlab_path.json b/reports/offline_standalone_verification_no_matlab_path.json
new file mode 100644
index 00000000..9b212a54
--- /dev/null
+++ b/reports/offline_standalone_verification_no_matlab_path.json
@@ -0,0 +1,73 @@
+{
+  "full_notebooks": false,
+  "steps": [
+    {
+      "cmd": [
+        "/Library/Developer/CommandLineTools/usr/bin/python3",
+        "-m",
+        "pip",
+        "install",
+        "--no-deps",
+        "./python",
+        "--target",
+        "/var/folders/tg/z6dfb8b13wg_h4f3v8whzpgh0000gn/T/nstat_offline_site_cwn3d943/site"
+      ],
+      "cwd": ".",
+      "returncode": 0,
+      "stdout": "Processing ./python\n  Installing build dependencies: started\n  Installing build dependencies: finished with status 'done'\n  Getting requirements to build wheel: started\n  Getting requirements to build wheel: finished with status 'done'\n    Preparing wheel metadata: started\n    Preparing wheel metadata: finished with status 'done'\nBuilding wheels for collected packages: UNKNOWN\n  Building wheel for UNKNOWN (PEP 517): started\n  Building wheel for UNKNOWN (PEP 517): finished with status 'done'\n  Created wheel for UNKNOWN: filename=UNKNOWN-0.0.0-py3-none-any.whl size=964 sha256=c90108beae5d6e47c6c92f0b9352de391932056a5d74b69c2720b860d3fce19c\n  Stored in directory: /private/var/folders/tg/z6dfb8b13wg_h4f3v8whzpgh0000gn/T/pip-ephem-wheel-cache-83_7ve9i/wheels/81/67/1b/46c5955793e14fd89065ce3e49006c6b43d36c440a1343a2c9\nSuccessfully built UNKNOWN\nInstalling collected packages: UNKNOWN\nSuccessfully installed UNKNOWN-0.0.0\n",
+      "stderr": "  DEPRECATION: A future pip version will change local packages to be built in-place without first copying to a temporary directory. We recommend you use --use-feature=in-tree-build to test your packages with this new behavior before it becomes the default.\n   pip 21.3 will remove support for this functionality. You can find discussion regarding this at https://github.com/pypa/pip/issues/7555.\n  WARNING: Value for prefixed-purelib does not match. Please report this to \n  distutils: /private/var/folders/tg/z6dfb8b13wg_h4f3v8whzpgh0000gn/T/pip-build-env-ff_yyb7u/normal/lib/python3.9/site-packages\n  sysconfig: /Library/Python/3.9/site-packages\n  WARNING: Value for prefixed-platlib does not match. Please report this to \n  distutils: /private/var/folders/tg/z6dfb8b13wg_h4f3v8whzpgh0000gn/T/pip-build-env-ff_yyb7u/normal/lib/python3.9/site-packages\n  sysconfig: /Library/Python/3.9/site-packages\n  WARNING: Additional context:\n  user = False\n  home = None\n  root = None\n  prefix = '/private/var/folders/tg/z6dfb8b13wg_h4f3v8whzpgh0000gn/T/pip-build-env-ff_yyb7u/normal'\n  WARNING: Value for prefixed-purelib does not match. Please report this to \n  distutils: /private/var/folders/tg/z6dfb8b13wg_h4f3v8whzpgh0000gn/T/pip-build-env-ff_yyb7u/overlay/lib/python3.9/site-packages\n  sysconfig: /Library/Python/3.9/site-packages\n  WARNING: Value for prefixed-platlib does not match. Please report this to \n  distutils: /private/var/folders/tg/z6dfb8b13wg_h4f3v8whzpgh0000gn/T/pip-build-env-ff_yyb7u/overlay/lib/python3.9/site-packages\n  sysconfig: /Library/Python/3.9/site-packages\n  WARNING: Additional context:\n  user = False\n  home = None\n  root = None\n  prefix = '/private/var/folders/tg/z6dfb8b13wg_h4f3v8whzpgh0000gn/T/pip-build-env-ff_yyb7u/overlay'\nWARNING: You are using pip version 21.2.4; however, version 26.0.1 is available.\nYou should consider upgrading via the '/Library/Developer/CommandLineTools/usr/bin/python3 -m pip install --upgrade pip' command.\n",
+      "ok": true
+    },
+    {
+      "cmd": [
+        "/Library/Developer/CommandLineTools/usr/bin/python3",
+        "-c",
+        "import json, pathlib, nstat; checks=nstat.verify_checksums(); print(json.dumps({'dataset_count': len(nstat.list_datasets()), 'checksum_all_true': all(checks.values()), 'nstat_path': str(pathlib.Path(nstat.__file__).resolve())}))"
+      ],
+      "cwd": ".",
+      "returncode": 1,
+      "stdout": "",
+      "stderr": "Traceback (most recent call last):\n  File \"\", line 1, in \nModuleNotFoundError: No module named 'nstat'\n",
+      "ok": false
+    },
+    {
+      "cmd": [
+        "/Library/Developer/CommandLineTools/usr/bin/python3",
+        "-c",
+        "import numpy as np; from nstat.signal import Signal; t=np.linspace(0.0,1.0,100); sig=Signal(t, np.column_stack([np.sin(t), np.cos(t)]), name='offline_check'); print(sig.dimension)"
+      ],
+      "cwd": ".",
+      "returncode": 1,
+      "stdout": "",
+      "stderr": "Traceback (most recent call last):\n  File \"\", line 1, in \nModuleNotFoundError: No module named 'nstat'\n",
+      "ok": false
+    },
+    {
+      "cmd": [
+        "/Library/Developer/CommandLineTools/usr/bin/python3",
+        "-c",
+        "import json, pathlib, nstat; checks=nstat.verify_checksums(); print(json.dumps({'dataset_count': len(nstat.list_datasets()), 'checksum_all_true': all(checks.values()), 'nstat_path': str(pathlib.Path(nstat.__file__).resolve())}))"
+      ],
+      "cwd": ".",
+      "returncode": 0,
+      "stdout": "{\"dataset_count\": 7, \"checksum_all_true\": true, \"nstat_path\": \"/Users/iahncajigas/Library/CloudStorage/Dropbox/Research/Matlab/nSTAT_currentRelease_Local/python/nstat/__init__.py\"}\n",
+      "stderr": "",
+      "ok": true
+    }
+  ],
+  "runtime_matlab_scan": {
+    "ok": true,
+    "hits": []
+  },
+  "target_install_ok": true,
+  "installed_runtime_ok": false,
+  "source_fallback_ok": true,
+  "notebook_checks_ok": true,
+  "install_mode": "source_fallback",
+  "pass_strict_target_install": false,
+  "pass": true,
+  "run_context": {
+    "path": "/usr/bin:/bin:/usr/sbin:/sbin",
+    "matlab_on_path": false
+  }
+}
\ No newline at end of file
diff --git a/reports/port_baseline_snapshot.json b/reports/port_baseline_snapshot.json
new file mode 100644
index 00000000..22367119
--- /dev/null
+++ b/reports/port_baseline_snapshot.json
@@ -0,0 +1,38 @@
+{
+  "generated_at_utc": "2026-02-25T13:51:32.513233+00:00",
+  "reports": {
+    "mfile_parity": {
+      "path": "python/reports/mfile_parity_report.json",
+      "exists": true,
+      "sha256": "14550105d488cd5f91d47dbbb1bd6ad96e34e2dd74d102d85b3f9b0c392a1e7a",
+      "size_bytes": 19449,
+      "summary": {
+        "total_m_files": 58,
+        "python_ok": 58,
+        "python_runnable_ok": 33,
+        "matlab_runnable_ok": 24,
+        "runnable_parity_pass": 24,
+        "interface_only": 25,
+        "runnable_total": 33
+      }
+    },
+    "examples_notebooks": {
+      "path": "python/reports/examples_notebook_verification.json",
+      "exists": true,
+      "sha256": "e7823adb5d5634a3ed345679dd4134f87b7c18246a27b1ef12d24fdeee5602ca",
+      "size_bytes": 12417,
+      "summary": {
+        "total_examples": 25,
+        "python_modules_ok": 25,
+        "notebooks_ok": 25,
+        "topic_alignment_ok": 25
+      }
+    },
+    "matlab_smoke_input": {
+      "path": "python/reports/matlab_smoke_input.json",
+      "exists": true,
+      "sha256": "3e5ffe693d440c094c529163ca403f791cc5f4c4210d379a220652cc487eb713",
+      "size_bytes": 3510
+    }
+  }
+}
\ No newline at end of file
diff --git a/reports/python_vs_matlab_similarity_baseline.json b/reports/python_vs_matlab_similarity_baseline.json
new file mode 100644
index 00000000..eaab6d23
--- /dev/null
+++ b/reports/python_vs_matlab_similarity_baseline.json
@@ -0,0 +1,1464 @@
+{
+  "frozen_at_utc": "2026-02-25T13:25:15.196500+00:00",
+  "source_report": "python/reports/python_vs_matlab_similarity_report.json",
+  "report": {
+    "class_similarity": {
+      "python": {
+        "nspike_getISIs": [
+          0.1,
+          0.2
+        ],
+        "nspike_rate": 3.0,
+        "nstcoll_psth_len": 5,
+        "nstcoll_psth_mean": 3.0,
+        "covcoll_shape": [
+          11,
+          2
+        ],
+        "history_num_columns": 2,
+        "trial_sample_rate": 10.0,
+        "trial_minmax": [
+          0.0,
+          1.0
+        ],
+        "cif_num_realizations": 3
+      },
+      "matlab": {
+        "nspike_getISIs": [
+          0.1,
+          0.2
+        ],
+        "nspike_rate": 3,
+        "nstcoll_psth_len": 5,
+        "nstcoll_psth_mean": 3,
+        "covcoll_shape": [
+          11,
+          2
+        ],
+        "history_num_columns": 2,
+        "trial_sample_rate": 10,
+        "trial_minmax": [
+          0,
+          1
+        ],
+        "cif_num_realizations": 3
+      },
+      "comparisons": [
+        {
+          "metric": "nspike_getISIs",
+          "python": [
+            0.1,
+            0.2
+          ],
+          "matlab": [
+            0.1,
+            0.2
+          ],
+          "pass": true
+        },
+        {
+          "metric": "nspike_rate",
+          "python": 3.0,
+          "matlab": 3.0,
+          "abs_diff": 0.0,
+          "pass": true
+        },
+        {
+          "metric": "nstcoll_psth_len",
+          "python": 5.0,
+          "matlab": 5.0,
+          "abs_diff": 0.0,
+          "pass": true
+        },
+        {
+          "metric": "nstcoll_psth_mean",
+          "python": 3.0,
+          "matlab": 3.0,
+          "abs_diff": 0.0,
+          "pass": true
+        },
+        {
+          "metric": "covcoll_shape",
+          "python": [
+            11.0,
+            2.0
+          ],
+          "matlab": [
+            11.0,
+            2.0
+          ],
+          "pass": true
+        },
+        {
+          "metric": "history_num_columns",
+          "python": 2.0,
+          "matlab": 2.0,
+          "abs_diff": 0.0,
+          "pass": true
+        },
+        {
+          "metric": "trial_sample_rate",
+          "python": 10.0,
+          "matlab": 10.0,
+          "abs_diff": 0.0,
+          "pass": true
+        },
+        {
+          "metric": "trial_minmax",
+          "python": [
+            0.0,
+            1.0
+          ],
+          "matlab": [
+            0.0,
+            1.0
+          ],
+          "pass": true
+        },
+        {
+          "metric": "cif_num_realizations",
+          "python": 3.0,
+          "matlab": 3.0,
+          "abs_diff": 0.0,
+          "pass": true
+        }
+      ],
+      "summary": {
+        "passed": 9,
+        "total": 9,
+        "similarity_score": 1.0
+      }
+    },
+    "helpfile_similarity": {
+      "summary": {
+        "total_topics": 25,
+        "both_ok": 25,
+        "python_ok": 25,
+        "matlab_ok": 25,
+        "scalar_overlap_topics": 25,
+        "scalar_overlap_pass_topics": 25,
+        "avg_similarity_score": 1.0
+      },
+      "rows": [
+        {
+          "topic": "SignalObjExamples",
+          "title": "Using the SignalObj Class",
+          "python_ok": true,
+          "python_error": "",
+          "python_output_keys": [
+            "dimension",
+            "parity",
+            "sample_rate",
+            "topic"
+          ],
+          "python_scalar_count": 6,
+          "matlab_ok": true,
+          "matlab_error": "",
+          "matlab_error_report": "",
+          "matlab_fallback_error": "",
+          "matlab_fallback_error_report": "",
+          "matlab_figures": 16,
+          "matlab_var_count": 19,
+          "matlab_scalar_count": 6,
+          "matlab_script_used": "helpfiles/SignalObjExamples.m [shadow_safe_copy]",
+          "matlab_fallback_script_used": "",
+          "matlab_runtime_s": 12.859008073806763,
+          "scalar_overlap": {
+            "overlaps": [
+              {
+                "python_key": "sample_rate",
+                "matlab_key": "sampleRate",
+                "python": 5000.00000000055,
+                "matlab": 5000.0,
+                "abs_diff": 5.502442945726216e-10,
+                "pass": true
+              },
+              {
+                "python_key": "figs",
+                "matlab_key": "figs",
+                "python": 16.0,
+                "matlab": 16.0,
+                "abs_diff": 0.0,
+                "pass": true
+              },
+              {
+                "python_key": "parity.sample_rate_hz",
+                "matlab_key": "parity_sample_rate_hz",
+                "python": 5000.00000000055,
+                "matlab": 5000.0,
+                "abs_diff": 5.502442945726216e-10,
+                "pass": true
+              },
+              {
+                "python_key": "sample_rate_hz",
+                "matlab_key": "sample_rate_hz",
+                "python": 5000.00000000055,
+                "matlab": 5000.0,
+                "abs_diff": 5.502442945726216e-10,
+                "pass": true
+              }
+            ],
+            "overlap_count": 4,
+            "overlap_passed": 4
+          },
+          "similarity_score": 1.0
+        },
+        {
+          "topic": "CovariateExamples",
+          "title": "Using the Covariate Class",
+          "python_ok": true,
+          "python_error": "",
+          "python_output_keys": [
+            "mean",
+            "parity",
+            "std",
+            "topic"
+          ],
+          "python_scalar_count": 4,
+          "matlab_ok": true,
+          "matlab_error": "",
+          "matlab_error_report": "",
+          "matlab_fallback_error": "",
+          "matlab_fallback_error_report": "",
+          "matlab_figures": 2,
+          "matlab_var_count": 16,
+          "matlab_scalar_count": 2,
+          "matlab_script_used": "helpfiles/CovariateExamples.mlx",
+          "matlab_fallback_script_used": "",
+          "matlab_runtime_s": 10.382561206817627,
+          "scalar_overlap": {
+            "overlaps": [
+              {
+                "python_key": "figs",
+                "matlab_key": "figs",
+                "python": 2.0,
+                "matlab": 2.0,
+                "abs_diff": 0.0,
+                "pass": true
+              }
+            ],
+            "overlap_count": 1,
+            "overlap_passed": 1
+          },
+          "similarity_score": 1.0
+        },
+        {
+          "topic": "CovCollExamples",
+          "title": "Using the CovColl Class",
+          "python_ok": true,
+          "python_error": "",
+          "python_output_keys": [
+            "labels",
+            "matrix_shape",
+            "parity",
+            "topic"
+          ],
+          "python_scalar_count": 2,
+          "matlab_ok": true,
+          "matlab_error": "",
+          "matlab_error_report": "",
+          "matlab_fallback_error": "",
+          "matlab_fallback_error_report": "",
+          "matlab_figures": 2,
+          "matlab_var_count": 7,
+          "matlab_scalar_count": 2,
+          "matlab_script_used": "helpfiles/CovCollExamples.mlx",
+          "matlab_fallback_script_used": "",
+          "matlab_runtime_s": 10.461670160293579,
+          "scalar_overlap": {
+            "overlaps": [
+              {
+                "python_key": "figs",
+                "matlab_key": "figs",
+                "python": 2.0,
+                "matlab": 2.0,
+                "abs_diff": 0.0,
+                "pass": true
+              }
+            ],
+            "overlap_count": 1,
+            "overlap_passed": 1
+          },
+          "similarity_score": 1.0
+        },
+        {
+          "topic": "nSpikeTrainExamples",
+          "title": "Using the nSpikeTrain Class",
+          "python_ok": true,
+          "python_error": "",
+          "python_output_keys": [
+            "n_spikes",
+            "parity",
+            "rate_hz",
+            "topic"
+          ],
+          "python_scalar_count": 4,
+          "matlab_ok": true,
+          "matlab_error": "",
+          "matlab_error_report": "",
+          "matlab_fallback_error": "",
+          "matlab_fallback_error_report": "",
+          "matlab_figures": 4,
+          "matlab_var_count": 6,
+          "matlab_scalar_count": 2,
+          "matlab_script_used": "helpfiles/nSpikeTrainExamples.mlx",
+          "matlab_fallback_script_used": "",
+          "matlab_runtime_s": 30.248419046401978,
+          "scalar_overlap": {
+            "overlaps": [
+              {
+                "python_key": "figs",
+                "matlab_key": "figs",
+                "python": 4.0,
+                "matlab": 4.0,
+                "abs_diff": 0.0,
+                "pass": true
+              }
+            ],
+            "overlap_count": 1,
+            "overlap_passed": 1
+          },
+          "similarity_score": 1.0
+        },
+        {
+          "topic": "nstCollExamples",
+          "title": "Using the nstColl Class",
+          "python_ok": true,
+          "python_error": "",
+          "python_output_keys": [
+            "num_trains",
+            "parity",
+            "psth_points",
+            "topic"
+          ],
+          "python_scalar_count": 4,
+          "matlab_ok": true,
+          "matlab_error": "",
+          "matlab_error_report": "",
+          "matlab_fallback_error": "",
+          "matlab_fallback_error_report": "",
+          "matlab_figures": 3,
+          "matlab_var_count": 8,
+          "matlab_scalar_count": 2,
+          "matlab_script_used": "helpfiles/nstCollExamples.mlx",
+          "matlab_fallback_script_used": "",
+          "matlab_runtime_s": 10.848538875579834,
+          "scalar_overlap": {
+            "overlaps": [
+              {
+                "python_key": "figs",
+                "matlab_key": "figs",
+                "python": 3.0,
+                "matlab": 3.0,
+                "abs_diff": 0.0,
+                "pass": true
+              }
+            ],
+            "overlap_count": 1,
+            "overlap_passed": 1
+          },
+          "similarity_score": 1.0
+        },
+        {
+          "topic": "EventsExamples",
+          "title": "Using the Events Class",
+          "python_ok": true,
+          "python_error": "",
+          "python_output_keys": [
+            "n_events",
+            "parity",
+            "topic"
+          ],
+          "python_scalar_count": 3,
+          "matlab_ok": true,
+          "matlab_error": "",
+          "matlab_error_report": "",
+          "matlab_fallback_error": "",
+          "matlab_fallback_error_report": "",
+          "matlab_figures": 3,
+          "matlab_var_count": 8,
+          "matlab_scalar_count": 2,
+          "matlab_script_used": "helpfiles/EventsExamples.mlx",
+          "matlab_fallback_script_used": "",
+          "matlab_runtime_s": 9.690116167068481,
+          "scalar_overlap": {
+            "overlaps": [
+              {
+                "python_key": "figs",
+                "matlab_key": "figs",
+                "python": 3.0,
+                "matlab": 3.0,
+                "abs_diff": 0.0,
+                "pass": true
+              }
+            ],
+            "overlap_count": 1,
+            "overlap_passed": 1
+          },
+          "similarity_score": 1.0
+        },
+        {
+          "topic": "HistoryExamples",
+          "title": "Using the History Class",
+          "python_ok": true,
+          "python_error": "",
+          "python_output_keys": [
+            "design_shape",
+            "lags",
+            "parity",
+            "topic"
+          ],
+          "python_scalar_count": 2,
+          "matlab_ok": true,
+          "matlab_error": "",
+          "matlab_error_report": "",
+          "matlab_fallback_error": "",
+          "matlab_fallback_error_report": "",
+          "matlab_figures": 3,
+          "matlab_var_count": 12,
+          "matlab_scalar_count": 3,
+          "matlab_script_used": "helpfiles/HistoryExamples.mlx",
+          "matlab_fallback_script_used": "",
+          "matlab_runtime_s": 30.391725063323975,
+          "scalar_overlap": {
+            "overlaps": [
+              {
+                "python_key": "figs",
+                "matlab_key": "figs",
+                "python": 3.0,
+                "matlab": 3.0,
+                "abs_diff": 0.0,
+                "pass": true
+              }
+            ],
+            "overlap_count": 1,
+            "overlap_passed": 1
+          },
+          "similarity_score": 1.0
+        },
+        {
+          "topic": "TrialExamples",
+          "title": "Using the Trial Class",
+          "python_ok": true,
+          "python_error": "",
+          "python_output_keys": [
+            "covariate_rows",
+            "neurons",
+            "parity",
+            "topic"
+          ],
+          "python_scalar_count": 4,
+          "matlab_ok": true,
+          "matlab_error": "",
+          "matlab_error_report": "",
+          "matlab_fallback_error": "",
+          "matlab_fallback_error_report": "",
+          "matlab_figures": 6,
+          "matlab_var_count": 16,
+          "matlab_scalar_count": 3,
+          "matlab_script_used": "helpfiles/TrialExamples.mlx",
+          "matlab_fallback_script_used": "",
+          "matlab_runtime_s": 13.00658917427063,
+          "scalar_overlap": {
+            "overlaps": [
+              {
+                "python_key": "figs",
+                "matlab_key": "figs",
+                "python": 6.0,
+                "matlab": 6.0,
+                "abs_diff": 0.0,
+                "pass": true
+              }
+            ],
+            "overlap_count": 1,
+            "overlap_passed": 1
+          },
+          "similarity_score": 1.0
+        },
+        {
+          "topic": "TrialConfigExamples",
+          "title": "Using the TrialConfig Class",
+          "python_ok": true,
+          "python_error": "",
+          "python_output_keys": [
+            "covariates",
+            "parity",
+            "sample_rate",
+            "topic"
+          ],
+          "python_scalar_count": 3,
+          "matlab_ok": true,
+          "matlab_error": "",
+          "matlab_error_report": "",
+          "matlab_fallback_error": "",
+          "matlab_fallback_error_report": "",
+          "matlab_figures": 0,
+          "matlab_var_count": 6,
+          "matlab_scalar_count": 2,
+          "matlab_script_used": "helpfiles/TrialConfigExamples.mlx",
+          "matlab_fallback_script_used": "",
+          "matlab_runtime_s": 7.838926076889038,
+          "scalar_overlap": {
+            "overlaps": [
+              {
+                "python_key": "figs",
+                "matlab_key": "figs",
+                "python": 0.0,
+                "matlab": 0.0,
+                "abs_diff": 0.0,
+                "pass": true
+              }
+            ],
+            "overlap_count": 1,
+            "overlap_passed": 1
+          },
+          "similarity_score": 1.0
+        },
+        {
+          "topic": "ConfigCollExamples",
+          "title": "Using the ConfigColl Class",
+          "python_ok": true,
+          "python_error": "",
+          "python_output_keys": [
+            "names",
+            "num_configs",
+            "parity",
+            "topic"
+          ],
+          "python_scalar_count": 3,
+          "matlab_ok": true,
+          "matlab_error": "",
+          "matlab_error_report": "",
+          "matlab_fallback_error": "",
+          "matlab_fallback_error_report": "",
+          "matlab_figures": 0,
+          "matlab_var_count": 6,
+          "matlab_scalar_count": 2,
+          "matlab_script_used": "helpfiles/ConfigCollExamples.mlx",
+          "matlab_fallback_script_used": "",
+          "matlab_runtime_s": 8.061589002609253,
+          "scalar_overlap": {
+            "overlaps": [
+              {
+                "python_key": "figs",
+                "matlab_key": "figs",
+                "python": 0.0,
+                "matlab": 0.0,
+                "abs_diff": 0.0,
+                "pass": true
+              }
+            ],
+            "overlap_count": 1,
+            "overlap_passed": 1
+          },
+          "similarity_score": 1.0
+        },
+        {
+          "topic": "AnalysisExamples",
+          "title": "Using the Analysis Class",
+          "python_ok": true,
+          "python_error": "",
+          "python_output_keys": [
+            "first_aic",
+            "num_results",
+            "parity",
+            "topic"
+          ],
+          "python_scalar_count": 4,
+          "matlab_ok": true,
+          "matlab_error": "",
+          "matlab_error_report": "",
+          "matlab_fallback_error": "",
+          "matlab_fallback_error_report": "",
+          "matlab_figures": 4,
+          "matlab_var_count": 40,
+          "matlab_scalar_count": 21,
+          "matlab_script_used": "helpfiles/AnalysisExamples.mlx",
+          "matlab_fallback_script_used": "",
+          "matlab_runtime_s": 10.786340713500977,
+          "scalar_overlap": {
+            "overlaps": [
+              {
+                "python_key": "figs",
+                "matlab_key": "figs",
+                "python": 4.0,
+                "matlab": 4.0,
+                "abs_diff": 0.0,
+                "pass": true
+              }
+            ],
+            "overlap_count": 1,
+            "overlap_passed": 1
+          },
+          "similarity_score": 1.0
+        },
+        {
+          "topic": "FitResultExamples",
+          "title": "Using the FitResult Class",
+          "python_ok": true,
+          "python_error": "",
+          "python_output_keys": [
+            "bic",
+            "coeffs",
+            "parity",
+            "topic"
+          ],
+          "python_scalar_count": 3,
+          "matlab_ok": true,
+          "matlab_error": "",
+          "matlab_error_report": "",
+          "matlab_fallback_error": "",
+          "matlab_fallback_error_report": "",
+          "matlab_figures": 0,
+          "matlab_var_count": 3,
+          "matlab_scalar_count": 2,
+          "matlab_script_used": "helpfiles/FitResultExamples.mlx",
+          "matlab_fallback_script_used": "",
+          "matlab_runtime_s": 8.028863906860352,
+          "scalar_overlap": {
+            "overlaps": [
+              {
+                "python_key": "figs",
+                "matlab_key": "figs",
+                "python": 0.0,
+                "matlab": 0.0,
+                "abs_diff": 0.0,
+                "pass": true
+              }
+            ],
+            "overlap_count": 1,
+            "overlap_passed": 1
+          },
+          "similarity_score": 1.0
+        },
+        {
+          "topic": "FitResSummaryExamples",
+          "title": "Using the FitResSummary Class",
+          "python_ok": true,
+          "python_error": "",
+          "python_output_keys": [
+            "mean_aic",
+            "mean_bic",
+            "parity",
+            "topic"
+          ],
+          "python_scalar_count": 2,
+          "matlab_ok": true,
+          "matlab_error": "",
+          "matlab_error_report": "",
+          "matlab_fallback_error": "",
+          "matlab_fallback_error_report": "",
+          "matlab_figures": 0,
+          "matlab_var_count": 3,
+          "matlab_scalar_count": 2,
+          "matlab_script_used": "helpfiles/FitResSummaryExamples.mlx",
+          "matlab_fallback_script_used": "",
+          "matlab_runtime_s": 8.054399967193604,
+          "scalar_overlap": {
+            "overlaps": [
+              {
+                "python_key": "figs",
+                "matlab_key": "figs",
+                "python": 0.0,
+                "matlab": 0.0,
+                "abs_diff": 0.0,
+                "pass": true
+              }
+            ],
+            "overlap_count": 1,
+            "overlap_passed": 1
+          },
+          "similarity_score": 1.0
+        },
+        {
+          "topic": "PPThinning",
+          "title": "Point Process Simulation via Thinning",
+          "python_ok": true,
+          "python_error": "",
+          "python_output_keys": [
+            "num_realizations",
+            "parity",
+            "topic"
+          ],
+          "python_scalar_count": 4,
+          "matlab_ok": true,
+          "matlab_error": "",
+          "matlab_error_report": "",
+          "matlab_fallback_error": "",
+          "matlab_fallback_error_report": "",
+          "matlab_figures": 3,
+          "matlab_var_count": 25,
+          "matlab_scalar_count": 10,
+          "matlab_script_used": "helpfiles/PPThinning.m",
+          "matlab_fallback_script_used": "",
+          "matlab_runtime_s": 20.007148027420044,
+          "scalar_overlap": {
+            "overlaps": [
+              {
+                "python_key": "num_realizations",
+                "matlab_key": "num_realizations",
+                "python": 20.0,
+                "matlab": 20.0,
+                "abs_diff": 0.0,
+                "pass": true
+              },
+              {
+                "python_key": "figs",
+                "matlab_key": "figs",
+                "python": 3.0,
+                "matlab": 3.0,
+                "abs_diff": 0.0,
+                "pass": true
+              },
+              {
+                "python_key": "parity.num_realizations",
+                "matlab_key": "parity_num_realizations",
+                "python": 20.0,
+                "matlab": 20.0,
+                "abs_diff": 0.0,
+                "pass": true
+              }
+            ],
+            "overlap_count": 3,
+            "overlap_passed": 3
+          },
+          "similarity_score": 1.0
+        },
+        {
+          "topic": "PSTHEstimation",
+          "title": "Example Data Analysis - Simulated Data - Computing a Peri-Stimulus Time Histogram (PSTH)",
+          "python_ok": true,
+          "python_error": "",
+          "python_output_keys": [
+            "num_realizations",
+            "parity",
+            "peak_rate",
+            "topic"
+          ],
+          "python_scalar_count": 5,
+          "matlab_ok": true,
+          "matlab_error": "",
+          "matlab_error_report": "",
+          "matlab_fallback_error": "",
+          "matlab_fallback_error_report": "",
+          "matlab_figures": 2,
+          "matlab_var_count": 23,
+          "matlab_scalar_count": 13,
+          "matlab_script_used": "helpfiles/PSTHEstimation.m",
+          "matlab_fallback_script_used": "",
+          "matlab_runtime_s": 19.249541997909546,
+          "scalar_overlap": {
+            "overlaps": [
+              {
+                "python_key": "num_realizations",
+                "matlab_key": "numRealizations",
+                "python": 20.0,
+                "matlab": 20.0,
+                "abs_diff": 0.0,
+                "pass": true
+              },
+              {
+                "python_key": "figs",
+                "matlab_key": "figs",
+                "python": 2.0,
+                "matlab": 2.0,
+                "abs_diff": 0.0,
+                "pass": true
+              }
+            ],
+            "overlap_count": 2,
+            "overlap_passed": 2
+          },
+          "similarity_score": 1.0
+        },
+        {
+          "topic": "ValidationDataSet",
+          "title": "Example Data Analysis - Simulated Constant (Piecewise Constant) Rate Poisson",
+          "python_ok": true,
+          "python_error": "",
+          "python_output_keys": [
+            "num_trials",
+            "parity",
+            "psth_mean_hz",
+            "psth_peak_hz",
+            "topic",
+            "total_spikes"
+          ],
+          "python_scalar_count": 6,
+          "matlab_ok": true,
+          "matlab_error": "",
+          "matlab_error_report": "",
+          "matlab_fallback_error": "",
+          "matlab_fallback_error_report": "",
+          "matlab_figures": 8,
+          "matlab_var_count": 41,
+          "matlab_scalar_count": 21,
+          "matlab_script_used": "helpfiles/ValidationDataSet.m",
+          "matlab_fallback_script_used": "",
+          "matlab_runtime_s": 26.339579105377197,
+          "scalar_overlap": {
+            "overlaps": [
+              {
+                "python_key": "figs",
+                "matlab_key": "figs",
+                "python": 8.0,
+                "matlab": 8.0,
+                "abs_diff": 0.0,
+                "pass": true
+              }
+            ],
+            "overlap_count": 1,
+            "overlap_passed": 1
+          },
+          "similarity_score": 1.0
+        },
+        {
+          "topic": "mEPSCAnalysis",
+          "title": "Example Data Analysis - Miniature Excitatory Post-Synaptic Currents (mEPSCs)",
+          "python_ok": true,
+          "python_error": "",
+          "python_output_keys": [
+            "const_condition_spikes",
+            "const_model_aic",
+            "const_model_bic",
+            "decreasing_condition_spikes",
+            "dt_seconds",
+            "parity",
+            "piecewise_history_model_aic",
+            "piecewise_history_model_bic",
+            "piecewise_model_aic",
+            "piecewise_model_bic",
+            "topic"
+          ],
+          "python_scalar_count": 11,
+          "matlab_ok": true,
+          "matlab_error": "",
+          "matlab_error_report": "",
+          "matlab_fallback_error": "",
+          "matlab_fallback_error_report": "",
+          "matlab_figures": 4,
+          "matlab_var_count": 31,
+          "matlab_scalar_count": 8,
+          "matlab_script_used": "helpfiles/mEPSCAnalysis.m",
+          "matlab_fallback_script_used": "",
+          "matlab_runtime_s": 51.48474884033203,
+          "scalar_overlap": {
+            "overlaps": [
+              {
+                "python_key": "figs",
+                "matlab_key": "figs",
+                "python": 4.0,
+                "matlab": 4.0,
+                "abs_diff": 0.0,
+                "pass": true
+              }
+            ],
+            "overlap_count": 1,
+            "overlap_passed": 1
+          },
+          "similarity_score": 1.0
+        },
+        {
+          "topic": "PPSimExample",
+          "title": "Example Data Analysis - Simulated Explicit Stimulus and History",
+          "python_ok": true,
+          "python_error": "",
+          "python_output_keys": [
+            "model1_aic",
+            "model1_bic",
+            "model2_aic",
+            "model2_bic",
+            "model3_aic",
+            "model3_bic",
+            "n_samples",
+            "parity",
+            "topic"
+          ],
+          "python_scalar_count": 9,
+          "matlab_ok": true,
+          "matlab_error": "",
+          "matlab_error_report": "",
+          "matlab_fallback_error": "",
+          "matlab_fallback_error_report": "",
+          "matlab_figures": 3,
+          "matlab_var_count": 33,
+          "matlab_scalar_count": 10,
+          "matlab_script_used": "helpfiles/PPSimExample.mlx",
+          "matlab_fallback_script_used": "",
+          "matlab_runtime_s": 44.576667070388794,
+          "scalar_overlap": {
+            "overlaps": [
+              {
+                "python_key": "figs",
+                "matlab_key": "figs",
+                "python": 3.0,
+                "matlab": 3.0,
+                "abs_diff": 0.0,
+                "pass": true
+              }
+            ],
+            "overlap_count": 1,
+            "overlap_passed": 1
+          },
+          "similarity_score": 1.0
+        },
+        {
+          "topic": "ExplicitStimulusWhiskerData",
+          "title": "Example Data Analysis - Explicit Stimulus",
+          "python_ok": true,
+          "python_error": "",
+          "python_output_keys": [
+            "model1_aic",
+            "model1_bic",
+            "model2_aic",
+            "model2_bic",
+            "model3_aic",
+            "model3_bic",
+            "n_samples",
+            "parity",
+            "topic"
+          ],
+          "python_scalar_count": 9,
+          "matlab_ok": true,
+          "matlab_error": "",
+          "matlab_error_report": "",
+          "matlab_fallback_error": "",
+          "matlab_fallback_error_report": "",
+          "matlab_figures": 8,
+          "matlab_var_count": 46,
+          "matlab_scalar_count": 22,
+          "matlab_script_used": "helpfiles/ExplicitStimulusWhiskerData.m",
+          "matlab_fallback_script_used": "",
+          "matlab_runtime_s": 27.45716691017151,
+          "scalar_overlap": {
+            "overlaps": [
+              {
+                "python_key": "figs",
+                "matlab_key": "figs",
+                "python": 8.0,
+                "matlab": 8.0,
+                "abs_diff": 0.0,
+                "pass": true
+              }
+            ],
+            "overlap_count": 1,
+            "overlap_passed": 1
+          },
+          "similarity_score": 1.0
+        },
+        {
+          "topic": "HippocampalPlaceCellExample",
+          "title": "Example Data Analysis - Hippocampal Place Cell Receptive Field Estimation",
+          "python_ok": true,
+          "python_error": "",
+          "python_output_keys": [
+            "mean_delta_aic_gaussian_minus_zernike",
+            "mean_delta_bic_gaussian_minus_zernike",
+            "num_cells_fit",
+            "parity",
+            "topic"
+          ],
+          "python_scalar_count": 5,
+          "matlab_ok": true,
+          "matlab_error": "",
+          "matlab_error_report": "",
+          "matlab_fallback_error": "",
+          "matlab_fallback_error_report": "",
+          "matlab_figures": 9,
+          "matlab_var_count": 47,
+          "matlab_scalar_count": 11,
+          "matlab_script_used": "helpfiles/HippocampalPlaceCellExample.mlx",
+          "matlab_fallback_script_used": "",
+          "matlab_runtime_s": 42.86396503448486,
+          "scalar_overlap": {
+            "overlaps": [
+              {
+                "python_key": "figs",
+                "matlab_key": "figs",
+                "python": 9.0,
+                "matlab": 9.0,
+                "abs_diff": 0.0,
+                "pass": true
+              }
+            ],
+            "overlap_count": 1,
+            "overlap_passed": 1
+          },
+          "similarity_score": 1.0
+        },
+        {
+          "topic": "DecodingExample",
+          "title": "Example Data Analysis - Decoding Univariate Simulated Stimuli (No History Effect)",
+          "python_ok": true,
+          "python_error": "",
+          "python_output_keys": [
+            "decode_rmse",
+            "num_cells",
+            "parity",
+            "topic"
+          ],
+          "python_scalar_count": 5,
+          "matlab_ok": true,
+          "matlab_error": "",
+          "matlab_error_report": "",
+          "matlab_fallback_error": "",
+          "matlab_fallback_error_report": "",
+          "matlab_figures": 5,
+          "matlab_var_count": 43,
+          "matlab_scalar_count": 11,
+          "matlab_script_used": "helpfiles/DecodingExample.mlx",
+          "matlab_fallback_script_used": "",
+          "matlab_runtime_s": 20.125417232513428,
+          "scalar_overlap": {
+            "overlaps": [
+              {
+                "python_key": "figs",
+                "matlab_key": "figs",
+                "python": 5.0,
+                "matlab": 5.0,
+                "abs_diff": 0.0,
+                "pass": true
+              }
+            ],
+            "overlap_count": 1,
+            "overlap_passed": 1
+          },
+          "similarity_score": 1.0
+        },
+        {
+          "topic": "DecodingExampleWithHist",
+          "title": "Example Data Analysis - Decoding Univariate Simulated Stimuli with and without History Effect",
+          "python_ok": true,
+          "python_error": "",
+          "python_output_keys": [
+            "decode_rmse_x",
+            "decode_rmse_y",
+            "num_cells",
+            "num_samples",
+            "parity",
+            "topic"
+          ],
+          "python_scalar_count": 7,
+          "matlab_ok": true,
+          "matlab_error": "",
+          "matlab_error_report": "",
+          "matlab_fallback_error": "",
+          "matlab_fallback_error_report": "",
+          "matlab_figures": 2,
+          "matlab_var_count": 46,
+          "matlab_scalar_count": 16,
+          "matlab_script_used": "helpfiles/DecodingExampleWithHist.m [shadow_safe_copy]",
+          "matlab_fallback_script_used": "",
+          "matlab_runtime_s": 129.56473088264465,
+          "scalar_overlap": {
+            "overlaps": [
+              {
+                "python_key": "figs",
+                "matlab_key": "figs",
+                "python": 2.0,
+                "matlab": 2.0,
+                "abs_diff": 0.0,
+                "pass": true
+              }
+            ],
+            "overlap_count": 1,
+            "overlap_passed": 1
+          },
+          "similarity_score": 1.0
+        },
+        {
+          "topic": "StimulusDecode2D",
+          "title": "Example Data Analysis - Decoding Bivariate Simulated Stimuli",
+          "python_ok": true,
+          "python_error": "",
+          "python_output_keys": [
+            "decode_rmse_x",
+            "decode_rmse_y",
+            "num_cells",
+            "num_samples",
+            "parity",
+            "topic"
+          ],
+          "python_scalar_count": 9,
+          "matlab_ok": true,
+          "matlab_error": "",
+          "matlab_error_report": "",
+          "matlab_fallback_error": "",
+          "matlab_fallback_error_report": "",
+          "matlab_figures": 4,
+          "matlab_var_count": 47,
+          "matlab_scalar_count": 13,
+          "matlab_script_used": "helpfiles/StimulusDecode2D.m",
+          "matlab_fallback_script_used": "",
+          "matlab_runtime_s": 15.194157123565674,
+          "scalar_overlap": {
+            "overlaps": [
+              {
+                "python_key": "num_cells",
+                "matlab_key": "num_cells",
+                "python": 80.0,
+                "matlab": 80.0,
+                "abs_diff": 0.0,
+                "pass": true
+              },
+              {
+                "python_key": "figs",
+                "matlab_key": "figs",
+                "python": 4.0,
+                "matlab": 4.0,
+                "abs_diff": 0.0,
+                "pass": true
+              },
+              {
+                "python_key": "parity.num_cells",
+                "matlab_key": "parity_num_cells",
+                "python": 80.0,
+                "matlab": 80.0,
+                "abs_diff": 0.0,
+                "pass": true
+              }
+            ],
+            "overlap_count": 3,
+            "overlap_passed": 3
+          },
+          "similarity_score": 1.0
+        },
+        {
+          "topic": "NetworkTutorial",
+          "title": "Example Data Analysis - Two Neuron Network Simulation and Estimation of Ensemble Effect",
+          "python_ok": true,
+          "python_error": "",
+          "python_output_keys": [
+            "neuron_count",
+            "parity",
+            "psth_peak",
+            "samples",
+            "topic"
+          ],
+          "python_scalar_count": 5,
+          "matlab_ok": true,
+          "matlab_error": "",
+          "matlab_error_report": "",
+          "matlab_fallback_error": "",
+          "matlab_fallback_error_report": "",
+          "matlab_figures": 4,
+          "matlab_var_count": 54,
+          "matlab_scalar_count": 13,
+          "matlab_script_used": "helpfiles/NetworkTutorial.m",
+          "matlab_fallback_script_used": "",
+          "matlab_runtime_s": 33.98667907714844,
+          "scalar_overlap": {
+            "overlaps": [
+              {
+                "python_key": "figs",
+                "matlab_key": "figs",
+                "python": 4.0,
+                "matlab": 4.0,
+                "abs_diff": 0.0,
+                "pass": true
+              }
+            ],
+            "overlap_count": 1,
+            "overlap_passed": 1
+          },
+          "similarity_score": 1.0
+        },
+        {
+          "topic": "nSTATPaperExamples",
+          "title": "nSTAT Paper Examples",
+          "python_ok": true,
+          "python_error": "",
+          "python_output_keys": [
+            "experiments",
+            "parity",
+            "summary",
+            "topic"
+          ],
+          "python_scalar_count": 30,
+          "matlab_ok": true,
+          "matlab_error": "",
+          "matlab_error_report": "",
+          "matlab_fallback_error": "",
+          "matlab_fallback_error_report": "",
+          "matlab_figures": 1,
+          "matlab_var_count": 79,
+          "matlab_scalar_count": 14,
+          "matlab_script_used": "helpfiles/nSTATPaperExamples.m [shadow_safe_copy]",
+          "matlab_fallback_script_used": "",
+          "matlab_runtime_s": 162.30554699897766,
+          "scalar_overlap": {
+            "overlaps": [
+              {
+                "python_key": "num_cells",
+                "matlab_key": "num_cells",
+                "python": 40.0,
+                "matlab": 40.0,
+                "abs_diff": 0.0,
+                "pass": true
+              },
+              {
+                "python_key": "figs",
+                "matlab_key": "figs",
+                "python": 1.0,
+                "matlab": 1.0,
+                "abs_diff": 0.0,
+                "pass": true
+              },
+              {
+                "python_key": "parity.num_cells",
+                "matlab_key": "parity_num_cells",
+                "python": 40.0,
+                "matlab": 40.0,
+                "abs_diff": 0.0,
+                "pass": true
+              }
+            ],
+            "overlap_count": 3,
+            "overlap_passed": 3
+          },
+          "similarity_score": 1.0
+        }
+      ]
+    },
+    "parity_contract": {
+      "pass": true,
+      "failures": [],
+      "rows": [
+        {
+          "topic": "SignalObjExamples",
+          "required_keys": [
+            "sample_rate_hz"
+          ],
+          "missing_keys": [],
+          "failing_keys": [],
+          "status": "pass"
+        },
+        {
+          "topic": "CovariateExamples",
+          "required_keys": [
+            "figs"
+          ],
+          "missing_keys": [],
+          "failing_keys": [],
+          "status": "pass"
+        },
+        {
+          "topic": "CovCollExamples",
+          "required_keys": [
+            "figs"
+          ],
+          "missing_keys": [],
+          "failing_keys": [],
+          "status": "pass"
+        },
+        {
+          "topic": "nSpikeTrainExamples",
+          "required_keys": [
+            "figs"
+          ],
+          "missing_keys": [],
+          "failing_keys": [],
+          "status": "pass"
+        },
+        {
+          "topic": "nstCollExamples",
+          "required_keys": [
+            "figs"
+          ],
+          "missing_keys": [],
+          "failing_keys": [],
+          "status": "pass"
+        },
+        {
+          "topic": "EventsExamples",
+          "required_keys": [
+            "figs"
+          ],
+          "missing_keys": [],
+          "failing_keys": [],
+          "status": "pass"
+        },
+        {
+          "topic": "HistoryExamples",
+          "required_keys": [
+            "figs"
+          ],
+          "missing_keys": [],
+          "failing_keys": [],
+          "status": "pass"
+        },
+        {
+          "topic": "TrialExamples",
+          "required_keys": [
+            "figs"
+          ],
+          "missing_keys": [],
+          "failing_keys": [],
+          "status": "pass"
+        },
+        {
+          "topic": "TrialConfigExamples",
+          "required_keys": [
+            "figs"
+          ],
+          "missing_keys": [],
+          "failing_keys": [],
+          "status": "pass"
+        },
+        {
+          "topic": "ConfigCollExamples",
+          "required_keys": [
+            "figs"
+          ],
+          "missing_keys": [],
+          "failing_keys": [],
+          "status": "pass"
+        },
+        {
+          "topic": "AnalysisExamples",
+          "required_keys": [
+            "figs"
+          ],
+          "missing_keys": [],
+          "failing_keys": [],
+          "status": "pass"
+        },
+        {
+          "topic": "FitResultExamples",
+          "required_keys": [
+            "figs"
+          ],
+          "missing_keys": [],
+          "failing_keys": [],
+          "status": "pass"
+        },
+        {
+          "topic": "FitResSummaryExamples",
+          "required_keys": [
+            "figs"
+          ],
+          "missing_keys": [],
+          "failing_keys": [],
+          "status": "pass"
+        },
+        {
+          "topic": "PPThinning",
+          "required_keys": [
+            "num_realizations"
+          ],
+          "missing_keys": [],
+          "failing_keys": [],
+          "status": "pass"
+        },
+        {
+          "topic": "PSTHEstimation",
+          "required_keys": [
+            "num_realizations"
+          ],
+          "missing_keys": [],
+          "failing_keys": [],
+          "status": "pass"
+        },
+        {
+          "topic": "ValidationDataSet",
+          "required_keys": [
+            "figs"
+          ],
+          "missing_keys": [],
+          "failing_keys": [],
+          "status": "pass"
+        },
+        {
+          "topic": "mEPSCAnalysis",
+          "required_keys": [
+            "figs"
+          ],
+          "missing_keys": [],
+          "failing_keys": [],
+          "status": "pass"
+        },
+        {
+          "topic": "PPSimExample",
+          "required_keys": [
+            "figs"
+          ],
+          "missing_keys": [],
+          "failing_keys": [],
+          "status": "pass"
+        },
+        {
+          "topic": "ExplicitStimulusWhiskerData",
+          "required_keys": [
+            "figs"
+          ],
+          "missing_keys": [],
+          "failing_keys": [],
+          "status": "pass"
+        },
+        {
+          "topic": "HippocampalPlaceCellExample",
+          "required_keys": [
+            "figs"
+          ],
+          "missing_keys": [],
+          "failing_keys": [],
+          "status": "pass"
+        },
+        {
+          "topic": "DecodingExample",
+          "required_keys": [
+            "figs"
+          ],
+          "missing_keys": [],
+          "failing_keys": [],
+          "status": "pass"
+        },
+        {
+          "topic": "DecodingExampleWithHist",
+          "required_keys": [
+            "figs"
+          ],
+          "missing_keys": [],
+          "failing_keys": [],
+          "status": "pass"
+        },
+        {
+          "topic": "StimulusDecode2D",
+          "required_keys": [
+            "num_cells"
+          ],
+          "missing_keys": [],
+          "failing_keys": [],
+          "status": "pass"
+        },
+        {
+          "topic": "NetworkTutorial",
+          "required_keys": [
+            "figs"
+          ],
+          "missing_keys": [],
+          "failing_keys": [],
+          "status": "pass"
+        },
+        {
+          "topic": "nSTATPaperExamples",
+          "required_keys": [
+            "num_cells"
+          ],
+          "missing_keys": [],
+          "failing_keys": [],
+          "status": "pass"
+        }
+      ]
+    },
+    "regression_gate": {
+      "pass": true,
+      "failures": [],
+      "matlab_failed_topics": [],
+      "known_allowlist": [],
+      "unexpected_failures": [],
+      "known_allowlist_not_currently_failing": [],
+      "parity_contract_pass": true
+    }
+  }
+}
\ No newline at end of file
diff --git a/reports/python_vs_matlab_similarity_report.json b/reports/python_vs_matlab_similarity_report.json
new file mode 100644
index 00000000..2b3d5ba6
--- /dev/null
+++ b/reports/python_vs_matlab_similarity_report.json
@@ -0,0 +1,1460 @@
+{
+  "class_similarity": {
+    "python": {
+      "nspike_getISIs": [
+        0.1,
+        0.2
+      ],
+      "nspike_rate": 3.0,
+      "nstcoll_psth_len": 5,
+      "nstcoll_psth_mean": 3.0,
+      "covcoll_shape": [
+        11,
+        2
+      ],
+      "history_num_columns": 2,
+      "trial_sample_rate": 10.0,
+      "trial_minmax": [
+        0.0,
+        1.0
+      ],
+      "cif_num_realizations": 3
+    },
+    "matlab": {
+      "nspike_getISIs": [
+        0.1,
+        0.2
+      ],
+      "nspike_rate": 3,
+      "nstcoll_psth_len": 5,
+      "nstcoll_psth_mean": 3,
+      "covcoll_shape": [
+        11,
+        2
+      ],
+      "history_num_columns": 2,
+      "trial_sample_rate": 10,
+      "trial_minmax": [
+        0,
+        1
+      ],
+      "cif_num_realizations": 3
+    },
+    "comparisons": [
+      {
+        "metric": "nspike_getISIs",
+        "python": [
+          0.1,
+          0.2
+        ],
+        "matlab": [
+          0.1,
+          0.2
+        ],
+        "pass": true
+      },
+      {
+        "metric": "nspike_rate",
+        "python": 3.0,
+        "matlab": 3.0,
+        "abs_diff": 0.0,
+        "pass": true
+      },
+      {
+        "metric": "nstcoll_psth_len",
+        "python": 5.0,
+        "matlab": 5.0,
+        "abs_diff": 0.0,
+        "pass": true
+      },
+      {
+        "metric": "nstcoll_psth_mean",
+        "python": 3.0,
+        "matlab": 3.0,
+        "abs_diff": 0.0,
+        "pass": true
+      },
+      {
+        "metric": "covcoll_shape",
+        "python": [
+          11.0,
+          2.0
+        ],
+        "matlab": [
+          11.0,
+          2.0
+        ],
+        "pass": true
+      },
+      {
+        "metric": "history_num_columns",
+        "python": 2.0,
+        "matlab": 2.0,
+        "abs_diff": 0.0,
+        "pass": true
+      },
+      {
+        "metric": "trial_sample_rate",
+        "python": 10.0,
+        "matlab": 10.0,
+        "abs_diff": 0.0,
+        "pass": true
+      },
+      {
+        "metric": "trial_minmax",
+        "python": [
+          0.0,
+          1.0
+        ],
+        "matlab": [
+          0.0,
+          1.0
+        ],
+        "pass": true
+      },
+      {
+        "metric": "cif_num_realizations",
+        "python": 3.0,
+        "matlab": 3.0,
+        "abs_diff": 0.0,
+        "pass": true
+      }
+    ],
+    "summary": {
+      "passed": 9,
+      "total": 9,
+      "similarity_score": 1.0
+    }
+  },
+  "helpfile_similarity": {
+    "summary": {
+      "total_topics": 25,
+      "both_ok": 25,
+      "python_ok": 25,
+      "matlab_ok": 25,
+      "scalar_overlap_topics": 25,
+      "scalar_overlap_pass_topics": 25,
+      "avg_similarity_score": 1.0
+    },
+    "rows": [
+      {
+        "topic": "SignalObjExamples",
+        "title": "Using the SignalObj Class",
+        "python_ok": true,
+        "python_error": "",
+        "python_output_keys": [
+          "dimension",
+          "parity",
+          "sample_rate",
+          "topic"
+        ],
+        "python_scalar_count": 6,
+        "matlab_ok": true,
+        "matlab_error": "",
+        "matlab_error_report": "",
+        "matlab_fallback_error": "",
+        "matlab_fallback_error_report": "",
+        "matlab_figures": 16,
+        "matlab_var_count": 19,
+        "matlab_scalar_count": 6,
+        "matlab_script_used": "helpfiles/SignalObjExamples.m [shadow_safe_copy]",
+        "matlab_fallback_script_used": "",
+        "matlab_runtime_s": 12.859008073806763,
+        "scalar_overlap": {
+          "overlaps": [
+            {
+              "python_key": "sample_rate",
+              "matlab_key": "sampleRate",
+              "python": 5000.00000000055,
+              "matlab": 5000.0,
+              "abs_diff": 5.502442945726216e-10,
+              "pass": true
+            },
+            {
+              "python_key": "figs",
+              "matlab_key": "figs",
+              "python": 16.0,
+              "matlab": 16.0,
+              "abs_diff": 0.0,
+              "pass": true
+            },
+            {
+              "python_key": "parity.sample_rate_hz",
+              "matlab_key": "parity_sample_rate_hz",
+              "python": 5000.00000000055,
+              "matlab": 5000.0,
+              "abs_diff": 5.502442945726216e-10,
+              "pass": true
+            },
+            {
+              "python_key": "sample_rate_hz",
+              "matlab_key": "sample_rate_hz",
+              "python": 5000.00000000055,
+              "matlab": 5000.0,
+              "abs_diff": 5.502442945726216e-10,
+              "pass": true
+            }
+          ],
+          "overlap_count": 4,
+          "overlap_passed": 4
+        },
+        "similarity_score": 1.0
+      },
+      {
+        "topic": "CovariateExamples",
+        "title": "Using the Covariate Class",
+        "python_ok": true,
+        "python_error": "",
+        "python_output_keys": [
+          "mean",
+          "parity",
+          "std",
+          "topic"
+        ],
+        "python_scalar_count": 4,
+        "matlab_ok": true,
+        "matlab_error": "",
+        "matlab_error_report": "",
+        "matlab_fallback_error": "",
+        "matlab_fallback_error_report": "",
+        "matlab_figures": 2,
+        "matlab_var_count": 16,
+        "matlab_scalar_count": 2,
+        "matlab_script_used": "helpfiles/CovariateExamples.mlx",
+        "matlab_fallback_script_used": "",
+        "matlab_runtime_s": 10.382561206817627,
+        "scalar_overlap": {
+          "overlaps": [
+            {
+              "python_key": "figs",
+              "matlab_key": "figs",
+              "python": 2.0,
+              "matlab": 2.0,
+              "abs_diff": 0.0,
+              "pass": true
+            }
+          ],
+          "overlap_count": 1,
+          "overlap_passed": 1
+        },
+        "similarity_score": 1.0
+      },
+      {
+        "topic": "CovCollExamples",
+        "title": "Using the CovColl Class",
+        "python_ok": true,
+        "python_error": "",
+        "python_output_keys": [
+          "labels",
+          "matrix_shape",
+          "parity",
+          "topic"
+        ],
+        "python_scalar_count": 2,
+        "matlab_ok": true,
+        "matlab_error": "",
+        "matlab_error_report": "",
+        "matlab_fallback_error": "",
+        "matlab_fallback_error_report": "",
+        "matlab_figures": 2,
+        "matlab_var_count": 7,
+        "matlab_scalar_count": 2,
+        "matlab_script_used": "helpfiles/CovCollExamples.mlx",
+        "matlab_fallback_script_used": "",
+        "matlab_runtime_s": 10.461670160293579,
+        "scalar_overlap": {
+          "overlaps": [
+            {
+              "python_key": "figs",
+              "matlab_key": "figs",
+              "python": 2.0,
+              "matlab": 2.0,
+              "abs_diff": 0.0,
+              "pass": true
+            }
+          ],
+          "overlap_count": 1,
+          "overlap_passed": 1
+        },
+        "similarity_score": 1.0
+      },
+      {
+        "topic": "nSpikeTrainExamples",
+        "title": "Using the nSpikeTrain Class",
+        "python_ok": true,
+        "python_error": "",
+        "python_output_keys": [
+          "n_spikes",
+          "parity",
+          "rate_hz",
+          "topic"
+        ],
+        "python_scalar_count": 4,
+        "matlab_ok": true,
+        "matlab_error": "",
+        "matlab_error_report": "",
+        "matlab_fallback_error": "",
+        "matlab_fallback_error_report": "",
+        "matlab_figures": 4,
+        "matlab_var_count": 6,
+        "matlab_scalar_count": 2,
+        "matlab_script_used": "helpfiles/nSpikeTrainExamples.mlx",
+        "matlab_fallback_script_used": "",
+        "matlab_runtime_s": 30.248419046401978,
+        "scalar_overlap": {
+          "overlaps": [
+            {
+              "python_key": "figs",
+              "matlab_key": "figs",
+              "python": 4.0,
+              "matlab": 4.0,
+              "abs_diff": 0.0,
+              "pass": true
+            }
+          ],
+          "overlap_count": 1,
+          "overlap_passed": 1
+        },
+        "similarity_score": 1.0
+      },
+      {
+        "topic": "nstCollExamples",
+        "title": "Using the nstColl Class",
+        "python_ok": true,
+        "python_error": "",
+        "python_output_keys": [
+          "num_trains",
+          "parity",
+          "psth_points",
+          "topic"
+        ],
+        "python_scalar_count": 4,
+        "matlab_ok": true,
+        "matlab_error": "",
+        "matlab_error_report": "",
+        "matlab_fallback_error": "",
+        "matlab_fallback_error_report": "",
+        "matlab_figures": 3,
+        "matlab_var_count": 8,
+        "matlab_scalar_count": 2,
+        "matlab_script_used": "helpfiles/nstCollExamples.mlx",
+        "matlab_fallback_script_used": "",
+        "matlab_runtime_s": 10.848538875579834,
+        "scalar_overlap": {
+          "overlaps": [
+            {
+              "python_key": "figs",
+              "matlab_key": "figs",
+              "python": 3.0,
+              "matlab": 3.0,
+              "abs_diff": 0.0,
+              "pass": true
+            }
+          ],
+          "overlap_count": 1,
+          "overlap_passed": 1
+        },
+        "similarity_score": 1.0
+      },
+      {
+        "topic": "EventsExamples",
+        "title": "Using the Events Class",
+        "python_ok": true,
+        "python_error": "",
+        "python_output_keys": [
+          "n_events",
+          "parity",
+          "topic"
+        ],
+        "python_scalar_count": 3,
+        "matlab_ok": true,
+        "matlab_error": "",
+        "matlab_error_report": "",
+        "matlab_fallback_error": "",
+        "matlab_fallback_error_report": "",
+        "matlab_figures": 3,
+        "matlab_var_count": 8,
+        "matlab_scalar_count": 2,
+        "matlab_script_used": "helpfiles/EventsExamples.mlx",
+        "matlab_fallback_script_used": "",
+        "matlab_runtime_s": 9.690116167068481,
+        "scalar_overlap": {
+          "overlaps": [
+            {
+              "python_key": "figs",
+              "matlab_key": "figs",
+              "python": 3.0,
+              "matlab": 3.0,
+              "abs_diff": 0.0,
+              "pass": true
+            }
+          ],
+          "overlap_count": 1,
+          "overlap_passed": 1
+        },
+        "similarity_score": 1.0
+      },
+      {
+        "topic": "HistoryExamples",
+        "title": "Using the History Class",
+        "python_ok": true,
+        "python_error": "",
+        "python_output_keys": [
+          "design_shape",
+          "lags",
+          "parity",
+          "topic"
+        ],
+        "python_scalar_count": 2,
+        "matlab_ok": true,
+        "matlab_error": "",
+        "matlab_error_report": "",
+        "matlab_fallback_error": "",
+        "matlab_fallback_error_report": "",
+        "matlab_figures": 3,
+        "matlab_var_count": 12,
+        "matlab_scalar_count": 3,
+        "matlab_script_used": "helpfiles/HistoryExamples.mlx",
+        "matlab_fallback_script_used": "",
+        "matlab_runtime_s": 30.391725063323975,
+        "scalar_overlap": {
+          "overlaps": [
+            {
+              "python_key": "figs",
+              "matlab_key": "figs",
+              "python": 3.0,
+              "matlab": 3.0,
+              "abs_diff": 0.0,
+              "pass": true
+            }
+          ],
+          "overlap_count": 1,
+          "overlap_passed": 1
+        },
+        "similarity_score": 1.0
+      },
+      {
+        "topic": "TrialExamples",
+        "title": "Using the Trial Class",
+        "python_ok": true,
+        "python_error": "",
+        "python_output_keys": [
+          "covariate_rows",
+          "neurons",
+          "parity",
+          "topic"
+        ],
+        "python_scalar_count": 4,
+        "matlab_ok": true,
+        "matlab_error": "",
+        "matlab_error_report": "",
+        "matlab_fallback_error": "",
+        "matlab_fallback_error_report": "",
+        "matlab_figures": 6,
+        "matlab_var_count": 16,
+        "matlab_scalar_count": 3,
+        "matlab_script_used": "helpfiles/TrialExamples.mlx",
+        "matlab_fallback_script_used": "",
+        "matlab_runtime_s": 13.00658917427063,
+        "scalar_overlap": {
+          "overlaps": [
+            {
+              "python_key": "figs",
+              "matlab_key": "figs",
+              "python": 6.0,
+              "matlab": 6.0,
+              "abs_diff": 0.0,
+              "pass": true
+            }
+          ],
+          "overlap_count": 1,
+          "overlap_passed": 1
+        },
+        "similarity_score": 1.0
+      },
+      {
+        "topic": "TrialConfigExamples",
+        "title": "Using the TrialConfig Class",
+        "python_ok": true,
+        "python_error": "",
+        "python_output_keys": [
+          "covariates",
+          "parity",
+          "sample_rate",
+          "topic"
+        ],
+        "python_scalar_count": 3,
+        "matlab_ok": true,
+        "matlab_error": "",
+        "matlab_error_report": "",
+        "matlab_fallback_error": "",
+        "matlab_fallback_error_report": "",
+        "matlab_figures": 0,
+        "matlab_var_count": 6,
+        "matlab_scalar_count": 2,
+        "matlab_script_used": "helpfiles/TrialConfigExamples.mlx",
+        "matlab_fallback_script_used": "",
+        "matlab_runtime_s": 7.838926076889038,
+        "scalar_overlap": {
+          "overlaps": [
+            {
+              "python_key": "figs",
+              "matlab_key": "figs",
+              "python": 0.0,
+              "matlab": 0.0,
+              "abs_diff": 0.0,
+              "pass": true
+            }
+          ],
+          "overlap_count": 1,
+          "overlap_passed": 1
+        },
+        "similarity_score": 1.0
+      },
+      {
+        "topic": "ConfigCollExamples",
+        "title": "Using the ConfigColl Class",
+        "python_ok": true,
+        "python_error": "",
+        "python_output_keys": [
+          "names",
+          "num_configs",
+          "parity",
+          "topic"
+        ],
+        "python_scalar_count": 3,
+        "matlab_ok": true,
+        "matlab_error": "",
+        "matlab_error_report": "",
+        "matlab_fallback_error": "",
+        "matlab_fallback_error_report": "",
+        "matlab_figures": 0,
+        "matlab_var_count": 6,
+        "matlab_scalar_count": 2,
+        "matlab_script_used": "helpfiles/ConfigCollExamples.mlx",
+        "matlab_fallback_script_used": "",
+        "matlab_runtime_s": 8.061589002609253,
+        "scalar_overlap": {
+          "overlaps": [
+            {
+              "python_key": "figs",
+              "matlab_key": "figs",
+              "python": 0.0,
+              "matlab": 0.0,
+              "abs_diff": 0.0,
+              "pass": true
+            }
+          ],
+          "overlap_count": 1,
+          "overlap_passed": 1
+        },
+        "similarity_score": 1.0
+      },
+      {
+        "topic": "AnalysisExamples",
+        "title": "Using the Analysis Class",
+        "python_ok": true,
+        "python_error": "",
+        "python_output_keys": [
+          "first_aic",
+          "num_results",
+          "parity",
+          "topic"
+        ],
+        "python_scalar_count": 4,
+        "matlab_ok": true,
+        "matlab_error": "",
+        "matlab_error_report": "",
+        "matlab_fallback_error": "",
+        "matlab_fallback_error_report": "",
+        "matlab_figures": 4,
+        "matlab_var_count": 40,
+        "matlab_scalar_count": 21,
+        "matlab_script_used": "helpfiles/AnalysisExamples.mlx",
+        "matlab_fallback_script_used": "",
+        "matlab_runtime_s": 10.786340713500977,
+        "scalar_overlap": {
+          "overlaps": [
+            {
+              "python_key": "figs",
+              "matlab_key": "figs",
+              "python": 4.0,
+              "matlab": 4.0,
+              "abs_diff": 0.0,
+              "pass": true
+            }
+          ],
+          "overlap_count": 1,
+          "overlap_passed": 1
+        },
+        "similarity_score": 1.0
+      },
+      {
+        "topic": "FitResultExamples",
+        "title": "Using the FitResult Class",
+        "python_ok": true,
+        "python_error": "",
+        "python_output_keys": [
+          "bic",
+          "coeffs",
+          "parity",
+          "topic"
+        ],
+        "python_scalar_count": 3,
+        "matlab_ok": true,
+        "matlab_error": "",
+        "matlab_error_report": "",
+        "matlab_fallback_error": "",
+        "matlab_fallback_error_report": "",
+        "matlab_figures": 0,
+        "matlab_var_count": 3,
+        "matlab_scalar_count": 2,
+        "matlab_script_used": "helpfiles/FitResultExamples.mlx",
+        "matlab_fallback_script_used": "",
+        "matlab_runtime_s": 8.028863906860352,
+        "scalar_overlap": {
+          "overlaps": [
+            {
+              "python_key": "figs",
+              "matlab_key": "figs",
+              "python": 0.0,
+              "matlab": 0.0,
+              "abs_diff": 0.0,
+              "pass": true
+            }
+          ],
+          "overlap_count": 1,
+          "overlap_passed": 1
+        },
+        "similarity_score": 1.0
+      },
+      {
+        "topic": "FitResSummaryExamples",
+        "title": "Using the FitResSummary Class",
+        "python_ok": true,
+        "python_error": "",
+        "python_output_keys": [
+          "mean_aic",
+          "mean_bic",
+          "parity",
+          "topic"
+        ],
+        "python_scalar_count": 2,
+        "matlab_ok": true,
+        "matlab_error": "",
+        "matlab_error_report": "",
+        "matlab_fallback_error": "",
+        "matlab_fallback_error_report": "",
+        "matlab_figures": 0,
+        "matlab_var_count": 3,
+        "matlab_scalar_count": 2,
+        "matlab_script_used": "helpfiles/FitResSummaryExamples.mlx",
+        "matlab_fallback_script_used": "",
+        "matlab_runtime_s": 8.054399967193604,
+        "scalar_overlap": {
+          "overlaps": [
+            {
+              "python_key": "figs",
+              "matlab_key": "figs",
+              "python": 0.0,
+              "matlab": 0.0,
+              "abs_diff": 0.0,
+              "pass": true
+            }
+          ],
+          "overlap_count": 1,
+          "overlap_passed": 1
+        },
+        "similarity_score": 1.0
+      },
+      {
+        "topic": "PPThinning",
+        "title": "Point Process Simulation via Thinning",
+        "python_ok": true,
+        "python_error": "",
+        "python_output_keys": [
+          "num_realizations",
+          "parity",
+          "topic"
+        ],
+        "python_scalar_count": 4,
+        "matlab_ok": true,
+        "matlab_error": "",
+        "matlab_error_report": "",
+        "matlab_fallback_error": "",
+        "matlab_fallback_error_report": "",
+        "matlab_figures": 3,
+        "matlab_var_count": 25,
+        "matlab_scalar_count": 10,
+        "matlab_script_used": "helpfiles/PPThinning.m",
+        "matlab_fallback_script_used": "",
+        "matlab_runtime_s": 20.007148027420044,
+        "scalar_overlap": {
+          "overlaps": [
+            {
+              "python_key": "num_realizations",
+              "matlab_key": "num_realizations",
+              "python": 20.0,
+              "matlab": 20.0,
+              "abs_diff": 0.0,
+              "pass": true
+            },
+            {
+              "python_key": "figs",
+              "matlab_key": "figs",
+              "python": 3.0,
+              "matlab": 3.0,
+              "abs_diff": 0.0,
+              "pass": true
+            },
+            {
+              "python_key": "parity.num_realizations",
+              "matlab_key": "parity_num_realizations",
+              "python": 20.0,
+              "matlab": 20.0,
+              "abs_diff": 0.0,
+              "pass": true
+            }
+          ],
+          "overlap_count": 3,
+          "overlap_passed": 3
+        },
+        "similarity_score": 1.0
+      },
+      {
+        "topic": "PSTHEstimation",
+        "title": "Example Data Analysis - Simulated Data - Computing a Peri-Stimulus Time Histogram (PSTH)",
+        "python_ok": true,
+        "python_error": "",
+        "python_output_keys": [
+          "num_realizations",
+          "parity",
+          "peak_rate",
+          "topic"
+        ],
+        "python_scalar_count": 5,
+        "matlab_ok": true,
+        "matlab_error": "",
+        "matlab_error_report": "",
+        "matlab_fallback_error": "",
+        "matlab_fallback_error_report": "",
+        "matlab_figures": 2,
+        "matlab_var_count": 23,
+        "matlab_scalar_count": 13,
+        "matlab_script_used": "helpfiles/PSTHEstimation.m",
+        "matlab_fallback_script_used": "",
+        "matlab_runtime_s": 19.249541997909546,
+        "scalar_overlap": {
+          "overlaps": [
+            {
+              "python_key": "num_realizations",
+              "matlab_key": "numRealizations",
+              "python": 20.0,
+              "matlab": 20.0,
+              "abs_diff": 0.0,
+              "pass": true
+            },
+            {
+              "python_key": "figs",
+              "matlab_key": "figs",
+              "python": 2.0,
+              "matlab": 2.0,
+              "abs_diff": 0.0,
+              "pass": true
+            }
+          ],
+          "overlap_count": 2,
+          "overlap_passed": 2
+        },
+        "similarity_score": 1.0
+      },
+      {
+        "topic": "ValidationDataSet",
+        "title": "Example Data Analysis - Simulated Constant (Piecewise Constant) Rate Poisson",
+        "python_ok": true,
+        "python_error": "",
+        "python_output_keys": [
+          "num_trials",
+          "parity",
+          "psth_mean_hz",
+          "psth_peak_hz",
+          "topic",
+          "total_spikes"
+        ],
+        "python_scalar_count": 6,
+        "matlab_ok": true,
+        "matlab_error": "",
+        "matlab_error_report": "",
+        "matlab_fallback_error": "",
+        "matlab_fallback_error_report": "",
+        "matlab_figures": 8,
+        "matlab_var_count": 41,
+        "matlab_scalar_count": 21,
+        "matlab_script_used": "helpfiles/ValidationDataSet.m",
+        "matlab_fallback_script_used": "",
+        "matlab_runtime_s": 26.339579105377197,
+        "scalar_overlap": {
+          "overlaps": [
+            {
+              "python_key": "figs",
+              "matlab_key": "figs",
+              "python": 8.0,
+              "matlab": 8.0,
+              "abs_diff": 0.0,
+              "pass": true
+            }
+          ],
+          "overlap_count": 1,
+          "overlap_passed": 1
+        },
+        "similarity_score": 1.0
+      },
+      {
+        "topic": "mEPSCAnalysis",
+        "title": "Example Data Analysis - Miniature Excitatory Post-Synaptic Currents (mEPSCs)",
+        "python_ok": true,
+        "python_error": "",
+        "python_output_keys": [
+          "const_condition_spikes",
+          "const_model_aic",
+          "const_model_bic",
+          "decreasing_condition_spikes",
+          "dt_seconds",
+          "parity",
+          "piecewise_history_model_aic",
+          "piecewise_history_model_bic",
+          "piecewise_model_aic",
+          "piecewise_model_bic",
+          "topic"
+        ],
+        "python_scalar_count": 11,
+        "matlab_ok": true,
+        "matlab_error": "",
+        "matlab_error_report": "",
+        "matlab_fallback_error": "",
+        "matlab_fallback_error_report": "",
+        "matlab_figures": 4,
+        "matlab_var_count": 31,
+        "matlab_scalar_count": 8,
+        "matlab_script_used": "helpfiles/mEPSCAnalysis.m",
+        "matlab_fallback_script_used": "",
+        "matlab_runtime_s": 51.48474884033203,
+        "scalar_overlap": {
+          "overlaps": [
+            {
+              "python_key": "figs",
+              "matlab_key": "figs",
+              "python": 4.0,
+              "matlab": 4.0,
+              "abs_diff": 0.0,
+              "pass": true
+            }
+          ],
+          "overlap_count": 1,
+          "overlap_passed": 1
+        },
+        "similarity_score": 1.0
+      },
+      {
+        "topic": "PPSimExample",
+        "title": "Example Data Analysis - Simulated Explicit Stimulus and History",
+        "python_ok": true,
+        "python_error": "",
+        "python_output_keys": [
+          "model1_aic",
+          "model1_bic",
+          "model2_aic",
+          "model2_bic",
+          "model3_aic",
+          "model3_bic",
+          "n_samples",
+          "parity",
+          "topic"
+        ],
+        "python_scalar_count": 9,
+        "matlab_ok": true,
+        "matlab_error": "",
+        "matlab_error_report": "",
+        "matlab_fallback_error": "",
+        "matlab_fallback_error_report": "",
+        "matlab_figures": 3,
+        "matlab_var_count": 33,
+        "matlab_scalar_count": 10,
+        "matlab_script_used": "helpfiles/PPSimExample.mlx",
+        "matlab_fallback_script_used": "",
+        "matlab_runtime_s": 44.576667070388794,
+        "scalar_overlap": {
+          "overlaps": [
+            {
+              "python_key": "figs",
+              "matlab_key": "figs",
+              "python": 3.0,
+              "matlab": 3.0,
+              "abs_diff": 0.0,
+              "pass": true
+            }
+          ],
+          "overlap_count": 1,
+          "overlap_passed": 1
+        },
+        "similarity_score": 1.0
+      },
+      {
+        "topic": "ExplicitStimulusWhiskerData",
+        "title": "Example Data Analysis - Explicit Stimulus",
+        "python_ok": true,
+        "python_error": "",
+        "python_output_keys": [
+          "model1_aic",
+          "model1_bic",
+          "model2_aic",
+          "model2_bic",
+          "model3_aic",
+          "model3_bic",
+          "n_samples",
+          "parity",
+          "topic"
+        ],
+        "python_scalar_count": 9,
+        "matlab_ok": true,
+        "matlab_error": "",
+        "matlab_error_report": "",
+        "matlab_fallback_error": "",
+        "matlab_fallback_error_report": "",
+        "matlab_figures": 8,
+        "matlab_var_count": 46,
+        "matlab_scalar_count": 22,
+        "matlab_script_used": "helpfiles/ExplicitStimulusWhiskerData.m",
+        "matlab_fallback_script_used": "",
+        "matlab_runtime_s": 27.45716691017151,
+        "scalar_overlap": {
+          "overlaps": [
+            {
+              "python_key": "figs",
+              "matlab_key": "figs",
+              "python": 8.0,
+              "matlab": 8.0,
+              "abs_diff": 0.0,
+              "pass": true
+            }
+          ],
+          "overlap_count": 1,
+          "overlap_passed": 1
+        },
+        "similarity_score": 1.0
+      },
+      {
+        "topic": "HippocampalPlaceCellExample",
+        "title": "Example Data Analysis - Hippocampal Place Cell Receptive Field Estimation",
+        "python_ok": true,
+        "python_error": "",
+        "python_output_keys": [
+          "mean_delta_aic_gaussian_minus_zernike",
+          "mean_delta_bic_gaussian_minus_zernike",
+          "num_cells_fit",
+          "parity",
+          "topic"
+        ],
+        "python_scalar_count": 5,
+        "matlab_ok": true,
+        "matlab_error": "",
+        "matlab_error_report": "",
+        "matlab_fallback_error": "",
+        "matlab_fallback_error_report": "",
+        "matlab_figures": 9,
+        "matlab_var_count": 47,
+        "matlab_scalar_count": 11,
+        "matlab_script_used": "helpfiles/HippocampalPlaceCellExample.mlx",
+        "matlab_fallback_script_used": "",
+        "matlab_runtime_s": 42.86396503448486,
+        "scalar_overlap": {
+          "overlaps": [
+            {
+              "python_key": "figs",
+              "matlab_key": "figs",
+              "python": 9.0,
+              "matlab": 9.0,
+              "abs_diff": 0.0,
+              "pass": true
+            }
+          ],
+          "overlap_count": 1,
+          "overlap_passed": 1
+        },
+        "similarity_score": 1.0
+      },
+      {
+        "topic": "DecodingExample",
+        "title": "Example Data Analysis - Decoding Univariate Simulated Stimuli (No History Effect)",
+        "python_ok": true,
+        "python_error": "",
+        "python_output_keys": [
+          "decode_rmse",
+          "num_cells",
+          "parity",
+          "topic"
+        ],
+        "python_scalar_count": 5,
+        "matlab_ok": true,
+        "matlab_error": "",
+        "matlab_error_report": "",
+        "matlab_fallback_error": "",
+        "matlab_fallback_error_report": "",
+        "matlab_figures": 5,
+        "matlab_var_count": 43,
+        "matlab_scalar_count": 11,
+        "matlab_script_used": "helpfiles/DecodingExample.mlx",
+        "matlab_fallback_script_used": "",
+        "matlab_runtime_s": 20.125417232513428,
+        "scalar_overlap": {
+          "overlaps": [
+            {
+              "python_key": "figs",
+              "matlab_key": "figs",
+              "python": 5.0,
+              "matlab": 5.0,
+              "abs_diff": 0.0,
+              "pass": true
+            }
+          ],
+          "overlap_count": 1,
+          "overlap_passed": 1
+        },
+        "similarity_score": 1.0
+      },
+      {
+        "topic": "DecodingExampleWithHist",
+        "title": "Example Data Analysis - Decoding Univariate Simulated Stimuli with and without History Effect",
+        "python_ok": true,
+        "python_error": "",
+        "python_output_keys": [
+          "decode_rmse_x",
+          "decode_rmse_y",
+          "num_cells",
+          "num_samples",
+          "parity",
+          "topic"
+        ],
+        "python_scalar_count": 7,
+        "matlab_ok": true,
+        "matlab_error": "",
+        "matlab_error_report": "",
+        "matlab_fallback_error": "",
+        "matlab_fallback_error_report": "",
+        "matlab_figures": 2,
+        "matlab_var_count": 46,
+        "matlab_scalar_count": 16,
+        "matlab_script_used": "helpfiles/DecodingExampleWithHist.m [shadow_safe_copy]",
+        "matlab_fallback_script_used": "",
+        "matlab_runtime_s": 129.56473088264465,
+        "scalar_overlap": {
+          "overlaps": [
+            {
+              "python_key": "figs",
+              "matlab_key": "figs",
+              "python": 2.0,
+              "matlab": 2.0,
+              "abs_diff": 0.0,
+              "pass": true
+            }
+          ],
+          "overlap_count": 1,
+          "overlap_passed": 1
+        },
+        "similarity_score": 1.0
+      },
+      {
+        "topic": "StimulusDecode2D",
+        "title": "Example Data Analysis - Decoding Bivariate Simulated Stimuli",
+        "python_ok": true,
+        "python_error": "",
+        "python_output_keys": [
+          "decode_rmse_x",
+          "decode_rmse_y",
+          "num_cells",
+          "num_samples",
+          "parity",
+          "topic"
+        ],
+        "python_scalar_count": 9,
+        "matlab_ok": true,
+        "matlab_error": "",
+        "matlab_error_report": "",
+        "matlab_fallback_error": "",
+        "matlab_fallback_error_report": "",
+        "matlab_figures": 4,
+        "matlab_var_count": 47,
+        "matlab_scalar_count": 13,
+        "matlab_script_used": "helpfiles/StimulusDecode2D.m",
+        "matlab_fallback_script_used": "",
+        "matlab_runtime_s": 15.194157123565674,
+        "scalar_overlap": {
+          "overlaps": [
+            {
+              "python_key": "num_cells",
+              "matlab_key": "num_cells",
+              "python": 80.0,
+              "matlab": 80.0,
+              "abs_diff": 0.0,
+              "pass": true
+            },
+            {
+              "python_key": "figs",
+              "matlab_key": "figs",
+              "python": 4.0,
+              "matlab": 4.0,
+              "abs_diff": 0.0,
+              "pass": true
+            },
+            {
+              "python_key": "parity.num_cells",
+              "matlab_key": "parity_num_cells",
+              "python": 80.0,
+              "matlab": 80.0,
+              "abs_diff": 0.0,
+              "pass": true
+            }
+          ],
+          "overlap_count": 3,
+          "overlap_passed": 3
+        },
+        "similarity_score": 1.0
+      },
+      {
+        "topic": "NetworkTutorial",
+        "title": "Example Data Analysis - Two Neuron Network Simulation and Estimation of Ensemble Effect",
+        "python_ok": true,
+        "python_error": "",
+        "python_output_keys": [
+          "neuron_count",
+          "parity",
+          "psth_peak",
+          "samples",
+          "topic"
+        ],
+        "python_scalar_count": 5,
+        "matlab_ok": true,
+        "matlab_error": "",
+        "matlab_error_report": "",
+        "matlab_fallback_error": "",
+        "matlab_fallback_error_report": "",
+        "matlab_figures": 4,
+        "matlab_var_count": 54,
+        "matlab_scalar_count": 13,
+        "matlab_script_used": "helpfiles/NetworkTutorial.m",
+        "matlab_fallback_script_used": "",
+        "matlab_runtime_s": 33.98667907714844,
+        "scalar_overlap": {
+          "overlaps": [
+            {
+              "python_key": "figs",
+              "matlab_key": "figs",
+              "python": 4.0,
+              "matlab": 4.0,
+              "abs_diff": 0.0,
+              "pass": true
+            }
+          ],
+          "overlap_count": 1,
+          "overlap_passed": 1
+        },
+        "similarity_score": 1.0
+      },
+      {
+        "topic": "nSTATPaperExamples",
+        "title": "nSTAT Paper Examples",
+        "python_ok": true,
+        "python_error": "",
+        "python_output_keys": [
+          "experiments",
+          "parity",
+          "summary",
+          "topic"
+        ],
+        "python_scalar_count": 30,
+        "matlab_ok": true,
+        "matlab_error": "",
+        "matlab_error_report": "",
+        "matlab_fallback_error": "",
+        "matlab_fallback_error_report": "",
+        "matlab_figures": 1,
+        "matlab_var_count": 79,
+        "matlab_scalar_count": 14,
+        "matlab_script_used": "helpfiles/nSTATPaperExamples.m [shadow_safe_copy]",
+        "matlab_fallback_script_used": "",
+        "matlab_runtime_s": 162.30554699897766,
+        "scalar_overlap": {
+          "overlaps": [
+            {
+              "python_key": "num_cells",
+              "matlab_key": "num_cells",
+              "python": 40.0,
+              "matlab": 40.0,
+              "abs_diff": 0.0,
+              "pass": true
+            },
+            {
+              "python_key": "figs",
+              "matlab_key": "figs",
+              "python": 1.0,
+              "matlab": 1.0,
+              "abs_diff": 0.0,
+              "pass": true
+            },
+            {
+              "python_key": "parity.num_cells",
+              "matlab_key": "parity_num_cells",
+              "python": 40.0,
+              "matlab": 40.0,
+              "abs_diff": 0.0,
+              "pass": true
+            }
+          ],
+          "overlap_count": 3,
+          "overlap_passed": 3
+        },
+        "similarity_score": 1.0
+      }
+    ]
+  },
+  "parity_contract": {
+    "pass": true,
+    "failures": [],
+    "rows": [
+      {
+        "topic": "SignalObjExamples",
+        "required_keys": [
+          "sample_rate_hz"
+        ],
+        "missing_keys": [],
+        "failing_keys": [],
+        "status": "pass"
+      },
+      {
+        "topic": "CovariateExamples",
+        "required_keys": [
+          "figs"
+        ],
+        "missing_keys": [],
+        "failing_keys": [],
+        "status": "pass"
+      },
+      {
+        "topic": "CovCollExamples",
+        "required_keys": [
+          "figs"
+        ],
+        "missing_keys": [],
+        "failing_keys": [],
+        "status": "pass"
+      },
+      {
+        "topic": "nSpikeTrainExamples",
+        "required_keys": [
+          "figs"
+        ],
+        "missing_keys": [],
+        "failing_keys": [],
+        "status": "pass"
+      },
+      {
+        "topic": "nstCollExamples",
+        "required_keys": [
+          "figs"
+        ],
+        "missing_keys": [],
+        "failing_keys": [],
+        "status": "pass"
+      },
+      {
+        "topic": "EventsExamples",
+        "required_keys": [
+          "figs"
+        ],
+        "missing_keys": [],
+        "failing_keys": [],
+        "status": "pass"
+      },
+      {
+        "topic": "HistoryExamples",
+        "required_keys": [
+          "figs"
+        ],
+        "missing_keys": [],
+        "failing_keys": [],
+        "status": "pass"
+      },
+      {
+        "topic": "TrialExamples",
+        "required_keys": [
+          "figs"
+        ],
+        "missing_keys": [],
+        "failing_keys": [],
+        "status": "pass"
+      },
+      {
+        "topic": "TrialConfigExamples",
+        "required_keys": [
+          "figs"
+        ],
+        "missing_keys": [],
+        "failing_keys": [],
+        "status": "pass"
+      },
+      {
+        "topic": "ConfigCollExamples",
+        "required_keys": [
+          "figs"
+        ],
+        "missing_keys": [],
+        "failing_keys": [],
+        "status": "pass"
+      },
+      {
+        "topic": "AnalysisExamples",
+        "required_keys": [
+          "figs"
+        ],
+        "missing_keys": [],
+        "failing_keys": [],
+        "status": "pass"
+      },
+      {
+        "topic": "FitResultExamples",
+        "required_keys": [
+          "figs"
+        ],
+        "missing_keys": [],
+        "failing_keys": [],
+        "status": "pass"
+      },
+      {
+        "topic": "FitResSummaryExamples",
+        "required_keys": [
+          "figs"
+        ],
+        "missing_keys": [],
+        "failing_keys": [],
+        "status": "pass"
+      },
+      {
+        "topic": "PPThinning",
+        "required_keys": [
+          "num_realizations"
+        ],
+        "missing_keys": [],
+        "failing_keys": [],
+        "status": "pass"
+      },
+      {
+        "topic": "PSTHEstimation",
+        "required_keys": [
+          "num_realizations"
+        ],
+        "missing_keys": [],
+        "failing_keys": [],
+        "status": "pass"
+      },
+      {
+        "topic": "ValidationDataSet",
+        "required_keys": [
+          "figs"
+        ],
+        "missing_keys": [],
+        "failing_keys": [],
+        "status": "pass"
+      },
+      {
+        "topic": "mEPSCAnalysis",
+        "required_keys": [
+          "figs"
+        ],
+        "missing_keys": [],
+        "failing_keys": [],
+        "status": "pass"
+      },
+      {
+        "topic": "PPSimExample",
+        "required_keys": [
+          "figs"
+        ],
+        "missing_keys": [],
+        "failing_keys": [],
+        "status": "pass"
+      },
+      {
+        "topic": "ExplicitStimulusWhiskerData",
+        "required_keys": [
+          "figs"
+        ],
+        "missing_keys": [],
+        "failing_keys": [],
+        "status": "pass"
+      },
+      {
+        "topic": "HippocampalPlaceCellExample",
+        "required_keys": [
+          "figs"
+        ],
+        "missing_keys": [],
+        "failing_keys": [],
+        "status": "pass"
+      },
+      {
+        "topic": "DecodingExample",
+        "required_keys": [
+          "figs"
+        ],
+        "missing_keys": [],
+        "failing_keys": [],
+        "status": "pass"
+      },
+      {
+        "topic": "DecodingExampleWithHist",
+        "required_keys": [
+          "figs"
+        ],
+        "missing_keys": [],
+        "failing_keys": [],
+        "status": "pass"
+      },
+      {
+        "topic": "StimulusDecode2D",
+        "required_keys": [
+          "num_cells"
+        ],
+        "missing_keys": [],
+        "failing_keys": [],
+        "status": "pass"
+      },
+      {
+        "topic": "NetworkTutorial",
+        "required_keys": [
+          "figs"
+        ],
+        "missing_keys": [],
+        "failing_keys": [],
+        "status": "pass"
+      },
+      {
+        "topic": "nSTATPaperExamples",
+        "required_keys": [
+          "num_cells"
+        ],
+        "missing_keys": [],
+        "failing_keys": [],
+        "status": "pass"
+      }
+    ]
+  },
+  "regression_gate": {
+    "pass": true,
+    "failures": [],
+    "matlab_failed_topics": [],
+    "known_allowlist": [],
+    "unexpected_failures": [],
+    "known_allowlist_not_currently_failing": [],
+    "parity_contract_pass": true
+  }
+}
\ No newline at end of file
diff --git a/reports/repo_split_inventory/split_readiness_gates.json b/reports/repo_split_inventory/split_readiness_gates.json
new file mode 100644
index 00000000..c6dd4697
--- /dev/null
+++ b/reports/repo_split_inventory/split_readiness_gates.json
@@ -0,0 +1,17 @@
+{
+  "python_example_topics_expected": 25,
+  "python_example_topics_ready": 25,
+  "python_example_topics_missing_coverage": [],
+  "matlab_example_topics_expected": 25,
+  "matlab_example_topics_with_mlx": 18,
+  "matlab_example_topics_missing_mlx": [
+    "ExplicitStimulusWhiskerData",
+    "NetworkTutorial",
+    "PPThinning",
+    "PSTHEstimation",
+    "StimulusDecode2D",
+    "ValidationDataSet",
+    "mEPSCAnalysis"
+  ],
+  "pass": false
+}
\ No newline at end of file
diff --git a/reports/repo_split_inventory/summary.json b/reports/repo_split_inventory/summary.json
new file mode 100644
index 00000000..47ded8a5
--- /dev/null
+++ b/reports/repo_split_inventory/summary.json
@@ -0,0 +1,53 @@
+{
+  "generated_at_utc": "2026-02-27T03:24:36+00:00",
+  "repo_root": "/Users/iahncajigas/Library/CloudStorage/Dropbox/Research/Matlab/nSTAT_currentRelease_Local",
+  "toc_target_topics": 31,
+  "toc_example_topics": 25,
+  "matlab_files": {
+    "m": 34,
+    "mlx": 21,
+    "html": 35
+  },
+  "python_assets": {
+    "docs_topics_rst": 31,
+    "notebooks_ipynb": 32,
+    "example_scripts_py": 27
+  },
+  "coverage_counts": {
+    "toc_topics_with_python_docs": 31,
+    "toc_topics_with_python_notebooks": 29,
+    "toc_topics_with_python_example_scripts": 25,
+    "example_topics_full_python_coverage": 25,
+    "example_topics_with_matlab_mlx": 18
+  },
+  "example_topic_stems_from_toc": [
+    "AnalysisExamples",
+    "ConfigCollExamples",
+    "CovCollExamples",
+    "CovariateExamples",
+    "DecodingExample",
+    "DecodingExampleWithHist",
+    "EventsExamples",
+    "ExplicitStimulusWhiskerData",
+    "FitResSummaryExamples",
+    "FitResultExamples",
+    "HippocampalPlaceCellExample",
+    "HistoryExamples",
+    "NetworkTutorial",
+    "PPSimExample",
+    "PPThinning",
+    "PSTHEstimation",
+    "SignalObjExamples",
+    "StimulusDecode2D",
+    "TrialConfigExamples",
+    "TrialExamples",
+    "ValidationDataSet",
+    "mEPSCAnalysis",
+    "nSTATPaperExamples",
+    "nSpikeTrainExamples",
+    "nstCollExamples"
+  ],
+  "python_only_topic_stems_not_in_toc": [
+    "_common"
+  ]
+}
\ No newline at end of file
diff --git a/reports/repo_split_inventory/topic_coverage_matrix.json b/reports/repo_split_inventory/topic_coverage_matrix.json
new file mode 100644
index 00000000..5305d3a0
--- /dev/null
+++ b/reports/repo_split_inventory/topic_coverage_matrix.json
@@ -0,0 +1,374 @@
+[
+  {
+    "title": "Using the Analysis Class",
+    "target": "AnalysisExamples.html",
+    "stem": "AnalysisExamples",
+    "is_example_topic": true,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": true,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": true
+  },
+  {
+    "title": "Class Definitions",
+    "target": "ClassDefinitions.html",
+    "stem": "ClassDefinitions",
+    "is_example_topic": false,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": false,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": false
+  },
+  {
+    "title": "Using the ConfigColl Class",
+    "target": "ConfigCollExamples.html",
+    "stem": "ConfigCollExamples",
+    "is_example_topic": true,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": true,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": true
+  },
+  {
+    "title": "Using the CovColl Class",
+    "target": "CovCollExamples.html",
+    "stem": "CovCollExamples",
+    "is_example_topic": true,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": true,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": true
+  },
+  {
+    "title": "Using the Covariate Class",
+    "target": "CovariateExamples.html",
+    "stem": "CovariateExamples",
+    "is_example_topic": true,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": true,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": true
+  },
+  {
+    "title": "Example Data Analysis - Decoding Univariate Simulated Stimuli (No History Effect)",
+    "target": "DecodingExample.html",
+    "stem": "DecodingExample",
+    "is_example_topic": true,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": true,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": true
+  },
+  {
+    "title": "Example Data Analysis - Decoding Univariate Simulated Stimuli with and without History Effect",
+    "target": "DecodingExampleWithHist.html",
+    "stem": "DecodingExampleWithHist",
+    "is_example_topic": true,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": true,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": true
+  },
+  {
+    "title": "MATLAB 2025b Help Integration",
+    "target": "DocumentationSetup2025b.html",
+    "stem": "DocumentationSetup2025b",
+    "is_example_topic": false,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": false,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": false,
+    "python_example_script_exists": false
+  },
+  {
+    "title": "Using the Events Class",
+    "target": "EventsExamples.html",
+    "stem": "EventsExamples",
+    "is_example_topic": true,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": true,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": true
+  },
+  {
+    "title": "Examples Using the SignalObj Class Using the Covariate Class Using the CovColl Class Using the nSpikeTrain Class Using the nstColl Class Using the Events Class Using the History Class Using the Trial Class Using the TrialConfig Class Using the ConfigColl Class Using the Analysis Class Using the FitResult Class Using the FitResSummary Class Point Process Simulation via Thinning Example Data Analysis - Simulated Data - Computing a Peri-Stimulus Time Histogram (PSTH) Example Data Analysis - Simulated Constant (Piecewise Constant) Rate Poisson Example Data Analysis - Miniature Excitatory Post-Synaptic Currents (mEPSCs) Example Data Analysis - Simulated Explicit Stimulus and History Example Data Analysis - Explicit Stimulus Example Data Analysis - Hippocampal Place Cell Receptive Field Estimation Example Data Analysis - Decoding Univariate Simulated Stimuli (No History Effect) Example Data Analysis - Decoding Univariate Simulated Stimuli with and without History Effect Example Data Analysis - Decoding Bivariate Simulated Stimuli Example Data Analysis - Two Neuron Network Simulation and Estimation of Ensemble Effect nSTAT Paper Examples",
+    "target": "Examples.html",
+    "stem": "Examples",
+    "is_example_topic": false,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": true,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": false
+  },
+  {
+    "title": "Example Data Analysis - Explicit Stimulus",
+    "target": "ExplicitStimulusWhiskerData.html",
+    "stem": "ExplicitStimulusWhiskerData",
+    "is_example_topic": true,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": false,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": true
+  },
+  {
+    "title": "Using the FitResSummary Class",
+    "target": "FitResSummaryExamples.html",
+    "stem": "FitResSummaryExamples",
+    "is_example_topic": true,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": true,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": true
+  },
+  {
+    "title": "FitResult Reference",
+    "target": "FitResult.html",
+    "stem": "FitResult",
+    "is_example_topic": false,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": false,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": false
+  },
+  {
+    "title": "Using the FitResult Class",
+    "target": "FitResultExamples.html",
+    "stem": "FitResultExamples",
+    "is_example_topic": true,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": true,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": true
+  },
+  {
+    "title": "Example Data Analysis - Hippocampal Place Cell Receptive Field Estimation",
+    "target": "HippocampalPlaceCellExample.html",
+    "stem": "HippocampalPlaceCellExample",
+    "is_example_topic": true,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": true,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": true
+  },
+  {
+    "title": "Using the History Class",
+    "target": "HistoryExamples.html",
+    "stem": "HistoryExamples",
+    "is_example_topic": true,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": true,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": true
+  },
+  {
+    "title": "Example Data Analysis - Two Neuron Network Simulation and Estimation of Ensemble Effect",
+    "target": "NetworkTutorial.html",
+    "stem": "NetworkTutorial",
+    "is_example_topic": true,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": false,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": true
+  },
+  {
+    "title": "nSTAT Neural Spike Train Analysis Toolbox Overview MATLAB 2025b Help Integration Class Definitions SignalObj Reference FitResult Reference Examples Using the SignalObj Class Using the Covariate Class Using the CovColl Class Using the nSpikeTrain Class Using the nstColl Class Using the Events Class Using the History Class Using the Trial Class Using the TrialConfig Class Using the ConfigColl Class Using the Analysis Class Using the FitResult Class Using the FitResSummary Class Point Process Simulation via Thinning Example Data Analysis - Simulated Data - Computing a Peri-Stimulus Time Histogram (PSTH) Example Data Analysis - Simulated Constant (Piecewise Constant) Rate Poisson Example Data Analysis - Miniature Excitatory Post-Synaptic Currents (mEPSCs) Example Data Analysis - Simulated Explicit Stimulus and History Example Data Analysis - Explicit Stimulus Example Data Analysis - Hippocampal Place Cell Receptive Field Estimation Example Data Analysis - Decoding Univariate Simulated Stimuli (No History Effect) Example Data Analysis - Decoding Univariate Simulated Stimuli with and without History Effect Example Data Analysis - Decoding Bivariate Simulated Stimuli Example Data Analysis - Two Neuron Network Simulation and Estimation of Ensemble Effect nSTAT Paper Examples Neuroscience Statistics Research Laboratory",
+    "target": "NeuralSpikeAnalysis_top.html",
+    "stem": "NeuralSpikeAnalysis_top",
+    "is_example_topic": false,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": false,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": false
+  },
+  {
+    "title": "Example Data Analysis - Simulated Explicit Stimulus and History",
+    "target": "PPSimExample.html",
+    "stem": "PPSimExample",
+    "is_example_topic": true,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": true,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": true
+  },
+  {
+    "title": "Point Process Simulation via Thinning",
+    "target": "PPThinning.html",
+    "stem": "PPThinning",
+    "is_example_topic": true,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": false,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": true
+  },
+  {
+    "title": "Example Data Analysis - Simulated Data - Computing a Peri-Stimulus Time Histogram (PSTH)",
+    "target": "PSTHEstimation.html",
+    "stem": "PSTHEstimation",
+    "is_example_topic": true,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": false,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": true
+  },
+  {
+    "title": "SignalObj Reference",
+    "target": "SignalObj.html",
+    "stem": "SignalObj",
+    "is_example_topic": false,
+    "matlab_m_exists": false,
+    "matlab_mlx_exists": false,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": false,
+    "python_example_script_exists": false
+  },
+  {
+    "title": "Using the SignalObj Class",
+    "target": "SignalObjExamples.html",
+    "stem": "SignalObjExamples",
+    "is_example_topic": true,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": true,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": true
+  },
+  {
+    "title": "Example Data Analysis - Decoding Bivariate Simulated Stimuli",
+    "target": "StimulusDecode2D.html",
+    "stem": "StimulusDecode2D",
+    "is_example_topic": true,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": false,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": true
+  },
+  {
+    "title": "Using the TrialConfig Class",
+    "target": "TrialConfigExamples.html",
+    "stem": "TrialConfigExamples",
+    "is_example_topic": true,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": true,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": true
+  },
+  {
+    "title": "Using the Trial Class",
+    "target": "TrialExamples.html",
+    "stem": "TrialExamples",
+    "is_example_topic": true,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": true,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": true
+  },
+  {
+    "title": "Example Data Analysis - Simulated Constant (Piecewise Constant) Rate Poisson",
+    "target": "ValidationDataSet.html",
+    "stem": "ValidationDataSet",
+    "is_example_topic": true,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": false,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": true
+  },
+  {
+    "title": "Example Data Analysis - Miniature Excitatory Post-Synaptic Currents (mEPSCs)",
+    "target": "mEPSCAnalysis.html",
+    "stem": "mEPSCAnalysis",
+    "is_example_topic": true,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": false,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": true
+  },
+  {
+    "title": "nSTAT Paper Examples",
+    "target": "nSTATPaperExamples.html",
+    "stem": "nSTATPaperExamples",
+    "is_example_topic": true,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": true,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": true
+  },
+  {
+    "title": "Using the nSpikeTrain Class",
+    "target": "nSpikeTrainExamples.html",
+    "stem": "nSpikeTrainExamples",
+    "is_example_topic": true,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": true,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": true
+  },
+  {
+    "title": "Using the nstColl Class",
+    "target": "nstCollExamples.html",
+    "stem": "nstCollExamples",
+    "is_example_topic": true,
+    "matlab_m_exists": true,
+    "matlab_mlx_exists": true,
+    "matlab_html_exists": true,
+    "python_doc_exists": true,
+    "python_notebook_exists": true,
+    "python_example_script_exists": true
+  }
+]
\ No newline at end of file
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
index 00000000..102eff98
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,25 @@
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+
+PROJECT_ROOT = Path(__file__).resolve().parents[1]
+if not (PROJECT_ROOT / "nstat").exists():
+    raise RuntimeError(f"Unable to locate project root from {__file__}")
+
+REPO_ROOT = PROJECT_ROOT if (PROJECT_ROOT / "helpfiles").exists() else PROJECT_ROOT.parent
+if str(PROJECT_ROOT) not in sys.path:
+    sys.path.insert(0, str(PROJECT_ROOT))
+
+
+@pytest.fixture(scope="session")
+def repo_root() -> Path:
+    return REPO_ROOT
+
+
+@pytest.fixture(scope="session")
+def project_root() -> Path:
+    return PROJECT_ROOT
diff --git a/tests/test_analysis_pipeline.py b/tests/test_analysis_pipeline.py
new file mode 100644
index 00000000..1da1fb7f
--- /dev/null
+++ b/tests/test_analysis_pipeline.py
@@ -0,0 +1,25 @@
+from __future__ import annotations
+
+import numpy as np
+
+from nstat import Analysis, CIFModel, ConfigCollection, Covariate, CovariateCollection, FitSummary, Trial, TrialConfig
+
+
+def test_trial_analysis_pipeline() -> None:
+    t = np.arange(0.0, 1.0, 0.001)
+    stim = np.sin(2 * np.pi * 2 * t)
+    cov = Covariate(t, stim, "stim", "time", "s", "a.u.", ["stim"])
+
+    model = CIFModel(t, 10.0 + 5.0 * np.maximum(stim, 0.0), name="lambda")
+    spikes = model.simulate(num_realizations=3, seed=2)
+
+    trial = Trial(spike_collection=spikes, covariate_collection=CovariateCollection([cov]))
+    cfgs = ConfigCollection([TrialConfig(covMask=["stim"], sampleRate=1000.0, name="stim_model")])
+
+    fits = Analysis.run_analysis_for_all_neurons(trial, cfgs)
+    assert len(fits) == 3
+    assert fits[0].AIC.shape == (1,)
+
+    summary = FitSummary(fits)
+    assert summary.numNeurons == 3
+    assert summary.AIC.shape == (1,)
diff --git a/tests/test_api_surface.py b/tests/test_api_surface.py
new file mode 100644
index 00000000..1aef5dc4
--- /dev/null
+++ b/tests/test_api_surface.py
@@ -0,0 +1,26 @@
+from __future__ import annotations
+
+import warnings
+
+import nstat
+
+
+def test_canonical_api_imports() -> None:
+    assert nstat.Signal is not None
+    assert nstat.SpikeTrain is not None
+    assert nstat.SpikeTrainCollection is not None
+    assert nstat.Trial is not None
+    assert nstat.Analysis is not None
+    assert nstat.FitResult is not None
+    assert nstat.FitSummary is not None
+    assert nstat.CIFModel is not None
+    assert nstat.DecoderSuite is not None
+
+
+def test_compatibility_adapters_emit_deprecation() -> None:
+    with warnings.catch_warnings(record=True) as w:
+        warnings.simplefilter("always")
+        from nstat.SignalObj import SignalObj
+
+        _ = SignalObj([0.0, 1.0], [1.0, 2.0])
+        assert any("deprecated" in str(item.message).lower() for item in w)
diff --git a/tests/test_datasets.py b/tests/test_datasets.py
new file mode 100644
index 00000000..869f4482
--- /dev/null
+++ b/tests/test_datasets.py
@@ -0,0 +1,23 @@
+from __future__ import annotations
+
+import os
+
+import nstat
+
+
+def test_dataset_manifest_and_checksums() -> None:
+    names = nstat.list_datasets()
+    assert names
+
+    check = nstat.verify_checksums()
+    assert set(check.keys()) == set(names)
+    assert all(isinstance(v, bool) for v in check.values())
+    allow_synthetic = os.environ.get("NSTAT_ALLOW_SYNTHETIC_DATA", "").strip().lower() in {"1", "true", "yes", "on"}
+    if not allow_synthetic:
+        assert all(check.values())
+
+
+def test_get_dataset_path() -> None:
+    name = nstat.list_datasets()[0]
+    path = nstat.get_dataset_path(name)
+    assert path.exists()
diff --git a/tests/test_docs.py b/tests/test_docs.py
new file mode 100644
index 00000000..c1b68de5
--- /dev/null
+++ b/tests/test_docs.py
@@ -0,0 +1,23 @@
+from __future__ import annotations
+
+import os
+import shutil
+import subprocess
+
+import pytest
+
+
+def test_sphinx_build(project_root) -> None:
+    if os.environ.get("NSTAT_CI_LIGHT") == "1":
+        pytest.skip("Sphinx build already validated in dedicated CI workflow step")
+    if shutil.which("sphinx-build") is None:
+        pytest.skip("sphinx-build not available in environment")
+
+    cp = subprocess.run(
+        ["sphinx-build", "-b", "html", "docs", "docs/_build/html"],
+        cwd=str(project_root),
+        capture_output=True,
+        text=True,
+        check=False,
+    )
+    assert cp.returncode == 0, cp.stdout + "\n" + cp.stderr
diff --git a/tests/test_help_topics.py b/tests/test_help_topics.py
new file mode 100644
index 00000000..426171e2
--- /dev/null
+++ b/tests/test_help_topics.py
@@ -0,0 +1,44 @@
+from __future__ import annotations
+
+import os
+
+import pytest
+
+from examples.help_topics._common import run_topic
+
+TOPICS = [
+    "SignalObjExamples",
+    "CovariateExamples",
+    "CovCollExamples",
+    "nSpikeTrainExamples",
+    "nstCollExamples",
+    "EventsExamples",
+    "HistoryExamples",
+    "TrialExamples",
+    "TrialConfigExamples",
+    "ConfigCollExamples",
+    "AnalysisExamples",
+    "FitResultExamples",
+    "FitResSummaryExamples",
+    "PPThinning",
+    "PSTHEstimation",
+    "ValidationDataSet",
+    "mEPSCAnalysis",
+    "PPSimExample",
+    "ExplicitStimulusWhiskerData",
+    "HippocampalPlaceCellExample",
+    "DecodingExample",
+    "DecodingExampleWithHist",
+    "StimulusDecode2D",
+    "NetworkTutorial",
+    "nSTATPaperExamples",
+]
+
+
+def test_help_topics_all_run(repo_root) -> None:
+    if os.environ.get("NSTAT_CI_LIGHT") == "1":
+        pytest.skip("Help-topic execution already validated in dedicated CI workflow step")
+    for topic in TOPICS:
+        out = run_topic(topic, repo_root)
+        assert isinstance(out, dict)
+        assert out.get("topic") == topic
diff --git a/tests/test_implemented_method_coverage_report.py b/tests/test_implemented_method_coverage_report.py
new file mode 100644
index 00000000..c820116f
--- /dev/null
+++ b/tests/test_implemented_method_coverage_report.py
@@ -0,0 +1,24 @@
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+
+import pytest
+
+
+def test_implemented_method_coverage_report(project_root) -> None:
+    if os.environ.get("NSTAT_CI_LIGHT") == "1":
+        pytest.skip("Method coverage report already generated in dedicated CI workflow step")
+    cp = subprocess.run(
+        [sys.executable, "tools/generate_implemented_method_coverage.py"],
+        cwd=str(project_root),
+        capture_output=True,
+        text=True,
+        check=True,
+    )
+    payload = json.loads(cp.stdout)
+    assert payload["pass"] is True
+    assert payload["summary"]["missing_in_smoke_count"] == 0
+    assert payload["summary"]["missing_doc_class_count"] == 0
diff --git a/tests/test_implemented_method_smoke.py b/tests/test_implemented_method_smoke.py
new file mode 100644
index 00000000..47235c2a
--- /dev/null
+++ b/tests/test_implemented_method_smoke.py
@@ -0,0 +1,176 @@
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+
+import numpy as np
+import pytest
+
+from nstat import Analysis, CIFModel, ConfigCollection, Covariate, CovariateCollection, SpikeTrain, SpikeTrainCollection, Trial, TrialConfig
+from nstat.DecodingAlgorithms import DecodingAlgorithms
+from nstat.ConfidenceInterval import ConfidenceInterval
+from nstat.cif import CIF
+from nstat.events import Events
+from nstat.fit import FitResSummary, FitResult
+from nstat.history import History
+from nstat.trial import CovColl
+
+
+COVERED_IMPLEMENTED_METHODS = {
+    ("nstColl", "dataToMatrix"),
+    ("CovColl", "addToColl"),
+    ("CovColl", "dataToMatrix"),
+    ("CovColl", "getCov"),
+    ("TrialConfig", "setName"),
+    ("ConfigColl", "addConfig"),
+    ("ConfigColl", "getConfig"),
+    ("ConfigColl", "getConfigNames"),
+    ("Trial", "getSpikeVector"),
+    ("History", "computeHistory"),
+    ("Events", "fromStructure"),
+    ("Events", "plot"),
+    ("Events", "toStructure"),
+    ("ConfidenceInterval", "setColor"),
+    ("CIF", "simulateCIFByThinningFromLambda"),
+    ("FitResult", "KSPlot"),
+    ("FitResult", "fromStructure"),
+    ("FitResult", "getCoeffs"),
+    ("FitResult", "getHistCoeffs"),
+    ("FitResult", "mergeResults"),
+    ("FitResult", "plotCoeffs"),
+    ("FitResult", "plotInvGausTrans"),
+    ("FitResult", "plotResidual"),
+    ("FitResult", "plotResults"),
+    ("FitResult", "plotSeqCorr"),
+    ("FitResult", "toStructure"),
+    ("FitResSummary", "getDiffAIC"),
+    ("FitResSummary", "getDiffBIC"),
+    ("FitResSummary", "plotSummary"),
+    ("Analysis", "RunAnalysisForAllNeurons"),
+    ("Analysis", "RunAnalysisForNeuron"),
+    ("DecodingAlgorithms", "PPDecodeFilter"),
+    ("DecodingAlgorithms", "PPDecodeFilterLinear"),
+    ("DecodingAlgorithms", "kalman_filter"),
+}
+
+
+def _build_trial_and_fits() -> tuple[Trial, ConfigCollection, list[FitResult]]:
+    t = np.arange(0.0, 1.0, 0.01)
+    cov = Covariate(t, np.sin(2.0 * np.pi * t), "stim", "time", "s", "a.u.", ["stim"])
+    cov_coll = CovariateCollection([cov])
+
+    st1 = SpikeTrain(np.array([0.1, 0.2, 0.5]), name="n1", binwidth=0.01, minTime=0.0, maxTime=1.0)
+    st2 = SpikeTrain(np.array([0.15, 0.35, 0.75]), name="n2", binwidth=0.01, minTime=0.0, maxTime=1.0)
+    spikes = SpikeTrainCollection([st1, st2])
+    trial = Trial(spike_collection=spikes, covariate_collection=cov_coll)
+
+    cfg = TrialConfig(covMask=["stim"], sampleRate=100.0, name="cfg1")
+    cfgs = ConfigCollection([cfg])
+    fits = Analysis.run_analysis_for_all_neurons(trial, cfgs)
+    return trial, cfgs, fits
+
+
+def _implemented_from_matrix(repo_root: Path) -> set[tuple[str, str]]:
+    project_root = repo_root if (repo_root / "nstat").exists() else (repo_root / "python")
+    matrix_path = project_root / "reports" / "method_parity_matrix.json"
+    payload = json.loads(matrix_path.read_text(encoding="utf-8"))
+    out: set[tuple[str, str]] = set()
+    for cls in payload.get("classes", []):
+        matlab_class = str(cls.get("matlab_class", ""))
+        for row in cls.get("methods", []):
+            if row.get("status") == "implemented":
+                out.add((matlab_class, str(row.get("matlab_method", ""))))
+    return out
+
+
+def test_implemented_method_set_matches_matrix(repo_root) -> None:
+    implemented = _implemented_from_matrix(repo_root)
+    assert implemented == COVERED_IMPLEMENTED_METHODS
+
+
+def test_implemented_methods_smoke_execute() -> None:
+    if os.environ.get("NSTAT_CI_LIGHT") == "1":
+        pytest.skip("Heavy method execution smoke is skipped in CI-light mode")
+    trial, cfgs, fits = _build_trial_and_fits()
+
+    # nstColl / Trial / CovColl / TrialConfig / ConfigColl / History
+    edges = np.linspace(0.0, 1.0, 11)
+    _ = trial.spike_collection.dataToMatrix(edges)
+    cov_coll = CovColl()
+    cov = Covariate(np.linspace(0.0, 1.0, 11), np.linspace(0.0, 1.0, 11), "c1", "time", "s", "a.u.", ["c1"])
+    cov_coll.addToColl(cov)
+    _, x, _ = cov_coll.dataToMatrix()
+    assert x.shape[0] == 11
+    assert cov_coll.getCov("c1").name == "c1"
+
+    cfg = TrialConfig(covMask=["stim"], sampleRate=100.0)
+    cfg.setName("renamed")
+    assert cfg.name == "renamed"
+
+    cfg_coll = ConfigCollection([])
+    cfg_coll.addConfig(cfg)
+    assert cfg_coll.getConfig(1).name == "renamed"
+    assert cfg_coll.getConfigNames() == ["renamed"]
+    _ = trial.getSpikeVector(edges, neuron_index=1)
+
+    hist = History([1, 2])
+    hist_cov = hist.computeHistory(trial.spike_collection.getNST(1))
+    assert hist_cov.dimension == 2
+
+    # Events / ConfidenceInterval
+    ev = Events([0.1, 0.2], labels=["a", "b"])
+    ev_struct = ev.toStructure()
+    ev2 = Events.fromStructure(ev_struct)
+    ev2.plot()
+    assert ev2.labels == ["a", "b"]
+
+    ci = ConfidenceInterval([0.0, 1.0], [[0.1, 0.2], [0.2, 0.3]])
+    ci.setColor("g")
+    assert ci.color == "g"
+
+    # CIF
+    lam = Covariate(np.linspace(0.0, 1.0, 101), np.full(101, 5.0), "lam", "time", "s", "Hz", ["lam"])
+    sim = CIF.simulateCIFByThinningFromLambda(lam, numRealizations=2)
+    assert sim.numSpikeTrains == 2
+
+    # FitResult + FitResSummary + Analysis MATLAB aliases
+    fit = fits[0]
+    _ = fit.getCoeffs()
+    _ = fit.getHistCoeffs()
+    fit.plotResults()
+    fit.KSPlot()
+    fit.plotResidual()
+    fit.plotInvGausTrans()
+    fit.plotSeqCorr()
+    fit.plotCoeffs()
+
+    merged = fit.mergeResults(fit)
+    assert merged.numResults == fit.numResults * 2
+
+    struct_payload = fit.toStructure()
+    fit_roundtrip = FitResult.fromStructure(struct_payload)
+    assert fit_roundtrip.numResults == fit.numResults
+
+    summary = FitResSummary(fits)
+    _ = summary.getDiffAIC()
+    _ = summary.getDiffBIC()
+    summary.plotSummary()
+
+    fit_single = Analysis.RunAnalysisForNeuron(trial, 1, cfgs)
+    fit_all = Analysis.RunAnalysisForAllNeurons(trial, cfgs)
+    assert fit_single.numResults >= 1
+    assert len(fit_all) == trial.spike_collection.num_spike_trains
+
+    # DecodingAlgorithms
+    y = np.zeros((8, 1))
+    a = np.eye(1)
+    h = np.eye(1)
+    q = np.eye(1) * 0.01
+    r = np.eye(1) * 0.1
+    x0 = np.zeros(1)
+    p0 = np.eye(1)
+    out0 = DecodingAlgorithms.kalman_filter(y, a, h, q, r, x0, p0)
+    out1 = DecodingAlgorithms.PPDecodeFilter(y, a, h, q, r, x0, p0)
+    out2 = DecodingAlgorithms.PPDecodeFilterLinear(y, a, h, q, r, x0, p0)
+    assert out0["state"].shape == out1["state"].shape == out2["state"].shape
diff --git a/tests/test_notebooks.py b/tests/test_notebooks.py
new file mode 100644
index 00000000..66042e76
--- /dev/null
+++ b/tests/test_notebooks.py
@@ -0,0 +1,25 @@
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+
+import pytest
+
+
+def test_generated_notebooks_execute(project_root) -> None:
+    if os.environ.get("NSTAT_CI_LIGHT") == "1":
+        pytest.skip("Notebook validation already executed in dedicated CI workflow step")
+    cp = subprocess.run(
+        [sys.executable, "tools/verify_examples_notebooks.py"],
+        cwd=str(project_root),
+        capture_output=True,
+        text=True,
+        check=True,
+    )
+    report = json.loads(cp.stdout)
+    assert report["total_examples"] == 25
+    assert report["python_modules_ok"] == 25
+    assert report["notebooks_ok"] == 25
+    assert report["topic_alignment_ok"] == 25
diff --git a/tests/test_reports.py b/tests/test_reports.py
new file mode 100644
index 00000000..e5303a24
--- /dev/null
+++ b/tests/test_reports.py
@@ -0,0 +1,23 @@
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+
+def test_phase0_reports_generation(project_root) -> None:
+    if os.environ.get("NSTAT_CI_LIGHT") == "1":
+        pytest.skip("Report generation already executed in dedicated CI workflow step")
+    subprocess.run([sys.executable, "tools/freeze_port_baseline.py"], cwd=str(project_root), check=True)
+    subprocess.run([sys.executable, "tools/generate_method_parity_matrix.py"], cwd=str(project_root), check=True)
+
+    snapshot = json.loads((project_root / "reports/port_baseline_snapshot.json").read_text(encoding="utf-8"))
+    matrix = json.loads((project_root / "reports/method_parity_matrix.json").read_text(encoding="utf-8"))
+
+    assert "reports" in snapshot
+    assert matrix["summary"]["total"] > 0
+    assert len(matrix["classes"]) >= 10
diff --git a/tools/debug_parity_blocks.py b/tools/debug_parity_blocks.py
new file mode 100644
index 00000000..0b64b2bf
--- /dev/null
+++ b/tools/debug_parity_blocks.py
@@ -0,0 +1,311 @@
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import subprocess
+import sys
+import time
+from collections import Counter
+from collections import deque
+from pathlib import Path
+from typing import Any
+
+
+PROJECT_ROOT = Path(__file__).resolve().parents[1]
+REPO_ROOT = PROJECT_ROOT if (PROJECT_ROOT / "helpfiles").exists() else PROJECT_ROOT.parent
+VERIFY_SCRIPT = PROJECT_ROOT / "tools" / "verify_python_vs_matlab_similarity.py"
+REPORT_DIR = PROJECT_ROOT / "reports"
+DEFAULT_OUTPUT = REPORT_DIR / "parity_block_benchmark_report.json"
+
+BLOCKS: list[tuple[str, list[str]]] = [
+    (
+        "core_smoke",
+        ["TrialConfigExamples", "ConfigCollExamples", "FitResultExamples", "FitResSummaryExamples"],
+    ),
+    (
+        "timeout_front",
+        [
+            "SignalObjExamples",
+            "CovariateExamples",
+            "CovCollExamples",
+            "nSpikeTrainExamples",
+            "nstCollExamples",
+            "EventsExamples",
+            "HistoryExamples",
+            "TrialExamples",
+            "AnalysisExamples",
+        ],
+    ),
+    (
+        "graphics_mid",
+        [
+            "PPThinning",
+            "PSTHEstimation",
+            "ValidationDataSet",
+            "mEPSCAnalysis",
+            "PPSimExample",
+            "ExplicitStimulusWhiskerData",
+            "HippocampalPlaceCellExample",
+            "DecodingExample",
+        ],
+    ),
+    (
+        "heavy_tail",
+        ["DecodingExampleWithHist", "StimulusDecode2D", "NetworkTutorial", "nSTATPaperExamples"],
+    ),
+    ("full_suite", []),
+]
+
+
+def _classify_matlab_failure(err: str) -> str:
+    e = (err or "").strip()
+    if not e:
+        return "unknown"
+    if e == "matlab_timeout":
+        return "timeout"
+    if "libmwhandle_graphics" in e or "MATLAB is exiting because of fatal error" in e:
+        return "graphics_crash"
+    if "matlab_json_missing" in e:
+        return "json_missing"
+    return "other_error"
+
+
+def _parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+    parser = argparse.ArgumentParser(
+        description="Run staged local parity blocks to isolate slow/failing MATLAB help topics."
+    )
+    parser.add_argument(
+        "--blocks",
+        nargs="+",
+        default=[name for name, _ in BLOCKS],
+        help="Block names to run. Defaults to all blocks.",
+    )
+    parser.add_argument(
+        "--matlab-extra-args",
+        default="-maca64 -nodisplay -noFigureWindows -softwareopengl",
+        help="Value for NSTAT_MATLAB_EXTRA_ARGS.",
+    )
+    parser.add_argument(
+        "--force-m-help-scripts",
+        action="store_true",
+        default=True,
+        help="Set NSTAT_FORCE_M_HELP_SCRIPTS=1 (default on).",
+    )
+    parser.add_argument(
+        "--no-force-m-help-scripts",
+        action="store_true",
+        help="Disable NSTAT_FORCE_M_HELP_SCRIPTS for this run.",
+    )
+    parser.add_argument(
+        "--default-topic-timeout",
+        type=int,
+        default=120,
+        help="Default per-topic timeout seconds passed to verify script.",
+    )
+    parser.add_argument(
+        "--set-actions-runner-svc",
+        action="store_true",
+        help="Set ACTIONS_RUNNER_SVC=1 for closer parity with self-hosted runner service mode.",
+    )
+    parser.add_argument(
+        "--output",
+        default=str(DEFAULT_OUTPUT.relative_to(REPO_ROOT)),
+        help="Output JSON report path (repo-relative or absolute).",
+    )
+    parser.add_argument(
+        "--no-stream-verify-output",
+        action="store_true",
+        help="Disable passthrough of verify-script output while each block is running.",
+    )
+    return parser.parse_args(argv)
+
+
+def _resolve_output(path_arg: str) -> Path:
+    out = Path(path_arg)
+    if not out.is_absolute():
+        out = REPO_ROOT / out
+    out.parent.mkdir(parents=True, exist_ok=True)
+    return out
+
+
+def _block_map() -> dict[str, list[str]]:
+    return {name: topics for name, topics in BLOCKS}
+
+
+def _run_block(
+    block_name: str,
+    topics: list[str],
+    matlab_extra_args: str,
+    force_m_help_scripts: bool,
+    default_topic_timeout: int,
+    set_actions_runner_svc: bool,
+    stream_verify_output: bool,
+) -> dict[str, Any]:
+    block_report = REPORT_DIR / f"parity_block_{block_name}.json"
+    cmd = [
+        sys.executable,
+        str(VERIFY_SCRIPT),
+        "--default-topic-timeout",
+        str(default_topic_timeout),
+        "--report-path",
+        str(block_report.relative_to(REPO_ROOT)),
+    ]
+    if topics:
+        cmd.extend(["--topics", *topics])
+
+    env = os.environ.copy()
+    env["NSTAT_MATLAB_EXTRA_ARGS"] = matlab_extra_args
+    env["NSTAT_FORCE_M_HELP_SCRIPTS"] = "1" if force_m_help_scripts else "0"
+    if set_actions_runner_svc:
+        env["ACTIONS_RUNNER_SVC"] = "1"
+
+    t0 = time.time()
+    stdout_tail = ""
+    stderr_tail = ""
+    if stream_verify_output:
+        stream_tail: deque[str] = deque(maxlen=40)
+        proc = subprocess.Popen(
+            cmd,
+            cwd=str(REPO_ROOT),
+            env=env,
+            stdout=subprocess.PIPE,
+            stderr=subprocess.STDOUT,
+            text=True,
+            bufsize=1,
+        )
+        if proc.stdout is not None:
+            for line in proc.stdout:
+                line = line.rstrip("\n")
+                print(f"[verify:{block_name}] {line}", flush=True)
+                stream_tail.append(line)
+        return_code = int(proc.wait())
+        stdout_tail = "\n".join(stream_tail)
+    else:
+        cp = subprocess.run(
+            cmd,
+            cwd=str(REPO_ROOT),
+            env=env,
+            capture_output=True,
+            text=True,
+            check=False,
+        )
+        return_code = int(cp.returncode)
+        stdout_tail = "\n".join((cp.stdout or "").splitlines()[-20:])
+        stderr_tail = "\n".join((cp.stderr or "").splitlines()[-20:])
+    wall_s = float(time.time() - t0)
+
+    report_payload: dict[str, Any] | None = None
+    if block_report.exists():
+        report_payload = json.loads(block_report.read_text(encoding="utf-8"))
+
+    result: dict[str, Any] = {
+        "block": block_name,
+        "topics_requested": topics,
+        "command": cmd,
+        "return_code": return_code,
+        "wall_runtime_s": wall_s,
+        "report_path": str(block_report.relative_to(REPO_ROOT)),
+        "stdout_tail": stdout_tail,
+        "stderr_tail": stderr_tail,
+    }
+    if report_payload is None:
+        result["report_missing"] = True
+        return result
+
+    help_rows = report_payload.get("helpfile_similarity", {}).get("rows", [])
+    failed = [r for r in help_rows if not bool(r.get("matlab_ok"))]
+    failure_counter = Counter(_classify_matlab_failure(str(r.get("matlab_error", ""))) for r in failed)
+    slowest = sorted(
+        [
+            {
+                "topic": str(r.get("topic", "")),
+                "runtime_s": float(r.get("matlab_runtime_s") or 0.0),
+                "timeout_s": int(r.get("matlab_timeout_s") or 0),
+                "matlab_ok": bool(r.get("matlab_ok")),
+            }
+            for r in help_rows
+        ],
+        key=lambda x: x["runtime_s"],
+        reverse=True,
+    )[:5]
+
+    result["summary"] = {
+        "class_similarity": report_payload.get("class_similarity", {}).get("summary", {}),
+        "help_similarity": report_payload.get("helpfile_similarity", {}).get("summary", {}),
+        "parity_contract_pass": bool(report_payload.get("parity_contract", {}).get("pass", False)),
+        "regression_gate_pass": bool(report_payload.get("regression_gate", {}).get("pass", False)),
+        "matlab_failure_types": dict(failure_counter),
+        "matlab_failed_topics": [str(r.get("topic", "")) for r in failed],
+        "slowest_topics": slowest,
+    }
+    return result
+
+
+def main(argv: list[str] | None = None) -> int:
+    args = _parse_args(argv)
+    block_topics = _block_map()
+    unknown = [b for b in args.blocks if b not in block_topics]
+    if unknown:
+        print(f"unknown block(s): {unknown}", file=sys.stderr)
+        return 2
+    if args.default_topic_timeout <= 0:
+        print("--default-topic-timeout must be positive", file=sys.stderr)
+        return 2
+
+    force_m_help_scripts = bool(args.force_m_help_scripts and not args.no_force_m_help_scripts)
+    out_path = _resolve_output(args.output)
+    started = time.time()
+    results: list[dict[str, Any]] = []
+
+    for block_name in args.blocks:
+        topics = block_topics[block_name]
+        print(f"[block] {block_name} ({'all topics' if not topics else len(topics)})", flush=True)
+        res = _run_block(
+            block_name=block_name,
+            topics=topics,
+            matlab_extra_args=args.matlab_extra_args,
+            force_m_help_scripts=force_m_help_scripts,
+            default_topic_timeout=args.default_topic_timeout,
+            set_actions_runner_svc=args.set_actions_runner_svc,
+            stream_verify_output=not bool(args.no_stream_verify_output),
+        )
+        results.append(res)
+        summary = res.get("summary", {})
+        help_summary = summary.get("help_similarity", {})
+        print(
+            json.dumps(
+                {
+                    "block": block_name,
+                    "return_code": res.get("return_code"),
+                    "wall_runtime_s": round(float(res.get("wall_runtime_s", 0.0)), 3),
+                    "help_matlab_ok": help_summary.get("matlab_ok"),
+                    "help_total": help_summary.get("total_topics"),
+                    "failure_types": summary.get("matlab_failure_types", {}),
+                }
+            ),
+            flush=True,
+        )
+
+    payload = {
+        "generated_at_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
+        "repo_root": str(REPO_ROOT),
+        "matlab_extra_args": args.matlab_extra_args,
+        "force_m_help_scripts": force_m_help_scripts,
+        "default_topic_timeout": int(args.default_topic_timeout),
+        "set_actions_runner_svc": bool(args.set_actions_runner_svc),
+        "blocks_requested": args.blocks,
+        "total_wall_runtime_s": float(time.time() - started),
+        "results": results,
+    }
+    out_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
+    try:
+        out_print = str(out_path.relative_to(REPO_ROOT))
+    except ValueError:
+        out_print = str(out_path)
+    print(json.dumps({"report": out_print, "blocks": len(results)}, indent=2))
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())
diff --git a/tools/freeze_port_baseline.py b/tools/freeze_port_baseline.py
new file mode 100644
index 00000000..1dc52b32
--- /dev/null
+++ b/tools/freeze_port_baseline.py
@@ -0,0 +1,71 @@
+from __future__ import annotations
+
+import hashlib
+import json
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+PROJECT_ROOT = Path(__file__).resolve().parents[1]
+REPO_ROOT = PROJECT_ROOT if (PROJECT_ROOT / "helpfiles").exists() else PROJECT_ROOT.parent
+REPORT_DIR = PROJECT_ROOT / "reports"
+
+SOURCE_REPORTS = {
+    "mfile_parity": "mfile_parity_report.json",
+    "examples_notebooks": "examples_notebook_verification.json",
+    "matlab_smoke_input": "matlab_smoke_input.json",
+}
+
+
+def _sha256(path: Path) -> str:
+    h = hashlib.sha256()
+    with path.open("rb") as f:
+        for chunk in iter(lambda: f.read(1024 * 1024), b""):
+            h.update(chunk)
+    return h.hexdigest()
+
+
+def _read_json(path: Path) -> Any:
+    return json.loads(path.read_text(encoding="utf-8"))
+
+
+def build_snapshot() -> dict[str, Any]:
+    payload: dict[str, Any] = {
+        "generated_at_utc": datetime.now(timezone.utc).isoformat(),
+        "reports": {},
+    }
+
+    for key, filename in SOURCE_REPORTS.items():
+        report_path = REPORT_DIR / filename
+        if not report_path.exists():
+            payload["reports"][key] = {
+                "path": str(report_path.relative_to(REPO_ROOT)),
+                "exists": False,
+            }
+            continue
+
+        data = _read_json(report_path)
+        entry: dict[str, Any] = {
+            "path": str(report_path.relative_to(REPO_ROOT)),
+            "exists": True,
+            "sha256": _sha256(report_path),
+            "size_bytes": report_path.stat().st_size,
+        }
+        if isinstance(data, dict) and "summary" in data:
+            entry["summary"] = data["summary"]
+        payload["reports"][key] = entry
+
+    return payload
+
+
+def main() -> int:
+    REPORT_DIR.mkdir(parents=True, exist_ok=True)
+    out = REPORT_DIR / "port_baseline_snapshot.json"
+    snapshot = build_snapshot()
+    out.write_text(json.dumps(snapshot, indent=2), encoding="utf-8")
+    print(json.dumps({"report": str(out.relative_to(REPO_ROOT))}, indent=2))
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())
diff --git a/tools/freeze_similarity_baseline.py b/tools/freeze_similarity_baseline.py
new file mode 100644
index 00000000..b639128d
--- /dev/null
+++ b/tools/freeze_similarity_baseline.py
@@ -0,0 +1,30 @@
+from __future__ import annotations
+
+import json
+from datetime import datetime, timezone
+from pathlib import Path
+
+
+PROJECT_ROOT = Path(__file__).resolve().parents[1]
+REPO_ROOT = PROJECT_ROOT if (PROJECT_ROOT / "helpfiles").exists() else PROJECT_ROOT.parent
+REPORT_PATH = PROJECT_ROOT / "reports" / "python_vs_matlab_similarity_report.json"
+BASELINE_PATH = PROJECT_ROOT / "reports" / "python_vs_matlab_similarity_baseline.json"
+
+
+def main() -> int:
+    if not REPORT_PATH.exists():
+        raise FileNotFoundError(f"Missing report: {REPORT_PATH}")
+
+    payload = json.loads(REPORT_PATH.read_text(encoding="utf-8"))
+    baseline = {
+        "frozen_at_utc": datetime.now(timezone.utc).isoformat(),
+        "source_report": str(REPORT_PATH.relative_to(REPO_ROOT)),
+        "report": payload,
+    }
+    BASELINE_PATH.write_text(json.dumps(baseline, indent=2), encoding="utf-8")
+    print(f"wrote {BASELINE_PATH.relative_to(REPO_ROOT)}")
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())
diff --git a/tools/generate_example_notebooks.py b/tools/generate_example_notebooks.py
new file mode 100644
index 00000000..bfcad4e1
--- /dev/null
+++ b/tools/generate_example_notebooks.py
@@ -0,0 +1,147 @@
+from __future__ import annotations
+
+import json
+import xml.etree.ElementTree as ET
+from pathlib import Path
+
+PROJECT_ROOT = Path(__file__).resolve().parents[1]
+REPO_ROOT = PROJECT_ROOT if (PROJECT_ROOT / "helpfiles").exists() else PROJECT_ROOT.parent
+TOC_PATH = REPO_ROOT / "helpfiles" / "helptoc.xml"
+NB_ROOT = PROJECT_ROOT / "notebooks" / "helpfiles"
+SRC_ROOT = PROJECT_ROOT / "examples" / "help_topics"
+
+
+def _example_topics() -> list[tuple[str, str]]:
+    tree = ET.parse(TOC_PATH)
+    root = tree.getroot()
+    examples = None
+    for item in root.iter("tocitem"):
+        if item.attrib.get("id") == "nstat_examples":
+            examples = item
+            break
+    if examples is None:
+        raise RuntimeError("Could not find examples section in helptoc.xml")
+
+    topics: list[tuple[str, str]] = []
+    for item in examples.findall("tocitem"):
+        title = " ".join((item.text or "").split()) or Path(item.attrib.get("target", "")).stem
+        target = item.attrib.get("target", "")
+        if not target:
+            continue
+        topics.append((title, target))
+    return topics
+
+
+def _build_notebook(title: str, stem: str, matlab_target: str) -> dict:
+    code_setup = (
+        "from pathlib import Path\n"
+        "import sys\n"
+        "import json\n\n"
+        "def find_repo_root(start: Path) -> Path:\n"
+        "    cur = start.resolve()\n"
+        "    for p in [cur, *cur.parents]:\n"
+        "        if (p / '.git').exists() and (p / 'nstat').exists() and (p / 'helpfiles').exists():\n"
+        "            return p\n"
+        "    raise RuntimeError('Could not find nSTAT repo root from notebook cwd')\n\n"
+        "repo_root = find_repo_root(Path.cwd())\n"
+        "py_root = repo_root\n"
+        "if str(py_root) not in sys.path:\n"
+        "    sys.path.insert(0, str(py_root))\n"
+        "print('repo_root =', repo_root)\n"
+    )
+
+    code_run = (
+        f"from examples.help_topics.{stem} import run\n"
+        "out = run(repo_root=repo_root)\n"
+        "print(json.dumps(out, indent=2, default=str))\n"
+    )
+
+    code_check = (
+        "assert isinstance(out, dict)\n"
+        "assert 'topic' in out\n"
+        "print('Notebook execution check: PASS')\n"
+    )
+
+    return {
+        "cells": [
+            {
+                "cell_type": "markdown",
+                "metadata": {},
+                "source": [
+                    f"# {title}\\n",
+                    "\\n",
+                    "Executable Python notebook generated from source help-topic scripts.\\n",
+                    f"MATLAB help target: `{matlab_target}`\\n",
+                ],
+            },
+            {
+                "cell_type": "code",
+                "execution_count": None,
+                "metadata": {},
+                "outputs": [],
+                "source": code_setup.splitlines(keepends=True),
+            },
+            {
+                "cell_type": "code",
+                "execution_count": None,
+                "metadata": {},
+                "outputs": [],
+                "source": code_run.splitlines(keepends=True),
+            },
+            {
+                "cell_type": "code",
+                "execution_count": None,
+                "metadata": {},
+                "outputs": [],
+                "source": code_check.splitlines(keepends=True),
+            },
+        ],
+        "metadata": {
+            "kernelspec": {
+                "display_name": "Python 3",
+                "language": "python",
+                "name": "python3",
+            },
+            "language_info": {
+                "name": "python",
+                "version": "3",
+            },
+        },
+        "nbformat": 4,
+        "nbformat_minor": 5,
+    }
+
+
+def main() -> int:
+    NB_ROOT.mkdir(parents=True, exist_ok=True)
+    topics = _example_topics()
+
+    generated = 0
+    missing_sources: list[str] = []
+    for title, target in topics:
+        stem = Path(target).stem
+        source_mod = SRC_ROOT / f"{stem}.py"
+        if not source_mod.exists():
+            missing_sources.append(stem)
+            continue
+
+        nb = _build_notebook(title, stem, target)
+        out = NB_ROOT / f"{stem}.ipynb"
+        out.write_text(json.dumps(nb, indent=2), encoding="utf-8")
+        generated += 1
+
+    report = {
+        "total_topics": len(topics),
+        "generated": generated,
+        "missing_sources": missing_sources,
+        "output_dir": str(NB_ROOT.relative_to(REPO_ROOT)),
+    }
+    print(json.dumps(report, indent=2))
+
+    if missing_sources:
+        return 1
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())
diff --git a/tools/generate_help_topic_docs.py b/tools/generate_help_topic_docs.py
new file mode 100644
index 00000000..0352466c
--- /dev/null
+++ b/tools/generate_help_topic_docs.py
@@ -0,0 +1,211 @@
+from __future__ import annotations
+
+import re
+import xml.etree.ElementTree as ET
+from pathlib import Path
+
+PROJECT_ROOT = Path(__file__).resolve().parents[1]
+REPO_ROOT = PROJECT_ROOT if (PROJECT_ROOT / "helpfiles").exists() else PROJECT_ROOT.parent
+TOC_PATH = REPO_ROOT / "helpfiles" / "helptoc.xml"
+DOCS_ROOT = PROJECT_ROOT / "docs"
+TOPICS_DIR = DOCS_ROOT / "topics"
+
+CLASS_API_MAP = {
+    "SignalObj": "nstat.signal.Signal",
+    "Covariate": "nstat.signal.Covariate",
+    "CovColl": "nstat.trial.CovariateCollection",
+    "nSpikeTrain": "nstat.spikes.SpikeTrain",
+    "nspikeTrain": "nstat.spikes.SpikeTrain",
+    "nstColl": "nstat.spikes.SpikeTrainCollection",
+    "Events": "nstat.events.Events",
+    "History": "nstat.history.HistoryBasis",
+    "Trial": "nstat.trial.Trial",
+    "TrialConfig": "nstat.trial.TrialConfig",
+    "ConfigColl": "nstat.trial.ConfigCollection",
+    "Analysis": "nstat.analysis.Analysis",
+    "FitResult": "nstat.fit.FitResult",
+    "FitResSummary": "nstat.fit.FitSummary",
+    "PPThinning": "nstat.cif.CIFModel.simulate",
+    "PSTHEstimation": "nstat.spikes.SpikeTrainCollection.psth",
+    "DecodingExample": "nstat.decoding.DecoderSuite",
+    "DecodingExampleWithHist": "nstat.decoding.DecoderSuite",
+    "StimulusDecode2D": "nstat.decoding.DecoderSuite",
+}
+
+
+def _slugify(value: str) -> str:
+    value = value.strip().lower()
+    value = re.sub(r"[^a-z0-9]+", "_", value)
+    return value.strip("_") or "topic"
+
+
+def _iter_topics(root: ET.Element):
+    for item in root.iter("tocitem"):
+        target = item.attrib.get("target", "").strip()
+        title = " ".join((item.text or "").split())
+        if not title:
+            title = Path(target).stem
+        if not target:
+            continue
+        yield title, target
+
+
+def _mapping_for_target(target: str) -> tuple[str, str]:
+    stem = Path(target).stem
+    base = stem[:-8] if (stem.endswith("Examples") and stem != "Examples") else stem
+    matlab_api = base
+    python_api = CLASS_API_MAP.get(base, "nstat (canonical module by topic)")
+    return matlab_api, python_api
+
+
+def _topic_body(title: str, target: str) -> str:
+    is_example = "example" in target.lower() or target.lower().endswith("examples.html")
+    notebook_name = Path(target).stem
+    matlab_api, python_api = _mapping_for_target(target)
+    lines = [
+        title,
+        "=" * len(title),
+        "",
+        f"MATLAB help target: ``{target}``",
+        "",
+        "Concept",
+        "-------",
+        "This page mirrors the corresponding MATLAB help topic and documents the Python standalone equivalent.",
+        "",
+        "API Mapping (MATLAB -> Python)",
+        "------------------------------",
+        ".. list-table::",
+        "   :header-rows: 1",
+        "",
+        "   * - MATLAB API",
+        "     - Python API",
+        f"   * - ``{matlab_api}``",
+        f"     - ``{python_api}``",
+        "",
+        "Migration Callout",
+        "-----------------",
+        "- MATLAB-style compatibility adapters remain importable for one major cycle and emit ``DeprecationWarning``.",
+        "- Prefer canonical Python modules under ``nstat`` for new code.",
+        "",
+        "Python Usage",
+        "------------",
+        ".. code-block:: python",
+        "",
+        "   import nstat",
+        "   print(nstat.__all__[:5])",
+        "",
+        "Data Requirements",
+        "-----------------",
+        "Use ``nstat.datasets.list_datasets()`` and ``nstat.datasets.get_dataset_path(...)`` to access bundled datasets.",
+        "",
+        "Expected Outputs",
+        "----------------",
+        "This topic should execute without MATLAB and produce deterministic summary metrics where applicable.",
+        "",
+        "Known Differences",
+        "-----------------",
+        "- Some legacy plotting helpers are represented via notebooks/docs instead of full method parity.",
+        "- Numerical outputs may vary if random seeds, bin widths, or sample rates differ from MATLAB defaults.",
+        "",
+    ]
+
+    if is_example:
+        lines.extend(
+            [
+                "Notebook",
+                "--------",
+                f"A generated executable notebook is available at ``notebooks/helpfiles/{notebook_name}.ipynb``.",
+                "",
+            ]
+        )
+
+    return "\n".join(lines)
+
+
+def generate_docs() -> list[Path]:
+    if not TOC_PATH.exists():
+        raise FileNotFoundError(f"Missing TOC file: {TOC_PATH}")
+
+    tree = ET.parse(TOC_PATH)
+    toc = tree.getroot()
+
+    TOPICS_DIR.mkdir(parents=True, exist_ok=True)
+    created: list[Path] = []
+    topic_entries: list[tuple[str, str, Path]] = []
+    seen_slugs: set[str] = set()
+
+    for title, target in _iter_topics(toc):
+        if target.startswith("http://") or target.startswith("https://"):
+            continue
+        slug = _slugify(Path(target).stem)
+        if slug in seen_slugs:
+            continue
+        seen_slugs.add(slug)
+        out = TOPICS_DIR / f"{slug}.rst"
+        out.write_text(_topic_body(title, target), encoding="utf-8")
+        created.append(out)
+        topic_entries.append((title, target, out))
+
+    topic_index_lines = [
+        "Help Topics",
+        "===========",
+        "",
+        ".. toctree::",
+        "   :maxdepth: 1",
+        "",
+    ]
+    for _, _, out in topic_entries:
+        topic_index_lines.append(f"   topics/{out.stem}")
+
+    (DOCS_ROOT / "help_topics.rst").write_text("\n".join(topic_index_lines) + "\n", encoding="utf-8")
+
+    api_lines = [
+        "API Reference",
+        "=============",
+        "",
+        ".. code-block:: python",
+        "",
+        "   import nstat",
+        "   print(nstat.__all__)",
+        "",
+        "Canonical modules include:",
+        "",
+        "- ``nstat.signal``",
+        "- ``nstat.spikes``",
+        "- ``nstat.trial``",
+        "- ``nstat.analysis``",
+        "- ``nstat.fit``",
+        "- ``nstat.cif``",
+        "- ``nstat.decoding``",
+        "- ``nstat.datasets``",
+    ]
+    (DOCS_ROOT / "api.rst").write_text("\n".join(api_lines) + "\n", encoding="utf-8")
+
+    index_lines = [
+        "nSTAT Python Documentation",
+        "==========================",
+        "",
+        "Standalone Python port of nSTAT with MATLAB-help topic coverage and executable notebooks.",
+        "",
+        ".. toctree::",
+        "   :maxdepth: 2",
+        "",
+        "   api",
+        "   help_topics",
+        "   parity_runbook",
+        "   repo_split_status",
+    ]
+    (DOCS_ROOT / "index.rst").write_text("\n".join(index_lines) + "\n", encoding="utf-8")
+
+    return created
+
+
+def main() -> int:
+    created = generate_docs()
+    print(f"generated_topics={len(created)}")
+    print(f"docs_root={DOCS_ROOT}")
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())
diff --git a/tools/generate_implemented_method_coverage.py b/tools/generate_implemented_method_coverage.py
new file mode 100644
index 00000000..097c7e57
--- /dev/null
+++ b/tools/generate_implemented_method_coverage.py
@@ -0,0 +1,107 @@
+from __future__ import annotations
+
+import ast
+import json
+import subprocess
+from pathlib import Path
+from typing import Any
+
+
+PROJECT_ROOT = Path(__file__).resolve().parents[1]
+REPO_ROOT = PROJECT_ROOT if (PROJECT_ROOT / "helpfiles").exists() else PROJECT_ROOT.parent
+MATRIX_PATH = PROJECT_ROOT / "reports" / "method_parity_matrix.json"
+SMOKE_TEST_PATH = PROJECT_ROOT / "tests" / "test_implemented_method_smoke.py"
+DOCS_TOPICS_DIR = PROJECT_ROOT / "docs" / "topics"
+OUT_PATH = PROJECT_ROOT / "reports" / "implemented_method_coverage.json"
+
+DOC_CLASS_TOKENS = {
+    "SignalObj": ["signalobj", "classdefinitions"],
+    "Covariate": ["covariate", "classdefinitions"],
+    "nspikeTrain": ["nspiketrain", "classdefinitions"],
+    "nstColl": ["nstcoll", "classdefinitions"],
+    "CovColl": ["covcoll", "classdefinitions"],
+    "TrialConfig": ["trialconfig", "classdefinitions"],
+    "ConfigColl": ["configcoll", "classdefinitions"],
+    "Trial": ["trial", "classdefinitions"],
+    "History": ["history", "classdefinitions"],
+    "Events": ["events", "classdefinitions"],
+    "ConfidenceInterval": ["classdefinitions"],
+    "CIF": ["cif", "ppthinning", "classdefinitions"],
+    "FitResult": ["fitresult", "classdefinitions"],
+    "FitResSummary": ["fitressummary", "classdefinitions"],
+    "Analysis": ["analysis", "classdefinitions"],
+    "DecodingAlgorithms": ["decoding", "classdefinitions"],
+}
+
+
+def _implemented_methods(matrix: dict[str, Any]) -> set[tuple[str, str]]:
+    out: set[tuple[str, str]] = set()
+    for cls in matrix.get("classes", []):
+        matlab_class = str(cls.get("matlab_class", ""))
+        for method in cls.get("methods", []):
+            if method.get("status") == "implemented":
+                out.add((matlab_class, str(method.get("matlab_method", ""))))
+    return out
+
+
+def _load_smoke_set() -> set[tuple[str, str]]:
+    src = SMOKE_TEST_PATH.read_text(encoding="utf-8")
+    tree = ast.parse(src)
+    for node in tree.body:
+        if isinstance(node, ast.Assign):
+            for target in node.targets:
+                if isinstance(target, ast.Name) and target.id == "COVERED_IMPLEMENTED_METHODS":
+                    value = ast.literal_eval(node.value)
+                    return {(str(a), str(b)) for (a, b) in value}
+    raise RuntimeError("Could not find COVERED_IMPLEMENTED_METHODS in smoke test file")
+
+
+def _doc_class_coverage(classes: set[str]) -> dict[str, bool]:
+    topic_names = [p.stem.lower() for p in DOCS_TOPICS_DIR.glob("*.rst")]
+    out: dict[str, bool] = {}
+    for c in sorted(classes):
+        tokens = DOC_CLASS_TOKENS.get(c, [c.lower()])
+        out[c] = any(any(tok in stem for tok in tokens) for stem in topic_names)
+    return out
+
+
+def main() -> int:
+    if not MATRIX_PATH.exists():
+        subprocess.run(["python3", "tools/generate_method_parity_matrix.py"], cwd=str(PROJECT_ROOT), check=True)
+
+    matrix = json.loads(MATRIX_PATH.read_text(encoding="utf-8"))
+    implemented = _implemented_methods(matrix)
+    smoke = _load_smoke_set()
+
+    missing_in_smoke = sorted(implemented - smoke)
+    extra_in_smoke = sorted(smoke - implemented)
+
+    classes = {c for c, _ in implemented}
+    doc_cov = _doc_class_coverage(classes)
+    missing_doc_classes = sorted([c for c, ok in doc_cov.items() if not ok])
+
+    report = {
+        "summary": {
+            "implemented_method_count": len(implemented),
+            "smoke_covered_count": len(smoke),
+            "missing_in_smoke_count": len(missing_in_smoke),
+            "extra_in_smoke_count": len(extra_in_smoke),
+            "implemented_class_count": len(classes),
+            "docs_class_covered_count": sum(1 for v in doc_cov.values() if v),
+            "missing_doc_class_count": len(missing_doc_classes),
+        },
+        "missing_in_smoke": [[c, m] for (c, m) in missing_in_smoke],
+        "extra_in_smoke": [[c, m] for (c, m) in extra_in_smoke],
+        "doc_class_coverage": doc_cov,
+        "missing_doc_classes": missing_doc_classes,
+        "pass": (len(missing_in_smoke) == 0 and len(extra_in_smoke) == 0 and len(missing_doc_classes) == 0),
+    }
+
+    OUT_PATH.parent.mkdir(parents=True, exist_ok=True)
+    OUT_PATH.write_text(json.dumps(report, indent=2), encoding="utf-8")
+    print(json.dumps({"report": str(OUT_PATH.relative_to(REPO_ROOT)), "summary": report["summary"], "pass": report["pass"]}, indent=2))
+    return 0 if report["pass"] else 1
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())
diff --git a/tools/generate_method_parity_matrix.py b/tools/generate_method_parity_matrix.py
new file mode 100644
index 00000000..747de8bb
--- /dev/null
+++ b/tools/generate_method_parity_matrix.py
@@ -0,0 +1,165 @@
+from __future__ import annotations
+
+import ast
+import json
+import re
+from pathlib import Path
+from typing import Any
+
+PROJECT_ROOT = Path(__file__).resolve().parents[1]
+REPO_ROOT = PROJECT_ROOT if (PROJECT_ROOT / "helpfiles").exists() else PROJECT_ROOT.parent
+REPORT_DIR = PROJECT_ROOT / "reports"
+PROJECT_PREFIX = "python/" if PROJECT_ROOT != REPO_ROOT else ""
+
+
+def _project_rel(rel: str) -> str:
+    return f"{PROJECT_PREFIX}{rel}" if PROJECT_PREFIX else rel
+
+CLASS_MAPPING = {
+    "SignalObj": ("SignalObj.m", "nstat/signal.py", "Signal"),
+    "Covariate": ("Covariate.m", "nstat/signal.py", "Covariate"),
+    "nspikeTrain": ("nspikeTrain.m", "nstat/spikes.py", "SpikeTrain"),
+    "nstColl": ("nstColl.m", "nstat/spikes.py", "SpikeTrainCollection"),
+    "CovColl": ("CovColl.m", "nstat/trial.py", "CovariateCollection"),
+    "TrialConfig": ("TrialConfig.m", "nstat/trial.py", "TrialConfig"),
+    "ConfigColl": ("ConfigColl.m", "nstat/trial.py", "ConfigCollection"),
+    "Trial": ("Trial.m", "nstat/trial.py", "Trial"),
+    "History": ("History.m", "nstat/history.py", "HistoryBasis"),
+    "Events": ("Events.m", "nstat/events.py", "Events"),
+    "ConfidenceInterval": ("ConfidenceInterval.m", "nstat/confidence_interval.py", "ConfidenceInterval"),
+    "CIF": ("CIF.m", "nstat/cif.py", "CIFModel"),
+    "FitResult": ("FitResult.m", "nstat/fit.py", "FitResult"),
+    "FitResSummary": ("FitResSummary.m", "nstat/fit.py", "FitSummary"),
+    "Analysis": ("Analysis.m", "nstat/analysis.py", "Analysis"),
+    "DecodingAlgorithms": ("DecodingAlgorithms.m", "nstat/decoding_algorithms.py", "DecodingAlgorithms"),
+}
+
+IMPLEMENTED_ALIAS_MAP = {
+    "runanalysisforallneurons": "run_analysis_for_all_neurons",
+    "runanalysisforneuron": "run_analysis_for_neuron",
+    "simulatecifbythinningfromlambda": "simulate",
+    "ppdecodefilter": "kalman_filter",
+    "ppdecodefilterlinear": "kalman_filter",
+    "getconfig": "get_config",
+    "addconfig": "add_config",
+    "getnst": "get_nst",
+    "getcov": "get",
+    "datatomatrix": "to_matrix",
+}
+
+
+def _normalize(name: str) -> str:
+    return re.sub(r"[^a-z0-9]", "", name.lower())
+
+
+def _matlab_methods(path: Path) -> list[str]:
+    text = path.read_text(encoding="utf-8", errors="ignore")
+    methods: list[str] = []
+    for m in re.finditer(r"^\s*function\s+(?:\[[^\]]*\]\s*=\s*|\w+\s*=\s*)?(\w+)\s*(?:\(|$)", text, flags=re.M):
+        methods.append(m.group(1))
+    return sorted(set(methods))
+
+
+def _python_methods(path: Path, class_name: str) -> list[str]:
+    src = path.read_text(encoding="utf-8", errors="ignore")
+    tree = ast.parse(src)
+    for node in tree.body:
+        if isinstance(node, ast.ClassDef) and node.name == class_name:
+            return sorted({n.name for n in node.body if isinstance(n, ast.FunctionDef)})
+    return []
+
+
+def _fallback_matlab_methods() -> dict[str, list[str]]:
+    path = REPORT_DIR / "method_parity_matrix.json"
+    if not path.exists():
+        return {}
+    try:
+        payload = json.loads(path.read_text(encoding="utf-8"))
+    except json.JSONDecodeError:
+        return {}
+
+    out: dict[str, list[str]] = {}
+    for cls in payload.get("classes", []):
+        matlab_class = str(cls.get("matlab_class", "")).strip()
+        if not matlab_class:
+            continue
+        methods = []
+        for row in cls.get("methods", []):
+            mm = str(row.get("matlab_method", "")).strip()
+            if mm:
+                methods.append(mm)
+        if methods:
+            out[matlab_class] = sorted(set(methods))
+    return out
+
+
+def _status_for_method(m_method: str, py_methods_norm: set[str]) -> tuple[str, str]:
+    m_norm = _normalize(m_method)
+    mapped = IMPLEMENTED_ALIAS_MAP.get(m_norm)
+
+    if m_norm in py_methods_norm:
+        return "implemented", "Method name exists in canonical Python class."
+    if mapped is not None and _normalize(mapped) in py_methods_norm:
+        return "implemented", f"Implemented via Pythonic rename: {mapped}."
+
+    if m_norm.startswith("plot") or "histogram" in m_norm or m_norm in {"dsxy2figxy"}:
+        return "intentionally_omitted", "Visualization helper is handled in notebooks/docs instead of core API."
+
+    return "planned", "Not yet implemented in canonical class; tracked for incremental parity completion."
+
+
+def build_matrix() -> dict[str, Any]:
+    rows: list[dict[str, Any]] = []
+    implemented_methods: list[dict[str, str]] = []
+    summary = {"implemented": 0, "planned": 0, "intentionally_omitted": 0, "total": 0}
+    fallback_catalog = _fallback_matlab_methods()
+
+    for matlab_class, (m_rel, py_rel, py_class) in CLASS_MAPPING.items():
+        m_path = REPO_ROOT / m_rel
+        py_path = PROJECT_ROOT / py_rel
+
+        m_methods = _matlab_methods(m_path) if m_path.exists() else fallback_catalog.get(matlab_class, [])
+        py_methods = _python_methods(py_path, py_class) if py_path.exists() else []
+        py_norm = {_normalize(x) for x in py_methods}
+
+        method_rows = []
+        for method in m_methods:
+            status, rationale = _status_for_method(method, py_norm)
+            method_rows.append(
+                {
+                    "matlab_method": method,
+                    "status": status,
+                    "rationale": rationale,
+                }
+            )
+            if status == "implemented":
+                implemented_methods.append({"matlab_class": matlab_class, "matlab_method": method})
+            summary[status] += 1
+            summary["total"] += 1
+
+        rows.append(
+            {
+                "matlab_class": matlab_class,
+                "matlab_source": m_rel,
+                "python_target": _project_rel(py_rel),
+                "python_class": py_class,
+                "python_methods": py_methods,
+                "methods": method_rows,
+            }
+        )
+
+    implemented_methods = sorted(implemented_methods, key=lambda r: (r["matlab_class"], r["matlab_method"]))
+    return {"summary": summary, "implemented_methods": implemented_methods, "classes": rows}
+
+
+def main() -> int:
+    REPORT_DIR.mkdir(parents=True, exist_ok=True)
+    out = REPORT_DIR / "method_parity_matrix.json"
+    matrix = build_matrix()
+    out.write_text(json.dumps(matrix, indent=2), encoding="utf-8")
+    print(json.dumps({"report": str(out.relative_to(REPO_ROOT)), "summary": matrix["summary"]}, indent=2))
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())
diff --git a/tools/generate_repo_split_inventory.py b/tools/generate_repo_split_inventory.py
new file mode 100644
index 00000000..b066444b
--- /dev/null
+++ b/tools/generate_repo_split_inventory.py
@@ -0,0 +1,187 @@
+from __future__ import annotations
+
+import json
+import xml.etree.ElementTree as ET
+from datetime import datetime, timezone
+from pathlib import Path
+
+PY_ROOT = Path(__file__).resolve().parents[1]
+REPO_ROOT = PY_ROOT if (PY_ROOT / "helpfiles").exists() else PY_ROOT.parent
+HELPFILES_ROOT = REPO_ROOT / "helpfiles"
+TOC_PATH = HELPFILES_ROOT / "helptoc.xml"
+OUT_ROOT = PY_ROOT / "reports" / "repo_split_inventory"
+
+
+def _utc_now() -> str:
+    return datetime.now(timezone.utc).replace(microsecond=0).isoformat()
+
+
+def _slugify(value: str) -> str:
+    out = []
+    for ch in value.strip().lower():
+        if ch.isalnum():
+            out.append(ch)
+    return "".join(out)
+
+
+def _iter_toc_targets() -> list[dict[str, str]]:
+    tree = ET.parse(TOC_PATH)
+    root = tree.getroot()
+
+    examples_node = None
+    for item in root.iter("tocitem"):
+        if item.attrib.get("id") == "nstat_examples":
+            examples_node = item
+            break
+
+    example_stems: set[str] = set()
+    if examples_node is not None:
+        for item in examples_node.findall("tocitem"):
+            target = item.attrib.get("target", "").strip()
+            if target:
+                example_stems.add(Path(target).stem)
+
+    rows: list[dict[str, str]] = []
+    seen: set[str] = set()
+    for item in root.iter("tocitem"):
+        target = item.attrib.get("target", "").strip()
+        if not target:
+            continue
+        if target.startswith("http://") or target.startswith("https://"):
+            continue
+        stem = Path(target).stem
+        key = f"{stem}|{target}"
+        if key in seen:
+            continue
+        seen.add(key)
+        rows.append(
+            {
+                "title": " ".join((item.text or "").split()) or stem,
+                "target": target,
+                "stem": stem,
+                "is_example_topic": stem in example_stems,
+            }
+        )
+    return rows
+
+
+def _file_stem_set(paths: list[Path], exclude_dunder: bool = False) -> set[str]:
+    out: set[str] = set()
+    for p in paths:
+        stem = p.stem
+        if exclude_dunder and stem.startswith("__"):
+            continue
+        out.add(stem)
+    return out
+
+
+def _write_json(path: Path, payload: dict | list) -> None:
+    path.parent.mkdir(parents=True, exist_ok=True)
+    path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
+
+
+def main() -> int:
+    if not TOC_PATH.exists():
+        raise FileNotFoundError(f"Missing TOC file: {TOC_PATH}")
+
+    toc_rows = _iter_toc_targets()
+    toc_stems = {row["stem"] for row in toc_rows}
+    example_stems = {row["stem"] for row in toc_rows if row["is_example_topic"]}
+
+    matlab_m = sorted(HELPFILES_ROOT.glob("*.m"))
+    matlab_mlx = sorted(HELPFILES_ROOT.glob("*.mlx"))
+    matlab_html = sorted(HELPFILES_ROOT.glob("*.html"))
+
+    matlab_m_stems = _file_stem_set(matlab_m)
+    matlab_mlx_stems = _file_stem_set(matlab_mlx)
+    matlab_html_stems = _file_stem_set(matlab_html)
+
+    py_docs_topics = sorted((PY_ROOT / "docs" / "topics").glob("*.rst"))
+    py_nb_topics = sorted((PY_ROOT / "notebooks" / "helpfiles").glob("*.ipynb"))
+    py_example_topics = sorted((PY_ROOT / "examples" / "help_topics").glob("*.py"))
+
+    py_doc_stems = _file_stem_set(py_docs_topics)
+    py_nb_stems = _file_stem_set(py_nb_topics)
+    py_example_stems = _file_stem_set(py_example_topics, exclude_dunder=True)
+    py_doc_slugs = {_slugify(s) for s in py_doc_stems}
+
+    coverage_rows: list[dict[str, object]] = []
+    for row in sorted(toc_rows, key=lambda r: r["stem"]):
+        stem = row["stem"]
+        stem_slug = _slugify(stem)
+        coverage_rows.append(
+            {
+                **row,
+                "matlab_m_exists": stem in matlab_m_stems,
+                "matlab_mlx_exists": stem in matlab_mlx_stems,
+                "matlab_html_exists": stem in matlab_html_stems,
+                "python_doc_exists": stem_slug in py_doc_slugs,
+                "python_notebook_exists": stem in py_nb_stems,
+                "python_example_script_exists": stem in py_example_stems,
+            }
+        )
+
+    example_rows = [r for r in coverage_rows if bool(r["is_example_topic"])]
+    example_all_python_ok = [
+        r
+        for r in example_rows
+        if bool(r["python_doc_exists"])
+        and bool(r["python_notebook_exists"])
+        and bool(r["python_example_script_exists"])
+    ]
+    matlab_example_has_mlx = [r for r in example_rows if bool(r["matlab_mlx_exists"])]
+
+    summary = {
+        "generated_at_utc": _utc_now(),
+        "repo_root": str(REPO_ROOT),
+        "toc_target_topics": len(toc_rows),
+        "toc_example_topics": len(example_rows),
+        "matlab_files": {
+            "m": len(matlab_m),
+            "mlx": len(matlab_mlx),
+            "html": len(matlab_html),
+        },
+        "python_assets": {
+            "docs_topics_rst": len(py_docs_topics),
+            "notebooks_ipynb": len(py_nb_topics),
+            "example_scripts_py": len(py_example_topics),
+        },
+        "coverage_counts": {
+            "toc_topics_with_python_docs": sum(1 for r in coverage_rows if bool(r["python_doc_exists"])),
+            "toc_topics_with_python_notebooks": sum(1 for r in coverage_rows if bool(r["python_notebook_exists"])),
+            "toc_topics_with_python_example_scripts": sum(
+                1 for r in coverage_rows if bool(r["python_example_script_exists"])
+            ),
+            "example_topics_full_python_coverage": len(example_all_python_ok),
+            "example_topics_with_matlab_mlx": len(matlab_example_has_mlx),
+        },
+        "example_topic_stems_from_toc": sorted(example_stems),
+        "python_only_topic_stems_not_in_toc": sorted(py_example_stems - toc_stems),
+    }
+
+    _write_json(OUT_ROOT / "summary.json", summary)
+    _write_json(OUT_ROOT / "topic_coverage_matrix.json", coverage_rows)
+    _write_json(
+        OUT_ROOT / "split_readiness_gates.json",
+        {
+            "python_example_topics_expected": len(example_rows),
+            "python_example_topics_ready": len(example_all_python_ok),
+            "python_example_topics_missing_coverage": [
+                r["stem"] for r in example_rows if r not in example_all_python_ok
+            ],
+            "matlab_example_topics_expected": len(example_rows),
+            "matlab_example_topics_with_mlx": len(matlab_example_has_mlx),
+            "matlab_example_topics_missing_mlx": [
+                r["stem"] for r in example_rows if not bool(r["matlab_mlx_exists"])
+            ],
+            "pass": len(example_rows) == len(example_all_python_ok) and len(example_rows) == len(matlab_example_has_mlx),
+        },
+    )
+
+    print(json.dumps(summary, indent=2))
+    print(f"wrote={OUT_ROOT}")
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())
diff --git a/tools/generate_translations_and_notebooks.py b/tools/generate_translations_and_notebooks.py
new file mode 100644
index 00000000..8cd61a67
--- /dev/null
+++ b/tools/generate_translations_and_notebooks.py
@@ -0,0 +1,89 @@
+from __future__ import annotations
+
+import json
+import re
+from pathlib import Path
+
+from generate_example_notebooks import main as generate_notebooks
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+PORT_ROOT = REPO_ROOT / "python" / "matlab_port"
+
+
+def _classify_m_file(path: Path) -> str:
+    text = path.read_text(encoding="utf-8", errors="ignore")
+    for line in text.splitlines():
+        s = line.strip()
+        if not s or s.startswith("%"):
+            continue
+        if s.startswith("classdef"):
+            return "classdef"
+        if s.startswith("function"):
+            return "function"
+        break
+    return "script"
+
+
+def _iter_matlab_sources() -> list[Path]:
+    files: list[Path] = []
+    for p in REPO_ROOT.rglob("*.m"):
+        rel = p.relative_to(REPO_ROOT)
+        if rel.parts and rel.parts[0] == "python":
+            continue
+        files.append(p)
+    return sorted(files)
+
+
+def _target_for_source(src: Path) -> str:
+    rel = src.relative_to(REPO_ROOT)
+    return str((PORT_ROOT / rel.parent / f"{src.stem}.py").relative_to(REPO_ROOT))
+
+
+def build_translation_map() -> dict[str, object]:
+    entries = []
+    counts: dict[str, int] = {}
+    for src in _iter_matlab_sources():
+        kind = _classify_m_file(src)
+        counts[kind] = counts.get(kind, 0) + 1
+        entries.append(
+            {
+                "source": str(src.relative_to(REPO_ROOT)),
+                "target": _target_for_source(src),
+                "kind": kind,
+                "status": "archived_reference",
+                "note": "matlab_port is kept as historical scaffold; canonical implementation lives in python/nstat",
+            }
+        )
+
+    return {
+        "repo_root": str(REPO_ROOT),
+        "output_root": str(PORT_ROOT),
+        "counts": {"total": len(entries), "by_kind": counts},
+        "entries": entries,
+    }
+
+
+def main() -> int:
+    PORT_ROOT.mkdir(parents=True, exist_ok=True)
+
+    mapping = build_translation_map()
+    map_path = PORT_ROOT / "TRANSLATION_MAP.json"
+    map_path.write_text(json.dumps(mapping, indent=2), encoding="utf-8")
+
+    nb_rc = generate_notebooks()
+
+    print(
+        json.dumps(
+            {
+                "translation_map": str(map_path.relative_to(REPO_ROOT)),
+                "matlab_sources": mapping["counts"]["total"],
+                "notebook_generation_rc": nb_rc,
+            },
+            indent=2,
+        )
+    )
+    return int(nb_rc)
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())
diff --git a/tools/run_parity_ladder.sh b/tools/run_parity_ladder.sh
new file mode 100755
index 00000000..61a18aa7
--- /dev/null
+++ b/tools/run_parity_ladder.sh
@@ -0,0 +1,381 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
+REPO_ROOT="${PROJECT_ROOT}"
+PYTHON_BIN="${PYTHON_BIN:-python3}"
+MATLAB_EXTRA_ARGS="${NSTAT_MATLAB_EXTRA_ARGS:--maca64 -nodisplay -noFigureWindows -softwareopengl}"
+MATLAB_BIN="${NSTAT_MATLAB_BIN:-/Applications/MATLAB_R2025b.app/bin/matlab}"
+SET_ACTIONS_RUNNER_SVC="${NSTAT_SET_ACTIONS_RUNNER_SVC:-1}"
+RUNTIME_MULTIPLIER="${NSTAT_PARITY_RUNTIME_MULTIPLIER:-2.5}"
+RETRY_TIMEOUT_BLOCKS="${NSTAT_PARITY_RETRY_TIMEOUT_BLOCKS:-0}"
+TIMEOUT_RETRY_BLOCKS="${NSTAT_PARITY_TIMEOUT_RETRY_BLOCKS:-timeout_front}"
+RETRY_RECOVERABLE_BLOCKS="${NSTAT_PARITY_RETRY_RECOVERABLE_BLOCKS:-1}"
+RECOVERABLE_RETRY_BLOCKS="${NSTAT_PARITY_RECOVERABLE_RETRY_BLOCKS:-graphics_mid,heavy_tail,full_suite}"
+RETRY_SUMMARY_PATH="${NSTAT_PARITY_RETRY_SUMMARY_PATH:-reports/parity_retry_summary.json}"
+
+DEFAULT_BLOCKS=(core_smoke timeout_front graphics_mid heavy_tail full_suite)
+if [[ $# -gt 0 ]]; then
+  BLOCKS=("$@")
+else
+  BLOCKS=("${DEFAULT_BLOCKS[@]}")
+fi
+
+baseline_runtime_sum_s() {
+  case "$1" in
+    core_smoke) echo 47 ;;
+    timeout_front) echo 122 ;;
+    graphics_mid) echo 291 ;;
+    heavy_tail) echo 385 ;;
+    full_suite) echo 826 ;;
+    *) return 1 ;;
+  esac
+}
+
+block_retry_enabled() {
+  local block="$1"
+  [[ "${RETRY_TIMEOUT_BLOCKS}" == "1" ]] || return 1
+  local token
+  for token in ${TIMEOUT_RETRY_BLOCKS//,/ }; do
+    [[ "${token}" == "${block}" ]] && return 0
+  done
+  return 1
+}
+
+block_recoverable_retry_enabled() {
+  local block="$1"
+  [[ "${RETRY_RECOVERABLE_BLOCKS}" == "1" ]] || return 1
+  local token
+  for token in ${RECOVERABLE_RETRY_BLOCKS//,/ }; do
+    [[ "${token}" == "${block}" ]] && return 0
+  done
+  return 1
+}
+
+is_timeout_only_regression() {
+  local report_path="$1"
+  "${PYTHON_BIN}" - "${report_path}" <<'PY'
+import json
+import sys
+from pathlib import Path
+
+path = Path(sys.argv[1])
+if not path.exists():
+    raise SystemExit(1)
+payload = json.loads(path.read_text(encoding="utf-8"))
+rows = payload.get("helpfile_similarity", {}).get("rows", [])
+if not rows:
+    raise SystemExit(1)
+failed = [r for r in rows if not bool(r.get("matlab_ok"))]
+if not failed or len(failed) != len(rows):
+    raise SystemExit(1)
+if not all(str(r.get("matlab_error", "")).strip() == "matlab_timeout" for r in failed):
+    raise SystemExit(1)
+topics = [str(r.get("topic", "")) for r in failed]
+print(f"[ladder] timeout-only regression detected across {len(topics)} topic(s): {topics}")
+raise SystemExit(0)
+PY
+}
+
+warmup_matlab() {
+  if [[ ! -x "${MATLAB_BIN}" ]]; then
+    echo "[ladder] matlab warmup skipped; binary not executable: ${MATLAB_BIN}"
+    return 0
+  fi
+  echo "[ladder] running matlab warmup before retry"
+  "${MATLAB_BIN}" ${MATLAB_EXTRA_ARGS} -batch "disp(version); exit" >/dev/null 2>&1 || true
+}
+
+resolve_path() {
+  local p="$1"
+  if [[ "${p}" = /* ]]; then
+    printf "%s" "${p}"
+  else
+    printf "%s/%s" "${REPO_ROOT}" "${p}"
+  fi
+}
+
+timeout_only_topics_csv() {
+  local report_path="$1"
+  "${PYTHON_BIN}" - "${report_path}" <<'PY'
+import json
+import sys
+from pathlib import Path
+
+path = Path(sys.argv[1])
+if not path.exists():
+    raise SystemExit(1)
+payload = json.loads(path.read_text(encoding="utf-8"))
+rows = payload.get("helpfile_similarity", {}).get("rows", [])
+if not rows:
+    raise SystemExit(1)
+failed = [r for r in rows if not bool(r.get("matlab_ok"))]
+if not failed or len(failed) != len(rows):
+    raise SystemExit(1)
+if not all(str(r.get("matlab_error", "")).strip() == "matlab_timeout" for r in failed):
+    raise SystemExit(1)
+topics = [str(r.get("topic", "")).strip() for r in failed if str(r.get("topic", "")).strip()]
+print(",".join(topics))
+raise SystemExit(0)
+PY
+}
+
+retryable_failure_topics_csv() {
+  local report_path="$1"
+  "${PYTHON_BIN}" - "${report_path}" <<'PY'
+import json
+import sys
+from pathlib import Path
+
+path = Path(sys.argv[1])
+if not path.exists():
+    raise SystemExit(1)
+payload = json.loads(path.read_text(encoding="utf-8"))
+rows = payload.get("helpfile_similarity", {}).get("rows", [])
+if not rows:
+    raise SystemExit(1)
+failed = [r for r in rows if not bool(r.get("matlab_ok"))]
+if not failed:
+    raise SystemExit(1)
+
+markers = (
+    "matlab_timeout",
+    "matlab is exiting because of fatal error",
+    "fatal error",
+    "mathworkscrashreporter",
+    "crash report has been saved",
+    "libmwhandle_graphics",
+)
+
+def retryable(err: str) -> bool:
+    e = (err or "").strip().lower()
+    if e == "matlab_timeout":
+        return True
+    return any(m in e for m in markers)
+
+if not all(retryable(str(r.get("matlab_error", ""))) for r in failed):
+    raise SystemExit(1)
+
+topics = [str(r.get("topic", "")).strip() for r in failed if str(r.get("topic", "")).strip()]
+if not topics:
+    raise SystemExit(1)
+print(",".join(topics))
+raise SystemExit(0)
+PY
+}
+
+init_retry_summary() {
+  "${PYTHON_BIN}" - "${RETRY_SUMMARY_ABS}" "${RETRY_TIMEOUT_BLOCKS}" "${TIMEOUT_RETRY_BLOCKS}" "${RETRY_RECOVERABLE_BLOCKS}" "${RECOVERABLE_RETRY_BLOCKS}" <<'PY'
+import json
+import sys
+from datetime import datetime, timezone
+from pathlib import Path
+
+path = Path(sys.argv[1])
+path.parent.mkdir(parents=True, exist_ok=True)
+payload = {
+    "generated_at_utc": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
+    "retry_timeout_blocks_enabled": sys.argv[2] == "1",
+    "timeout_retry_blocks": [b for b in sys.argv[3].replace(",", " ").split() if b],
+    "retry_recoverable_blocks_enabled": sys.argv[4] == "1",
+    "recoverable_retry_blocks": [b for b in sys.argv[5].replace(",", " ").split() if b],
+    "events": [],
+}
+path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
+PY
+}
+
+append_retry_summary_event() {
+  local kind="$1"
+  local block="$2"
+  local attempt="$3"
+  local max_attempts="$4"
+  local status="$5"
+  local return_code="$6"
+  local reason="$7"
+  local timeout_topics_csv="$8"
+  "${PYTHON_BIN}" - "${RETRY_SUMMARY_ABS}" "${kind}" "${block}" "${attempt}" "${max_attempts}" "${status}" "${return_code}" "${reason}" "${timeout_topics_csv}" <<'PY'
+import json
+import sys
+from datetime import datetime, timezone
+from pathlib import Path
+
+path = Path(sys.argv[1])
+if path.exists():
+    payload = json.loads(path.read_text(encoding="utf-8"))
+else:
+    payload = {"generated_at_utc": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "events": []}
+events = payload.setdefault("events", [])
+topics_raw = sys.argv[9].strip()
+event = {
+    "ts_utc": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
+    "kind": sys.argv[2],
+    "block": sys.argv[3],
+    "attempt": int(sys.argv[4]),
+    "max_attempts": int(sys.argv[5]),
+    "status": sys.argv[6],
+    "return_code": int(sys.argv[7]),
+    "reason": sys.argv[8],
+    "timeout_topics": [t for t in topics_raw.split(",") if t] if topics_raw else [],
+}
+events.append(event)
+path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
+PY
+}
+
+cd "${REPO_ROOT}"
+RETRY_SUMMARY_ABS="$(resolve_path "${RETRY_SUMMARY_PATH}")"
+init_retry_summary
+
+echo "[ladder] repo: ${REPO_ROOT}"
+echo "[ladder] python: ${PYTHON_BIN}"
+echo "[ladder] matlab args: ${MATLAB_EXTRA_ARGS}"
+echo "[ladder] blocks: ${BLOCKS[*]}"
+echo "[ladder] runtime multiplier: ${RUNTIME_MULTIPLIER} (<=0 disables runtime regression checks)"
+echo "[ladder] retry timeout-only blocks: ${RETRY_TIMEOUT_BLOCKS} (blocks: ${TIMEOUT_RETRY_BLOCKS})"
+echo "[ladder] retry recoverable-failure blocks: ${RETRY_RECOVERABLE_BLOCKS} (blocks: ${RECOVERABLE_RETRY_BLOCKS})"
+echo "[ladder] retry summary path: ${RETRY_SUMMARY_PATH}"
+
+for block in "${BLOCKS[@]}"; do
+  if ! baseline_s="$(baseline_runtime_sum_s "${block}")"; then
+    echo "[ladder] unknown block: ${block}" >&2
+    exit 2
+  fi
+
+  echo "[ladder] running block: ${block}"
+  report_path="${PROJECT_ROOT}/reports/parity_block_${block}.json"
+  max_attempts=1
+  if block_retry_enabled "${block}" || block_recoverable_retry_enabled "${block}"; then
+    max_attempts=2
+  fi
+  attempt=1
+  while true; do
+    cmd=(
+      "${PYTHON_BIN}"
+      "${PROJECT_ROOT}/tools/debug_parity_blocks.py"
+      --blocks "${block}"
+      --matlab-extra-args "${MATLAB_EXTRA_ARGS}"
+      --output "reports/parity_block_benchmark_report_ladder_${block}.json"
+    )
+    if [[ "${SET_ACTIONS_RUNNER_SVC}" == "1" ]]; then
+      cmd+=(--set-actions-runner-svc)
+    fi
+
+    "${cmd[@]}"
+
+    if [[ ! -f "${report_path}" ]]; then
+      echo "[ladder] missing report: ${report_path}" >&2
+      exit 3
+    fi
+
+    if "${PYTHON_BIN}" - "${report_path}" "${block}" "${baseline_s}" "${RUNTIME_MULTIPLIER}" <<'PY'
+import json
+import sys
+from pathlib import Path
+
+report = Path(sys.argv[1])
+block = sys.argv[2]
+baseline = float(sys.argv[3])
+mult = float(sys.argv[4])
+
+payload = json.loads(report.read_text(encoding="utf-8"))
+summary = payload.get("helpfile_similarity", {}).get("summary", {})
+rows = payload.get("helpfile_similarity", {}).get("rows", [])
+
+
+def i(name: str) -> int:
+    try:
+        return int(summary.get(name, 0) or 0)
+    except Exception:
+        return 0
+
+
+total = i("total_topics")
+python_ok = i("python_ok")
+matlab_ok = i("matlab_ok")
+both_ok = i("both_ok")
+scalar_ok = i("scalar_overlap_pass_topics")
+parity_pass = bool(payload.get("parity_contract", {}).get("pass", False))
+regression_pass = bool(payload.get("regression_gate", {}).get("pass", False))
+matlab_failed = [str(r.get("topic", "")) for r in rows if not bool(r.get("matlab_ok"))]
+runtime_sum = sum(float(r.get("matlab_runtime_s") or 0.0) for r in rows)
+
+print(
+    f"[ladder] block={block} total={total} python_ok={python_ok} matlab_ok={matlab_ok} "
+    f"both_ok={both_ok} scalar_ok={scalar_ok} parity_pass={parity_pass} "
+    f"regression_pass={regression_pass} runtime_sum_s={runtime_sum:.2f}"
+)
+
+regression_reasons = []
+if total <= 0:
+    regression_reasons.append("no topics were executed")
+if python_ok != total:
+    regression_reasons.append(f"python_ok={python_ok}/{total}")
+if matlab_ok != total:
+    regression_reasons.append(f"matlab_ok={matlab_ok}/{total}")
+if both_ok != total:
+    regression_reasons.append(f"both_ok={both_ok}/{total}")
+if scalar_ok != total:
+    regression_reasons.append(f"scalar_overlap_pass_topics={scalar_ok}/{total}")
+if not parity_pass:
+    regression_reasons.append("parity_contract=fail")
+if not regression_pass:
+    regression_reasons.append("regression_gate=fail")
+
+if regression_reasons:
+    print(f"[ladder] regression in {block}: {'; '.join(regression_reasons)}", file=sys.stderr)
+    if matlab_failed:
+        print(f"[ladder] failing matlab topics: {matlab_failed}", file=sys.stderr)
+    sys.exit(10)
+
+if mult > 0:
+    threshold = baseline * mult
+    if runtime_sum > threshold:
+        print(
+            f"[ladder] runtime regression in {block}: runtime_sum_s={runtime_sum:.2f} > "
+            f"threshold_s={threshold:.2f} (baseline={baseline:.2f}, mult={mult:.2f})",
+            file=sys.stderr,
+        )
+        sys.exit(11)
+
+print(f"[ladder] block passed: {block}")
+PY
+    then
+      append_retry_summary_event "block_result" "${block}" "${attempt}" "${max_attempts}" "pass" "0" "ok" ""
+      break
+    fi
+
+    rc=$?
+    if [[ "${rc}" -eq 10 ]] && [[ "${attempt}" -lt "${max_attempts}" ]] && timeout_topics_csv="$(timeout_only_topics_csv "${report_path}")"; then
+      is_timeout_only_regression "${report_path}" >/dev/null
+      echo "[ladder] retrying block ${block} after timeout-only regression (attempt ${attempt}/${max_attempts}); topics=${timeout_topics_csv}"
+      append_retry_summary_event "retry_scheduled" "${block}" "${attempt}" "${max_attempts}" "retry" "${rc}" "timeout_only_regression" "${timeout_topics_csv}"
+      warmup_matlab
+      attempt=$((attempt + 1))
+      continue
+    fi
+    if [[ "${rc}" -eq 10 ]] && [[ "${attempt}" -lt "${max_attempts}" ]] && retry_topics_csv="$(retryable_failure_topics_csv "${report_path}")"; then
+      echo "[ladder] retrying block ${block} after recoverable MATLAB failures (attempt ${attempt}/${max_attempts}); topics=${retry_topics_csv}"
+      append_retry_summary_event "retry_scheduled" "${block}" "${attempt}" "${max_attempts}" "retry" "${rc}" "recoverable_matlab_failures" "${retry_topics_csv}"
+      warmup_matlab
+      attempt=$((attempt + 1))
+      continue
+    fi
+    reason="block_failure"
+    if [[ "${rc}" -eq 10 ]]; then
+      reason="regression_gate_failure"
+    elif [[ "${rc}" -eq 11 ]]; then
+      reason="runtime_regression"
+    fi
+    timeout_topics_csv=""
+    if timeout_topics_tmp="$(timeout_only_topics_csv "${report_path}")"; then
+      timeout_topics_csv="${timeout_topics_tmp}"
+    fi
+    append_retry_summary_event "block_result" "${block}" "${attempt}" "${max_attempts}" "fail" "${rc}" "${reason}" "${timeout_topics_csv}"
+    exit "${rc}"
+  done
+
+done
+
+echo "[ladder] all requested blocks passed"
diff --git a/tools/run_parity_preflight.sh b/tools/run_parity_preflight.sh
new file mode 100755
index 00000000..a72a93af
--- /dev/null
+++ b/tools/run_parity_preflight.sh
@@ -0,0 +1,50 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
+REPO_ROOT="${PROJECT_ROOT}"
+PYTHON_BIN="${PYTHON_BIN:-python3}"
+MATLAB_EXTRA_ARGS="${NSTAT_MATLAB_EXTRA_ARGS:--maca64 -nodisplay -noFigureWindows -softwareopengl}"
+STAGE_A_BLOCKS_RAW="${NSTAT_PARITY_PREFLIGHT_STAGEA_BLOCKS:-core_smoke timeout_front}"
+STAGE_B_TOPICS_RAW="${NSTAT_PARITY_PREFLIGHT_STAGEB_TOPICS:-PPThinning,ValidationDataSet,DecodingExample,StimulusDecode2D}"
+STAGE_B_REPORT_PATH="${NSTAT_PARITY_PREFLIGHT_STAGEB_REPORT:-reports/parity_preflight_stageb_selected.json}"
+
+stage_a_tokens="${STAGE_A_BLOCKS_RAW//,/ }"
+read -r -a STAGE_A_BLOCKS <<< "${stage_a_tokens}"
+if [[ "${#STAGE_A_BLOCKS[@]}" -eq 0 ]]; then
+  echo "[preflight] no Stage A blocks resolved from NSTAT_PARITY_PREFLIGHT_STAGEA_BLOCKS='${STAGE_A_BLOCKS_RAW}'" >&2
+  exit 2
+fi
+
+stage_b_tokens="${STAGE_B_TOPICS_RAW//,/ }"
+read -r -a STAGE_B_TOPICS <<< "${stage_b_tokens}"
+if [[ "${#STAGE_B_TOPICS[@]}" -eq 0 ]]; then
+  echo "[preflight] no Stage B topics resolved from NSTAT_PARITY_PREFLIGHT_STAGEB_TOPICS='${STAGE_B_TOPICS_RAW}'" >&2
+  exit 2
+fi
+
+cd "${REPO_ROOT}"
+export NSTAT_MATLAB_EXTRA_ARGS="${MATLAB_EXTRA_ARGS}"
+export NSTAT_FORCE_M_HELP_SCRIPTS="${NSTAT_FORCE_M_HELP_SCRIPTS:-1}"
+if [[ "${NSTAT_SET_ACTIONS_RUNNER_SVC:-1}" == "1" ]]; then
+  export ACTIONS_RUNNER_SVC=1
+fi
+
+echo "[preflight] repo: ${REPO_ROOT}"
+echo "[preflight] python: ${PYTHON_BIN}"
+echo "[preflight] matlab args: ${NSTAT_MATLAB_EXTRA_ARGS}"
+echo "[preflight] stage A blocks: ${STAGE_A_BLOCKS[*]}"
+echo "[preflight] stage B selected topics: ${STAGE_B_TOPICS[*]}"
+echo "[preflight] stage B report: ${STAGE_B_REPORT_PATH}"
+
+tools/run_parity_ladder.sh "${STAGE_A_BLOCKS[@]}"
+
+"${PYTHON_BIN}" tools/verify_python_vs_matlab_similarity.py \
+  --enforce-gate \
+  --report-path "${STAGE_B_REPORT_PATH}" \
+  --topics "${STAGE_B_TOPICS[@]}"
+
+"${PYTHON_BIN}" tools/summarize_parity_report.py "${STAGE_B_REPORT_PATH}" || true
+
+echo "[preflight] complete"
diff --git a/tools/summarize_parity_report.py b/tools/summarize_parity_report.py
new file mode 100644
index 00000000..46a8afe8
--- /dev/null
+++ b/tools/summarize_parity_report.py
@@ -0,0 +1,134 @@
+from __future__ import annotations
+
+import argparse
+import json
+import statistics
+from collections import Counter
+from pathlib import Path
+from typing import Any
+
+
+def _classify_failure(err: str) -> str:
+    e = (err or "").strip()
+    if not e:
+        return "unknown"
+    if e == "matlab_timeout":
+        return "timeout"
+    if "libmwhandle_graphics" in e or "MATLAB is exiting because of fatal error" in e:
+        return "graphics_crash"
+    if "matlab_json_missing" in e:
+        return "json_missing"
+    return "other_error"
+
+
+def _parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+    parser = argparse.ArgumentParser(description="Summarize nSTAT MATLAB/Python parity report runtime and failures.")
+    parser.add_argument("report", help="Path to python_vs_matlab_similarity_report.json style file.")
+    parser.add_argument("--top", type=int, default=10, help="Number of slowest topics to print.")
+    parser.add_argument("--json", action="store_true", help="Emit machine-readable summary JSON.")
+    return parser.parse_args(argv)
+
+
+def _load(path: Path) -> dict[str, Any]:
+    return json.loads(path.read_text(encoding="utf-8"))
+
+
+def _summarize_rows(rows: list[dict[str, Any]], top: int) -> dict[str, Any]:
+    runtimes = [float(r.get("matlab_runtime_s") or 0.0) for r in rows]
+    failures = [r for r in rows if not bool(r.get("matlab_ok"))]
+    failure_types = Counter(_classify_failure(str(r.get("matlab_error", ""))) for r in failures)
+    sorted_rows = sorted(rows, key=lambda r: float(r.get("matlab_runtime_s") or 0.0), reverse=True)
+    slowest = [
+        {
+            "topic": str(r.get("topic", "")),
+            "runtime_s": float(r.get("matlab_runtime_s") or 0.0),
+            "timeout_s": int(r.get("matlab_timeout_s") or 0),
+            "matlab_ok": bool(r.get("matlab_ok")),
+            "matlab_error": str(r.get("matlab_error", "")),
+        }
+        for r in sorted_rows[: max(1, top)]
+    ]
+    near_timeout = []
+    for r in rows:
+        timeout_s = int(r.get("matlab_timeout_s") or 0)
+        runtime_s = float(r.get("matlab_runtime_s") or 0.0)
+        if timeout_s > 0 and runtime_s / timeout_s >= 0.8:
+            near_timeout.append(
+                {
+                    "topic": str(r.get("topic", "")),
+                    "runtime_s": runtime_s,
+                    "timeout_s": timeout_s,
+                    "pct_timeout": round((runtime_s / timeout_s) * 100.0, 2),
+                    "matlab_error": str(r.get("matlab_error", "")),
+                }
+            )
+    near_timeout.sort(key=lambda x: float(x["pct_timeout"]), reverse=True)
+    p50 = statistics.median(runtimes) if runtimes else 0.0
+    p90 = sorted(runtimes)[int(0.9 * (len(runtimes) - 1))] if runtimes else 0.0
+    return {
+        "topic_count": len(rows),
+        "matlab_failures": len(failures),
+        "failure_types": dict(failure_types),
+        "runtime_s": {
+            "sum": round(sum(runtimes), 3),
+            "p50": round(float(p50), 3),
+            "p90": round(float(p90), 3),
+            "max": round(max(runtimes) if runtimes else 0.0, 3),
+        },
+        "slowest_topics": slowest,
+        "near_timeout_topics": near_timeout,
+    }
+
+
+def main(argv: list[str] | None = None) -> int:
+    args = _parse_args(argv)
+    path = Path(args.report).expanduser().resolve()
+    payload = _load(path)
+
+    if "helpfile_similarity" not in payload:
+        raise SystemExit(f"Unsupported report schema: {path}")
+
+    summary = payload.get("helpfile_similarity", {}).get("summary", {})
+    rows = payload.get("helpfile_similarity", {}).get("rows", [])
+    details = _summarize_rows(rows, top=args.top)
+    out = {
+        "report_path": str(path),
+        "help_summary": summary,
+        "details": details,
+    }
+
+    if args.json:
+        print(json.dumps(out, indent=2))
+        return 0
+
+    print(f"report: {path}")
+    print(f"help summary: {summary}")
+    print(
+        "runtime seconds: "
+        f"sum={details['runtime_s']['sum']} p50={details['runtime_s']['p50']} "
+        f"p90={details['runtime_s']['p90']} max={details['runtime_s']['max']}"
+    )
+    print(f"matlab failures: {details['matlab_failures']} ({details['failure_types']})")
+
+    print("slowest topics:")
+    for row in details["slowest_topics"]:
+        print(
+            f"  - {row['topic']}: runtime={row['runtime_s']:.2f}s "
+            f"timeout={row['timeout_s']} ok={row['matlab_ok']}"
+        )
+
+    if details["near_timeout_topics"]:
+        print("near-timeout topics (>=80% of timeout):")
+        for row in details["near_timeout_topics"]:
+            print(
+                f"  - {row['topic']}: {row['runtime_s']:.2f}/{row['timeout_s']}s "
+                f"({row['pct_timeout']:.1f}%)"
+            )
+    else:
+        print("near-timeout topics (>=80% of timeout): none")
+
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())
diff --git a/tools/verify_examples_notebooks.py b/tools/verify_examples_notebooks.py
new file mode 100644
index 00000000..29e8d9c7
--- /dev/null
+++ b/tools/verify_examples_notebooks.py
@@ -0,0 +1,143 @@
+from __future__ import annotations
+
+import contextlib
+import importlib
+import io
+import json
+import os
+import sys
+import traceback
+import xml.etree.ElementTree as ET
+from pathlib import Path
+from typing import Any
+
+PROJECT_ROOT = Path(__file__).resolve().parents[1]
+REPO_ROOT = PROJECT_ROOT if (PROJECT_ROOT / "helpfiles").exists() else PROJECT_ROOT.parent
+NOTEBOOK_ROOT = PROJECT_ROOT / "notebooks" / "helpfiles"
+SRC_ROOT = PROJECT_ROOT / "examples" / "help_topics"
+REPORT_DIR = PROJECT_ROOT / "reports"
+TOC_PATH = REPO_ROOT / "helpfiles" / "helptoc.xml"
+PY_ROOT = PROJECT_ROOT
+if str(PY_ROOT) not in sys.path:
+    sys.path.insert(0, str(PY_ROOT))
+
+
+def example_topics() -> list[tuple[str, str]]:
+    tree = ET.parse(TOC_PATH)
+    root = tree.getroot()
+    examples = None
+    for item in root.iter("tocitem"):
+        if item.attrib.get("id") == "nstat_examples":
+            examples = item
+            break
+    if examples is None:
+        raise RuntimeError("Unable to locate examples node in helptoc.xml")
+
+    out: list[tuple[str, str]] = []
+    for item in examples.findall("tocitem"):
+        title = " ".join((item.text or "").split()) or Path(item.attrib.get("target", "")).stem
+        target = item.attrib.get("target", "")
+        if target:
+            out.append((title, target))
+    return out
+
+
+def run_python_module(stem: str) -> dict[str, Any]:
+    try:
+        mod = importlib.import_module(f"examples.help_topics.{stem}")
+    except Exception as exc:  # noqa: BLE001
+        return {"ok": False, "error": f"import_error: {exc}"}
+
+    if not hasattr(mod, "run"):
+        return {"ok": False, "error": "missing run()"}
+    try:
+        out = mod.run(repo_root=REPO_ROOT)
+    except Exception as exc:  # noqa: BLE001
+        return {
+            "ok": False,
+            "error": "".join(traceback.format_exception_only(type(exc), exc)).strip(),
+        }
+    return {"ok": True, "output": out}
+
+
+def execute_notebook(path: Path) -> dict[str, Any]:
+    if not path.exists():
+        return {"ok": False, "error": "notebook_missing", "stdout": "", "code_cells": 0}
+    data = json.loads(path.read_text(encoding="utf-8"))
+    ns: dict[str, Any] = {}
+    buf = io.StringIO()
+    code_cells = 0
+    try:
+        for idx, cell in enumerate(data.get("cells", []), start=1):
+            if cell.get("cell_type") != "code":
+                continue
+            code_cells += 1
+            code = "".join(cell.get("source", []))
+            with contextlib.redirect_stdout(buf), contextlib.redirect_stderr(buf):
+                exec(compile(code, f"{path}:{idx}", "exec"), ns, ns)
+    except Exception as exc:  # noqa: BLE001
+        return {
+            "ok": False,
+            "error": "".join(traceback.format_exception_only(type(exc), exc)).strip(),
+            "stdout": buf.getvalue(),
+            "code_cells": code_cells,
+        }
+    return {"ok": True, "error": "", "stdout": buf.getvalue(), "code_cells": code_cells}
+
+
+def main() -> int:
+    topics = example_topics()
+    expected_total = int(os.environ.get("NSTAT_EXPECTED_EXAMPLE_NOTEBOOKS", "25"))
+    rows: list[dict[str, Any]] = []
+    summary = {
+        "total_examples": len(topics),
+        "python_modules_ok": 0,
+        "notebooks_ok": 0,
+        "topic_alignment_ok": 0,
+    }
+
+    for title, target in topics:
+        stem = Path(target).stem
+        py = run_python_module(stem)
+        nb = execute_notebook(NOTEBOOK_ROOT / f"{stem}.ipynb")
+
+        if py["ok"]:
+            summary["python_modules_ok"] += 1
+        if nb["ok"]:
+            summary["notebooks_ok"] += 1
+
+        topic_ok = bool(py.get("ok") and isinstance(py.get("output"), dict) and py["output"].get("topic") == stem)
+        if topic_ok:
+            summary["topic_alignment_ok"] += 1
+
+        rows.append(
+            {
+                "example": stem,
+                "title": title,
+                "matlab_target": target,
+                "python_module_ok": py["ok"],
+                "python_module_error": py.get("error", ""),
+                "python_output_keys": sorted(list(py.get("output", {}).keys())) if py["ok"] and isinstance(py.get("output"), dict) else [],
+                "notebook_ok": nb["ok"],
+                "notebook_error": nb.get("error", ""),
+                "notebook_code_cells": nb.get("code_cells"),
+                "topic_alignment_ok": topic_ok,
+            }
+        )
+
+    REPORT_DIR.mkdir(parents=True, exist_ok=True)
+    out = REPORT_DIR / "examples_notebook_verification.json"
+    out.write_text(json.dumps({"summary": summary, "rows": rows}, indent=2), encoding="utf-8")
+
+    pass_gate = (
+        summary["total_examples"] == expected_total
+        and summary["python_modules_ok"] == expected_total
+        and summary["notebooks_ok"] == expected_total
+        and summary["topic_alignment_ok"] == expected_total
+    )
+    print(json.dumps({"report": str(out.relative_to(REPO_ROOT)), "expected_examples": expected_total, "pass": pass_gate, **summary}, indent=2))
+    return 0 if pass_gate else 1
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())
diff --git a/tools/verify_help_docs_coverage.py b/tools/verify_help_docs_coverage.py
new file mode 100644
index 00000000..622bc372
--- /dev/null
+++ b/tools/verify_help_docs_coverage.py
@@ -0,0 +1,77 @@
+from __future__ import annotations
+
+import json
+import re
+import sys
+import xml.etree.ElementTree as ET
+from pathlib import Path
+
+PROJECT_ROOT = Path(__file__).resolve().parents[1]
+REPO_ROOT = PROJECT_ROOT if (PROJECT_ROOT / "helpfiles").exists() else PROJECT_ROOT.parent
+TOC_PATH = REPO_ROOT / "helpfiles" / "helptoc.xml"
+DOCS_ROOT = PROJECT_ROOT / "docs"
+TOPICS_DIR = DOCS_ROOT / "topics"
+HELP_TOPICS_INDEX = DOCS_ROOT / "help_topics.rst"
+
+
+def _slugify(value: str) -> str:
+    value = value.strip().lower()
+    value = re.sub(r"[^a-z0-9]+", "_", value)
+    return value.strip("_") or "topic"
+
+
+def _expected_topic_slugs() -> list[str]:
+    tree = ET.parse(TOC_PATH)
+    root = tree.getroot()
+    seen: set[str] = set()
+    slugs: list[str] = []
+    for item in root.iter("tocitem"):
+        target = item.attrib.get("target", "").strip()
+        if not target:
+            continue
+        if target.startswith("http://") or target.startswith("https://"):
+            continue
+        slug = _slugify(Path(target).stem)
+        if slug in seen:
+            continue
+        seen.add(slug)
+        slugs.append(slug)
+    return slugs
+
+
+def _index_entries() -> set[str]:
+    if not HELP_TOPICS_INDEX.exists():
+        return set()
+    entries: set[str] = set()
+    for line in HELP_TOPICS_INDEX.read_text(encoding="utf-8").splitlines():
+        line = line.strip()
+        if not line.startswith("topics/"):
+            continue
+        entries.add(line.split("/", 1)[1])
+    return entries
+
+
+def main() -> int:
+    if not TOC_PATH.exists():
+        print(json.dumps({"error": f"missing TOC: {TOC_PATH}"}, indent=2))
+        return 2
+
+    expected = _expected_topic_slugs()
+    index = _index_entries()
+
+    missing_topic_files = [slug for slug in expected if not (TOPICS_DIR / f"{slug}.rst").exists()]
+    missing_index_entries = [slug for slug in expected if slug not in index]
+
+    payload = {
+        "toc_topics": len(expected),
+        "missing_topic_files": missing_topic_files,
+        "missing_index_entries": missing_index_entries,
+        "pass": not missing_topic_files and not missing_index_entries,
+    }
+    print(json.dumps(payload, indent=2))
+
+    return 0 if payload["pass"] else 1
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())
diff --git a/tools/verify_mfile_parity.py b/tools/verify_mfile_parity.py
new file mode 100644
index 00000000..41067fd6
--- /dev/null
+++ b/tools/verify_mfile_parity.py
@@ -0,0 +1,233 @@
+from __future__ import annotations
+
+import importlib
+import json
+import re
+import subprocess
+import sys
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+PORT_ROOT = REPO_ROOT / "python" / "matlab_port"
+REPORT_DIR = REPO_ROOT / "python" / "reports"
+MATLAB_BIN = Path("/Applications/MATLAB_R2025b.app/bin/matlab")
+
+
+@dataclass
+class Entry:
+    source: str
+    kind: str
+    function_name: str | None
+    target: str
+
+
+def first_code_line(text: str) -> str:
+    for line in text.splitlines():
+        s = line.strip()
+        if not s or s.startswith("%"):
+            continue
+        return s
+    return ""
+
+
+def classify_m_file(path: Path) -> tuple[str, str | None]:
+    text = path.read_text(encoding="utf-8", errors="ignore")
+    first = first_code_line(text)
+    if first.startswith("classdef "):
+        return "classdef", None
+
+    if first.startswith("function"):
+        fn = None
+        args = ""
+        patterns = [
+            r"^function\s+\[[^\]]*\]\s*=\s*(\w+)\s*\(([^)]*)\)",
+            r"^function\s+\w+\s*=\s*(\w+)\s*\(([^)]*)\)",
+            r"^function\s+(\w+)\s*\(([^)]*)\)",
+            r"^function\s+\[[^\]]*\]\s*=\s*(\w+)\s*$",
+            r"^function\s+\w+\s*=\s*(\w+)\s*$",
+            r"^function\s+(\w+)\s*$",
+        ]
+        for p in patterns:
+            m = re.match(p, first)
+            if m:
+                fn = m.group(1)
+                if m.lastindex and m.lastindex >= 2:
+                    args = m.group(2)
+                break
+        if fn is None:
+            fn = path.stem
+        nargs = 0 if args.strip() == "" else len([x for x in args.split(",") if x.strip()])
+        return ("function_no_args" if nargs == 0 else "function_args"), fn
+
+    return "script", None
+
+
+def python_module_name(target_rel: str) -> str:
+    rel = Path(target_rel)
+    if rel.parts and rel.parts[0] == "python":
+        rel = Path(*rel.parts[1:])
+    return str(rel.with_suffix("")).replace("/", ".")
+
+
+def run_python_entry(module_name: str, kind: str, function_name: str | None) -> tuple[bool, str]:
+    try:
+        mod = importlib.import_module(module_name)
+    except Exception as e:  # noqa: BLE001
+        return False, f"import_error: {e}"
+
+    if kind in {"classdef", "function_args"}:
+        return True, "interface_checked"
+
+    try:
+        if hasattr(mod, "run"):
+            _ = mod.run(repo_root=REPO_ROOT)
+            return True, "run_ok"
+        if kind == "function_no_args" and function_name and hasattr(mod, function_name):
+            _ = getattr(mod, function_name)()
+            return True, "function_ok"
+        if hasattr(mod, "main"):
+            _ = mod.main()
+            return True, "main_ok"
+        return False, "no_runnable_entrypoint"
+    except Exception as e:  # noqa: BLE001
+        return False, f"runtime_error: {e}"
+
+
+def run_matlab_smoke(entries: list[Entry]) -> dict[str, dict[str, Any]]:
+    results: dict[str, dict[str, Any]] = {}
+    runnable = [e for e in entries if e.kind in {"script", "function_no_args"}]
+
+    if not runnable:
+        return results
+
+    if not MATLAB_BIN.exists():
+        for e in runnable:
+            results[e.source] = {"ok": False, "message": "matlab_not_found"}
+        return results
+
+    repo_q = str(REPO_ROOT).replace("'", "''")
+    for e in runnable:
+        src_q = e.source.replace("'", "''")
+        fn_q = (e.function_name or "").replace("'", "''")
+        if e.kind == "script":
+            run_expr = f"run(fullfile(repo,'{src_q}'));"
+        else:
+            run_expr = f"feval('{fn_q}');"
+
+        cmd = (
+            "restoredefaultpath; "
+            f"repo='{repo_q}'; "
+            "cd(repo); addpath(genpath(repo),'-begin'); set(0,'DefaultFigureVisible','off'); "
+            "try; "
+            + run_expr
+            + " disp('CODEX_SMOKE_OK'); "
+            "catch ME; disp('CODEX_SMOKE_FAIL'); disp([ME.identifier ' | ' ME.message]); "
+            "end; exit(0);"
+        )
+        try:
+            cp = subprocess.run(
+                [str(MATLAB_BIN), "-batch", cmd],
+                cwd=str(REPO_ROOT),
+                capture_output=True,
+                text=True,
+                timeout=120,
+                check=False,
+            )
+        except subprocess.TimeoutExpired:
+            results[e.source] = {"ok": False, "message": "matlab_timeout"}
+            continue
+
+        out = (cp.stdout or "") + "\n" + (cp.stderr or "")
+        if "CODEX_SMOKE_OK" in out:
+            results[e.source] = {"ok": True, "message": "ok"}
+        else:
+            # Keep tail concise but preserve exact MATLAB error lines.
+            tail = "\n".join([ln for ln in out.splitlines() if ln.strip()][-8:])
+            results[e.source] = {"ok": False, "message": tail or "matlab_failed_without_message"}
+    return results
+
+
+def main() -> int:
+    entries: list[Entry] = []
+    for m in sorted(REPO_ROOT.rglob("*.m")):
+        if PORT_ROOT in m.parents:
+            continue
+        rel_path = m.relative_to(REPO_ROOT)
+        if rel_path.parts and rel_path.parts[0] == "python":
+            continue
+        rel = str(m.relative_to(REPO_ROOT))
+        kind, fn = classify_m_file(m)
+        tgt = PORT_ROOT.joinpath(*m.relative_to(REPO_ROOT).parts[:-1], f"{m.stem}.py")
+        entries.append(Entry(source=rel, kind=kind, function_name=fn, target=str(tgt.relative_to(REPO_ROOT))))
+
+    py_root = REPO_ROOT / "python"
+    if str(py_root) not in sys.path:
+        sys.path.insert(0, str(py_root))
+
+    matlab_results = run_matlab_smoke(entries)
+
+    rows: list[dict[str, Any]] = []
+    summary = {
+        "total_m_files": len(entries),
+        "python_ok": 0,
+        "python_runnable_ok": 0,
+        "matlab_runnable_ok": 0,
+        "runnable_parity_pass": 0,
+        "interface_only": 0,
+        "runnable_total": 0,
+    }
+
+    for e in entries:
+        tgt_exists = (REPO_ROOT / e.target).exists()
+        py_ok = False
+        py_msg = "target_missing"
+        if tgt_exists:
+            py_ok, py_msg = run_python_entry(python_module_name(e.target), e.kind, e.function_name)
+
+        if py_ok:
+            summary["python_ok"] += 1
+
+        matlab_ok = None
+        matlab_msg = "not_run"
+        parity = "interface_only"
+
+        if e.kind in {"script", "function_no_args"}:
+            summary["runnable_total"] += 1
+            mr = matlab_results.get(e.source, {"ok": False, "message": "missing_matlab_result"})
+            matlab_ok = bool(mr["ok"])
+            matlab_msg = str(mr["message"])
+            if py_ok:
+                summary["python_runnable_ok"] += 1
+            if matlab_ok:
+                summary["matlab_runnable_ok"] += 1
+            parity = "pass" if (py_ok and matlab_ok) else "fail"
+            if parity == "pass":
+                summary["runnable_parity_pass"] += 1
+        else:
+            summary["interface_only"] += 1
+
+        rows.append(
+            {
+                "source": e.source,
+                "kind": e.kind,
+                "python_target": e.target,
+                "python_ok": py_ok,
+                "python_message": py_msg,
+                "matlab_ok": matlab_ok,
+                "matlab_message": matlab_msg,
+                "parity": parity,
+            }
+        )
+
+    REPORT_DIR.mkdir(parents=True, exist_ok=True)
+    out = REPORT_DIR / "mfile_parity_report.json"
+    out.write_text(json.dumps({"summary": summary, "rows": rows}, indent=2), encoding="utf-8")
+
+    print(json.dumps({"report": str(out.relative_to(REPO_ROOT)), **summary}, indent=2))
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())
diff --git a/tools/verify_offline_standalone.py b/tools/verify_offline_standalone.py
new file mode 100644
index 00000000..61dbd026
--- /dev/null
+++ b/tools/verify_offline_standalone.py
@@ -0,0 +1,192 @@
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import re
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+from typing import Any
+
+
+PROJECT_ROOT = Path(__file__).resolve().parents[1]
+REPO_ROOT = PROJECT_ROOT if (PROJECT_ROOT / "helpfiles").exists() else PROJECT_ROOT.parent
+REPORT_PATH = PROJECT_ROOT / "reports" / "offline_standalone_verification.json"
+
+
+def _run(cmd: list[str], *, cwd: Path, env: dict[str, str]) -> dict[str, Any]:
+    cp = subprocess.run(cmd, cwd=str(cwd), env=env, capture_output=True, text=True, check=False)
+    return {
+        "cmd": cmd,
+        "cwd": str(cwd.relative_to(REPO_ROOT)),
+        "returncode": cp.returncode,
+        "stdout": cp.stdout[-4000:],
+        "stderr": cp.stderr[-4000:],
+        "ok": cp.returncode == 0,
+    }
+
+
+def _sanitize_path(path_value: str) -> str:
+    parts = [p for p in path_value.split(os.pathsep) if p and "matlab" not in p.lower()]
+    return os.pathsep.join(parts)
+
+
+def _runtime_matlab_dependency_scan() -> dict[str, Any]:
+    py_root = PROJECT_ROOT / "nstat"
+    bad_hits: list[str] = []
+    pattern = re.compile(r"(/Applications/MATLAB|subprocess\..*matlab|MATLAB_BIN)", re.IGNORECASE)
+    for p in py_root.rglob("*.py"):
+        text = p.read_text(encoding="utf-8", errors="ignore")
+        if pattern.search(text):
+            bad_hits.append(str(p.relative_to(REPO_ROOT)))
+    return {"ok": len(bad_hits) == 0, "hits": bad_hits}
+
+
+def verify(full_notebooks: bool = False) -> dict[str, Any]:
+    REPORT_PATH.parent.mkdir(parents=True, exist_ok=True)
+    report: dict[str, Any] = {"full_notebooks": bool(full_notebooks)}
+
+    with tempfile.TemporaryDirectory(prefix="nstat_offline_site_") as td:
+        site_dir = Path(td) / "site"
+        site_dir.mkdir(parents=True, exist_ok=True)
+        py = Path(sys.executable)
+        env = dict(os.environ)
+        env["PATH"] = _sanitize_path(env.get("PATH", ""))
+        env["PYTHONPATH"] = str(site_dir)
+
+        install_env = {**env, "PYTHONPATH": str(site_dir)}
+        source_env = {**env, "PYTHONPATH": str(PROJECT_ROOT)}
+        steps = []
+        steps.append(
+            _run(
+                [
+                    str(py),
+                    "-m",
+                    "pip",
+                    "install",
+                    "--no-deps",
+                    ".",
+                    "--target",
+                    str(site_dir),
+                ],
+                cwd=PROJECT_ROOT,
+                env=install_env,
+            )
+        )
+        steps.append(
+            _run(
+                [
+                    str(py),
+                    "-c",
+                    (
+                        "import json, pathlib, nstat; "
+                        "checks=nstat.verify_checksums(); "
+                        "print(json.dumps({'dataset_count': len(nstat.list_datasets()), "
+                        "'checksum_all_true': all(checks.values()), "
+                        "'nstat_path': str(pathlib.Path(nstat.__file__).resolve())}))"
+                    ),
+                ],
+                cwd=PROJECT_ROOT,
+                env=install_env,
+            )
+        )
+        steps.append(
+            _run(
+                [
+                    str(py),
+                    "-c",
+                    (
+                        "import numpy as np; "
+                        "from nstat.signal import Signal; "
+                        "t=np.linspace(0.0,1.0,100); "
+                        "sig=Signal(t, np.column_stack([np.sin(t), np.cos(t)]), name='offline_check'); "
+                        "print(sig.dimension)"
+                    ),
+                ],
+                cwd=PROJECT_ROOT,
+                env=install_env,
+            )
+        )
+        # Source-path fallback check keeps CI resilient if pip --target behavior changes.
+        steps.append(
+            _run(
+                [
+                    str(py),
+                    "-c",
+                    (
+                        "import json, pathlib, nstat; "
+                        "checks=nstat.verify_checksums(); "
+                        "print(json.dumps({'dataset_count': len(nstat.list_datasets()), "
+                        "'checksum_all_true': all(checks.values()), "
+                        "'nstat_path': str(pathlib.Path(nstat.__file__).resolve())}))"
+                    ),
+                ],
+                cwd=PROJECT_ROOT,
+                env=source_env,
+            )
+        )
+        if full_notebooks:
+            steps.append(
+                _run(
+                    [str(py), "tools/verify_examples_notebooks.py"],
+                    cwd=PROJECT_ROOT,
+                    env=source_env,
+                )
+            )
+
+        report["steps"] = steps
+
+    report["runtime_matlab_scan"] = _runtime_matlab_dependency_scan()
+    report["target_install_ok"] = bool(report["steps"][0]["ok"])
+    report["installed_runtime_ok"] = bool(report["steps"][1]["ok"] and report["steps"][2]["ok"])
+    report["source_fallback_ok"] = bool(report["steps"][3]["ok"])
+    report["notebook_checks_ok"] = bool((not full_notebooks) or report["steps"][-1]["ok"])
+    report["install_mode"] = (
+        "target_install"
+        if (report["target_install_ok"] and report["installed_runtime_ok"])
+        else ("source_fallback" if report["source_fallback_ok"] else "failed")
+    )
+    report["pass_strict_target_install"] = bool(
+        report["target_install_ok"]
+        and report["installed_runtime_ok"]
+        and report["notebook_checks_ok"]
+        and report["runtime_matlab_scan"]["ok"]
+    )
+    report["pass"] = bool(
+        report["notebook_checks_ok"]
+        and report["runtime_matlab_scan"]["ok"]
+        and (report["pass_strict_target_install"] or report["source_fallback_ok"])
+    )
+    REPORT_PATH.write_text(json.dumps(report, indent=2), encoding="utf-8")
+    return report
+
+
+def main() -> int:
+    parser = argparse.ArgumentParser(description="Verify standalone offline Python nSTAT usage from source checkout.")
+    parser.add_argument("--full-notebooks", action="store_true", help="Also execute all generated notebooks.")
+    parser.add_argument(
+        "--require-target-install",
+        action="store_true",
+        help="Fail unless pip --target install succeeds (no source fallback mode).",
+    )
+    args = parser.parse_args()
+
+    report = verify(full_notebooks=args.full_notebooks)
+    effective_pass = bool(report["pass_strict_target_install"] if args.require_target_install else report["pass"])
+    printable = {
+        "report": str(REPORT_PATH.relative_to(REPO_ROOT)),
+        "pass": effective_pass,
+        "steps_ok": [step["ok"] for step in report["steps"]],
+        "runtime_matlab_scan_ok": report["runtime_matlab_scan"]["ok"],
+        "target_install_ok": report["target_install_ok"],
+        "install_mode": report["install_mode"],
+        "pass_strict_target_install": report["pass_strict_target_install"],
+    }
+    print(json.dumps(printable, indent=2))
+    return 0 if effective_pass else 1
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())
diff --git a/tools/verify_python_vs_matlab_similarity.py b/tools/verify_python_vs_matlab_similarity.py
new file mode 100644
index 00000000..d9a29d1f
--- /dev/null
+++ b/tools/verify_python_vs_matlab_similarity.py
@@ -0,0 +1,1171 @@
+from __future__ import annotations
+
+import argparse
+import importlib
+import json
+import math
+import os
+import re
+import shutil
+import signal
+import subprocess
+import sys
+import tempfile
+import time
+import traceback
+import xml.etree.ElementTree as ET
+from pathlib import Path
+from typing import Any
+
+PROJECT_ROOT = Path(__file__).resolve().parents[1]
+REPO_ROOT = PROJECT_ROOT if (PROJECT_ROOT / "helpfiles").exists() else PROJECT_ROOT.parent
+MATLAB_BIN = Path("/Applications/MATLAB_R2025b.app/bin/matlab")
+MATLAB_EXTRA_ARGS = [arg for arg in os.environ.get("NSTAT_MATLAB_EXTRA_ARGS", "").split() if arg]
+FORCE_M_HELP_SCRIPTS = os.environ.get("NSTAT_FORCE_M_HELP_SCRIPTS", "").strip().lower() in {"1", "true", "yes", "on"}
+TOC_PATH = REPO_ROOT / "helpfiles" / "helptoc.xml"
+PY_ROOT = PROJECT_ROOT
+if str(PY_ROOT) not in sys.path:
+    sys.path.insert(0, str(PY_ROOT))
+
+EXPECTED_CLASS_TOTAL = 9
+HELP_PYTHON_REQUIRED_OK = 25
+HELP_MATLAB_MIN_OK = 25
+SCALAR_OVERLAP_PASS_MIN_TOPICS = 25
+KNOWN_MATLAB_HELP_FAILURES: set[str] = set()
+PARITY_CONTRACT: dict[str, list[str]] = {
+    "SignalObjExamples": ["sample_rate_hz"],
+    "CovariateExamples": ["figs"],
+    "CovCollExamples": ["figs"],
+    "nSpikeTrainExamples": ["figs"],
+    "nstCollExamples": ["figs"],
+    "EventsExamples": ["figs"],
+    "HistoryExamples": ["figs"],
+    "TrialExamples": ["figs"],
+    "TrialConfigExamples": ["figs"],
+    "ConfigCollExamples": ["figs"],
+    "AnalysisExamples": ["figs"],
+    "FitResultExamples": ["figs"],
+    "FitResSummaryExamples": ["figs"],
+    "PPThinning": ["num_realizations"],
+    "PSTHEstimation": ["num_realizations"],
+    "ValidationDataSet": ["figs"],
+    "mEPSCAnalysis": ["figs"],
+    "PPSimExample": ["figs"],
+    "ExplicitStimulusWhiskerData": ["figs"],
+    "HippocampalPlaceCellExample": ["figs"],
+    "DecodingExample": ["figs"],
+    "DecodingExampleWithHist": ["figs"],
+    "StimulusDecode2D": ["num_cells"],
+    "NetworkTutorial": ["figs"],
+    "nSTATPaperExamples": ["num_cells"],
+}
+FORCE_M_SCRIPT_TOPICS: set[str] = {
+    "SignalObjExamples",
+    "PPThinning",
+    "PSTHEstimation",
+    "StimulusDecode2D",
+    "nSTATPaperExamples",
+}
+DEFAULT_HELP_TOPIC_TIMEOUT_S = 120
+try:
+    DEFAULT_MATLAB_MAX_ATTEMPTS = max(1, int(os.environ.get("NSTAT_MATLAB_TOPIC_MAX_ATTEMPTS", "1")))
+except ValueError:
+    DEFAULT_MATLAB_MAX_ATTEMPTS = 1
+CRASH_ERROR_MARKERS = (
+    "matlab is exiting because of fatal error",
+    "fatal error",
+    "mathworkscrashreporter",
+    "crash report has been saved",
+    "libmwhandle_graphics",
+)
+DEFAULT_TOPIC_TIMEOUT_OVERRIDES: dict[str, int] = {
+    "SignalObjExamples": 180,
+    "CovariateExamples": 180,
+    "CovCollExamples": 180,
+    "nSpikeTrainExamples": 180,
+    "nstCollExamples": 180,
+    "EventsExamples": 180,
+    "HistoryExamples": 180,
+    "TrialExamples": 180,
+    "AnalysisExamples": 180,
+    "DecodingExampleWithHist": 360,
+    "StimulusDecode2D": 180,
+    "nSTATPaperExamples": 240,
+}
+
+
+def _matlab_batch_command(batch_cmd: str) -> list[str]:
+    return [str(MATLAB_BIN), *MATLAB_EXTRA_ARGS, "-batch", batch_cmd]
+
+
+def _env_truthy(name: str, default: bool = False) -> bool:
+    raw = os.environ.get(name)
+    if raw is None:
+        return default
+    return raw.strip().lower() in {"1", "true", "yes", "on"}
+
+
+def _runner_service_mode() -> bool:
+    return _env_truthy("ACTIONS_RUNNER_SVC")
+
+
+def _matlab_cleanup_allowed() -> bool:
+    # Safety default: only cleanup MATLAB processes automatically on runner hosts,
+    # unless explicitly enabled for local investigations.
+    return _runner_service_mode() or _env_truthy("NSTAT_MATLAB_ALLOW_LOCAL_PROCESS_CLEANUP")
+
+
+def _force_topic_isolation_enabled() -> bool:
+    return _env_truthy("NSTAT_MATLAB_FORCE_TOPIC_ISOLATION")
+
+
+def _hard_cleanup_on_failure_enabled() -> bool:
+    return _env_truthy("NSTAT_MATLAB_HARD_CLEANUP_ON_FAILURE")
+
+
+def _output_has_crash_marker(text: str) -> bool:
+    lowered = str(text or "").lower()
+    return any(marker in lowered for marker in CRASH_ERROR_MARKERS)
+
+
+def _matlab_process_snapshot(max_lines: int = 40) -> str:
+    try:
+        cp = subprocess.run(
+            ["ps", "-axo", "pid,ppid,etime,pcpu,pmem,command"],
+            capture_output=True,
+            text=True,
+            check=False,
+        )
+    except Exception:
+        return ""
+    if cp.returncode != 0:
+        return ""
+    patterns = (
+        "MATLAB_R2025b.app/bin/maca64/MATLAB",
+        "MATLABWindow.app/Contents/MacOS/MATLABWindow",
+        "matlabwindowhelper.app/Contents/MacOS/matlabwindowhelper",
+        "MathWorksCrashReporter",
+    )
+    lines = [ln for ln in (cp.stdout or "").splitlines() if any(p in ln for p in patterns)]
+    return "\n".join(lines[-max_lines:])
+
+
+def _cleanup_runner_matlab_processes(hard: bool = False) -> bool:
+    if not _matlab_cleanup_allowed():
+        return False
+    kill_patterns = [
+        "/Applications/MATLAB_R2025b.app/bin/maca64/MATLAB",
+        "/Applications/MATLAB_R2025b.app/bin/matlab",
+        "MATLABWindow.app/Contents/MacOS/MATLABWindow",
+        "matlabwindowhelper.app/Contents/MacOS/matlabwindowhelper",
+        "MathWorksCrashReporter",
+    ]
+    signals = ["-TERM", "-KILL"] if hard else ["-TERM"]
+    for sig in signals:
+        for pat in kill_patterns:
+            try:
+                subprocess.run(["pkill", sig, "-f", pat], capture_output=True, text=True, check=False)
+            except Exception:
+                pass
+        time.sleep(0.4 if sig == "-TERM" else 0.2)
+    return True
+
+
+def _cleanup_runner_matlab_processes_with_snapshots(hard: bool = False) -> dict[str, Any]:
+    snapshot_before = _matlab_process_snapshot()
+    applied = _cleanup_runner_matlab_processes(hard=hard)
+    snapshot_after = _matlab_process_snapshot() if applied else snapshot_before
+    return {
+        "failure_process_snapshot_before_cleanup": snapshot_before,
+        "failure_process_snapshot_after_cleanup": snapshot_after,
+        "runner_service_cleanup": bool(applied),
+    }
+
+
+def _matlab_warmup(timeout_s: int = 90) -> None:
+    if not MATLAB_BIN.exists():
+        return
+    try:
+        _run_matlab_batch_logged("disp(version); exit", timeout_s=timeout_s)
+    except Exception:
+        return
+
+
+def _is_retryable_matlab_failure(payload: dict[str, Any]) -> bool:
+    if bool(payload.get("ok")):
+        return False
+    error = str(payload.get("error", "")).strip()
+    if error == "matlab_timeout":
+        return True
+    combined = " ".join(
+        [
+            error,
+            str(payload.get("error_report", "")),
+            str(payload.get("fallback_error", "")),
+            str(payload.get("fallback_error_report", "")),
+        ]
+    ).lower()
+    return any(marker in combined for marker in CRASH_ERROR_MARKERS)
+
+
+def _kill_process_group(pid: int) -> None:
+    try:
+        os.killpg(pid, signal.SIGKILL)
+        return
+    except Exception:
+        pass
+    try:
+        os.kill(pid, signal.SIGKILL)
+    except Exception:
+        pass
+
+
+def _run_matlab_batch_logged(batch_cmd: str, timeout_s: int) -> dict[str, Any]:
+    cmd = _matlab_batch_command(batch_cmd)
+    with tempfile.NamedTemporaryFile(prefix="nstat_matlab_", suffix=".log", delete=False) as tf:
+        log_path = Path(tf.name)
+
+    timed_out = False
+    returncode: int | None = None
+    t0 = time.time()
+    try:
+        with log_path.open("w", encoding="utf-8", errors="replace") as fh:
+            proc = subprocess.Popen(
+                cmd,
+                cwd=str(REPO_ROOT),
+                stdout=fh,
+                stderr=subprocess.STDOUT,
+                text=True,
+                start_new_session=True,
+            )
+            try:
+                returncode = int(proc.wait(timeout=timeout_s))
+            except subprocess.TimeoutExpired:
+                timed_out = True
+                _kill_process_group(proc.pid)
+                try:
+                    proc.wait(timeout=5)
+                except Exception:
+                    pass
+        out = log_path.read_text(encoding="utf-8", errors="ignore")
+    finally:
+        try:
+            log_path.unlink()
+        except OSError:
+            pass
+
+    return {
+        "timed_out": timed_out,
+        "returncode": returncode,
+        "runtime_s": float(time.time() - t0),
+        "output": out,
+    }
+
+
+def _normalize_key(s: str) -> str:
+    return re.sub(r"[^a-z0-9]", "", s.lower())
+
+
+def _is_number(x: Any) -> bool:
+    return isinstance(x, (int, float)) and math.isfinite(float(x))
+
+
+def _flatten_numeric_scalars(obj: Any, prefix: str = "", out: dict[str, float] | None = None, depth: int = 0) -> dict[str, float]:
+    """Collect finite numeric scalars from nested dict payloads."""
+    if out is None:
+        out = {}
+    if depth > 8:
+        return out
+
+    if isinstance(obj, dict):
+        for k, v in obj.items():
+            key = str(k)
+            next_prefix = f"{prefix}.{key}" if prefix else key
+            _flatten_numeric_scalars(v, next_prefix, out, depth + 1)
+        return out
+
+    if _is_number(obj):
+        val = float(obj)
+        if prefix:
+            out[prefix] = val
+            leaf = prefix.split(".")[-1]
+            out.setdefault(leaf, val)
+    return out
+
+
+def _python_class_checks() -> dict[str, Any]:
+    import numpy as np
+
+    from nstat import CIFModel, Covariate, CovariateCollection, SpikeTrain, SpikeTrainCollection, Trial
+    from nstat.history import HistoryBasis
+
+    nst = SpikeTrain(np.array([0.1, 0.2, 0.4]), name="n1", binwidth=0.1, minTime=0.0, maxTime=1.0)
+    isis = nst.getISIs().tolist()
+    rate = float(nst.firing_rate_hz)
+
+    n1 = SpikeTrain(np.array([0.1, 0.2, 0.4]), name="a", binwidth=0.1, minTime=0.0, maxTime=1.0)
+    n2 = SpikeTrain(np.array([0.15, 0.25, 0.45]), name="b", binwidth=0.1, minTime=0.0, maxTime=1.0)
+    coll = SpikeTrainCollection([n1, n2])
+    psth = coll.psth(0.2)
+
+    t = np.arange(0.0, 1.0 + 1e-12, 0.1)
+    c1 = Covariate(t, np.sin(t), "c1", "time", "s", "", ["c1"])
+    c2 = Covariate(t, np.cos(t), "c2", "time", "s", "", ["c2"])
+    cc = CovariateCollection([c1, c2])
+    _, x, _ = cc.dataToMatrix()
+
+    h = HistoryBasis([1, 2])
+    hmat = h.design_matrix(n1.getSigRep(0.1, 0.0, 1.0).data[:, 0])
+
+    trial = Trial(spike_collection=coll, covariate_collection=cc)
+
+    lam = Covariate(t, np.ones_like(t) * 5.0, "lam", "time", "s", "Hz", ["lam"])
+    sim = CIFModel(lam.time, lam.data[:, 0], "lam").simulate(num_realizations=3, seed=0)
+
+    return {
+        "nspike_getISIs": isis,
+        "nspike_rate": rate,
+        "nstcoll_psth_len": int(psth.data.shape[0]),
+        "nstcoll_psth_mean": float(np.mean(psth.data)),
+        "covcoll_shape": [int(x.shape[0]), int(x.shape[1])],
+        "history_num_columns": int(hmat.shape[1]),
+        "trial_sample_rate": float(trial.spike_collection.sampleRate),
+        "trial_minmax": [float(trial.spike_collection.minTime), float(trial.spike_collection.maxTime)],
+        "cif_num_realizations": int(sim.numSpikeTrains),
+    }
+
+
+def _matlab_class_checks(timeout_s: int = 180) -> dict[str, Any]:
+    if not MATLAB_BIN.exists():
+        return {"ok": False, "error": "matlab_not_found"}
+    if _force_topic_isolation_enabled():
+        _cleanup_runner_matlab_processes(hard=True)
+
+    repo_q = str(REPO_ROOT).replace("'", "''")
+    cmd = (
+        "restoredefaultpath; "
+        f"repo='{repo_q}'; "
+        "cd(repo); addpath(genpath(repo),'-begin'); set(0,'DefaultFigureVisible','off'); "
+        "try; "
+        "R=struct(); "
+        "nst=nspikeTrain([0.1 0.2 0.4],'n1',0.1,0,1); "
+        "R.nspike_getISIs=nst.getISIs(); "
+        "R.nspike_rate=nst.avgFiringRate; "
+        "n1=nspikeTrain([0.1 0.2 0.4],'a',0.1,0,1); "
+        "n2=nspikeTrain([0.15 0.25 0.45],'b',0.1,0,1); "
+        "coll=nstColl({n1,n2}); "
+        "psth=coll.psth(0.2); "
+        "R.nstcoll_psth_len=length(psth.data); "
+        "R.nstcoll_psth_mean=mean(psth.data); "
+        "t=(0:0.1:1)'; "
+        "c1=Covariate(t,sin(t),'c1','time','s','','c1'); "
+        "c2=Covariate(t,cos(t),'c2','time','s','','c2'); "
+        "cc=CovColl({c1,c2}); "
+        "X=cc.dataToMatrix(); "
+        "R.covcoll_shape=size(X); "
+        "h=History([0 0.1 0.2],0,1); "
+        "hc=h.computeHistory(n1); "
+        "hcov=hc.getCov(1); "
+        "R.history_num_columns=hcov.dimension; "
+        "tr=Trial(coll,cc); "
+        "R.trial_sample_rate=tr.sampleRate; "
+        "R.trial_minmax=[tr.minTime tr.maxTime]; "
+        "lam=Covariate(t,ones(size(t))*5,'lam','time','s','Hz','lam'); "
+        "sim=CIF.simulateCIFByThinningFromLambda(lam,3); "
+        "R.cif_num_realizations=sim.numSpikeTrains; "
+        "disp(['CODEX_JSON:' jsonencode(R)]); "
+        "catch ME; "
+        "disp('CODEX_JSON_ERROR'); disp([ME.identifier ' | ' ME.message]); "
+        "end; exit(0);"
+    )
+
+    try:
+        run = _run_matlab_batch_logged(cmd, timeout_s)
+    except Exception as exc:  # noqa: BLE001
+        return {"ok": False, "error": f"matlab_subprocess_error: {exc}"}
+
+    if bool(run.get("timed_out", False)):
+        cleanup_meta = {}
+        if _hard_cleanup_on_failure_enabled() or _force_topic_isolation_enabled():
+            cleanup_meta = _cleanup_runner_matlab_processes_with_snapshots(hard=True)
+        return {
+            "ok": False,
+            "error": "matlab_timeout",
+            "runtime_s": float(timeout_s),
+            "timeout_process_snapshot_before_cleanup": cleanup_meta.get("failure_process_snapshot_before_cleanup", ""),
+            "timeout_process_snapshot_after_cleanup": cleanup_meta.get("failure_process_snapshot_after_cleanup", ""),
+            "runner_service_cleanup": bool(cleanup_meta.get("runner_service_cleanup", False)),
+            "cleanup_reason": "matlab_timeout",
+        }
+
+    out = str(run.get("output", ""))
+    m = re.search(r"CODEX_JSON:(\{.*\})", out, flags=re.S)
+    if not m:
+        tail = "\n".join([ln for ln in out.splitlines() if ln.strip()][-12:])
+        payload = {"ok": False, "error": tail or "matlab_json_missing"}
+        if _output_has_crash_marker(out) and (_hard_cleanup_on_failure_enabled() or _force_topic_isolation_enabled()):
+            payload.update(_cleanup_runner_matlab_processes_with_snapshots(hard=True))
+            payload["cleanup_reason"] = "matlab_crash_no_json"
+        return payload
+
+    try:
+        payload = json.loads(m.group(1))
+    except json.JSONDecodeError as exc:
+        return {"ok": False, "error": f"json_decode_error: {exc}"}
+
+    return {"ok": True, "payload": payload}
+
+
+def _compare_class_results(py: dict[str, Any], ml: dict[str, Any]) -> dict[str, Any]:
+    comparisons = []
+
+    def cmp_scalar(name: str, atol: float = 1e-6, rtol: float = 1e-4):
+        pv = float(py[name])
+        mv = float(ml[name])
+        diff = abs(pv - mv)
+        tol = atol + rtol * abs(mv)
+        ok = diff <= tol
+        comparisons.append({"metric": name, "python": pv, "matlab": mv, "abs_diff": diff, "pass": ok})
+
+    def cmp_list(name: str, atol: float = 1e-6):
+        pa = [float(x) for x in py[name]]
+        ma = [float(x) for x in ml[name]]
+        ok = len(pa) == len(ma) and all(abs(a - b) <= atol for a, b in zip(pa, ma))
+        comparisons.append({"metric": name, "python": pa, "matlab": ma, "pass": ok})
+
+    cmp_list("nspike_getISIs", atol=1e-9)
+    cmp_scalar("nspike_rate", atol=1e-9, rtol=1e-9)
+    cmp_scalar("nstcoll_psth_len", atol=0.0, rtol=0.0)
+    cmp_scalar("nstcoll_psth_mean", atol=1e-9, rtol=1e-6)
+    cmp_list("covcoll_shape", atol=0.0)
+    cmp_scalar("history_num_columns", atol=0.0, rtol=0.0)
+    cmp_scalar("trial_sample_rate", atol=1e-9, rtol=1e-9)
+    cmp_list("trial_minmax", atol=1e-9)
+    cmp_scalar("cif_num_realizations", atol=0.0, rtol=0.0)
+
+    passed = sum(1 for c in comparisons if c["pass"])
+    total = len(comparisons)
+    return {
+        "comparisons": comparisons,
+        "summary": {
+            "passed": passed,
+            "total": total,
+            "similarity_score": float(passed / total if total else 0.0),
+        },
+    }
+
+
+def _example_topics() -> list[tuple[str, str]]:
+    tree = ET.parse(TOC_PATH)
+    root = tree.getroot()
+    examples = None
+    for item in root.iter("tocitem"):
+        if item.attrib.get("id") == "nstat_examples":
+            examples = item
+            break
+    if examples is None:
+        raise RuntimeError("Unable to locate examples node in helptoc.xml")
+
+    out: list[tuple[str, str]] = []
+    for item in examples.findall("tocitem"):
+        title = " ".join("".join(item.itertext()).split())
+        target = item.attrib.get("target", "")
+        if target:
+            out.append((title, target))
+    return out
+
+
+def _parse_topics_arg(topics_arg: list[str] | None) -> set[str] | None:
+    if not topics_arg:
+        return None
+    topics: set[str] = set()
+    for raw in topics_arg:
+        for part in raw.split(","):
+            stem = part.strip()
+            if stem:
+                topics.add(stem)
+    return topics or None
+
+
+def _parse_topic_timeout_overrides(specs: list[str]) -> dict[str, int]:
+    out: dict[str, int] = {}
+    for spec in specs:
+        key, sep, value = spec.partition("=")
+        topic = key.strip()
+        raw_seconds = value.strip()
+        if sep != "=" or not topic or not raw_seconds:
+            raise ValueError(f"invalid --topic-timeout '{spec}'; expected TOPIC=SECONDS")
+        try:
+            seconds = int(raw_seconds)
+        except ValueError as exc:
+            raise ValueError(f"invalid timeout value in '{spec}': {raw_seconds}") from exc
+        if seconds <= 0:
+            raise ValueError(f"timeout must be positive in '{spec}'")
+        out[topic] = seconds
+    return out
+
+
+def _resolve_topics(requested_topics: set[str] | None) -> list[tuple[str, str]]:
+    topics = _example_topics()
+    if requested_topics is None:
+        return topics
+
+    available = {Path(target).stem for _, target in topics}
+    missing = sorted(requested_topics - available)
+    if missing:
+        raise ValueError(f"unknown topic(s): {missing}")
+
+    return [(title, target) for title, target in topics if Path(target).stem in requested_topics]
+
+
+def _run_python_topic(stem: str) -> dict[str, Any]:
+    try:
+        mod = importlib.import_module(f"examples.help_topics.{stem}")
+        out = mod.run(repo_root=REPO_ROOT)
+        if not isinstance(out, dict):
+            return {"ok": False, "error": "non_dict_output", "output": out}
+
+        scalar_map = _flatten_numeric_scalars(out)
+        return {"ok": True, "output": out, "scalar_map": scalar_map}
+    except Exception as exc:  # noqa: BLE001
+        return {
+            "ok": False,
+            "error": "".join(traceback.format_exception_only(type(exc), exc)).strip(),
+        }
+
+
+def _run_matlab_help_script(script_rel: str, timeout_s: int = 240) -> dict[str, Any]:
+    if not MATLAB_BIN.exists():
+        return {"ok": False, "error": "matlab_not_found"}
+
+    def run_script_path(path: Path, timeout: int, source_label: str | None = None) -> dict[str, Any]:
+        repo_q = str(REPO_ROOT).replace("'", "''")
+        path_q = str(path).replace("'", "''")
+        script_used = source_label or str(path.relative_to(REPO_ROOT))
+        isolation_enabled = _force_topic_isolation_enabled()
+        hard_cleanup_enabled = _hard_cleanup_on_failure_enabled() or isolation_enabled
+        cmd = (
+            "restoredefaultpath; "
+            f"repo='{repo_q}'; "
+            "cd(repo); addpath(genpath(repo),'-begin'); set(0,'DefaultFigureVisible','off'); close all force; "
+            "try; "
+            f"run('{path_q}'); "
+            "figs=numel(findall(0,'Type','figure')); "
+            "vars=whos; "
+            "scalars=struct(); "
+            "for ii=1:numel(vars); "
+            "vn=vars(ii).name; "
+            "if(strcmp(vn,'P')||strcmp(vn,'ME')||strcmp(vn,'ans')); continue; end; "
+            "try; vv=eval(vn); "
+            "if (isnumeric(vv)&&isscalar(vv)&&isfinite(vv)); "
+            "scalars.(vn)=double(vv); "
+            "elseif (islogical(vv)&&isscalar(vv)); "
+            "scalars.(vn)=double(vv); "
+            "elseif (isstruct(vv)&&isscalar(vv)); "
+            "fn=fieldnames(vv); "
+            "for jj=1:numel(fn); "
+            "f=fn{jj}; sv=vv.(f); "
+            "if (isnumeric(sv)&&isscalar(sv)&&isfinite(sv)); "
+            "if ~isfield(scalars,f); scalars.(f)=double(sv); end; "
+            "scalars.([vn '_' f])=double(sv); "
+            "end; "
+            "end; "
+            "end; "
+            "catch; end; "
+            "end; "
+            "P=struct('ok',logical(1),'figures',figs,'var_count',numel(vars),'scalars',scalars); "
+            "disp(['CODEX_JSON:' jsonencode(P)]); "
+            "catch ME; "
+            "errId=ME.identifier; errMsg=ME.message; "
+            "try; errRep=getReport(ME,'extended','hyperlinks','off'); catch; errRep=''; end; "
+            "P=struct('ok',logical(0),'error',[errId ' | ' errMsg],'error_report',errRep); "
+            "disp(['CODEX_JSON:' jsonencode(P)]); "
+            "end; exit(0);"
+        )
+
+        # Optional strict isolation: clear any pre-existing MATLAB helper/process state
+        # before launching each topic attempt.
+        if isolation_enabled:
+            _cleanup_runner_matlab_processes(hard=True)
+
+        t0 = time.time()
+        try:
+            run = _run_matlab_batch_logged(cmd, timeout)
+        except Exception as exc:  # noqa: BLE001
+            cleanup_meta = {}
+            if hard_cleanup_enabled:
+                cleanup_meta = _cleanup_runner_matlab_processes_with_snapshots(hard=True)
+            return {
+                "ok": False,
+                "error": f"matlab_subprocess_error: {exc}",
+                "runtime_s": float(time.time() - t0),
+                "script_used": script_used,
+                "topic_isolation_enabled": isolation_enabled,
+                "cleanup_reason": "matlab_subprocess_error",
+                **cleanup_meta,
+            }
+
+        if bool(run.get("timed_out", False)):
+            cleanup_meta = {}
+            if hard_cleanup_enabled:
+                cleanup_meta = _cleanup_runner_matlab_processes_with_snapshots(hard=True)
+            return {
+                "ok": False,
+                "error": "matlab_timeout",
+                "runtime_s": float(timeout),
+                "script_used": script_used,
+                "topic_isolation_enabled": isolation_enabled,
+                "timeout_process_snapshot_before_cleanup": cleanup_meta.get("failure_process_snapshot_before_cleanup", ""),
+                "timeout_process_snapshot_after_cleanup": cleanup_meta.get("failure_process_snapshot_after_cleanup", ""),
+                "runner_service_cleanup": bool(cleanup_meta.get("runner_service_cleanup", False)),
+                "cleanup_reason": "matlab_timeout",
+                **cleanup_meta,
+            }
+
+        runtime = float(run.get("runtime_s", time.time() - t0))
+        out = str(run.get("output", ""))
+        m = re.search(r"CODEX_JSON:(\{.*\})", out, flags=re.S)
+        if not m:
+            tail = "\n".join([ln for ln in out.splitlines() if ln.strip()][-10:])
+            payload: dict[str, Any] = {
+                "ok": False,
+                "error": tail or "matlab_json_missing",
+                "runtime_s": runtime,
+                "script_used": script_used,
+                "topic_isolation_enabled": isolation_enabled,
+            }
+            if _output_has_crash_marker(out) and hard_cleanup_enabled:
+                payload.update(_cleanup_runner_matlab_processes_with_snapshots(hard=True))
+                payload["cleanup_reason"] = "matlab_crash_no_json"
+            return payload
+
+        try:
+            payload = json.loads(m.group(1))
+        except json.JSONDecodeError as exc:
+            error_payload: dict[str, Any] = {
+                "ok": False,
+                "error": f"json_decode_error: {exc}",
+                "runtime_s": runtime,
+                "script_used": script_used,
+                "topic_isolation_enabled": isolation_enabled,
+            }
+            if _output_has_crash_marker(out) and hard_cleanup_enabled:
+                error_payload.update(_cleanup_runner_matlab_processes_with_snapshots(hard=True))
+                error_payload["cleanup_reason"] = "json_decode_after_crash_output"
+            return error_payload
+
+        payload["runtime_s"] = runtime
+        payload["script_used"] = script_used
+        payload["topic_isolation_enabled"] = isolation_enabled
+        if (
+            not bool(payload.get("ok"))
+            and hard_cleanup_enabled
+            and _is_retryable_matlab_failure(payload)
+            and str(payload.get("error", "")).strip() != "matlab_timeout"
+        ):
+            payload.update(_cleanup_runner_matlab_processes_with_snapshots(hard=True))
+            payload["cleanup_reason"] = "retryable_matlab_failure"
+        return payload
+
+    def run_with_shadow_safe_copy(path: Path, timeout: int) -> dict[str, Any]:
+        # If a same-stem .mlx exists, direct run() of .m is shadowed in MATLAB.
+        # Execute a temporary copy with a unique name to preserve .m behavior.
+        if path.suffix.lower() == ".m" and path.with_suffix(".mlx").exists():
+            with tempfile.TemporaryDirectory(prefix="nstat_verify_") as temp_dir:
+                temp_script = Path(temp_dir) / f"codex_{path.stem}_shadowsafe.m"
+                shutil.copy2(path, temp_script)
+                out = run_script_path(temp_script, timeout, f"{path.relative_to(REPO_ROOT)} [shadow_safe_copy]")
+            return out
+        return run_script_path(path, timeout, str(path.relative_to(REPO_ROOT)))
+
+    script_abs = REPO_ROOT / script_rel
+    if not script_abs.exists():
+        return {"ok": False, "error": f"missing_script: {script_rel}"}
+
+    primary = run_with_shadow_safe_copy(script_abs, timeout_s)
+    if primary.get("ok"):
+        return primary
+
+    # If .mlx fails and peer .m exists, try .m as fallback to recover from
+    # live-script execution issues and timeout-heavy topics.
+    if script_abs.suffix.lower() == ".mlx":
+        m_peer = script_abs.with_suffix(".m")
+        if m_peer.exists():
+            fallback_timeout = max(timeout_s, 180)
+            fallback = run_with_shadow_safe_copy(m_peer, fallback_timeout)
+            fallback["fallback_from"] = str(script_abs.relative_to(REPO_ROOT))
+            if fallback.get("ok"):
+                return fallback
+            combined = dict(primary)
+            combined["fallback_script_used"] = fallback.get("script_used")
+            combined["fallback_error"] = fallback.get("error", "")
+            combined["fallback_error_report"] = fallback.get("error_report", "")
+            combined["error"] = f"{primary.get('error', '')} || fallback_error: {fallback.get('error', '')}"
+            if not combined.get("cleanup_reason"):
+                combined["cleanup_reason"] = fallback.get("cleanup_reason", "")
+            if not combined.get("failure_process_snapshot_before_cleanup"):
+                combined["failure_process_snapshot_before_cleanup"] = fallback.get(
+                    "failure_process_snapshot_before_cleanup", ""
+                )
+            if not combined.get("failure_process_snapshot_after_cleanup"):
+                combined["failure_process_snapshot_after_cleanup"] = fallback.get(
+                    "failure_process_snapshot_after_cleanup", ""
+                )
+            combined["runner_service_cleanup"] = bool(
+                combined.get("runner_service_cleanup", False) or fallback.get("runner_service_cleanup", False)
+            )
+            combined["topic_isolation_enabled"] = bool(
+                combined.get("topic_isolation_enabled", False) or fallback.get("topic_isolation_enabled", False)
+            )
+            return combined
+
+    return primary
+
+
+def _compare_topic_scalars(py_scalars: dict[str, float], ml_scalars: dict[str, float]) -> dict[str, Any]:
+    ml_norm = {_normalize_key(k): (k, float(v)) for k, v in ml_scalars.items() if _is_number(v)}
+    overlaps = []
+    for pk, pv in py_scalars.items():
+        nk = _normalize_key(pk)
+        if nk in ml_norm:
+            mk, mv = ml_norm[nk]
+            diff = abs(float(pv) - float(mv))
+            tol = 1e-6 + 1e-3 * abs(mv)
+            overlaps.append(
+                {
+                    "python_key": pk,
+                    "matlab_key": mk,
+                    "python": float(pv),
+                    "matlab": float(mv),
+                    "abs_diff": diff,
+                    "pass": diff <= tol,
+                }
+            )
+    passed = sum(1 for o in overlaps if o["pass"])
+    return {
+        "overlaps": overlaps,
+        "overlap_count": len(overlaps),
+        "overlap_passed": passed,
+    }
+
+
+def _help_similarity(
+    topics: list[tuple[str, str]],
+    default_timeout_s: int = DEFAULT_HELP_TOPIC_TIMEOUT_S,
+    topic_timeout_overrides: dict[str, int] | None = None,
+    matlab_max_attempts: int = DEFAULT_MATLAB_MAX_ATTEMPTS,
+) -> dict[str, Any]:
+    rows: list[dict[str, Any]] = []
+
+    summary = {
+        "total_topics": len(topics),
+        "both_ok": 0,
+        "python_ok": 0,
+        "matlab_ok": 0,
+        "scalar_overlap_topics": 0,
+        "scalar_overlap_pass_topics": 0,
+        "avg_similarity_score": 0.0,
+    }
+
+    scores: list[float] = []
+    topic_timeouts = dict(DEFAULT_TOPIC_TIMEOUT_OVERRIDES)
+    if topic_timeout_overrides:
+        topic_timeouts.update(topic_timeout_overrides)
+    for idx, (title, target) in enumerate(topics, start=1):
+        stem = Path(target).stem
+        m_rel = f"helpfiles/{stem}.m"
+        mlx_rel = f"helpfiles/{stem}.mlx"
+        if (FORCE_M_HELP_SCRIPTS or stem in FORCE_M_SCRIPT_TOPICS) and (REPO_ROOT / m_rel).exists():
+            script_rel = m_rel
+        elif (REPO_ROOT / mlx_rel).exists():
+            script_rel = mlx_rel
+        elif (REPO_ROOT / m_rel).exists():
+            script_rel = m_rel
+        else:
+            script_rel = m_rel
+
+        print(f"[help {idx}/{len(topics)}] {stem}", flush=True)
+
+        py = _run_python_topic(stem)
+        timeout_s = topic_timeouts.get(stem, default_timeout_s)
+        ml_attempt_history: list[dict[str, Any]] = []
+        ml = _run_matlab_help_script(script_rel, timeout_s=timeout_s)
+        ml_attempt_history.append(
+            {
+                "attempt": 1,
+                "ok": bool(ml.get("ok")),
+                "error": str(ml.get("error", "")),
+                "runtime_s": float(ml.get("runtime_s") or 0.0),
+                "script_used": str(ml.get("script_used", script_rel)),
+                "cleanup_reason": str(ml.get("cleanup_reason", "")),
+                "runner_service_cleanup": bool(ml.get("runner_service_cleanup", False)),
+                "topic_isolation_enabled": bool(ml.get("topic_isolation_enabled", False)),
+            }
+        )
+        attempt = 1
+        while (
+            attempt < matlab_max_attempts
+            and not bool(ml.get("ok"))
+            and _is_retryable_matlab_failure(ml)
+        ):
+            next_attempt = attempt + 1
+            print(
+                f"[help retry {next_attempt}/{matlab_max_attempts}] {stem} "
+                f"after retryable MATLAB failure: {ml.get('error', '')}",
+                flush=True,
+            )
+            _matlab_warmup()
+            ml = _run_matlab_help_script(script_rel, timeout_s=timeout_s)
+            ml_attempt_history.append(
+                {
+                    "attempt": next_attempt,
+                    "ok": bool(ml.get("ok")),
+                    "error": str(ml.get("error", "")),
+                    "runtime_s": float(ml.get("runtime_s") or 0.0),
+                    "script_used": str(ml.get("script_used", script_rel)),
+                    "cleanup_reason": str(ml.get("cleanup_reason", "")),
+                    "runner_service_cleanup": bool(ml.get("runner_service_cleanup", False)),
+                    "topic_isolation_enabled": bool(ml.get("topic_isolation_enabled", False)),
+                }
+            )
+            attempt = next_attempt
+
+        if py.get("ok"):
+            summary["python_ok"] += 1
+        if ml.get("ok"):
+            summary["matlab_ok"] += 1
+
+        scalar_cmp = {"overlaps": [], "overlap_count": 0, "overlap_passed": 0}
+        if py.get("ok") and ml.get("ok"):
+            scalar_cmp = _compare_topic_scalars(py.get("scalar_map", {}), ml.get("scalars", {}))
+
+        both_ok = bool(py.get("ok") and ml.get("ok"))
+        if both_ok:
+            summary["both_ok"] += 1
+
+        if scalar_cmp["overlap_count"] > 0:
+            summary["scalar_overlap_topics"] += 1
+            if scalar_cmp["overlap_passed"] == scalar_cmp["overlap_count"]:
+                summary["scalar_overlap_pass_topics"] += 1
+
+        if not both_ok:
+            score = 0.0
+        elif scalar_cmp["overlap_count"] == 0:
+            score = 0.7
+        else:
+            score = 0.7 + 0.3 * (scalar_cmp["overlap_passed"] / scalar_cmp["overlap_count"])
+        scores.append(score)
+
+        rows.append(
+            {
+                "topic": stem,
+                "title": title,
+                "python_ok": bool(py.get("ok")),
+                "python_error": py.get("error", ""),
+                "python_output_keys": sorted(list(py.get("output", {}).keys())) if py.get("ok") else [],
+                "python_scalar_count": len(py.get("scalar_map", {})) if py.get("ok") else 0,
+                "matlab_ok": bool(ml.get("ok")),
+                "matlab_error": ml.get("error", ""),
+                "matlab_error_report": ml.get("error_report", ""),
+                "matlab_fallback_error": ml.get("fallback_error", ""),
+                "matlab_fallback_error_report": ml.get("fallback_error_report", ""),
+                "matlab_figures": ml.get("figures"),
+                "matlab_var_count": ml.get("var_count"),
+                "matlab_scalar_count": len(ml.get("scalars", {})) if isinstance(ml.get("scalars"), dict) else 0,
+                "matlab_script_used": ml.get("script_used", script_rel),
+                "matlab_fallback_script_used": ml.get("fallback_script_used", ""),
+                "matlab_runtime_s": ml.get("runtime_s"),
+                "matlab_timeout_s": timeout_s,
+                "matlab_attempts": len(ml_attempt_history),
+                "matlab_retry_applied": len(ml_attempt_history) > 1,
+                "matlab_attempt_history": ml_attempt_history,
+                "matlab_timeout_snapshot_before_cleanup": ml.get("timeout_process_snapshot_before_cleanup", ""),
+                "matlab_timeout_snapshot_after_cleanup": ml.get("timeout_process_snapshot_after_cleanup", ""),
+                "matlab_failure_snapshot_before_cleanup": ml.get("failure_process_snapshot_before_cleanup", ""),
+                "matlab_failure_snapshot_after_cleanup": ml.get("failure_process_snapshot_after_cleanup", ""),
+                "matlab_runner_service_cleanup": bool(ml.get("runner_service_cleanup", False)),
+                "matlab_cleanup_reason": ml.get("cleanup_reason", ""),
+                "matlab_topic_isolation_enabled": bool(ml.get("topic_isolation_enabled", False)),
+                "scalar_overlap": scalar_cmp,
+                "similarity_score": score,
+            }
+        )
+
+    summary["avg_similarity_score"] = float(sum(scores) / len(scores) if scores else 0.0)
+    return {"summary": summary, "rows": rows}
+
+
+def _evaluate_parity_contract(help_rows: list[dict[str, Any]], topics_filter: set[str] | None = None) -> dict[str, Any]:
+    by_topic = {str(r.get("topic", "")): r for r in help_rows}
+    rows: list[dict[str, Any]] = []
+    failures: list[str] = []
+    if topics_filter is None:
+        contract_items = list(PARITY_CONTRACT.items())
+    else:
+        contract_items = [(topic, required_keys) for topic, required_keys in PARITY_CONTRACT.items() if topic in topics_filter]
+        missing_contract_entries = sorted(topics_filter - set(PARITY_CONTRACT))
+        for topic in missing_contract_entries:
+            failures.append(f"{topic}: missing parity contract entry")
+            rows.append({"topic": topic, "required_keys": [], "status": "missing_contract"})
+
+    for topic, required_keys in contract_items:
+        row = by_topic.get(topic)
+        if row is None:
+            failures.append(f"{topic}: missing topic row")
+            rows.append({"topic": topic, "required_keys": required_keys, "status": "missing_topic"})
+            continue
+
+        if not (bool(row.get("python_ok")) and bool(row.get("matlab_ok"))):
+            failures.append(f"{topic}: python_ok={row.get('python_ok')} matlab_ok={row.get('matlab_ok')}")
+            rows.append(
+                {
+                    "topic": topic,
+                    "required_keys": required_keys,
+                    "status": "topic_not_ok",
+                    "python_ok": bool(row.get("python_ok")),
+                    "matlab_ok": bool(row.get("matlab_ok")),
+                }
+            )
+            continue
+
+        overlaps = row.get("scalar_overlap", {}).get("overlaps", [])
+        normalized = {}
+        for ov in overlaps:
+            pkey = str(ov.get("python_key", ""))
+            mkey = str(ov.get("matlab_key", ""))
+            normalized[_normalize_key(pkey)] = ov
+            normalized[_normalize_key(mkey)] = ov
+
+        missing: list[str] = []
+        failing: list[str] = []
+        for key in required_keys:
+            nk = _normalize_key(key)
+            ov = normalized.get(nk)
+            if ov is None:
+                missing.append(key)
+                continue
+            if not bool(ov.get("pass")):
+                failing.append(key)
+
+        status = "pass" if not missing and not failing else "fail"
+        if status == "fail":
+            failures.append(f"{topic}: missing={missing} failing={failing}")
+        rows.append(
+            {
+                "topic": topic,
+                "required_keys": required_keys,
+                "missing_keys": missing,
+                "failing_keys": failing,
+                "status": status,
+            }
+        )
+
+    return {
+        "pass": len(failures) == 0,
+        "failures": failures,
+        "rows": rows,
+    }
+
+
+def _evaluate_regression_gate(report: dict[str, Any]) -> dict[str, Any]:
+    topic_selection = report.get("topic_selection", {})
+    class_summary = report.get("class_similarity", {}).get("summary", {})
+    help_summary = report.get("helpfile_similarity", {}).get("summary", {})
+    help_rows = report.get("helpfile_similarity", {}).get("rows", [])
+    parity_contract = report.get("parity_contract", {})
+
+    failures: list[str] = []
+    full_suite = bool(topic_selection.get("full_suite", True))
+    selected_topics = int(topic_selection.get("total_topics", help_summary.get("total_topics", 0)))
+    python_required = HELP_PYTHON_REQUIRED_OK if full_suite else selected_topics
+    matlab_required = HELP_MATLAB_MIN_OK if full_suite else selected_topics
+    scalar_required = SCALAR_OVERLAP_PASS_MIN_TOPICS if full_suite else selected_topics
+
+    class_passed = int(class_summary.get("passed", 0))
+    class_total = int(class_summary.get("total", 0))
+    if class_total < EXPECTED_CLASS_TOTAL or class_passed != class_total:
+        failures.append(
+            f"class gate failed: expected {EXPECTED_CLASS_TOTAL}/{EXPECTED_CLASS_TOTAL}, got {class_passed}/{class_total}"
+        )
+
+    python_ok = int(help_summary.get("python_ok", 0))
+    total_topics = int(help_summary.get("total_topics", 0))
+    if python_ok < python_required or python_ok != total_topics:
+        if full_suite:
+            failures.append(f"python help gate failed: expected all topics ok, got {python_ok}/{total_topics}")
+        else:
+            failures.append(
+                f"python help gate failed for selected topics: expected {python_required}/{selected_topics}, "
+                f"got {python_ok}/{total_topics}"
+            )
+
+    matlab_ok = int(help_summary.get("matlab_ok", 0))
+    if matlab_ok < matlab_required:
+        if full_suite:
+            failures.append(f"matlab help gate failed: minimum {HELP_MATLAB_MIN_OK}, got {matlab_ok}")
+        else:
+            failures.append(
+                f"matlab help gate failed for selected topics: minimum {matlab_required}, got {matlab_ok}"
+            )
+
+    scalar_overlap_pass_topics = int(help_summary.get("scalar_overlap_pass_topics", 0))
+    if scalar_overlap_pass_topics < scalar_required:
+        if full_suite:
+            failures.append(
+                f"scalar overlap gate failed: minimum {SCALAR_OVERLAP_PASS_MIN_TOPICS}, got {scalar_overlap_pass_topics}"
+            )
+        else:
+            failures.append(
+                f"scalar overlap gate failed for selected topics: minimum {scalar_required}, got {scalar_overlap_pass_topics}"
+            )
+
+    matlab_failed_topics = sorted([str(r.get("topic", "")) for r in help_rows if not bool(r.get("matlab_ok"))])
+    unexpected_failures = sorted(set(matlab_failed_topics) - KNOWN_MATLAB_HELP_FAILURES)
+    if unexpected_failures:
+        failures.append(f"unexpected matlab topic failures: {unexpected_failures}")
+
+    if not bool(parity_contract.get("pass", False)):
+        failures.append(f"parity contract failed: {parity_contract.get('failures', [])}")
+
+    known_missing = sorted(KNOWN_MATLAB_HELP_FAILURES - set(matlab_failed_topics))
+    return {
+        "pass": len(failures) == 0,
+        "failures": failures,
+        "matlab_failed_topics": matlab_failed_topics,
+        "known_allowlist": sorted(KNOWN_MATLAB_HELP_FAILURES),
+        "unexpected_failures": unexpected_failures,
+        "known_allowlist_not_currently_failing": known_missing,
+        "parity_contract_pass": bool(parity_contract.get("pass", False)),
+    }
+
+
+def _parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+    parser = argparse.ArgumentParser(description="Verify MATLAB/Python output similarity for nSTAT.")
+    parser.add_argument(
+        "--enforce-gate",
+        action="store_true",
+        help="Return non-zero exit code if regression gate fails.",
+    )
+    parser.add_argument(
+        "--topics",
+        nargs="+",
+        default=None,
+        help="Optional help-topic stems to run (space/comma separated). Default is all topics.",
+    )
+    parser.add_argument(
+        "--default-topic-timeout",
+        type=int,
+        default=DEFAULT_HELP_TOPIC_TIMEOUT_S,
+        help=f"Default MATLAB timeout per topic in seconds (default: {DEFAULT_HELP_TOPIC_TIMEOUT_S}).",
+    )
+    parser.add_argument(
+        "--topic-timeout",
+        action="append",
+        default=[],
+        help="Override per-topic MATLAB timeout using TOPIC=SECONDS (repeatable).",
+    )
+    parser.add_argument(
+        "--matlab-max-attempts",
+        type=int,
+        default=DEFAULT_MATLAB_MAX_ATTEMPTS,
+        help=(
+            "Maximum MATLAB attempts per help topic for retryable failures "
+            f"(default: {DEFAULT_MATLAB_MAX_ATTEMPTS})."
+        ),
+    )
+    parser.add_argument(
+        "--report-path",
+        default="reports/python_vs_matlab_similarity_report.json",
+        help="Output report path (absolute or repo-relative).",
+    )
+    return parser.parse_args(argv)
+
+
+def main(argv: list[str] | None = None) -> int:
+    args = _parse_args(argv)
+    report: dict[str, Any] = {}
+    if args.default_topic_timeout <= 0:
+        print("--default-topic-timeout must be positive", file=sys.stderr)
+        return 2
+    if args.matlab_max_attempts <= 0:
+        print("--matlab-max-attempts must be positive", file=sys.stderr)
+        return 2
+    try:
+        requested_topics = _parse_topics_arg(args.topics)
+        topics = _resolve_topics(requested_topics)
+        topic_timeout_overrides = _parse_topic_timeout_overrides(args.topic_timeout)
+    except ValueError as exc:
+        print(str(exc), file=sys.stderr)
+        return 2
+
+    selected_topic_stems = [Path(target).stem for _, target in topics]
+    full_suite = requested_topics is None
+    report["topic_selection"] = {
+        "full_suite": full_suite,
+        "requested_topics": sorted(requested_topics) if requested_topics else [],
+        "selected_topics": selected_topic_stems,
+        "total_topics": len(selected_topic_stems),
+        "default_timeout_s": args.default_topic_timeout,
+        "topic_timeout_overrides": topic_timeout_overrides,
+        "force_m_help_scripts": FORCE_M_HELP_SCRIPTS,
+        "matlab_max_attempts": args.matlab_max_attempts,
+        "runner_service_mode": _runner_service_mode(),
+        "matlab_cleanup_allowed": _matlab_cleanup_allowed(),
+        "matlab_force_topic_isolation": _force_topic_isolation_enabled(),
+        "matlab_hard_cleanup_on_failure": _hard_cleanup_on_failure_enabled(),
+    }
+
+    print("[class] running Python/MATLAB class checks", flush=True)
+    py_cls = _python_class_checks()
+    ml_cls = _matlab_class_checks()
+    if ml_cls.get("ok"):
+        class_cmp = _compare_class_results(py_cls, ml_cls["payload"])
+        report["class_similarity"] = {
+            "python": py_cls,
+            "matlab": ml_cls["payload"],
+            **class_cmp,
+        }
+    else:
+        report["class_similarity"] = {
+            "python": py_cls,
+            "matlab_error": ml_cls.get("error", "matlab_unavailable"),
+            "summary": {"passed": 0, "total": 0, "similarity_score": 0.0},
+            "comparisons": [],
+        }
+
+    report["helpfile_similarity"] = _help_similarity(
+        topics=topics,
+        default_timeout_s=args.default_topic_timeout,
+        topic_timeout_overrides=topic_timeout_overrides,
+        matlab_max_attempts=args.matlab_max_attempts,
+    )
+    contract_topics = None if full_suite else set(selected_topic_stems)
+    report["parity_contract"] = _evaluate_parity_contract(report["helpfile_similarity"]["rows"], topics_filter=contract_topics)
+    report["regression_gate"] = _evaluate_regression_gate(report)
+
+    out = Path(args.report_path)
+    if not out.is_absolute():
+        out = REPO_ROOT / out
+    out.parent.mkdir(parents=True, exist_ok=True)
+    out.write_text(json.dumps(report, indent=2), encoding="utf-8")
+    try:
+        out_print = str(out.relative_to(REPO_ROOT))
+    except ValueError:
+        out_print = str(out)
+
+    printable = {
+        "report": out_print,
+        "topic_selection": report["topic_selection"],
+        "class_similarity": report["class_similarity"]["summary"],
+        "helpfile_similarity": report["helpfile_similarity"]["summary"],
+        "parity_contract": report["parity_contract"],
+        "regression_gate": report["regression_gate"],
+    }
+    print(json.dumps(printable, indent=2))
+    if args.enforce_gate and not report["regression_gate"]["pass"]:
+        return 1
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())