-
Notifications
You must be signed in to change notification settings - Fork 16
/
Analysis.m
1778 lines (1557 loc) · 80 KB
/
Analysis.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
classdef Analysis
% ANALYSIS Collection of functions (static methods) used for GLM analysis
% of point process data.
% <a href="matlab: methods('Analysis')">methods</a>
% <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>
%%
% 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 ([email protected]).
% 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)));
parfor 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)));
parfor 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 ([email protected]).
% 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 ([email protected]).
% 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<alphaVal/2,1,'last'));
% CIs(k,2) = 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)<length(sumSpikes.data))
sumSpikesOverWindow = sumSpikes.data(2:end);
end
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(1:end),[zeros(1,size(Mdata,2));Mdata],'M(t_k)',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