-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNeurons.m
1705 lines (1393 loc) · 72.9 KB
/
Neurons.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 Neurons
properties
dimensionality = 1;
popSize = 1;
preferredStimulus = 0;
integrationTime = 0;
distribution = 'Gaussian';
a = 1.0;
alpha = 0.5;
R = [];
add = 0.0;
exponent = 1.0;
truncate = false;
end
methods
function obj = Neurons(varargin)
% NEURONS Neuron population class constructor.
% n = Neurons(dimensionality, preferredStimuli, integrationTime, variabilityScheme, variabilityOpts)
%
% dimensionality - stimulus dimensionality (only 1-D stimuli currently supported)
% preferred Stimuli - column vector of (N = popsize) characteristic stimuli
% integrationTime - spike counting time per trial
% variabilityScheme - the type of variablilty model
% variabiltyOpts - an array of arguments specific to the chosen variability model
%
switch nargin
case 5
% Standard constructor
if length(varargin{1}) == 1 && isnumeric(varargin{1})
obj.dimensionality = varargin{1};
else
error([inputname(1) ' is not a valid stimulus dimensionality'])
end
if isnumeric(varargin{2}) && size(varargin{2}, 1) == obj.dimensionality
obj.preferredStimulus = varargin{2}';
obj.popSize = size(varargin{2}, 2);
else
error([inputname(2) ' is not a valid preferred stimulus value or vector'])
end
%if length(varargin{3}) == 1 && isnumeric(varargin{3})
% obj.maxRate = double(varargin{3}(ones(obj.popSize, 1)));
%elseif length(varargin{3}) == obj.popSize && isvector(varargin{3}) && isnumeric(varargin{3})
% obj.maxRate = reshape(double(varargin{3}), obj.popSize, 1);
%else
% error([inputname(3) ' is not a valid maximum firing rate value or vector for population size ' obj.popSize])
%end
%if length(varargin{4}) == 1 && isnumeric(varargin{4})
% obj.backgroundRate = double(varargin{4}(ones(obj.popSize, 1)));
%elseif length(varargin{4}) == obj.popSize && isvector(varargin{4}) && isnumeric(varargin{4})
% obj.backgroundRate = reshape(double(varargin{4}), obj.popSize, 1);
%else
% error([inputname(4) ' is not a valid background firing rate value or vector for population size ' obj.popSize])
%end
if length(varargin{3}) == 1 && isnumeric(varargin{3})
obj.integrationTime = double(varargin{3});
else
error([inputname(3) ' is not a valid integration time'])
end
switch lower(varargin{4})
case 'poisson'
obj.distribution = 'Poisson';
obj.a = [];
obj.alpha = [];
obj.R = [];
obj.add = 0.0;
case 'gaussian-independent'
obj.distribution = 'Gaussian';
obj.a = varargin{5}(1); % need checks
obj.alpha = varargin{5}(2); % need checks
obj.R = eye(obj.popSize);
if length(varargin{5}) == 3
obj.add = varargin{5}(3); % need checks
else
obj.add = 0.0;
end
case 'gaussian-uniform'
obj.distribution = 'Gaussian';
obj.a = varargin{5}(1); % need checks
obj.alpha = varargin{5}(2); % need checks
obj.R = varargin{5}(3) * ~eye(obj.popSize) + eye(obj.popSize);
obj.add = 0.0;
case 'gaussian-exponential'
obj.distribution = 'Gaussian';
obj.a = varargin{5}(1); % need checks
obj.alpha = varargin{5}(2); % need checks
c = varargin{5}(3); % need checks
rho = varargin{5}(4); % need checks
prefDiff = repmat(obj.preferredStimulus, 1, obj.popSize);
prefDiff = prefDiff - prefDiff.';
obj.R = c .* exp(-abs(double(prefDiff)) ./ rho) .* ~eye(obj.popSize) + eye(obj.popSize);
obj.add = 0.0;
case 'gaussian-gaussian'
obj.distribution = 'Gaussian';
obj.a = varargin{5}(1); % need checks
obj.alpha = varargin{5}(2); % need checks
c = varargin{5}(3); % need checks
beta = 1.0 ./ degToRad(varargin{5}(4)).^2; % need checks
prefDiff = repmat(obj.preferredStimulus, 1, obj.popSize);
prefDiff = prefDiff - prefDiff.';
obj.R = c .* exp((cosd(double(prefDiff)) - 1) .* beta) .* ~eye(obj.popSize) + eye(obj.popSize);
obj.add = 0.0;
case 'cercal'
obj.distribution = 'Gaussian';
obj.add = varargin{5}(1);
obj.a = varargin{5}(2);
obj.alpha = 0.5;
obj.R = eye(obj.popSize);
obj.exponent = 2.0;
otherwise
error([varargin{4} ' is not a valid variability regime'])
end
otherwise
error('Wrong number of arguments')
end
end
function varargout = mi(obj, method, stim, tol, maxiter)
if ~isa(stim, 'StimulusEnsemble')
error([inputname(3) ' is not a SimulusEnsemble object'])
end
% obj.popSize x stim.n
rMean = obj.integrationTime .* meanR(obj, stim);
rMeanCell = squeeze(mat2cell(rMean, obj.popSize, ones(stim.n, 1)));
% Do distribution-specific one-time prep
switch obj.distribution
case 'Gaussian'
% Compute mean response dependent cov matrix stack Q [ (popSize x popSize) x stim.n ]
QCell1 = obj.Q(rMeanCell);
% Compute lower triangular Chol(Q) for sampling
cholQ = cellfun(@(q) chol(q)', QCell1, 'UniformOutput', false);
% Compute upper triangular Chol(Q^-1) for fast PDF computation
cholInvQCell = cellfun(@(q) chol(inv(q)), QCell1, 'UniformOutput', false);
clear QCell1
% Define function for multivariate gaussian sampling
% Multiply by Cholesky decomposition of cov matrix Q, and add in mean
if obj.truncate
fRand = @(m, c, z) max((m + c * z), 0.0); % truncate
else
fRand = @(m, c, z) m + c * z; % don't truncate
end
case 'Poisson'
% Nothing to do here
otherwise
error('Unsupported distribution: %s', obj.distribution)
end
iter = 0; % iteration counter
miEst = OnlineStats([1 1], maxiter);
adaptive = false;
cpS = cumsum(stim.pS);
cont = true;
while cont
iter = iter + 1;
% Display progress every 100 iterations
if ~mod(iter, 100)
fprintf('mi() iter: %d val: %.4g rel. error: %.4g\n', iter, miEst.runMean, miEst.runDelta)
end
switch method
case 'randMC'
% Sample s from stimulus distribution
[dummy, bin] = histc(rand(), cpS); %#ok<ASGLU>
bin = bin + 1;
%s = double(stim.ensemble);
%s = s(bin);
% Sample r from response distribution
switch obj.distribution
case 'Gaussian'
% Generate vector of independent normal random numbers (mu=0, sigma=1)
z = randn(obj.popSize, 1);
% Multiply by Cholesky decomposition of cov matrix Q, and add in mean
% !!! NOTE NEGATIVE RESPONSES MAY BE TRUNCATED TO ZERO depending on value of obj.truncate !!!
r = fRand(rMeanCell{bin}, cholQ{bin}, z);
case 'Poisson'
% Sample from Poisson distributions
r = poissrnd(rMeanCell{bin});
end
otherwise
error('Unsupported method: %s', method)
end
if ~adaptive
% log P(r|s)
% Replicate to form a stim.n x stim.n cell array of response vectors
rCell = repmat({r}, [stim.n 1]);
% Calculate response log probability densities
switch obj.distribution
case 'Gaussian'
lpRgS = cell2mat(cellsxfun(@mvnormpdfln, rCell, rMeanCell', cholInvQCell', {'inv'}));
case 'Poisson'
lpRgS = cell2mat(cellsxfun(@(x, l) sum(poisspdfln(x, l)), rCell, rMeanCell'));
end
% log P(r,s')
% Mutiply P(r|s) and P(s) to find joint distribution
pS = stim.pS;
lpRS = lpRgS + log(pS');
% log P(r)
% Calculate marginal by summing over s'
lpR = logsumexp(lpRS);
lpR_sparse = mean([logsumexp(lpRS(1:2:end) + log(2)), logsumexp(lpRS(2:2:end) + log(2))]);
% log p(r,s)
lpRS = lpRS(bin);
if abs((lpR - lpR_sparse) / lpR) > tol
% One-shot trapezoid rule is insufficiently accurate; switch to adaptive method
fprintf('Switching to adaptive integration algorithm.\n')
adaptive = true;
end
end
if adaptive
pR = [0 0 0];
trace = false; % debug flag
fAdInt = @quad; % Use the quad function
% log p(r,s)
lpRS = obj.flpSR(stim.ensemble(bin), r, stim, []);
% Log space offset for numerical stability
quadOffset = round(-lpRS);
% Absolute tolerance for integration
quadTol = tol;
switch bin
case 1 % Bottom bin - do first 2 bins, remainder
[pR(1), fcnt(1)] = fAdInt(@(s) obj.fpSR_offset(s, r, stim, quadOffset, []), stim.lowerLimit, stim.ensemble(bin+1), quadTol, trace);
[pR(2), fcnt(2)] = fAdInt(@(s) obj.fpSR_offset(s, r, stim, quadOffset, []), stim.ensemble(bin+1), stim.upperLimit, quadTol, trace);
case stim.n % Top bin - do first bin, last bin, remainder
[pR(1), fcnt(1)] = fAdInt(@(s) obj.fpSR_offset(s, r, stim, quadOffset, []), stim.lowerLimit, stim.ensemble(1), quadTol, trace);
[pR(2), fcnt(2)] = fAdInt(@(s) obj.fpSR_offset(s, r, stim, quadOffset, []), stim.ensemble(1), stim.ensemble(end-1), quadTol, trace);
[pR(3), fcnt(3)] = fAdInt(@(s) obj.fpSR_offset(s, r, stim, quadOffset, []), stim.ensemble(end-1), stim.upperLimit, quadTol, trace);
otherwise % Other bins - do one bin either side, remainder above, remainder below
[pR(1), fcnt(1)] = fAdInt(@(s) obj.fpSR_offset(s, r, stim, quadOffset, []), stim.lowerLimit, stim.ensemble(bin-1), quadTol, trace);
[pR(2), fcnt(2)] = fAdInt(@(s) obj.fpSR_offset(s, r, stim, quadOffset, []), stim.ensemble(bin-1), stim.ensemble(bin+1), quadTol, trace);
[pR(3), fcnt(3)] = fAdInt(@(s) obj.fpSR_offset(s, r, stim, quadOffset, []), stim.ensemble(bin+1), stim.upperLimit, quadTol, trace);
end
lpR = log(sum(pR)) - quadOffset;
end
% log P(s)
lpS = log(pS(bin));
% sample MI in bits (convert from log_e to log_2)
miEst.appendSample((lpRS - (lpR + lpS)) ./ log(2));
if isnan(miEst.samples(iter))
foo
end
% Test halting criteria (SEM, max iterations limit)
cont = miEst.runDelta > tol & iter < maxiter;
% Impose minimum iteration limit so we get a sensible estimate of SEM
cont = cont | iter < 1000;
end
% Trim unused samples from buffer
miEst.trim;
% Recompute MI, SEM cleanly
i = miEst.mean;
iSem = miEst.sem;
% Report final values
fprintf('mi() halting iter: %d val: %.4g SEM: %.4g\n', iter, i, iSem)
switch nargout
case 1
varargout = {i};
case 2
varargout = {i iSem};
case 3
varargout = {i iSem miEst};
otherwise
error('Unsupported number of return values.')
end
end
function varargout = ssiss(obj, n, method, stim, stimOrds, tol, maxiter, timeout)
fAdInt = @quad; % Use the quad function
trace = false; % debug flag
try
time = toc; %#ok<NASGU>
catch
tic;
end
try
% Test sanity of neuron indices
obj.preferredStimulus(n);
catch err %#ok<NASGU>
error([inputname(2) ' is not a valid neuron index'])
end
try
% Test sanity of stimulus ordinate indices
stim.ensemble(stimOrds);
catch err %#ok<NASGU>
error([inputname(5) ' is not a valid stimulus ordinate index'])
end
if ~any(strcmp(method, {'quadrature' 'randMC' 'quasirandMC'}))
error([method ' is not a valid SSI calculation method'])
end
if ~isa(stim, 'StimulusEnsemble')
error([inputname(4) ' is not a SimulusEnsemble object'])
end
% Create mask for calculating specific stimulus ordinates only
if ~isempty(stimOrds)
sMask = false(stim.n, 1);
sMask(stimOrds) = true;
sMaskN = sum(sMask + 0);
stimOrds = find(sMask);
else
sMask = true(stim.n, 1);
sMaskN = stim.n;
stimOrds = 1:stim.n;
end
% Indexes for quickly pulling out p(r|s'=s)
distPeaks = logical(eye(stim.n));
distPeaks = distPeaks(:,sMask);
% Get mean responses for each stimulus ordinate
% obj.popSize x stim.n
rMean = obj.integrationTime .* obj.meanR(stim);
rMeanCell = squeeze(mat2cell(rMean, obj.popSize, ones(stim.n, 1)));
% Setup for computing marginals
if ~isempty(n)
% Create logical vector (mask) identifying neurons that are *not* part of the marginal SSI
margMask = true(obj.popSize, 1);
margMask(n) = false;
% Get mean responses for each stimulus ordinate
rMeanMargCell = cellfun(@(r) r(margMask), rMeanCell, 'UniformOutput', false);
end
% Do distribution-specific initialisation
switch obj.distribution
case 'Gaussian'
% Compute mean response dependent cov matrix stack Q [ (popSize x popSize) x stim.n ]
QCell1 = obj.Q(rMeanCell);
% Compute lower triangular Chol(Q) for sampling
cholQ = cellfun(@(q) chol(q)', QCell1, 'UniformOutput', false);
% Compute upper triangular Chol(Q^-1) for fast PDF computation
cholInvQCell = cellfun(@(q) chol(inv(q)), QCell1, 'UniformOutput', false);
if ~isempty(n)
% Compute mean response dependent cov matrix stack Q
QCellMarg1 = cellfun(@(q) q(margMask, margMask), QCell1, 'UniformOutput', false);
% Invert Q matrices and compute Cholesky decomps
cholInvQCellMarg = cellfun(@(q) chol(inv(q)), QCellMarg1, 'UniformOutput', false);
clear QCellMarg1
end
clear QCell1
% Define function for multivariate gaussian sampling
% Multiply by Cholesky decomposition of cov matrix Q, and add in mean
if obj.truncate
fRand = @(m, c, z) max((m + c * z), 0.0); % truncate
else
fRand = @(m, c, z) m + c * z; % don't truncate
end
case 'Poisson'
% Nothing to be done here
otherwise
error('Unsupported distribution: %s', obj.distribution)
end
% Initialise main loop, preallocate MC sample arrays
iter = 0;
cont = true;
adaptive = false;
delta = 0;
lastUpdate = toc;
Issi = OnlineStats([1 sMaskN], maxiter);
Isur = OnlineStats([1 sMaskN], maxiter);
IssiMarg = OnlineStats([1 sMaskN], maxiter);
IsurMarg = OnlineStats([1 sMaskN], maxiter);
% Main MC sampling loop
while cont
iter = iter + 1;
time = toc;
if ~mod(iter, 10) && (time - lastUpdate) > 10
fprintf('SSISS iter: %d of %d, rel. error: %.4g\n', iter, maxiter, delta)
lastUpdate = toc;
end
switch method
case 'randMC'
% Sample r from response distribution
switch obj.distribution
case 'Gaussian'
% Generate vector of independent normal random numbers (mu=0, sigma=1)
zCell = mat2cell(randn(obj.popSize, sMaskN), obj.popSize, ones(sMaskN, 1));
% Multiply by Cholesky decomposition of cov matrix Q, and add in mean
% !!! NOTE NEGATIVE RESPONSES MAY BE TRUNCATED TO ZERO, SEE ABOVE !!!
rCell = cellfun(fRand, rMeanCell(sMask), cholQ(sMask), zCell, 'UniformOutput', false); % stim.n cell array of obj.popSize vectors
case 'Poisson'
% Sample from Poisson distributions
rCell = cellfun(@poissrnd, rMeanCell(sMask), 'UniformOutput', false);
end
otherwise
error('Unsupported method: %s', method)
end
if ~adaptive
% log P(r|s')
% Calculate response probability densities
switch obj.distribution
case 'Gaussian'
lpRgS = cell2mat(cellsxfun(@mvnormpdfln, rCell, rMeanCell', cholInvQCell', {'inv'}));
case 'Poisson'
lpRgS = cell2mat(cellsxfun(@(x, l) sum(poisspdfln(x, l)), rCell, rMeanCell'));
end
% log P(r,s')
% Mutiply P(r|s) and P(s) to find joint distribution
lpRS = bsxfun(@plus, lpRgS, log(stim.pS')); % stim'.n x stim
% log P(r)
% Calculate marginal by integrating over s'
offsets = max(lpRS, [], 1);
lpRS_offset = bsxfun(@minus, lpRS, offsets);
lpR = log(stim.integrate(exp(lpRS_offset), 1));
lpR = lpR + offsets;
if stim.continuous
% If the stimulus variable is continuous
% Check integration accuracy
lpR_sparse1 = log(stim.integrate(exp(lpRS_offset(1:2:end,:)), 1));
lpR_sparse2 = log(stim.integrate(exp(lpRS_offset(2:2:end,:)), 1));
lpR_sparse = mean([lpR_sparse1 ; lpR_sparse2]) + log(2) + offsets;
if any((lpR_sparse - lpR) ./ lpR > tol * 1e-2)
% One-shot trapezoid rule is insufficiently accurate; switch to adaptive method
fprintf('Switching to adaptive integration algorithm.\n')
adaptive = true;
end
end
end
if adaptive
% log p(r,s')
lpRS = cell2mat(cellsxfun(@(a,b) obj.flpSR(a, b, stim, []), num2cell(stim.ensemble)', rCell));
% Log space offset for numerical stability
quadOffset = -lpRS(distPeaks);
% Absolute tolerance for integration
quadTol = tol * 1e-2;
for si = 1 : sMaskN
pR = [0 0 0];
bin = stimOrds(si);
r = rCell{si};
switch bin
case 1 % Bottom bin - do first 2 bins, remainder
[pR(1), fcnt(1)] = fAdInt(@(s) obj.fpSR_offset(s, r, stim, quadOffset(si), []), stim.lowerLimit, stim.ensemble(bin+1), quadTol, trace);
[pR(2), fcnt(2)] = fAdInt(@(s) obj.fpSR_offset(s, r, stim, quadOffset(si), []), stim.ensemble(bin+1), stim.upperLimit, quadTol, trace);
case stim.n % Top bin - do first bin, last bin, remainder
[pR(1), fcnt(1)] = fAdInt(@(s) obj.fpSR_offset(s, r, stim, quadOffset(si), []), stim.lowerLimit, stim.ensemble(1), quadTol, trace);
[pR(2), fcnt(2)] = fAdInt(@(s) obj.fpSR_offset(s, r, stim, quadOffset(si), []), stim.ensemble(1), stim.ensemble(end-1), quadTol, trace);
[pR(3), fcnt(3)] = fAdInt(@(s) obj.fpSR_offset(s, r, stim, quadOffset(si), []), stim.ensemble(end-1), stim.upperLimit, quadTol, trace);
otherwise % Other bins - do one bin either side, remainder above, remainder below
[pR(1), fcnt(1)] = fAdInt(@(s) obj.fpSR_offset(s, r, stim, quadOffset(si), []), stim.lowerLimit, stim.ensemble(bin-1), quadTol, trace);
[pR(2), fcnt(2)] = fAdInt(@(s) obj.fpSR_offset(s, r, stim, quadOffset(si), []), stim.ensemble(bin-1), stim.ensemble(bin+1), quadTol, trace);
[pR(3), fcnt(3)] = fAdInt(@(s) obj.fpSR_offset(s, r, stim, quadOffset(si), []), stim.ensemble(bin+1), stim.upperLimit, quadTol, trace);
end
lpR(1,si) = log(sum(pR)) - quadOffset(si);
end
end
% log P(s'|r)
% Divide joint by marginal P(r)
lpSgR = bsxfun(@minus, lpRS, lpR);
% H(s'|r), in bits, converting from log_e to log_2
hSgR = -stim.integrate(exp(lpSgR) .* (lpSgR ./ log(2)), 1);
if stim.continuous
sparse1 = -stim.integrate(exp(lpSgR(1:2:end,:)) .* (lpSgR(1:2:end,:) ./ log(2)), 1);
sparse2 = -stim.integrate(exp(lpSgR(2:2:end,:)) .* (lpSgR(2:2:end,:) ./ log(2)), 1);
propErr = (sparse1 + sparse2) ./ hSgR - 1;
if any(propErr > 0.1)
warning('popcode:badintegration', 'Possible insufficient sampling density for numerical integration (H(S''|r)).')
end
end
% Sample specific information Isp(r)
% Specific information; reduction in stimulus entropy due to observation of r
fSSIsamp = stim.entropy - hSgR;
Issi.appendSample(fSSIsamp);
% Sample specific surprise
% log_2( P(r|s) / P(r) )
% Accumulate samples
Isur.appendSample((diag(lpRgS(stimOrds,:))' - lpR) ./ log(2));
if exist('margMask', 'var')
% If we are calculating a marginal SSI, compute the SSI for remaining neurons
% Mask out neurons of interest in response vectors
rCellMarg = cellfun(@(r) r(margMask), rCell, 'UniformOutput', false);
if ~adaptive
% log P(r|s')
% Calculate response probability densities
switch obj.distribution
case 'Gaussian'
lpRgS = cell2mat(cellsxfun(@mvnormpdfln, rCellMarg, rMeanMargCell', cholInvQCellMarg', {'inv'}));
case 'Poisson'
lpRgS = cell2mat(cellsxfun(@(x, l) sum(poisspdfln(x, l)), rCellMarg, rMeanMargCell'));
end
% log P(r,s')
% Mutiply P(r|s) and P(s) to find joint distribution
lpRS = bsxfun(@plus, lpRgS, log(stim.pS')); % stim'.n x stim
% log P(r)
% Calculate marginal by integrating over s'
offsets = max(lpRS, [], 1);
lpRS_offset = bsxfun(@minus, lpRS, offsets);
lpR = log(stim.integrate(exp(lpRS_offset), 1));
lpR = lpR + offsets;
if stim.continuous
% If the stimulus variable is continuous
% Check integration accuracy
lpR_sparse1 = log(stim.integrate(exp(lpRS_offset(1:2:end,:)), 1));
lpR_sparse2 = log(stim.integrate(exp(lpRS_offset(2:2:end,:)), 1));
lpR_sparse = mean([lpR_sparse1 ; lpR_sparse2]) + log(2) + offsets;
if any((lpR_sparse - lpR) ./ lpR > tol * 1e-2)
% One-shot trapezoid rule is insufficiently accurate; switch to adaptive method
fprintf('Switching to adaptive integration algorithm.\n')
adaptive = true;
end
end
end
if adaptive
% log p(r,s')
lpRS = cell2mat(cellsxfun(@(a,b) obj.flpSR(a, b, stim, margMask), num2cell(stim.ensemble)', rCellMarg));
% Log space offset for numerical stability
quadOffset = -lpRS(distPeaks);
% Absolute tolerance for integration
quadTol = tol * 1e-2;
for si = 1 : sMaskN
pR = [0 0 0];
bin = stimOrds(si);
r = rCellMarg{si};
switch bin
case 1 % Bottom bin - do first 2 bins, remainder
[pR(1), fcnt(1)] = fAdInt(@(s) obj.fpSR_offset(s, r, stim, quadOffset(si), margMask), stim.lowerLimit, stim.ensemble(bin+1), quadTol, trace);
[pR(2), fcnt(2)] = fAdInt(@(s) obj.fpSR_offset(s, r, stim, quadOffset(si), margMask), stim.ensemble(bin+1), stim.upperLimit, quadTol, trace);
case stim.n % Top bin - do first bin, last bin, remainder
[pR(1), fcnt(1)] = fAdInt(@(s) obj.fpSR_offset(s, r, stim, quadOffset(si), margMask), stim.lowerLimit, stim.ensemble(1), quadTol, trace);
[pR(2), fcnt(2)] = fAdInt(@(s) obj.fpSR_offset(s, r, stim, quadOffset(si), margMask), stim.ensemble(1), stim.ensemble(end-1), quadTol, trace);
[pR(3), fcnt(3)] = fAdInt(@(s) obj.fpSR_offset(s, r, stim, quadOffset(si), margMask), stim.ensemble(end-1), stim.upperLimit, quadTol, trace);
otherwise % Other bins - do one bin either side, remainder above, remainder below
[pR(1), fcnt(1)] = fAdInt(@(s) obj.fpSR_offset(s, r, stim, quadOffset(si), margMask), stim.lowerLimit, stim.ensemble(bin-1), quadTol, trace);
[pR(2), fcnt(2)] = fAdInt(@(s) obj.fpSR_offset(s, r, stim, quadOffset(si), margMask), stim.ensemble(bin-1), stim.ensemble(bin+1), quadTol, trace);
[pR(3), fcnt(3)] = fAdInt(@(s) obj.fpSR_offset(s, r, stim, quadOffset(si), margMask), stim.ensemble(bin+1), stim.upperLimit, quadTol, trace);
end
lpR(1,si) = log(sum(pR)) - quadOffset(si);
end
end
% log P(s|r)
% Divide joint by marginal P(r)
lpSgR = bsxfun(@minus, lpRS, lpR);
% H(s'|r), in bits, converting from log_e to log_2
hSgR = -stim.integrate(exp(lpSgR) .* (lpSgR ./ log(2)), 1);
if stim.continuous
sparse1 = -stim.integrate(exp(lpSgR(1:2:end,:)) .* (lpSgR(1:2:end,:) ./ log(2)), 1);
sparse2 = -stim.integrate(exp(lpSgR(2:2:end,:)) .* (lpSgR(2:2:end,:) ./ log(2)), 1);
propErr = (sparse1 + sparse2) ./ hSgR - 1;
if any(propErr > 0.1)
warning('popcode:badintegration', 'Possible insufficient sampling density for numerical integration (H(S''|r)).')
end
end
% Isp(r)
% Specific information; reduction in stimulus entropy due to observation of r
% Compute MC sample
rSSIsamp = stim.entropy - hSgR;
IssiMarg.appendSample(rSSIsamp);
% Specific surprise
% log_2( P(r|s) / P(r) )
% Compute MC sample
IsurMarg.appendSample((diag(lpRgS(stimOrds,:))' - lpR) ./ log(2));
end
% Test halting criteria (SEM, max iterations limit, timeout)
if exist('margMask', 'var')
delta = mean(max([Issi.runDelta ; IssiMarg.runDelta], [], 1));
else
delta = mean(Issi.runDelta);
end
cont = delta > tol & iter < maxiter;
% If the wall clock is running, check the elapsed time
try
cont = cont && toc < timeout;
catch
% do nothing
end
% Impose minimum iteration limit so we get a valid estimate of SEM
cont = cont | iter < 100;
end
try
fprintf('SSISS iter: %d elapsed time: %.4f seconds\n', iter, toc)
catch
fprintf('SSISS iter: %d\n', iter)
end
% Trim sample arrays
Issi.trim;
Isur.trim;
IssiMarg.trim;
IsurMarg.trim;
% Recalculate means cleanly
fullSSI = Issi.mean;
fullIsur = Isur.mean;
if exist('margMask', 'var')
remSSI = IssiMarg.mean;
SSI = fullSSI - remSSI;
remIsur = IsurMarg.mean;
else
remSSI = fullSSI;
SSI = fullSSI;
remIsur = fullIsur;
end
switch nargout
case 1
varargout = {SSI};
case 2
varargout = {SSI iter};
case 3
varargout = {fullSSI remSSI iter};
case 4
varargout = {fullSSI remSSI Issi IssiMarg};
case 5
varargout = {fullSSI remSSI fullIsur remIsur iter};
case 9
varargout = {fullSSI remSSI fullIsur remIsur iter Issi Isur IssiMarg IsurMarg};
otherwise
error('Unsupported number of outputs')
end
end
function varargout = fisher(obj, method, stim, tol, maxiter)
% Wrapper function for calculating Fisher information
switch method
case 'analytic'
switch obj.distribution
case 'Gaussian'
[J_mean, J_cov] = obj.fisher_analytic_gauss(stim);
switch nargout
case 0
varargout = {J_mean + J_cov};
case 1
varargout = {J_mean + J_cov};
case 2
varargout = {J_mean J_cov};
otherwise
error('Wrong number of outputs')
end
case 'Poisson'
J = obj.fisher_analytic_poiss(stim);
if nargout == 1
varargout = {J};
else
error('Wrong number of outputs')
end
otherwise
error('Unsupported distribution: %s', obj.distribution)
end
case 'randMC'
[J, samples] = obj.fisher_mc(method, stim, tol, maxiter);
switch nargout
case 1
varargout = {J};
case 2
varargout = {J samples};
otherwise
error('Wrong number of outputs')
end
otherwise
error('"%s" is not a valid FI calculation method', method)
end
end
function [fullFisher, remainderFisher] = margFisher(obj, nMarg, method, stim, tol)
% Function for calculating fisher of population with and
% without neuron(s) of interest
if ~isa(stim, 'StimulusEnsemble')
error([inputname(4) ' is not a SimulusEnsemble object'])
end
% Compute FI of full population
fullFisher = fisher(obj, method, stim, tol);
% Create population of remaining neurons
remainingNeurons = obj.remove(nMarg);
% FI of remaining neurons
remainderFisher = fisher(remainingNeurons, method, stim, tol);
end
function ifish = Ifisher(obj, stim)
% Function for computing I_Fisher, see:
%
% Brunel N, Nadal J (1998)
% Mutual information, Fisher information, and population coding.
% Neural Comput 10:1731?1757.
%if true
% Fisher information
fish = obj.fisher('analytic', stim, 0);
% Ignore zero Fisher information values
zeroJ = find(fish == 0);
pS = stim.pS;
if ~isempty(zeroJ)
fish(zeroJ) = [];
pS(zeroJ) = [];
pS = pS ./ sum(pS);
end
ifish = stim.entropy - 0.5 .* sum(pS .* (1.0 + log2(pi) + log2(exp(1)) - log2(fish)));
%else
% ifish = stim.entropy - 0.5 .* quad(@(s) stim.pSint(s) .* (1.0 + log2(pi) + log2(exp(1)) - log2(obj.fisher('analytic', s, 0))), stim.ensemble(1) - diff(stim.ensemble(1:2)), stim.ensemble(end));
%end
end
function varargout = mIfisher(obj, nMarg, stim)
% Function for computing the marginal I_Fisher
% Get whole-population I_Fisher
ifishFull = obj.Ifisher(stim);
% Create population of remaining neurons
remainingNeurons = obj.remove(nMarg);
% Compute remainder I_Fisher
ifishRem = remainingNeurons.Ifisher(stim);
switch nargout
case 1
varargout = {ifishFull - ifishRem};
case 2
varargout = {ifishFull ifishRem};
otherwise
error('Wrong number of outputs')
end
end
function ssif = SSIfisher(obj, n, fisherMethod, stim, tol)
% Function for computing SSI_Fisher, see:
%
% Yarrow S, Challis E, Series P (2012)
% Fisher and Shannon information in finite neural populations
% Neural Computation 24:1740-80
% S stimulus
sMat = repmat(stim.ensemble, [stim.n 1]);
% sHat stimulus estimate
sHatMat = repmat(stim.ensemble', [1 stim.n]);
% log p(S)
psMat = repmat(stim.pS, [stim.n 1]);
if stim.circular
% circular difference
dS = mod(sHatMat - sMat, stim.circular);
i = find(dS > (0.5 * stim.circular));
dS(i) = dS(i) - stim.circular;
i = find(dS < (-0.5 * stim.circular));
dS(i) = dS(i) + stim.circular;
else
% linear difference
dS = sHatMat - sMat;
end
if ~isempty(n)
[fullFI, remFI] = obj.margFisher(n, fisherMethod, stim, tol);
% Compute SSIfisher excluding cells of interest
% sigma(s)
% Compute SD of optimal estimator as a function of the stimulus
sigma = remFI .^ -0.5;
sigmaMat = repmat(sigma, [stim.n 1]);
% log p(sHat|S)
lpsHat_s = cellfun(@mvnormpdfln, num2cell(dS), num2cell(zeros([stim.n stim.n])), num2cell(sigmaMat));
% log p(S)
lpS = log(psMat);
% log p(sHat,S)
lpsHats = lpsHat_s + lpS;
% log p(sHat)
lpsHat = logsumexp(lpsHats, 2);
% log p(S|sHat)
lps_sHat = lpsHats - repmat(lpsHat, [1 stim.n]);
% H(s|sHat) as a function of sHat
Hs_sHat = -sum(exp(lps_sHat) .* lps_sHat ./ log(2), 2);
% Isp(sHat) specific information
isp = stim.entropy - Hs_sHat;
% SSIfisher
ssifRem = sum(exp(lpsHat_s + repmat(log(isp), [1 stim.n])), 1);
else
fullFI = obj.fisher(fisherMethod, stim, tol);
end
% Compute SSIfisher for full population
% sigma(s)
% Compute SD of optimal estimator as a function of the stimulus
sigma = fullFI .^ -0.5;
sigmaMat = repmat(sigma, [stim.n 1]);
% log p(sHat|S)
lpsHat_s = cellfun(@mvnormpdfln, num2cell(dS), repmat({0}, [stim.n stim.n]), num2cell(sigmaMat));
% log p(S)
lpS = log(psMat);
% log p(sHat,S)
lpsHats = lpsHat_s + lpS;
% log p(sHat)
lpsHat = logsumexp(lpsHats, 2);
% log p(S|sHat)
lps_sHat = lpsHats - repmat(lpsHat, [1 stim.n]);
% H(s|sHat) as a function of sHat
Hs_sHat = -sum(exp(lps_sHat) .* lps_sHat ./ log(2), 2);
% Isp(sHat) specific information
isp = stim.entropy - Hs_sHat;
% SSIfisher
ssifFull = sum(exp(lpsHat_s + repmat(log(isp), [1 stim.n])), 1);
if ~isempty(n)
ssif = ssifFull - ssifRem;
else
ssif = ssifFull;
end
end
function [pZgS, hZgS, SSI, SI] = pZgS(obj, stim, maxSpikes)
assert(strcmp(obj.distribution, 'Poisson'), 'pZgS() only supports Poisson distribution')
assert(~stim.continuous, 'pZgS() only supports discrete stimuli')
% Dims: S, Z, R
% Set up vector of possible response spike counts
rr = permute(0:maxSpikes, [1 3 2]);
% Get the expected response as a function of S
muRgS = obj.meanR(stim) * obj.integrationTime;
% Compute log[ P(R|S) ]
lpRgS = bsxfun(@poisspdfln, rr, muRgS);
% log[P(R|Z)] is the same but transposed
lpRgZ = permute(lpRgS, [2 1 3]);
% Prior: log[ P(Z) ]
lpZ = log(stim.pS)';
% Joint: log[ P(R,Z) ]
lpRZ = bsxfun(@plus, lpRgZ, lpZ);
% Marginal on R: log[P(R)]
lpR = logsumexp(lpRZ, 1);
% Conditional: log[ P(Z|R) ]
lpZgR = bsxfun(@minus, lpRZ, lpR);
% 3-D conditional: log[ P(Z|R|S) ]
lpZgRgS = bsxfun(@plus, lpZgR, lpRgS);
% Marginalise out R to get log[ P(Z|S) ]
lpZgS = logsumexp(lpZgRgS, 3);
% Conditional entropy: H(Z|S=s)
hZgS = -sum(exp(lpZgS) .* lpZgS, 1) ./ log(2);
pZgS = exp(lpZgS);
% (Response) Specific information
SI = sum(bsxfun(@minus, lpZgR .* exp(lpZgR), lpZ .* exp(lpZ)), 1) ./ log(2);
% Stimlus specific information
SSI = sum(bsxfun(@times, SI, exp(lpRgS)), 3);
end
function varargout = pZgS_MC(obj, n, stim, stimOrds, tol, maxiter, timeout)
fAdInt = @quad; % Use the quad function
trace = false; % debug flag
assert(isa(stim, 'StimulusEnsemble'), '%s is not a SimulusEnsemble object', inputname(4))
try
% Test sanity of neuron indices
obj.preferredStimulus(n);
catch err %#ok<NASGU>
error([inputname(2) ' is not a valid neuron index'])
end
try
% Test sanity of stimulus ordinate indices
stim.ensemble(stimOrds);
catch err %#ok<NASGU>
error([inputname(5) ' is not a valid stimulus ordinate index'])
end
% Create mask for calculating specific stimulus ordinates only
if ~isempty(stimOrds)
sMask = false(stim.n, 1);
sMask(stimOrds) = true;
sMaskN = sum(sMask + 0);
stimOrds = find(sMask);
else
sMask = true(stim.n, 1);
sMaskN = stim.n;
stimOrds = 1:stim.n;
end