-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInfoT.cpp
1362 lines (1232 loc) · 41.2 KB
/
InfoT.cpp
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
// $Id: InfoT.cpp,v 1.17 2009/01/23 00:54:32 samn Exp $
#include "stdafx.h"
#include "InfoT.h"
#include "WCMath.h"
#include "combination.h"
//#define LOG_TEST 1
#ifdef DO_TIMING
MTimer oMT("getnnrsq btest=true");
MTimer oMF("getnnrsq btest=false");
#endif
#define SLOWER_KD 1
#define FASTER_KD 2
#define BOTH_KD 4
#define KD_MODE FASTER_KD
bool NeighborClustCount(Neighbor** vNeighbors,vector<int>& vClustIDs,vector<ClusterInfo>& vPrct,int iNNToFind,int iClusts)
{
int iSz = vClustIDs.size();
if(vPrct.size()!=iClusts+1)
return false;
int i;
vector<int> vCounts(iClusts+1);
for(i=1;i<=iClusts;i++)
vCounts[i]=count(vClustIDs.begin(),vClustIDs.end(),i);
vector< vector<prob_t> > vprct(iClusts+1);
for(i=1;i<=iClusts;i++)
vprct[i]=vector<prob_t>(vCounts[i],0.0);
vector<int> vIndex(iClusts+1,0);
for(i=0;i<iSz;i++)
{
int j, iCount = 0, iClust = vClustIDs[i];
if(!iClust)continue;//skip background vectors
int idx = vIndex[iClust]++;
for(j=0;j<iNNToFind;j++)
{
if(vClustIDs[vNeighbors[i][j].m_id]==iClust)
vprct[iClust][idx]+=1.0f;
}
vprct[iClust][idx] /= iNNToFind;
}
for(i=1;i<=iClusts;i++)
vPrct[i].m_fPrctKNNInClust=Avg(vprct[i]);
return true;
}
prob_t FastKLDivPQ(KDTreeHist& p,KDTreeHist& q,Neighbor** vNeighbors,int iClustIDP,int iClustIDQ,vector<int>& vClustIDs,int iNNToFind,vector<int>& vNCount)
{
int iFastP = 0, iFastQ = 0, iSlowP = 0 , iSlowQ = 0;
#ifdef LOG_TEST
double kldiv = 1.0;
double kldivQ=1.0,kldivP=1.0;
#else
prob_t kldiv = 0.0;
#endif
int isz = vClustIDs.size() , iV = 0, iT = 0, iNN = 0, iLessP = 0, iLessQ = 0;
for(iV=0;iV<isz;iV++)
{
if(vClustIDs[iV]!=iClustIDP) //skip vectors not in cluster p
continue;
prob_t dDistP = 0.0 , dDistQ = 0.0; // squared distances
Neighbor* vnn = vNeighbors[iV]; //these are the neighbors of an element in cluster p
int nsz = vNCount[iV]; //iNNToFind;//vnn.size();
bool bFoundP = false, bFoundQ = false;
for(iNN=0;iNN<nsz;iNN++)
{ Neighbor& oN = vnn[iNN];
if(!bFoundP && vClustIDs[oN.m_id]==iClustIDP)
{ if(oN.m_dist>0.0)
{ //found a different neighbor in the same cluster p
dDistP = oN.m_dist;
iFastP++;
bFoundP = true;
}
}
else if(!bFoundQ && vClustIDs[oN.m_id]==iClustIDQ)
{ //found a neighbor in the other cluster q
dDistQ = oN.m_dist;
iFastQ++;
bFoundQ = true;
}
if(bFoundP && bFoundQ) break; //found neighbors so break
}
if(!bFoundP)
{ //use slow method of searching KD-tree
#if KD_MODE == BOTH_KD // to make sure get same results
dDistP = p.GetNearestRadiusSQ(iT,false);
float dDistP2 = p.GetNearestRadiusSQ(iT,true);
if(dDistP!=dDistP2)
{
Write2Log("not eq %.6f %.6f",dDistP,dDistP2);
}
#elif KD_MODE == SLOWER_KD // in case have to revert for some unkown reason...
dDistP = p.GetNearestRadiusSQ(iT,false);
#else
dDistP = p.GetNearestRadiusSQ(iT,true);
#endif
iSlowP++;
}
if(!bFoundQ)
{ //use slow method of searching KD-tree
#if KD_MODE == BOTH_KD // to make sure get same results
dDistQ = q.GetNearestRadiusSQ(p[iT],true,false);//true==alow zero distance,since diff cluster,can have same exact point with 0 dist
float dDistQ2 = q.GetNearestRadiusSQ(p[iT],true,true);
if(dDistQ2!=dDistQ)
{
Write2Log("not eq %.6f %.6f",dDistQ,dDistQ2);
}
#elif KD_MODE == SLOWER_KD
dDistQ = q.GetNearestRadiusSQ(p[iT],true,false);//true==alow zero distance,since diff cluster,can have same exact point with 0 dist
#else
dDistQ = q.GetNearestRadiusSQ(p[iT],true,true);//true==alow zero distance,since diff cluster,can have same exact point with 0 dist
#endif
iSlowQ++;
}
if(dDistP>0.0 && dDistQ>0.0)
{ //avoid exceptions of log(0)
//if(dDistP<dDistQ)iLessP++; else iLessQ++;
#ifdef LOG_TEST
//kldiv *= dDistQ / dDistP;
// kldivQ *= dDistQ;
// kldivP *= dDistP;
kldiv += log( dDistQ / dDistP );
#else
kldiv += log2( dDistQ / dDistP ) / 2.0;
#endif
}
iT++; //increment index into cluster p's KD-tree
}
//finish the calculation
#ifdef LOG_TEST
//kldiv = log2( kldiv ) / 2.0;
//kldiv = log2( kldivQ / kldivP ) / 2.0;
kldiv /= ( log(2.0) * 2.0 );
#endif
kldiv *= p.NumDims() / ((prob_t) p.NumElems() );
kldiv += log2( (prob_t)q.NumElems() / (p.NumElems()-1.0 ) );
//write some stats
//Write2Log("FastKLDivPQ:kldiv=%.4f iSlow=%d iSlowP=%d iSlowQ=%d iFast=%d iFastP=%d iFastQ=%d",kldiv,iSlowP+iSlowQ,iSlowP,iSlowQ,iFastP+iFastQ,iFastP,iFastQ);
return kldiv;
}
prob_t FastKLDivPNOTP(KDTreeHist& p,KDTreeHist& notp,Neighbor** vNeighbors,int iClustIDP,vector<int>& vClustIDs,int iNNToFind,vector<int>& vNCount)
{
int iFastP = 0, iFastNotP = 0, iSlowP = 0 , iSlowNotP = 0;
#ifdef LOG_TEST
double kldiv = 1.0;
double kldivP=1.0,kldivNOTP=1.0;
#else
prob_t kldiv = 0.0;
#endif
int isz = vClustIDs.size() , iV = 0, iT = 0, iNN = 0, iLessP = 0, iLessNotP = 0;
for(iV=0;iV<isz;iV++)
{
if(vClustIDs[iV]!=iClustIDP) //skip vectors not in cluster p
continue;
prob_t dDistP = 0.0 , dDistNotP = 0.0; // squared distances
Neighbor* vnn = vNeighbors[iV]; //these are the neighbors of an element in cluster p
int nsz = vNCount[iV]; //iNNToFind;//vnn.size();
bool bFoundP = false, bFoundNotP = false;
for(iNN=0;iNN<nsz;iNN++)
{ Neighbor& oN = vnn[iNN];
if(!bFoundP && vClustIDs[oN.m_id]==iClustIDP)
{ if(oN.m_dist>0.0)
{ //found a different neighbor in the same cluster p
dDistP = oN.m_dist;
iFastP++;
bFoundP = true;
}
}
else if(!bFoundNotP && vClustIDs[oN.m_id]!=iClustIDP)
{ //found a neighbor in the other cluster q
dDistNotP = oN.m_dist;
iFastNotP++;
bFoundNotP = true;
}
if(bFoundP && bFoundNotP) break; //found neighbors so break
}
if(!bFoundP)
{ //use slow method of searching KD-tree
#if KD_MODE == BOTH_KD // to make sure get same results
dDistP = p.GetNearestRadiusSQ(iT,false);
float dDistP2 = p.GetNearestRadiusSQ(iT,true);
if(dDistP!=dDistP2)
{
Write2Log("not eq %.6f %.6f",dDistP,dDistP2);
}
#elif KD_MODE == SLOWER_KD
dDistP = p.GetNearestRadiusSQ(iT,false);
#else
dDistP = p.GetNearestRadiusSQ(iT,true);
#endif
iSlowP++;
}
if(!bFoundNotP)
{ //use slow method of searching KD-tree
#if KD_MODE == BOTH_KD // to make sure get same results
dDistNotP = notp.GetNearestRadiusSQ(p[iT],true,false);//true==alow zero distance,since diff cluster,can have same exact point with 0 dist
float dDistNotP2 = notp.GetNearestRadiusSQ(p[iT],true,true);
if(dDistNotP!=dDistNotP2)
{
Write2Log("not eq %.6f %.6f",dDistNotP,dDistNotP2);
}
#elif KD_MODE == SLOWER_KD
dDistNotP = notp.GetNearestRadiusSQ(p[iT],true,false);//true==alow zero distance,since diff cluster,can have same exact point with 0 dist
#else
dDistNotP = notp.GetNearestRadiusSQ(p[iT],true,true);//true==alow zero distance,since diff cluster,can have same exact point with 0 dist
#endif
iSlowNotP++;
}
if(dDistP>0.0 && dDistNotP>0.0)
{ //avoid exceptions of log(0)
//if(dDistP<dDistNotP)iLessP++; else iLessNotP++;
#ifdef LOG_TEST
//kldiv *= dDistNotP / dDistP;
//kldivP *= dDistP;
//kldivNOTP *= dDistNotP;
kldiv += log ( dDistNotP / dDistP );
#else
kldiv += log2( dDistNotP / dDistP ) / 2.0;
#endif
}
iT++; //increment index into cluster p's KD-tree
}
//finish the calculation
#ifdef LOG_TEST
//kldiv = log2( kldiv ) / 2.0;
//kldiv = log2( kldivNOTP / kldivP ) / 2.0;
kldiv /= ( log(2.0) * 2.0 );
#endif
kldiv *= p.NumDims() / ((prob_t) p.NumElems() );
kldiv += log2( (prob_t)notp.NumElems() / (p.NumElems()-1.0 ) );
//write some stats
//Write2Log("FastKLDivPNOTP:kldiv=%.4f iSlow=%d iSlowP=%d iSlowNotP=%d iFast=%d iFastP=%d iFastNotP=%d",kldiv,iSlowP+iSlowNotP,iSlowP,iSlowNotP,iFastP+iFastNotP,iFastP,iFastNotP);
return kldiv;
}
//notp is all points not in p
//this version gets the distance from notp to p
prob_t FastKLDivNOTPP(KDTreeHist& p,KDTreeHist& notp,Neighbor** vNeighbors,int iClustIDP,vector<int>& vClustIDs,int iNNToFind,vector<int>& vNCount)
{
int iFastP = 0, iFastNP = 0, iSlowP = 0, iSlowNP = 0;
#ifdef LOG_TEST
double kldiv = 1.0;
double kldivNOTP=1.0,kldivP=1.0;
#else
prob_t kldiv = 0.0;
#endif
int isz = vClustIDs.size() , iV = 0, iT = 0, iNN = 0, iLessP = 0, iLessNotP = 0;
for(iV=0;iV<isz;iV++)
{
if(vClustIDs[iV]==iClustIDP) //skip all points in p
continue;
prob_t dDistP = 0.0 , dDistNotP = 0.0;
Neighbor* vnn = vNeighbors[iV];
int nsz = vNCount[iV]; //iNNToFind;
bool bFoundP = false, bFoundNotP = false;
for(iNN=0;iNN<nsz;iNN++)
{ Neighbor& oN = vnn[iNN];
if(!bFoundP && vClustIDs[oN.m_id]==iClustIDP)
{
dDistP = oN.m_dist;
iFastP++;
bFoundP = true;
}
else if(!bFoundNotP && vClustIDs[oN.m_id]!=iClustIDP)
{
if(oN.m_dist>0.0)
{
dDistNotP = oN.m_dist;
iFastNP++;
bFoundNotP = true;
}
}
if(bFoundP && bFoundNotP) break;
}
if(!bFoundP)
{
#if KD_MODE == BOTH_KD // to make sure get same results
dDistP = p.GetNearestRadiusSQ(notp[iT],true,false);
float dDistP2 = p.GetNearestRadiusSQ(notp[iT],true,true);
if(dDistP!=dDistP2)
{
Write2Log("not eq %.6f %.6f",dDistP,dDistP2);
}
#elif KD_MODE == SLOWER_KD
dDistP = p.GetNearestRadiusSQ(notp[iT],true,false);
#else
dDistP = p.GetNearestRadiusSQ(notp[iT],true,true);
#endif
iSlowP++;
}
if(!bFoundNotP)
{
#if KD_MODE == BOTH_KD // to make sure get same results
dDistNotP = notp.GetNearestRadiusSQ(iT,false);
float dDistNotP2 = notp.GetNearestRadiusSQ(iT,true);
if(dDistNotP!=dDistNotP2)
{
Write2Log("not eq %.6f %.6f",dDistNotP,dDistNotP2);
}
#elif KD_MODE == SLOWER_KD
dDistNotP = notp.GetNearestRadiusSQ(iT,false);
#else
dDistNotP = notp.GetNearestRadiusSQ(iT,true);
#endif
iSlowNP++;
}
if(dDistP>0.0 && dDistNotP>0.0)
{
//if(dDistNotP<dDistP)iLessNotP++; else iLessP++;
#ifdef LOG_TEST
//kldiv *= dDistP / dDistNotP;
//kldivP *= dDistP;
//kldivNOTP *= dDistNotP;
kldiv += log ( dDistP / dDistNotP );
#else
kldiv += log2( dDistP / dDistNotP ) / 2.0;
#endif
}
iT++;
}
#ifdef LOG_TEST
//kldiv = log2( kldiv ) / 2.0;
//kldiv = log2( kldivP / kldivNOTP ) / 2.0;
kldiv /= ( log(2.0) * 2.0 );
#endif
kldiv *= notp.NumDims() / ((prob_t) notp.NumElems() );
kldiv += log2( (prob_t)p.NumElems() / (notp.NumElems()-1.0 ) );
//Write2Log("FastKLDivNOTPP:kldiv=%.4f iSlow=%d iSlowP=%d iSlowNP=%d iFast=%d iFastP=%d iFastNP=%d",kldiv,iSlowP+iSlowNP,iSlowP,iSlowNP,iFastP+iFastNP,iFastP,iFastNP);
return kldiv;
}
//symmetric kldiv
//(dpq * dqp ) / (dpq + dqp)
//dpq == distance from p to q
//dqp == distance from q to p
//both q and p are actual clusters with valid IDs!!
prob_t FastKLDivSymPQ(KDTreeHist& p,KDTreeHist& q,Neighbor** vNeighbors,int iClustIDP,int iClustIDQ,vector<int>& vClustIDs,int iNNToFind,vector<int>& vNCount)
{
prob_t dpq = FastKLDivPQ(p,q,vNeighbors,iClustIDP,iClustIDQ,vClustIDs,iNNToFind,vNCount), //dist from p to q
dqp = FastKLDivPQ(q,p,vNeighbors,iClustIDQ,iClustIDP,vClustIDs,iNNToFind,vNCount); //dist from q to p
if(!dpq && !dqp) return 0.0;
return dpq*dqp / (dpq+dqp);
}
//symmetric kldiv
//(dpnotp * dnotpp) / (dpnotp + dnotpp)
//dpnotp == distance from p to not p
//dnotpp == distance from not p to p
//p == actual cluster with valid ID
//notp == complement of p (all vectors not in p), without an actual ID
prob_t FastKLDivSymPNOTP(KDTreeHist& p,KDTreeHist& notp,Neighbor** pNeighbors,int iClustIDP,vector<int>& vClustIDs,int iNNToFind,vector<int>& vNCount)
{
prob_t dpq = FastKLDivPNOTP(p,notp,pNeighbors,iClustIDP,vClustIDs,iNNToFind,vNCount), //dist from p to notp
dqp = FastKLDivNOTPP(p,notp,pNeighbors,iClustIDP,vClustIDs,iNNToFind,vNCount); //dist from notp to p
if(!dpq && !dqp) return 0.0;
return dpq*dqp / (dpq+dqp);
}
//make tree using dimension indices stored in pBestDims
//iRows is # of elements in full vFloat matrix, iCols is full # of dimensions in vFloat
void FillTree(vector<float>& vFloat,int iRows,int iCols,int iClustID,int iClustSz,vector<int>& vClustIDs,int* pBestDims,int iBestDims,KDTreeHist& oT,vector<float>& vClustData)
{
vClustData.resize(iClustSz*iBestDims);
int iV = 0 , idx = 0;
for(;iV<iRows;iV++)
{ if(vClustIDs[iV]!=iClustID) continue;
int iD = 0;
for(;iD<iBestDims;iD++)
vClustData[idx++]=vFloat[iV*iCols+pBestDims[iD]];
}
oT.SetData(iBestDims,&vClustData[0],iClustSz);
}
//computes kldiv between each pair of actual clusters and adds the min to CCluster::m_vInfo
bool InterClustKLD(CCluster& Clusters,vector<KDTreeHist>& vDistribs,vector<int>& vClustIDs,vector<int>& vClustCounts,int iClusts,bool bFast,Neighbor** vnn,int WhichDraw,const CUPDUPDATA* pUp,int iNNToFind,vector<int>& vNCount,vector<float>& vFloat,int iRows,int iCols)
{ //kldiv cluster to other clusters
int iC1 = 0, iC2 = 0, iTot = ((iClusts-1)*(iClusts-1)+iClusts-1)/2, iCurr = 0;
try
{ CString msg;
vector< vector<prob_t> > vcInfInter(iClusts+1, vector<prob_t>(iClusts+1));
//Write2Log("Calculating inter-cluster KLDiv");
prob_t kldiv = 0.0f;
if(Clusters.m_oCQO.m_bFindBestDims) //compute inter-clust kldiv using best dimensions
{ iTot = iClusts*iClusts; //distances are not symmetrical since use different dimensions
for(iC1=1;iC1<=iClusts && !pUp->ShouldTerminate();iC1++)
{ for(iC2=1;iC2<=iClusts && !pUp->ShouldTerminate();iC2++,iCurr++)
{ if(iC2==iC1) continue;
msg.Format("Calculating kldiv btwn clust %d and %d",iC1,iC2);
pUp->SetProgress(msg,100*(iCurr/static_cast<double>(iTot)));
//Write2Log(msg);
KDTreeHist oT; vector<float> vTmpData; //make temporary tree
FillTree(vFloat,iRows,iCols,iC2,vClustCounts[iC2],vClustIDs,Clusters.m_vBestDims[iC1],Clusters.m_oCQO.m_iBestDims,oT,vTmpData);
vcInfInter[iC1][iC2]=KLDivSym(vDistribs[iC1],oT);
//Write2Log("sym. kldiv from %d to %d = %.4f",iC1,iC2,vcInfInter[iC1][iC2]);
}
}
}
else
{ for(iC1=1;iC1<=iClusts && !pUp->ShouldTerminate();iC1++)
{ for(iC2=iC1+1;iC2<=iClusts && !pUp->ShouldTerminate();iC2++,iCurr++)
{ msg.Format("Calculating kldiv btwn clust %d and %d",iC1,iC2);
pUp->SetProgress(msg,100*(iCurr/static_cast<double>(iTot)));
//Write2Log(msg);
if(bFast)
vcInfInter[iC1][iC2]=vcInfInter[iC2][iC1]=FastKLDivSymPQ(vDistribs[iC1],vDistribs[iC2],vnn,iC1,iC2,vClustIDs,iNNToFind,vNCount);
else
vcInfInter[iC1][iC2]=vcInfInter[iC2][iC1]=KLDivSym(vDistribs[iC1],vDistribs[iC2]);
//Write2Log("sym. kldiv from %d to %d = %.4f",iC1,iC2,vcInfInter[iC1][iC2]);
}
}
}
if(!pUp->ShouldTerminate()){ for(iC1=1;iC1<=iClusts;iC1++)
{ prob_t min_int = iClusts>1 ? INF : 0.0; //*INF;
int min_ind = 0;
if(iClusts>1) for(iC2=1;iC2<=iClusts;iC2++)
{ if(iC1==iC2 || vClustCounts[iC2]<2)continue;
prob_t tmpK = vcInfInter[iC1][iC2];
if(tmpK<min_int)
{ min_int=tmpK;
min_ind=iC2;
}
}
Clusters.m_vInfo[WhichDraw][iC1].m_fInterClustGain = min_int;
Clusters.m_vInfo[WhichDraw][iC1].m_iClosestID = min_ind;
//Write2Log("Nearest kldiv from clust %d to %d is %.6f",iC1,min_ind,min_int);
}
if(false) {
CString strTab("\ninter clust kldiv table\n") , strTmp;//write inter-cluster kldiv table to log for inspection...
for(iC1=1;iC1<=iClusts;iC1++)
{ for(iC2=1;iC2<=iClusts;iC2++)
{ strTmp.Format("%.6f\t",vcInfInter[iC1][iC2]);
strTab += strTmp;
}
strTab += "\n";
}
Write2Log(strTab); }
}
}
catch(...)
{ Write2Log("Exception in InterClustKLD!!! iC1=%d iC2=%d iClusts=%d",iC1,iC2,iClusts);
return false;
}
return true;
}
//gets KLDiv using approximate probabilities
//P(j) = (nj+0.5)/(N+0.5jmax)
//n1+n2+...+nmax=N
//the p distribution's counts are first subtracted
//from the q distribution so that the function will
//calculate the "exclusive" information gain
//p is "partial" distribution
//q is "full" distribution
prob_t KLDivApproxExclusiveProb(Hist& p,Hist& q)
{
if(p.NumBins() != q.NumBins()) return -1.0;
prob_t d = 0.0;
int i = 0, iBins = p.NumBins();
prob_t eps = 1e-100;
prob_t pelems = p.NumElems();
prob_t qelems = q.NumElems();
for(i=0;i<iBins;i++)
{
prob_t pcount = p[i];
prob_t qcount = q[i];
//approximate probability of bin i in distribution p
prob_t pp = (pcount+0.5) / ( pelems + 0.5*iBins);
//approximate probability of bin i in distribution q
//must subtract pcount elements from numerator & denominator of probability
//approximation so as to maintain "exclusivity" of p distribution
// prob_t qp = (qcount - pcount + 0.5) / ( qelems - pcount + 0.5*iBins);
prob_t qp = (qcount - pcount + 0.5) / ( qelems - pelems + 0.5*iBins);
if(pp<=eps) continue;
if(qp<=eps) continue;
d += pp * ( log2(pp) - log2(qp) );
}
return d;
}
prob_t KLDiv(KDTreeHist& p,KDTreeHist& q,bool bAllowZeroQDist)
{
int i=0;
#ifdef DO_TIMING
char sMsg[1024];
sprintf(sMsg,"KLDiv szp=%d, szq=%d, dims=%d",p.NumElems(),q.NumElems(),p.NumDims());
ScopedTimer S(sMsg);
#endif
try //just in case something goes wrong from invalid type of data passed in
{
//make sure we can do calculation with div by zero and need same # of dimensions
//in each distribution
if(p.NumElems() < 2 || q.NumElems()<1 || p.NumDims()!=q.NumDims())
return 0.0;
int iLessP = 0, iLessQ = 0;
prob_t dpq = 0.0;
const prob_t eps = 0.0;
int isz = p.NumElems();
i = 0;
for(i=0;i<isz;i++)
{
prob_t distp = p.GetNearestRadiusSQ(i,true);
if(distp<=eps)
continue;
prob_t distq = q.GetNearestRadiusSQ(p[i],bAllowZeroQDist,true);
if(distq<=eps)
continue;
dpq += log2(distq / distp) / 2.0;
}
dpq *= ((prob_t)p.NumDims()/p.NumElems());
dpq += log2( (prob_t)q.NumElems() / (p.NumElems()-1.0 ) );
#ifdef DO_TIMING
sprintf(sMsg,"iLessP=%d iLessQ=%d",iLessP,iLessQ);
MessageBox(0,sMsg,"WClust",MB_ICONINFORMATION);
#endif
return dpq;
}
catch(...)
{
char sMsg[1024];
sprintf(sMsg,"KLDiv caught exception!! i=%d",i);
MessageBox(0,sMsg,"WClust",MB_ICONERROR);
Write2Log(sMsg);
return -666.0;
}
}
//resistor avg.
prob_t KLDivSym(KDTreeHist& p,KDTreeHist& q)
{
prob_t dpq = KLDiv(p,q), dqp = KLDiv(q,p);
//Write2Log("dpg=%g dqp=%g",dpq,dqp);
if(!dpq && !dqp) return 0.0;
return dpq*dqp / (dpq+dqp);
}
//returns -1 iff num bins not equal
//otherwise returns KL divergence of histogram/distributions
//this returns "divergence" of distribution q from p
//so q should be a cluster's distribution and p should be full distribution
//make sure when passing in...
//the order matters because it is not symmetric
//however...
//In Bayesian statistics the KL divergence can be used as a measure of the information
//gain in moving from a prior distribution to a posterior distribution. If some new fact
//Y=y is discovered, it can be used to update the probability distribution for X from p(x|I)
//to a new posterior probability distribution p(x|y) using Bayes' theorem
// DKL(p(x|y)||p(x|I)) = sum( p(x|y) * log( p(x|y) / p(x|I) )
//so p can be cluster distribution and q can be full distribution
prob_t KLDiv(Hist& p,Hist& q)
{
if(p.NumBins() != q.NumBins())
{
return -1.0;
}
prob_t d = 0.0;
int i = 0 , iBins = p.NumBins();
prob_t eps = 1e-100;
for(i=0;i<iBins;i++)
{
prob_t pp = p.BinProb(i); //probability of bin i in distribution p
if(pp<=eps)
continue;
prob_t qp = q.BinProb(i); //probability of bin i in distribution q
if(qp<=eps)
continue;
d += pp * ( log2(pp) - log2(qp) );
}
/*#ifdef _DEBUG
if(d<0.0)
{
prob_t pf = FullProb(p);
prob_t qf = FullProb(q);
FILE* fp = fopen("kl_prob.txt","w");
fprintf(fp,"p:\n");
p.Print(fp);
fprintf(fp,"q:\n");
q.Print(fp);
fclose(fp);
int moo=0;
}
#endif*/
return d;
}
prob_t ResistorAvg(prob_t& p,prob_t& q)
{ if(!p && !q) return 0.0f;
return p*q/(p+q);
}
//symmetrized form of KL-divergence
prob_t ResistorAvg(Hist& p,Hist& q)
{
prob_t d12 = KLDiv(p,q), d21 = KLDiv(q,p); // why not call above func to be safe???
return (d12 * d21) / (d12 + d21);
}
//symmetrized form of KL-divergence
prob_t KLDivSym(HashHist& P,HashHist& Q)
{ float p=P.KLDiv(Q),q=Q.KLDiv(P);
return ResistorAvg(p,q);
}
//vZeroes = vector of dimensions that shouldn't contribute to calculations
//vZeroes[i] == 1 , iff you want to exclude dimension i
void CalcUDDist(vector< vector<Hist> >& vDistribs,int iClusts,vector<prob_t>& vcInf,vector< vector<prob_t> >& vcInfInter,vector<int>& vCounts,int iElems,vector<int>& vZeroes,bool bUseCounts)
{
if(vDistribs.size() != iClusts + 2) return;
vcInf = vector<prob_t>(iClusts+1);
vcInfInter = vector< vector<prob_t> >(iClusts+1);
int iC=1;
for(iC=1;iC<=iClusts;iC++) vcInfInter[iC] = vector<prob_t>(iClusts+1);
int iDims = vDistribs[1].size() , iD = 0;
//uniqueness from full distribution for each cluster
int iC1=1,iC2=1;
for(iC1=1;iC1<=iClusts;iC1++)
{
prob_t kldiv=0.0;
for(iD=0;iD<iDims;iD++)
{
if(vZeroes[iD]) continue;
kldiv += KLDiv(vDistribs[iC1][iD],vDistribs[iClusts+1][iD]);
}
vcInf[iC1] = kldiv;
}
//inter-cluster distinction measures, KL divergence between
//a cluster and cluster+other_cluster
for(iC1=1;iC1<=iClusts;iC1++)
{
for(iC2=1;iC2<=iClusts;iC2++)
{
if(iC1==iC2)
vcInfInter[iC1][iC2]=0.0;
else
{
for(iD=0;iD<iDims;iD++)
{
if(vZeroes[iD]) continue;
Hist oTmp = vDistribs[iC1][iD];
oTmp.Add(vDistribs[iC2][iD]);
vcInfInter[iC1][iC2] += KLDiv(vDistribs[iC1][iD],oTmp);
}
}
}
}
//add smallest inter-cluster KL-div
for(iC1=1;iC1<=iClusts;iC1++)
{
prob_t dMinInter = 9e10;
bool bFound = false;
if(vCounts[iC1])
for(iC2=1;iC2<=iClusts;iC2++)
{
if(iC1 != iC2 && vCounts[iC2] && vcInfInter[iC1][iC2] < dMinInter)
{
dMinInter = vcInfInter[iC1][iC2];
bFound = true;
}
}
if(bFound)
vcInf[iC1] += dMinInter;
}
if(bUseCounts)
{
for(iC1=1;iC1<=iClusts;iC1++)
{
vcInf[iC1] = ( (prob_t)vCounts[iC1] / iElems) * vcInf[iC1];
}
}
}
void CalcUDDist(vector< KDTreeHist >& vDistribs,vector< KDTreeHist >& vCompDistribs,int iClusts,vector<prob_t>& vcInf,vector< vector<prob_t> >& vcInfInter,vector<int>& vCounts)
{
if(vDistribs.size() != iClusts + 2 || vDistribs.size()!=vCompDistribs.size()) return;
vcInf = vector<prob_t>(iClusts+1);
vcInfInter = vector< vector<prob_t> >(iClusts+1);
int iC=1;
for(iC=1;iC<=iClusts;iC++) vcInfInter[iC] = vector<prob_t>(iClusts+1);
//uniqueness from full distribution for each cluster
int iC1=1,iC2=1;
for(iC1=1;iC1<=iClusts;iC1++)
vcInf[iC1] = KLDiv(vDistribs[iC1],vCompDistribs[iC1]);//KLDivSym(vDistribs[iC1],vCompDistribs[iC1]);
//inter-cluster distinction measures, KL divergence between
//a cluster and cluster+other_cluster
for(iC1=1;iC1<=iClusts;iC1++)
{
//for(iC2=iC1+1;iC2<=iClusts;iC2++)
for(iC1=1;iC2<=iClusts;iC2++)
{
if(iC1==iC2)
vcInfInter[iC1][iC2]=0.0;
else
//vcInfInter[iC1][iC2] = vcInfInter[iC2][iC1] = KLDivSym(vDistribs[iC1],vDistribs[iC2]);
vcInfInter[iC1][iC2] = KLDiv(vDistribs[iC1],vDistribs[iC2]);
}
}
//add smallest inter-cluster KL-div
for(iC1=1;iC1<=iClusts;iC1++)
{
prob_t dMinInter = 9e10;
bool bFound = false;
if(vCounts[iC1])
for(iC2=1;iC2<=iClusts;iC2++)
{
if(iC1 != iC2 && vCounts[iC2] && vcInfInter[iC1][iC2] < dMinInter)
{
dMinInter = vcInfInter[iC1][iC2];
bFound = true;
}
}
if(bFound)
vcInf[iC1] += dMinInter;
}
}
//calculates information gain as resistor average of all clusters against full distribution
//plus smallest resistor average between cluster and all other clusters
//vDistribs must have size of iClusts + 1
void CalcRDist(vector< vector<Hist> >& vDistribs,int iClusts,vector<prob_t>& vcInf,vector< vector<prob_t> >& vcInfInter)
{
if(vDistribs.size() != iClusts + 2) return;
vcInf = vector<prob_t>(iClusts+1);
vcInfInter = vector< vector<prob_t> >(iClusts+1);
int iC=1;
for(iC=0;iC<=iClusts;iC++) vcInfInter[iC] = vector<prob_t>(iClusts+1);
int iDims = vDistribs[1].size() , iD = 0;
//only need this for first time, since its recalculated for distributions who's
//points change, when they change
int iC1=1,iC2=1;
for(iC1=1;iC1<=iClusts;iC1++)
{
prob_t kldiv=0.0;
for(iD=0;iD<iDims;iD++)
{
kldiv += ResistorAvg(vDistribs[iC1][iD],vDistribs[iClusts+1][iD]);
}
vcInf[iC1]=kldiv;
}
//fill inter-cluster resistor averages
for(iC1=1;iC1<=iClusts;iC1++)
{
for(iC2=1;iC2<=iC1;iC2++)
{
if(iC1==iC2)
vcInfInter[iC1][iC2]=0.0;
else
{
for(iD=0;iD<iDims;iD++)
{
vcInfInter[iC1][iC2]+=ResistorAvg(vDistribs[iC1][iD],vDistribs[iC2][iD]);
}
vcInfInter[iC2][iC1]=vcInfInter[iC1][iC2];
}
}
}
//add largest inter-cluster resistor average
for(iC1=1;iC1<=iClusts;iC1++)
{
prob_t dMinInter = 9e10;
bool bFound = false;
for(iC2=1;iC2<=iClusts;iC2++)
{
if(iC1 != iC2 && vcInfInter[iC1][iC2] < dMinInter)
{
dMinInter = vcInfInter[iC1][iC2];
bFound = true;
}
}
if(bFound)
vcInf[iC1] += dMinInter;
}
}
double DistSQBG(KDTreeHist& oTree,Neighbor& oN,int iClustID,vector<int>& vClustIDs,int iNodeID)
{
if(vClustIDs[oN.m_id]!=iClustID)
return oN.m_dist;
int iNN = 5;
double fRad = 5. , fFctr = 5.;
vector<Neighbor> vnn;
while(true)
{
vnn.resize(iNN);
oTree.GetKNN(oTree[iNodeID],vnn,iNN,fRad,fFctr);
int i;
for(i=0;i<iNN;i++)
if(vClustIDs[vnn[i].m_id]!=iClustID)
return vnn[i].m_dist;
//fRad *= 2.0;
iNN*=2;
if(iNN >= oTree.NumElems())
return 1e5;
}
}
double DistSQSelf(KDTreeHist& oTree,Neighbor& oN,int iClustID,vector<int>& vClustIDs,int iNodeID)
{
if(vClustIDs[oN.m_id]==iClustID)
return oN.m_dist;
int iNN = 5;
double fRad = 5. , fFctr = 5.;
vector<Neighbor> vnn;
while(true)
{
vnn.resize(iNN);
oTree.GetKNN(oTree[iNodeID],vnn,iNN,fRad,fFctr);
int i;
for(i=0;i<iNN;i++)
if(vClustIDs[vnn[i].m_id]==iClustID)
return vnn[i].m_dist;
//fRad *= 2.0;
iNN*=2;
if(iNN >= oTree.NumElems())
return 1e5;
}
}
double DistD(KDTreeHist& oTree,Neighbor& oN,int iClustID,vector<int>& vClustIDs,int iNodeID)
{
double d1 = DistSQBG(oTree,oN,iClustID,vClustIDs,iNodeID) ,
d2 = DistSQSelf(oTree,oN,iClustID,vClustIDs,iNodeID);
if(d2) return d1 / d2;
}
prob_t Entropy(KDTreeHist& oTree,vector<Neighbor>& vNeighbors,int iClustID,vector<int>& vClustIDs)
{
//ScopedTimer S("Entropy...");
int iFast = 0,iSlow = 0;
prob_t dEntrop = 0.0;
int isz = vClustIDs.size() , iV = 0, iT = 0, iNN = 0;
double tsz = oTree.NumElems();
for(iV=0;iV<isz;iV++)
{
if(vClustIDs[iV]!=iClustID)
continue;
prob_t dDist = 0.0;
Neighbor& oN = vNeighbors[iV];
if(vClustIDs[oN.m_id]==iClustID && oN.m_dist>0.0)
{
dDist = oN.m_dist;
iFast++;
}
if(dDist <= 0.0)
{
dDist = oTree.GetNearestRadiusSQ(iT,true);
iSlow++;
}
if(dDist >= 0.0)
{
//prob_t dProb = oTree.RProb(MySqrt(dDist));
//if(dProb >= 0.0)
{
//dEntrop += dProb * log2(dProb);
dEntrop += log2(tsz*MySqrt(dDist));
}
}
iT++;
}
//dEntrop *= (oTree.NumDims() / oTree.NumElems());
dEntrop /= (double) isz;
//dEntrop +=
//double r = oTree.NumDims();
//double N = oTree.NumDims();
//double PI = 3.14159265;
//double Sr = r * pow(PI,r/2.0) / Gamma(N/2.0+1.0);
//double Sr = r * pow(PI,r/2.0) / Gamma(r/2.0+1.0);
//dEntrop += log2( Sr * (N-1.0) / r);
return dEntrop;
}
void CalcEXInfo(vector< vector< Hist> >& vDistribs,vector<prob_t>& vcInf,int iClusts,int iDim,vector<int>& vCounts,int iElems)
{
const bool bUseCounts = false;
int iC;
if(!vcInf.size()) vcInf = vector<prob_t>(iClusts+1);
for(iC=1;iC<=iClusts;iC++)
{
prob_t kldiv=0.0;
int iD=0;
for(iD=0;iD<iDim;iD++)
{
kldiv += KLDivApproxExclusiveProb(vDistribs[iC][iD],vDistribs[iClusts+1][iD]);
}
if(bUseCounts)
vcInf[iC] = ( (prob_t)vCounts[iC] / (prob_t)iElems ) * kldiv;
else
vcInf[iC] = kldiv;
}
}
//which 2D slices do we skip?
//slices that are X vs X or
//T1-V(peak) and T1-Peak are highly correlated so skip them too
inline bool SkipPair(int idx1,int idx2)
{
if(idx1==idx2) // same dimensions or...
return true;
// idx 0 thru 3 == T1,2,3,4-Peak
// idx 4 thru 7 == T1,2,3,4-V(peak)
// idx 8 thru 11 == T1,2,3,4-Valley
// idx 12 thru 15 == T1,2,3,4-V-(valley)
return (idx1==0 && idx2==4)|| // 0,4 4,0 T1-Peak and T1-V(peak)
(idx1==4 && idx2==0)||
(idx1==1 && idx2==5)|| // 1,5 5,1 T2-Peak and T2-V(peak)
(idx1==5 && idx2==1)||
(idx1==2 && idx2==6)|| // 2,6 6,2 T3-Peak and T3-V(peak)
(idx1==6 && idx2==2)||
(idx1==3 && idx2==7)|| // 3,7 7,3 T4-Peak and T4-V(peak)
(idx1==7 && idx2==3)||
(idx1==8 && idx2==12)|| // 8,12 12,8 T1-Valley and T1-V(valley)
(idx1==12 && idx2==8)||