-
Notifications
You must be signed in to change notification settings - Fork 2
/
SetOfHyps.m
1355 lines (1279 loc) · 62.1 KB
/
SetOfHyps.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 SetOfHyps < Hypersphere
% Inherited from Hypersphere:
% properties (SetObservable, GetObservable, AbortSet)
% centers % [n x d] matrix: n centers of d-dimensional hyperspheres
% radii % [1 x n] vector: radii of each of n hyperspheres
% categories(1,1) % a Categories object (see help Categories)
% end
properties (SetAccess = protected)
volume % volume of hypersphere(s) (auto-computed)
dists % distances between centers of hyperspheres (auto-computed)
margins % margins between hyperspheres along center-connection lines (auto-computed)
ci = []; % confidence intervals, with raw bootstrap data
error = NaN; % [n-choose-2 x 1] vector of errors for each summary stat
sig = []; % significance tests results
sigp = []; % significance tests p-values
sigdiff = []; % significant differences tests results
sigdiffp = []; % significant differences tests p-values
msflips = []; % margin sign flips
end
properties (Dependent, SetAccess = protected)
overlap % overlaps (negative margins) between hyperspheres along center-connection lines
end
properties (GetAccess = 'private', SetAccess = 'private')
boxPos = [0.65 0.65];
boxSize = 0.3;
nSigLevs = 3; % 3 means [0.95 0.99 0.999] levels
end
methods
function obj = SetOfHyps(centers,radii,varargin)
% Constructor for SetOfHyps object for hypersphere2sphere, Hypersphere
% e.g.:
% hypset = SetOfHyps(centers,radii,categories) % (1)
% hypset = SetOfHyps('estimate',points,categories,extraargs) % (2)
% hypset = SetOfHyps(hyp,ci) % (3)
% hypset = SetOfHyps(hypstruct) % (4)
% hypset = SetOfHyps({hyps},radii,extraargs) % (5)
% hypset = SetOfHyps(centers,radii,categories,'cvdists',cvdists) % (6)
% hypset = SetOfHyps(hypset,hypsetTarget) % (7)
%
% Constructor input options:
% (1-2) Same as Hypersphere input options (1-2), but yields a SetOfHyps.
% (3) Similar to Hypersphere input option (3), except this SetOfHyps
% constructor: (a) converts a Hypersphere object to a SetOfHyps
% object (instead of vice-versa), and (b) can take in an optional
% ci argument, which is a structure containing the confidence
% intervals and bootstrapped Hypersphere/SetOfHyps objects (computed
% using SetOfHyps.significance), and saves it in the SetOfHyps object.
% (4-6) Same as Hypersphere input options (4-6), but yields a SetOfHyps.
% (7) Regardless of the preceding inputs, if a SetOfHyps object is
% included as an additional (i.e., not the first) input argument, it
% is treated as the "target" SetOfHyps from which errors of the
% existing/first input/newly constructed SetOfHyps are computed.
% This is equivalent to calling hypset.stressUpdate(hypsetTarget).
%
% N.B.: unlike Hypersphere, volume, dists, margins, and overlap are all
% automatically computed once and stored as properties. These are
% computed upon SetOfHyps object construction and re-computed if a
% change was made to either centers or radii. The methods for
% computing these quantities are inherited from Hypersphere.
%
% Inherited Properties (from Hypersphere):
% centers - [n x d] matrix: n centers of d-dimensional hyperspheres
% radii - [1 x n] vector: radii of each of n hyperspheres
% categories - a Categories object (see help Categories)
% distsCV - (protected) false or vector of squared cross-validated distances
% Properties:
% volume - volume of hypersphere(s) (auto-computed)
% dists - distances between centers of hyperspheres (auto-computed)
% margins - margins between hyperspheres along center-connection
% lines (auto-computed)
% ci - confidence intervals, with raw bootstrap data
% error - [n-choose-2 x 1] vector of errors for each summary stat
% sig - significance tests results
% sigdiff - significant differences tests results
% msflips - margin sign flips
% overlap - overlaps (negative margins) between hyperspheres along
% center-connection lines (auto-computed)
%
% Inherited Methods (from Hypersphere):
% SetOfHyps.resetRandStream
% SetOfHyps.getRandStream
% SetOfHyps.isempty
% SetOfHyps.select
% SetOfHyps.snip
% SetOfHyps.concat
% SetOfHyps.unconcat
% SetOfHyps.meanAndMerge
% SetOfHyps.sample
% SetOfHyps.plotSamples
% SetOfHyps.show
% SetOfHyps.camera
% SetOfHyps.movie
% SetOfHyps.estimate (Static method)
% Methods:
% SetOfHyps.significance
% SetOfHyps.dropBootstraps
% SetOfHyps.importStats
% SetOfHyps.h2s
% SetOfHyps.plotOverlapErrors
% SetOfHyps.plotDynamics
% SetOfHyps.showSig
% SetOfHyps.showValues
% SetOfHyps.showSigLegend
% SetOfHyps.toJSON
% SetOfHyps.stressUpdate
% SetOfHyps.stress (Static method: h2s objective function and gradients)
%
% 2018-06-07 AZ Created
%
% See also HYPERSPHERE, CATEGORIES, ESTIMATEHYPERSPHERE
if nargin==0; return; end
if isa(centers,'SetOfHyps'), obj = centers; % input option (7)
elseif isa(centers,'Hypersphere') % input option (3)
if numel(centers) == 1
for fn = fieldnames(centers)'
obj.(fn{1}) = centers.(fn{1});
end
if exist('radii','var') && isstruct(radii)
obj.ci = radii; % assumes merged Hypersphere object
end
else
sameSpace = unique([centers.belongsToCommonSpace]);
if numel(sameSpace)==1 && sameSpace(1) > 0
obj = arrayfun(@SetOfHyps,centers);
return
else
obj = SetOfHyps(centers.meanAndMerge,varargin{:});
end
end
else % input options (1-2,4-6)
% Use Hypersphere constructor to handle other possible inputs
if ~exist('radii','var'), radii = []; end
obj = Hypersphere(centers,radii,varargin{:});
% Deal with multiple Hyperspheres, convert to SetOfHyps
MCMC = any(strcmpi(varargin,'mcmc'));
if obj(end).categories.ispermuted || MCMC
obj = obj.meanAndMerge(MCMC);
else
% assume multiple objects are not bootstraps, but different
% frames etc, leave them as multiple objects
obj = arrayfun(@(x) SetOfHyps(x,[],varargin{:}),obj);
return
end
end
for v = 1:numel(varargin) % input option (7)
if isa(varargin{v},'SetOfHyps'), hypsTarget = varargin{v};
elseif isa(varargin{v},'Categories'), obj.categories = varargin{v};
end
end
if ~isa(obj.categories,'Categories')
obj.categories = Categories(numel(obj.radii));
end
% Update dependent properties, but save them to reduce on-line compute
obj.volume = obj.volume();
obj = setPostCenters(obj,[],[],true);
% Set up listeners to update dependent properties only on centers/radii set
addlistener(obj,'centers','PostSet',@obj.setPostCenters);
addlistener(obj,'radii' ,'PostSet',@obj.setPostRadii);
% Update error if another SetOfHyps given
if exist('hypsTarget','var'), obj = obj.stressUpdate(hypsTarget); end
end
%% SET FUNCTIONS TO COMPUTE AND STORE VOLUME, DISTS, MARGINS, OVERLAPS
function self = set.volume(self,~) % Compute volume of a single hypersphere
self.volume = Hypersphere.calcVolume(self.centers,self.radii);
end
function self = set.dists(self,~) % Compute distance between two hyperspheres
self.dists = Hypersphere.calcDists(self.centers);
end
function self = set.margins(self,~)
self.margins = Hypersphere.calcMargins(self.radii,self.dists);
end
function ov = get.overlap(self,~) % Compute overlap distance of two hyperspheres
ov = -self.margins;
end
%% HIGHER ORDER FUNCTIONS
function self = significance(self,points,N,varargin)
% SetOfHyps.significance: tests 'statistics of interest' (distances,
% margins/overlaps, radii), and their pairwise differences, for
% significance. It uses bootstrapped and permuted SetOfHyps or
% Hypersphere objects found in self.ci.bootstraps and
% self.ci.permutations or if they don't exist, does the bootstrapping
% /permutation on inputted points, and saves the bootstraps/permutations
% (and 95% confidence intervals) in self.ci. Alternatively, the ci
% struct can be passed as an input and embedded into the SetOfHyps
% object. One can choose to run only permutation- or bootstrap-based
% tests with the 'permute' or 'bootstrap'/'stratified' input options.
%
% Significance testing is based on the percentile confidence interval
% that contains 0 (for primary significance tests)*. Significant
% difference testing involves computing the percentile confidence
% interval (two-tailed) of the difference of two of the same type of
% statistics of interest from different hyperspheres. This is true for
% all tests except (first-order) distance significance, which is a
% permutation-based test asking if the distance computed on the
% unpermuted data is within the 95% confidnece interval of the
% permuted distances.
%
% p-values are stored in self.sigp and self.sigdiffp, and logicals
% indicating whether the null hypothesis was rejected (true) in self.sig
% and self.sigdiff.
%
% *Radii are always significant by definition.
%
% e.g.:
% hyps = hyps.significance(points)
% hyps = hyps.significance(points,N)
% hyps = hyps.significance(points,N,'permute') % only runs permutation tests
% hyps = hyps.significance(ci)
% hyps = hyps.significance % works only if hyps.ci is populated
%
% SEE ALSO ESTIMATEHYPERSPHERE, HYPERSPHERE.MEANANDMERGE,
% SETOFHYPS.NULLHYPOTHESISREJECTED
testtype = 'calcStats';
CVDISTS = 'nocvdists'; % default, unless overwritten by input option
for v = 1:numel(varargin)
if ischar(varargin{v})
switch lower(varargin{v})
case{'calcstats','permute','stratified','bootstrap'}
testtype = varargin{v};
varargin{v} = [];
case {'cvdists','nocvdists'}
CVDISTS = varargin{v};
varargin{v} = [];
end
end
end
if ~exist('N','var') || isempty(N), N=100; end
if ~exist('points','var') && isstruct(self.ci) && ~isempty(self.ci.bootstraps)
% then use self.ci.bootstraps
elseif isstruct(points) && ~isempty(points)
self.ci = points;
elseif ~size(self.categories.vectors,1)==size(points,1)
error('self.categories.vectors needs to index points');
else
% Compute confidence intervals on bootstrapped overlaps & radii for significance
bootsNperms = Hypersphere.estimate(points,self.categories,N,testtype,CVDISTS,varargin{:});
marginSamps = marginSampling(points,self.categories,'jackknife');
bootsNperms = [bootsNperms marginSamps];
bootsNperms = bootsNperms.meanAndMerge;
self.ci = bootsNperms.ci;
if islogical(self.distsCV)
self.distsCV = bootsNperms.distsCV;
end
end
%% set up significance measures
n = numel(self.radii);
nc2 = nchoosek(n,2);
% compute indices of radii corresponding to overlaps
ix = nchoosek_ix(n);
if n < 3, nc2c2 = 0;
else nc2c2 = nchoosek(nc2,2);
ixc2 = nchoosek_ix(nc2);
end
self.sigp = struct('ra',[],'ma',NaN(1,nc2),'ov',NaN(1,nc2),'di',NaN(1,nc2));
self.sigdiffp = struct('ra',NaN(1,nc2),...
'ma',NaN(1,nc2c2),'ov',NaN(1,nc2c2),'di',NaN(1,nc2c2));
%% Collect relevant permutations/bootstraps
if numel(self.ci.permutations)>0
if strcmpi(CVDISTS,'cvdists')
distCV_perm = cat(1,self.ci.permutations.distsCV);
else
dist_perm = cat(1,self.ci.permutations.dists);
end
radii_perm = cat(1,self.ci.permutations.radii);
end
if numel(self.ci.bootstraps)>0
radii_boot = cat(1,self.ci.bootstraps.radii);
overlap_boot = self.ci.bootstraps.overlap;
margin_boot = self.ci.bootstraps.margins;
dist_boot = cat(1,self.ci.bootstraps.dists);
end
if numel(self.ci.jackknives)>0
radii_jack = cat(1,self.ci.jackknives.radii);
overlap_jack = self.ci.jackknives.overlap;
margin_jack = self.ci.jackknives.margins;
dist_jack = cat(1,self.ci.jackknives.dists);
end
%% COMPUTE SIGNIFICANCE (smaller values more significant)
% helper functions
furthertail = @(x) min(cat(3,1-x,x),[],3);
ciprctile = @(x,t) sum([-Inf(1,size(x,2));x;Inf(1,size(x,2))]<=t)/(size(x,1)+3);
ciprctileFuTail = @(x,t) furthertail(ciprctile(x,t));
% What percentile confidence interval of bootstrapped margins contains 0?
if numel(self.ci.bootstraps)>0
if numel(self.ci.jackknives)>0
self.sigp.ov = ones(1,nc2);
self.sigp.ma = ones(1,nc2);
for i = 1:nc2
for thresh = [0.05 0.01 0.001]
ci = bca(self.overlap(i),overlap_boot(:,i),overlap_jack(:,i),thresh);
% Is 0 below the 95% BCa CI?
if ci(1)>0 % NOTE THIS IS NOT A P-VALUE, BUT H0
self.sigp.ov(i) = thresh/2;
end
ci = bca(self.margins(i),margin_boot(:,i),margin_jack(:,i),thresh);
% Is 0 below the 95% BCa CI?
if ci(1)>0 % NOTE THIS IS NOT A P-VALUE, BUT H0
self.sigp.ma(i) = thresh/2;
end
end
end
else
% What percentile confidence interval of bootstrapped overlap/margins contains 0?
% Overlap/margin is significant if 0 does not exceed the lowest 5% range
for i = 1:nc2
self.sigp.ov(i) = ciprctile(overlap_boot(:,i),0);
self.sigp.ma(i) = ciprctile( margin_boot(:,i),0);
end
end
end
if numel(self.ci.bootstraps)==0 && numel(self.ci.jackknives)>0
for i = 1:nc2
self.sigp.ma(i) = ciprctile( margin_jack(:,i),0);
end
end
if ~any(strcmpi(varargin,'mcmc')) && numel(self.ci.permutations)>0
% At what percentile confidence interval of permuted distances does
% the unpermuted distance estimate occur?
for i = 1:nc2
if strcmpi(CVDISTS,'cvdists')
self.sigp.di(i) = ciprctileFuTail(distCV_perm(:,i),self.distsCV(i));
else
self.sigp.di(i) = 1-ciprctile(dist_perm(:,i),self.dists(i));
end
end
elseif any(strcmpi(varargin,'mcmc')) && numel(self.ci.bootstraps)>0
for i = 1:nc2
self.sigp.di(i) = 1-ciprctile(dist_boot(:,i),0);
end
end
%% SECOND-ORDER COMPARISONS
if numel(self.ci.bootstraps)>0
if numel(self.ci.jackknives)>0
self.sigdiffp.ra = ones(1,nc2);
for i = 1:nc2
for thresh = [0.05 0.01 0.001]
ci = bca(diff(self.radii(ix(:,i))),diff(radii_boot(:,ix(:,i)),[],2),...
diff(radii_jack(:,ix(:,i)),[],2),thresh);
% Is 0 below the 95% BCa CI?
if ci(1)>0 || ci(2)<0 % NOTE THIS IS NOT A P-VALUE, BUT H0
self.sigdiffp.ra(i) = thresh/2;
end
end
end
else
for i = 1:nc2
self.sigdiffp.ra(i) = ciprctileFuTail(diff( radii_boot(:, ix(:,i)),[],2),0);
end
end
for i = 1:nc2c2
self.sigdiffp.ov(i) = ciprctileFuTail(diff(overlap_boot(:,ixc2(:,i)),[],2),0);
self.sigdiffp.di(i) = ciprctileFuTail(diff( dist_boot(:,ixc2(:,i)),[],2),0);
end
self.sigdiffp.ma = self.sigdiffp.ov; % Margin/overlap sigdiff is same bc smaller tail
end
if ~any(strcmpi(varargin,'mcmc')) && numel(self.ci.permutations)>0
for i = 1:nc2
self.sigdiffp.ra(i) = ciprctileFuTail(diff( radii_perm(:, ix(:,i)),[],2),diff(self.radii(ix(:,i))));
end
end
self = self.nullHypothesisRejected(0.05);
% %% DEBUG distances
% fh = newfigure([nc2 1]);
% for i=1:nc2
% axtivate(i)
% hist(dist_boot(:,i));
% plot((self.dists(i)^2)*[1 1],[0 N/nc2],'r-','LineWidth',2);
% end
% matchy(fh.a.h,{'XLim','YLim'})
end
function self = dropBootstraps(self)
% SetOfHyps.dropBootstraps: deletes bootstrapped Hyperspheres from self.ci
% Useful for saving SetOfHyps objects without creating enormous files
btypes = {'bootstraps','jackknives','permutations'};
for b = btypes; b=b{1};
self.ci.(b) = [];
end
end
function self = importStats(self,hypsTarget)
% SetOfHyps.importStats: copy stats (sig, sigp, sigdiff, sigdiffp, ci)
% from another SetOfHyps object. Also force msflips refresh.
%
% Also refills PostCenters fields if they are empty (useful for loading
% from file).
felds = {'ci', 'sig', 'sigp', 'sigdiff', 'sigdiffp'};
for f = felds; f=f{1};
self.(f) = hypsTarget.(f);
end
if isempty(self.dists), self = self.setPostCenters; end
if isempty(hypsTarget.dists), hypsTarget = hypsTarget.setPostCenters; end
[~,~,~,self.msflips] = self.stress(Hypersphere(self),hypsTarget);
end
function self = stressUpdate(self,hypsTarget)
% SetOfHyps.stressUpdate: populates error and msflips properties, computed
% by evaluating the error between the self SetOfHyps object and the
% hypsTarget SetOfHyps input.
%
% e.g.:
% hypset = hypset.stressUpdate(hypsTarget)
%
% SEE ALSO SETOFHYPS.STRESS
for i = 1:numel(self)
[~,~,self(i).error,self(i).msflips] = self(i).stress(self(i),hypsTarget(i));
end
end
function model = h2s(self,varargin)
% SetOfHyps.h2s: optimizes the hypersphere2sphere algorithm, and outputs
% a SetOfHyps object that has dimensionality reduced to dimLow (2 or 3).
% If self is an array of SetOfHyps objects, self.h2s will be recursively
% run on each element.
%
% e.g.
% hypslo = hypshi.h2s
% hypslo = hypslo.h2s(hypsTarget)
% hypsjointlo = severalhyps.h2s(hypsTargets) % jointly optimizes all
% SetOfHyps objects in severalhyps if belongsToCommonSpace is true
% (useful for movies)
% hypslo = hypshi.h2s([dimLow ninits]). % (optional numeric inputs)
% hypslo = hypshi.h2s({alpha}) % alpha values must be in a cell
% hypslo = hypshi.h2s('mdsinit','debugplot','verbose') % (string flags)
% ... or any combination of the above, with the restriction that if ninits
% is specified, dimLow must also be specified first in the array.
% hypslo = hypshi.h2s('mdsinit','debug') % equivalent to previous, if all
% inputs in previous are provided
% hypslo = hypshi.h2s('randinit') % (as opposed to 'mdsinit')
%
% Optional inputs:
% hypsTarget (DEFAULT = self): a SetOfHyps object, which contains the
% high-dimensional summary statistics of interest against which the
% h2s stress function will measure errors and be optimized to match.
% dimLow (DEFAULT = 3, or the number of hyperspheres, or the
% dimensionality of the high-dimensional space, whichever is
% smallest): a scalar numeric, either 2 or 3, that determines the
% dimensionality of the visualization space.
% N.B. providing a negative value tells h2s to use the default value,
% so an ninits value can be provided.
% ninits (DEFAULT = 0): the number of additional (random)
% initializations (plus the 1 MDS/random initialization) for stress
% function optimization, keeping the best result. Must be provided
% as a second element in a numeric vector.
% e.g.:
% self.h2s([3 5]) sets dimLow to 3 and sets ninits to 5
% self.h2s(3) sets dimLow to 3
% self.h2s([-1 5]) uses dimLow default and sets ninits to 5
% {alpha} (DEFAULT = {1 1 1}): a numeric 3-element cell (or 3-vector
% in a cell) specifying the regularization hyperparameters on the
% 3 components of the objective function: the elements weight the
% distances, margins, and radii, in that order, in the error
% (stress) function.
% e.g. the following disables margins in error:
% self.h2s({[1 0 1]}) or self.h2s({1 0 1})
% self.h2s({1 1 0}) and self.h2s({1 0 0}) keep radii fixed, and
% are both equivalent to MDS on the centers
% String input options:
% 'mdsinit'/'randinit' (DEFAULT = 'mdsinit'): use MDS for low centers
% initialization (as opposed to random initialization(s)).
% 'debugplot' (DEFAULT = false): display the h2s optimization
% debugging plot, which updates on each iteration. Must be second
% element in logical vector.
% 'verbose' (DEFAULT = false): prints fmincon optimization messages
% to the command prompt on every iteration. Must be third element
% in logical vector.
% 'debug': equivalent to 'debugplot' and 'verbose'
% 'quiet' (DEFAULT): debug and verbose are off
% e.g.:
% self.h2s('debug') uses MDS for low centers
% initialization, displays the fit debugging plot, and
% prints optimization messages to the command prompt.
%
% SEE ALSO SETOFHYPS.STRESS, SETOFHYPS.STRESSUPDATE, SETOFHYPS.STRESSPLOTFCN
lo = self;
for v = 2:nargin
if isa(varargin{v-1},'SetOfHyps')
hi = varargin{v-1};
elseif isnumeric(varargin{v-1})
[dimLow,ninits] = dealvec(varargin{v-1});
if numel(varargin{v-1})==3
varargin{v-1}(3) = 1; % change to 1 for recursive call below
end
elseif iscell(varargin{v-1})
alpha = [varargin{v-1}{:}];
else
switch lower(varargin{v-1})
case 'mdsinit'; MDS_INIT = true;
case 'randinit'; MDS_INIT = false;
case 'debugplot'; DBUGPLOT = true;
case 'verbose'; VERBOSE = true;
case 'debug'; DBUGPLOT = true; VERBOSE = true;
case 'quiet'; DBUGPLOT = false; VERBOSE = false;
end
end
end
if ~exist('hi' ,'var'), hi = self; end
n = numel(hi);
[nr,d] = size(cat(1,hi.centers));
if ~exist('dimLow' ,'var') || dimLow<0, dimLow = min([3 nr d]); end
if ~exist('ninits' ,'var'), ninits = 0; end
if ~exist('MDS_INIT','var'), MDS_INIT = true; end
if ~exist('DBUGPLOT','var'), DBUGPLOT = false; end
if ~exist('VERBOSE' ,'var'), VERBOSE = false; end
if ~exist('alpha' ,'var'), alpha = [1 1 1]; end
%% TODO: figure out what to do with heterogeneous common space situation
% Recurse for multiple SetOfHyps objects
if n > 1 && ~all([hi.belongsToCommonSpace])
for i = 1:n
stationarycounter(i,n);
model(i) = lo(i).h2s(varargin);
end
return
end
% Setup optimization and run
if MDS_INIT
multimds = arrayfun(@(h) mdscale(h.dists,dimLow,'Criterion','metricstress'),...
hi,'UniformOutput',false);
x0 = [cat(2,hi.radii)' cell2mat_concat(multimds)];
else
allcentervals = cat(1,hi.centers);
cminmax = [min(allcentervals(:)) max(allcentervals(:))];
%% initialization of centers: random noise added to projection onto first 2 dimensions
x0 = [cat(2,hi.radii)' ...
-0.1*diff(cminmax)*rand(nr,dimLow) + allcentervals(:,1:dimLow)];
end
if (all(alpha(1:2)==1) && alpha(3)==0)
fit = x0;
else
opts = optimoptions(@fmincon,'TolFun',1e-4,'TolX',1e-4,'Display','off',...
'SpecifyObjectiveGradient',true);%,'DerivativeCheck','on');
if DBUGPLOT, opts.OutputFcn = @self.stressPlotFcn; end
if VERBOSE, opts.Display = 'iter'; end
lb = [zeros(nr,1) -Inf(nr,dimLow)];
ub = Inf(nr,1+dimLow);
fit = fmincon(@(x) SetOfHyps.stress(x,hi,alpha),x0,...
[],[],[],[],lb,ub,[],opts);
end
% Output reduced SetOfHyps model
nc = size(fit,1)/n;
model = SetOfHyps(mat2cell(fit(:,2:end),repmat(nc,[n 1])),...
mat2cell(fit(:,1 ),repmat(nc,[n 1])),self.categories);
model.stressUpdate(hi);
% Recurse for multiple random initializations
if ninits > 0
% Make sure other initializations are random
if MDS_INIT
for v = 2:nargin
if islogical(varargin{v-1})
MDS_INIT = false;
varargin{v-1}(2) = MDS_INIT;
end
end
end
% force randinit if mdsinit is specified
tochange = strcmpi(varargin,'mdsinit');
if any(tochange)
varargin{tochange} = 'randinit';
end
% Loop through recursive function calls
for iinit = 1:ninits
tmp = self.h2s(varargin);
if max(cat(2,tmp.error)) < max(cat(2,model.error))
model = tmp; % keep lower error solutions
end
end
end
end
function errlines = plotOverlapErrors(self)
% SetOfHyps.plotOverlapErrors: plots a line where a true overlap is
% visualized as a margin, or a true margin is visualized as an
% overlap, but *ONLY IF THE TRUE OVERLAP/MARGIN is SIGNIFICANT*. Uses
% self.sig and self.msflips properties, populated by self.significance.
% If no information about significance is available, then all overlap/
% margins are considered significant and any flip is plotted.
%
% e.g.:
% hyps.plotOverlapErrors
%
% SEE ALSO HYPERSPHERE.SHOW, SETOFHYPS.SIGNIFICANCE
if isempty(self.sig), sigov = false(1,numel(self.margins));
else sigov = sum([self.sig.ov;self.sig.ma]);
end
if isempty(self.msflips), self.msflips = zeros(size(sigov));
end
sigov = sigov .* self.msflips;
if isempty(sigov) || ~any(sigov)
errlines = [];
return
end
n = numel(self.radii);
ix = nchoosek_ix(n);
for i = find(sigov)
err = self.error(n+i); % assumes order of errors is radii, margins, distances
centers = self.centers(ix(:,i),:);
dxy = diff(centers);
dxy = dxy/norm(dxy);
midpoint = mean(centers);
% Compute overlap midpoint
% need to assign +/-1 to larger/smaller center coordinate?
ov_edges = centers + [1;-1].*self.radii(ix(:,i))'*dxy;
ov_midpoint = mean(ov_edges);
% % debug
% keyboard
% plot(centers(:,1),centers(:,2),'ko')
% plot(midpoint(:,1),midpoint(:,2),'ro')
% plot(ov_edges(:,1),ov_edges(:,2),'go')
% plot(ov_midpoint(:,1),ov_midpoint(:,2),'rx')
if size(self.centers,2)==2
errlines(i) = plot( ov_midpoint(1) + [-1 1]*dxy(1)*err/2,...
ov_midpoint(2) + [-1 1]*dxy(2)*err/2,'k-','LineWidth',2);
else
errlines(i) = plot3(ov_midpoint(1) + [-1 1]*dxy(1)*err/2,...
ov_midpoint(2) + [-1 1]*dxy(2)*err/2,...
ov_midpoint(3) + [-1 1]*dxy(3)*err/2,'k-','LineWidth',2);
end
end
end
function plotDynamics(self,prop,varargin)
% SetOfHyps.plotDynamics: Plots the progression of specified SetOfHyps
% object properties ('prop' string input argument) through the array
% of SetOfHyps objects this is called on. Can optionally add a legend,
% plot multiple properties, and specify the x-axis values each object
% corresponds to (e.g., the times of the frames each object represents).
%
% e.g.:
% bunchohyps.plotDynamics('dists') % plots all distance comparisons
% bunchohyps.plotDynamics({'radii','margins','dists'})
% bunchohyps.plotDynamics('all') % equivalent to line above
% bunchohyps.plotDynamics('all',times) % specifies x-axis values
%
% Required input argument:
% prop (string or cell of strings): The summary stat(s) to plot. Can be:
% 'radii'
% 'margins'
% 'dists'
% 'volume'
% 'error'
% 'all': equivalent to {'radii','margins','dists'}
% Or a cell of any combination of the above
%
% Optional inputs:
% ax (DEFAULT = gca): Axes handle(s) where the plots will be placed.
% times (DEFAULT = 1:nframes): x-axis values for each frame, e.g., the
% time of that frame.
% LEGEND (DEFAULT = false): If true, places a categories.legend at the
% top left.
%
% SEE ALSO CATEGORIES.LEGEND
for v = 3:nargin
if ishandle(varargin{v-2}), ax = varargin{v-2};
elseif islogical(varargin{v-2}), LEGEND = varargin{v-2};
elseif isnumeric(varargin{v-2}), times = varargin{v-2};
end
end
if ~exist('LEGEND','var') || isempty(LEGEND), LEGEND = false; end
if ~exist('ax' ,'var') || isempty(ax), ax = gca; end
if ~exist('times' ,'var') || isempty(times), times = 1:numel(self); end
if ischar(prop) && strcmpi(prop,'all')
prop = {'radii','margins','dists'};
end
if iscell(prop)
for i = 1:numel(prop)
self.plotDynamics(prop{i},times,ax(i));
end
matchy(ax,'XLim')
if LEGEND, self(1).categories.legend; end
return
end
n = numel(self(1).radii);
nk = nchoosek(n,2);
ix = nchoosek_ix(n)';
axtivate(ax);
set(ax,'ColorOrder',self(1).categories.colors(ix(:),:))
if strcmpi(prop,'radii') || strcmpi(prop,'volume')
plot(times,reshape([self.(prop)],n ,[])','LineWidth',1)
else
plot(times,reshape([self.(prop)],nk,[])','LineWidth',1)
plot(times,reshape([self.(prop)],nk,[])','--','LineWidth',1)
end
switch prop
case 'dists', prop = 'distances';
case 'margins' % do nothing
case 'radii', prop = 'sizes';
case 'volume', prop = 'volumes';
case 'error', prop = 'errors';
end
ylabel(prop)
xlim([min(times) max(times)]);
if LEGEND, self(1).categories.legend; end
end
function showSig(self,varargin)
% SetOfHyps.showSig: Visualizes SIGNIFICANT summary statistics (radii,
% distances, and overlaps/margins), and/or the significances of their
% DIFFERENCES, in an elaborated Hinton diagram.
%
% As in SetOfHyps.showValues, the diagonal corresponds to radii, the
% upper triangle the overlaps/margins, and the lower triangle the
% distances. If differences are being plotted, these respective pairwise
% differences. Circle means positive value, square means negative value
% (relevant for overlaps/margins).
%
% N.B. As opposed to SetOfHyps.showValues, each shape's grayscale value
% corresponds to the level of significance.
%
% e.g.:
% hyps.showSig
% hyps.showSig('legend') % shows significances with legend
% hyps.showSig(true) % shows significances with legend
% hyps.showSig('sigdiff',axHandle) % significant differences in axHandle
% hyps.showSig(twoAxHandles) % sig & sigdiff in each axes handles
%
% Optional inputs:
% ax (DEFAULT = gca): Axes handle where the visualization(s) should be
% plotted. If two axes are given, showSig automatically plots both
% significances and significant differences.
% 'sig' (DEFAULT): plots significances.
% 'sigdiff'/'diff': plots significant differences.
% 'legend': plots a legend explaining the grayscale values and their
% corresponding significance levels.
%
% SEE ALSO SETOFHYPS.SHOWVALUES, SETOFHYPS.SIGNIFICANCE, STATSMAT,
% SETOFHYPS.SHOWSIGLEGEND, SETOFHYPS.SHAPESINABOX
for v = 1:nargin-1
if ishandle(varargin{v}), ax = varargin{v};
elseif ischar(varargin{v})
switch lower(varargin{v})
case 'legend'; LGND = varargin{v};
case 'sig'; sig = self.sigp;
DIFF = lower(varargin{v});
case {'sigdiff', 'diff'}; sig = self.sigdiffp;
DIFF = lower(varargin{v});
end
end
end
if ~exist('ax' ,'var') || isempty(ax) , ax = gca; end
if ~exist('sig' ,'var') || isempty(sig) , sig = self.sigp;
DIFF = 'sig'; end
if ~exist('LGND','var') || isempty(LGND), LGND = 'nolegend'; end
if isempty(sig)
error(['need to populate obj.sigp/sigdiffp first,'...
' e.g. with:\nobj = obj.significance(points);']);
end
if numel(ax) == 2
% if two axes given, plot sig in first, sigdiff in second
self.showSig(ax(1),LGND); % if legend requested, put here
self.showSig(ax(2),'diff');
return
end
nSigLevs = self.nSigLevs; % 3 means [0.05 0.01 0.001] levels
% Convert to sigmas significance, maxed to nSig(=3) and floored
% Use False Discovery Rate correction for significance computation
sigThresh = self.nullHypothesisRejected([0.05 10.^(-2:-1:-nSigLevs)],DIFF);
sigThresh = structfun(@(x) max(0,x/nSigLevs-1e-5),sigThresh(1),'UniformOutput',false);
n = numel(self.radii);
% Time to get a-plottin'
if strcmpi(DIFF,'sig')
self.elaborateHinton(statsmat(sigThresh.ov-sigThresh.ma,sigThresh.di,sigThresh.ra),...
'color',ax,DIFF)
else
self.elaborateHinton(statsmat(sigThresh.ov,sigThresh.di,sigThresh.ra),...
'color',ax,DIFF)
end
if strcmpi(DIFF,'sig'), title('Significant values')
else title('Significant differences')
end
if strcmpi(LGND,'legend'), self.showSigLegend(ax); end
end
function showValues(self,varargin)
% SetOfHyps.showValues: Visualizes significant summary statistic (radii,
% distances, and overlaps/margins) VALUES in an elaborated Hinton
% diagram. A reference SetOfHyps object can be additionally provided to
% compare estimated vs visualized values.
%
% As in SetOfHyps.showSig, the diagonal corresponds to radii, the upper
% triangle the overlaps/margins, and the lower triangle the distances.
% Circle means positive value, square means negative value (relevant for
% overlaps/margins).
%
% N.B. As opposed to SetOfHyps.showSig, the radii of each shape
% represents the corresponding summary statistic's value. These radii
% are normalized to the maximum of the absolute value of ALL summary
% statistics provided.
%
% Furthermore, each shape can be split into left/right sides, their
% radii corresponding to the high/low, estimated/visualized values. This
% happens only when an additional SetOfHyps object is provided as input.
%
% e.g.:
% hyps.showValues
% hyps.showValues(hypsTarget) % splits shapes left/right hypsTarget/hyps
% hyps.showValues(axHandle) % puts diagram in axHandle
%
% Optional inputs:
% hypsTarget (DEFAULT = self): reference (high-dimensional) SetOfHyps
% object containing summary statistics to be rendered on left half of
% each shape.
% axHandle (DEFAULT = gca): Axes handle where the visualization should
% be plotted.
%
% SEE ALSO SETOFHYPS.SHOWSIG, SETOFHYPS.SIGNIFICANCE, STATSMAT,
% SETOFHYPS.SHOWSIGLEGEND, SETOFHYPS.SHAPESINABOX
% Parse inputs
for v = 1:nargin-1
if isa(varargin{v},'SetOfHyps'), hi = varargin{v};
elseif ishandle(varargin{v}), ax = varargin{v};
end
end
if ~exist('ax','var') || isempty(ax), ax = gca; axis ij off; end
if ~exist('hi','var') || isempty(hi), hi = self; self = []; end
himat = statsmat( -hi.margins, hi.dists, hi.radii);
if ~isempty(self)
lomat = statsmat(-self.margins,self.dists,self.radii);
% Normalize both to same scale
maxval = max(abs([himat(:);lomat(:)]));
hi.elaborateHinton(himat/maxval,'left', ax)
self.elaborateHinton(lomat/maxval,'right',ax)
title('Values comparison')
else
hi.elaborateHinton(himat/max(abs(himat(:))),'size',ax)
title('Values')
end
end
function showSigLegend(self,ax)
% SetOfHyps.showSigLegend: Renders legend for a significance/significant
% differences elaborated Hinton diagram. Indicates the correspondence
% between color and significance level.
%
% e.g.:
% hyps.showSigLegend
% hyps.showSigLegend(axHandle)
%
% Optional input:
% axHandle (DEFAULT = gca): Axes handle where the legend should be
% rendered. Should be the same one where SetOfHyps.showSig was/will
% be.
%
% SEE ALSO SETOFHYPS.SHOWSIG
n = numel(self.radii);
boxPos = self.boxPos;
sqSz = self.boxSize/n;
nSigLevs = self.nSigLevs; % 3 means [0.95 0.99 0.999] levels
if ~exist('ax','var') || isempty(ax), ax = gca; axis ij off; end
% Time to get a-plottin'
set(0,'CurrentFigure',get(ax,'Parent'))
set(get(ax,'Parent'),'CurrentAxes',ax,'Units','normalized')
%% Draw Legend
for i = 1:nSigLevs
rectangle('Position',[boxPos+[0.01+sqSz*(n+1/3) sqSz*(i-1)/3] sqSz/3 sqSz/3],...
'FaceColor',[1 1 1]*(1-i/nSigLevs),'EdgeColor','none')
end
% Probability labels
text('Position',[boxPos+[0.01+sqSz*(n+0.7) sqSz/6]],'String','p<0.05')
for i = 2:nSigLevs
text('Position',[boxPos+[0.01+sqSz*(n+0.7) sqSz*(2*i-1)/6]],'String',...
['p<' num2str(10^-i)])
end
axis equal ij off
end
function varargout = toJSON(self, saveFile)
% SetOfHyps.toJSON(<saveFile>): exports SetOfHyps object as an array of
% Hypersphere objects in JSON format. Optional saveFile input argument
% specifies where to save the JSON.
% e.g.:
% hyps.toJSON % prints JSON in command line
% hyps.toJSON('hypsjson') % saves JSON in file named hypsjson.json
%
% SEE ALSO HYPERSPHERE.UNCONCAT
for i = 1:numel(self)
self.categories.vectors = [];
end
json = jsonencode(Hypersphere(self).unconcat);
% Saves JSON to file, if requested
if exist('saveFile','var') && ~isempty(saveFile) && any(saveFile)
fileID = fopen([saveFile '.json'],'w');
fprintf(fileID,'%s',json);
fclose(fileID);
fprintf('JSON saved to %s.json\n',saveFile);
end
if nargout || ~exist('fileID','var')
varargout = {json};
end
end
end % methods (public)
methods(Access = 'private')
%% UPDATE DISTS, MARGINS IF CENTERS CHANGED
function self = setPostCenters(self,src,event,FIRSTRUN)
if ~exist('FIRSTRUN','var') || isempty(FIRSTRUN)
FIRSTRUN = false;
end
self.dists = dists(self);
self.margins = margins(self);
if ~FIRSTRUN
if ~any(isnan(self.error))
warning(['SetOfHyps object updated, but obj.errors/ci/sig/sigdiff '...
'are out of sync']);
elseif self.distsCV
warning(['SetOfHyps object updated, but self.distsCV, '...
'and thus self.dists, are out of sync'])
end
end
end
function self = setPostRadii(self,src,event,FIRSTRUN)
if ~exist('FIRSTRUN','var') || isempty(FIRSTRUN)
FIRSTRUN = false;
end
self.volume = volume(self);
self.margins = margins(self);
if ~FIRSTRUN && ~any(isnan(self.error))
warning('SetOfHyps object updated, but obj.errors/ci/sig/sigdiff are out of sync');
end
end
function stop = stressPlotFcn(self,varargin)%x,optimValues,state)
% stressPlotFcn: private function that plots errors and summary statistics
% as a function of optimization iteration. This is only relevant as a
% debugging plot for h2s.
%
% e.g.
% hypslo = hypshi.h2s('debugplot')
%
% SEE ALSO SETOFHYPS.H2S, SETOFHYPS.STRESS, SETOFHYPS.STRESSUPDATE
% unpack inputs
x = varargin{1};
optimValues = varargin{2};
state = varargin{3};
% preliminaries
n = size(x,1);
cols = colormap('lines');
% copy hi radii to lo SetOfHyps
lo = SetOfHyps(x,self.radii);
% Recalculate error from high dimensional SetOfHyps self
lo = lo.stressUpdate(self);
loerr = lo.error.^2;
% Plot
figure(99);
if strcmpi(state,'init')
clf; subplot(3,3,1); hold on; lo.show; title('initial');
end
subplot(3,3,2); hold on; lo.show; title('fit')
subplot(3,3,3); hold on % Plot error value
plot(optimValues.iteration,optimValues.fval,'ko')
ylabel('Error')
xlabel('Iteration')
for i = 1:(n^2-n)/2
subplot(3,3,9); hold on;title('dists' )
plot(optimValues.iteration,lo.dists(i) ,'o','Color',cols(i,:));
subplot(3,3,8); hold on;title('margins')
plot(optimValues.iteration,lo.margins(i),'o','Color',cols(i,:));
subplot(3,3,7); hold on;title('overlaps')