aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/lipi-toolkit/3rdparty/lipi-toolkit/src/util/lib/LTKHierarchicalClustering.h
blob: 921c60856898ee5f21181e90ea76d2961905b465 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
/*****************************************************************************************
* Copyright (c) 2006 Hewlett-Packard Development Company, L.P.
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*****************************************************************************************/

/************************************************************************
 * FILE DESCR: Definitions of Agglomerative Hierarchical Clustering module
 *
 * CONTENTS:
 *             cluster
 *             getProximityMatrix
 *             setOutputConfig
 *             setHyperlinkMap
 *             getClusterResult
 *             computeProximityMatrix
 *             computeDistances
 *             clusterToFindNumClusters
 *             getInterObjectDistance
 *             findGroup
 *             findInterClusterDistance
 *             writeClustersAsHTML
 *             determineNumOfClusters
 *             determineKnee
 *             findRMSE
 *             computeAvgSil
 *
 *
 * AUTHOR:     Bharath A
 *
 * DATE:       February 22, 2005
 * CHANGE HISTORY:
 * Author      Date           Description of change
 ************************************************************************/
#ifndef __LTKHIERARCHICALCLUSTERING_H
#define __LTKHIERARCHICALCLUSTERING_H


#ifndef _WIN32
//#include <values.h>
#endif

#include "LTKInc.h"
#include "LTKTypes.h"
#include "LTKLoggerUtil.h"
#include "LTKException.h"
#include "LTKErrors.h"

/*Enumerator for stopping criterion to be used*/
enum ELTKHCStoppingCriterion
{
     LMETHOD,
     AVG_SIL
};

/*Enumerator for methods in hierarchical clustering*/
 enum ELTKHCMethod
 {
     SINGLE_LINKAGE,
     COMPLETE_LINKAGE,
     AVERAGE_LINKAGE
 };

#define OUTPUT_HTML_FILE_NAME "output.html"
#define MIN_CUTOFF 20

/**
 * @class LTKHierarchicalClustering
 * <p> This class does agglomerative hierarchical clustering. The data objects
        which could be LTKTrace or LTKTraceGroup, are supplied as a vector.
        Function that defines the distance between two data objects needs to be
       supplied as a function pointer.One of the 3 methods (Single,Average or
       Complete linkage) needs to be selected to define the way inter-cluster
       has to be determined. In case number of clusters is not supplied,
       it is determined using the L-method (default stopping criterion)<p> */

template <class ClusterObjType,class DistanceClass>
class LTKHierarchicalClustering
{

     private:

          //reference to the vector containing the data objects to be clustered
         const vector<ClusterObjType>& m_data;

          //triangular matrix containing the pairwise distances between data
          //objects
          float2DVector m_proximityMatrix;

          //data structure that stores current (intermediate) state of the
          //clusters
          int2DVector m_intermediateCG;

          //vector mapping the data object id and path to the data (unipen) file
          stringVector m_hyperlinksVec;

          //contains the number of clusters required
          int m_numOfClusters;

          //output file handle to write the cluster results as html
          //with name of the file as OUTPUT_HTML_FILE_NAME
          ofstream m_output;

          //flag to indicate whether the output is required as html
          bool m_writeHTML;

          //flag to indicate whether to show all levels of the hierarchy in the
          //html file
          bool m_showAllLevels;

          //vector to hold merging distance for each number of clusters
          floatVector m_mergingDist;

          //flag for determining number of clusters
          bool m_determineClusters;

          //output result directory
          string m_outputDir;

          //extension of the image corresponding to each data object in
          //order to write in the html
          string m_imageFileExtn;

          //Method for defining inter-cluster distance
          ELTKHCMethod m_method;

           //number of clusters determined by Average Silhouette method
          int m_numBySil;

          //cached clustering result corresponding minimum average silhouette
          int2DVector m_cachedResult;

          //stopping criterion selected - LMethod or Average Silhouette
          ELTKHCStoppingCriterion m_stoppingCriterion;

          //pointer to the class that has the definition of distance function
          DistanceClass* m_distClassPtr;

          //function pointer type of the function that defines inter-object distance
          typedef int (DistanceClass::*FN_PTR_DISTANCE)(const ClusterObjType&,
                                                      const ClusterObjType&,
                                                      float&) ;

          //distance function pointer
          FN_PTR_DISTANCE m_distancePtr;


     public:

/**********************************************************************************
* AUTHOR       : Bharath A
* DATE              : 22-FEB-2005
* NAME              : LTKHierarchicalClustering
* DESCRIPTION  : Constructor to initialise the required parameters
* ARGUMENTS         : clusterObjects - vector of data objects which could be LKTrace or
*                                            LTKTraceGroup for HWR
*                     noOfClusters - Number of clusters required
*                     clusteringMethod - One of the 3 methods:
*                                             SINGLE_LINKAGE,AVERAGE_LINKAGE
*                                             or COMPLETE_LINKAGE
*
* RETURNS      :
* NOTES             :
* CHANGE HISTROY
* Author            Date                Description of change
*************************************************************************************/


LTKHierarchicalClustering(const vector<ClusterObjType>& clusterObjects,int noOfClusters,
                                ELTKHCMethod clusteringMethod=AVERAGE_LINKAGE) :
                                m_data(clusterObjects),m_method(clusteringMethod),
                                m_numOfClusters(noOfClusters),m_writeHTML(false),
                                m_showAllLevels(false),
                                m_determineClusters(false)
{

     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Entering: "
          <<"LTKHierarchicalClustering::LTKHierarchicalClustering"
          <<"(vector<ClusterObjType>,int,ELTKHCMethod)"<<endl;

     if(m_numOfClusters < 1 || m_numOfClusters>=clusterObjects.size())
     {
           LOG(LTKLogger::LTK_LOGLEVEL_ERR)
                <<"Number of clusters:"<<m_numOfClusters<<endl;

           LOG(LTKLogger::LTK_LOGLEVEL_ERR)
               <<"Error : "<< EINVALID_NUM_CLUSTERS <<":"<< getErrorMessage(EINVALID_NUM_CLUSTERS)
            <<" LTKHierarchicalClustering::"
               <<"LTKHierarchicalClustering(vector<ClusterObjType>,int,ELTKHCMethod)"<<endl;

          throw LTKException(EINVALID_NUM_CLUSTERS);
     }

     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Exiting: "
          <<"LTKHierarchicalClustering::LTKHierarchicalClustering"
          <<"(vector<ClusterObjType>,int,ELTKHCMethod)"<<endl;

}


/**********************************************************************************
* AUTHOR       : Bharath A
* DATE              : 22-FEB-2005
* NAME              : LTKHierarchicalClustering
* DESCRIPTION  : Constructor to initialise the required parameters.
*                 Number of clusters is determined by L-method
* ARGUMENTS         : clusterObjects - vector of data objects which could be LKTrace or
*                                            LTKTraceGroup for HWR
*                     clusteringMethod - One of the 3 methods:
*                                             SINGLE_LINKAGE,AVERAGE_LINKAGE
*                                             or COMPLETE_LINKAGE
*                     stoppingCriterion - stopping criterion to determine the
*                                              right set of clusters: LMETHOD or AVG_SIL
*
* RETURNS      :
* NOTES             :
* CHANGE HISTROY
* Author            Date                Description of change
*************************************************************************************/


LTKHierarchicalClustering(const vector<ClusterObjType>& clusterObjects,
                                ELTKHCMethod clusteringMethod=AVERAGE_LINKAGE,
                                ELTKHCStoppingCriterion stoppingCriterion=LMETHOD) :
                                m_data(clusterObjects),
                                m_method(clusteringMethod),
                                m_stoppingCriterion(stoppingCriterion),
                                m_writeHTML(false),
                                m_showAllLevels(false),
                                m_determineClusters(true)
{

     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Entering: "
          <<"LTKHierarchicalClustering::LTKHierarchicalClustering"
          <<"(vector<ClusterObjType>,ELTKHCMethod,ELTKHCStoppingCriterion)"<<endl;

     if(clusterObjects.size()==0)
     {
          LOG(LTKLogger::LTK_LOGLEVEL_ERR)
               <<"Number of elements in clusterObjects vector is zero"<<endl;

           LOG(LTKLogger::LTK_LOGLEVEL_ERR)
               <<"Error : "<< ENO_DATA_TO_CLUSTER <<":"<< getErrorMessage(ENO_DATA_TO_CLUSTER)
            <<" LTKHierarchicalClustering::LTKHierarchicalClustering"
               <<"(vector<ClusterObjType>,ELTKHCMethod,ELTKHCStoppingCriterion)"<<endl;


          throw LTKException(ENO_DATA_TO_CLUSTER);
     }

     if(clusterObjects.size() < 6 && stoppingCriterion == LMETHOD)
     {
          LOG(LTKLogger::LTK_LOGLEVEL_ERR)
               <<"Number of elements in clusterObjects vector is:"
               <<clusterObjects.size()<<endl;

           LOG(LTKLogger::LTK_LOGLEVEL_ERR)
               <<"Error : "<< EINSUFFICIENT_DATA_FOR_LMETHOD
               <<":"<< getErrorMessage(EINSUFFICIENT_DATA_FOR_LMETHOD)
            <<" LTKHierarchicalClustering::LTKHierarchicalClustering"
               <<"(vector<ClusterObjType>,ELTKHCMethod,ELTKHCStoppingCriterion)"<<endl;

          throw LTKException(EINSUFFICIENT_DATA_FOR_LMETHOD);
     }

     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Exiting: "
          <<"LTKHierarchicalClustering::LTKHierarchicalClustering"
          <<"(vector<ClusterObjType>,ELTKHCMethod,ELTKHCStoppingCriterion)"<<endl;

}



/**********************************************************************************
* AUTHOR       : Bharath A
* DATE              : 22-FEB-2005
* NAME              : cluster
* DESCRIPTION  : Clusters the input data objects. The number of clusters is determined
*                     based on the stopping criterion or as specified by the user.
* ARGUMENTS         : distanceClassPtr - pointer to the class that contains the distance
*                                             function defintion
*                     distFuncPtr - distance function pointer
* RETURNS      : error code
* NOTES             :
* CHANGE HISTROY
* Author            Date                Description of change
*************************************************************************************/
int cluster(DistanceClass* distanceClassPtr,FN_PTR_DISTANCE distFuncPtr)
{

     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Entering: "
          <<"LTKHierarchicalClustering::cluster()"<<endl;


     m_distancePtr=distFuncPtr;

     m_distClassPtr=distanceClassPtr;


     //To compute inter-object distances
     int errorCode = computeDistances();

     if (errorCode != SUCCESS )
     {
          LOG(LTKLogger::LTK_LOGLEVEL_ERR)
        <<"Error: LTKHierarchicalClustering::cluster()"<<endl;

          LTKReturnError(errorCode)
     }

     //if the user has specified the number of clusters
     if(!m_determineClusters)
     {
           clusterToFindNumClusters();
     }
     else
     {
               m_numOfClusters=1;

               //clustering to determine the number of
               //clusters vs merging distance curve
               clusterToFindNumClusters();

               m_determineClusters=false;

               if(m_stoppingCriterion==LMETHOD)
               {
                    //Number of clusters determined by L-method
                   m_numOfClusters=determineNumOfClusters();

                    LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
                         <<"Number of clusters determined using L-Method"
                         <<m_numOfClusters<<endl;

               }
               else if(m_stoppingCriterion==AVG_SIL)
               {

                    //Number of clusters determined by silhouette method
                   m_numOfClusters=m_numBySil;

                    LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
                         <<"Number of clusters determined using Average Silhouette method"
                         <<m_numOfClusters<<endl;

               }

               //clearing intermediate clusters formed during evaluation
               //of the stopping criterion
               m_intermediateCG.clear();

               //clustering to the number of clusters determined
               //by the stopping criterion
               clusterToFindNumClusters();

       }


     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Exiting: "
          <<"LTKHierarchicalClustering::cluster()"<<endl;
      return SUCCESS;

}



/**********************************************************************************
* AUTHOR       : Dinesh M
* DATE              : 23-Jan-2006
* NAME              : getProximityMatrix
* DESCRIPTION  : returns the distance matrix
* ARGUMENTS         :
* RETURNS      : proximity matrix (float2DVector)
* NOTES             :
* CHANGE HISTROY
* Author            Date                Description of change
*************************************************************************************/

const float2DVector& getProximityMatrix() const
{

     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Entering: "
          <<"LTKHierarchicalClustering::getProximityMatrix()"<<endl;


     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Exiting: "
          <<"LTKHierarchicalClustering::getProximityMatrix()"<<endl;

     return m_proximityMatrix;
}


/**********************************************************************************
* AUTHOR       : Bharath A
* DATE              : 22-FEB-2005
* NAME              : setOutputConfig
* DESCRIPTION  : This function sets the configuration for the output of clustering.
* ARGUMENTS         : outputDirectory - path to the directory where output html
*                                            is to be generated
*                     displayAllLevels - flag to indicate whether all levels in the
*                                             clustering need to written to the file
*                     imageFileExtension - extension of the image file (ex)"png".
*                                            If not specified <img> tag in the output html is not created.
* RETURNS      : error code
* NOTES             :
* CHANGE HISTROY
* Author            Date                Description of change
*************************************************************************************/
//int setOutputConfig(const string& outputDirectory,
//                              bool displayAllLevels=false,
//                              string imageFileExtension="")
int setOutputConfig(const string& outputDirectory,bool displayAllLevels=false,
                         const string& imageFileExtension="")
{

     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Entering: "
          <<"LTKHierarchicalClustering::setOutputConfig()"<<endl;

     m_writeHTML=true;

     m_showAllLevels=displayAllLevels;

     string tempOutputFilePath=outputDirectory+"/"+OUTPUT_HTML_FILE_NAME;

     m_output.open(tempOutputFilePath.c_str());

     if(m_output.fail())
     {

          LOG(LTKLogger::LTK_LOGLEVEL_ERR)
               <<"Unable to create file:"
               <<tempOutputFilePath<<endl;

          LOG(LTKLogger::LTK_LOGLEVEL_ERR)
               <<"Error : "<< EFILE_CREATION_FAILED <<":"
               <<getErrorMessage(EFILE_CREATION_FAILED)
            <<" LTKHierarchicalClustering::setOutputConfig()" <<endl;

          LTKReturnError(EFILE_CREATION_FAILED)
     }

     m_outputDir=outputDirectory;

     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
          <<"Clustering results output directory:"
          <<m_outputDir<<endl;

     m_output.close();

     //If it takes the default value, <img> tag in the output is not generated
     m_imageFileExtn=imageFileExtension;

     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
          <<"Image file extension:"<<m_imageFileExtn<<endl;

     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Exiting: "
          <<"LTKHierarchicalClustering::setOutputConfig()"<<endl;

     return SUCCESS;
}


/**********************************************************************************
* AUTHOR       : Bharath A
* DATE              : 22-FEB-2005
* NAME              : setHyperlinkMap
* DESCRIPTION  : To set hyperlinks for each data object which refers to actual data file.
*                     Assumes one-to-one correspondence with the data vector
*                     passed in the constructor.
* ARGUMENTS         : hyperlinksVector - Vector containing paths to physical
*                                             files of each data object.
*
* RETURNS      : error code
* NOTES             :
* CHANGE HISTROY
* Author            Date                Description of change
*************************************************************************************/
//int setHyperlinkMap(const vector<string>& hyperlinksVector)
int setHyperlinkMap(const vector<string>& hyperlinksVector)
{

     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Entering: "
          <<"LTKHierarchicalClustering::setHyperlinkMap()"<<endl;

     if(m_data.size()!=hyperlinksVector.size())
     {
          LOG(LTKLogger::LTK_LOGLEVEL_ERR)
               <<"cluster objects vector size:"<<m_data.size()
               <<" and hyperlinks vector size:"<<hyperlinksVector.size()<<endl;

          LOG(LTKLogger::LTK_LOGLEVEL_ERR)
               <<"Error : "<< EDATA_HYPERLINK_VEC_SIZE_MISMATCH
               <<":"<< getErrorMessage(EDATA_HYPERLINK_VEC_SIZE_MISMATCH)
            <<" LTKHierarchicalClustering::setHyperlinkMap()" <<endl;

          LTKReturnError(EDATA_HYPERLINK_VEC_SIZE_MISMATCH);
     }

     m_hyperlinksVec=hyperlinksVector; //Vector for hyperlinks is set


     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Exiting: "
          <<"LTKHierarchicalClustering::setHyperlinkMap()"<<endl;

     return SUCCESS;

}


/**********************************************************************************
* AUTHOR       : Bharath A
* DATE              : 22-FEB-2005
* NAME              : getClusterResult
* DESCRIPTION  : Populates the argument (vector of vectors) with data objects indices.
*                     Each row (inner vector) corresponds to a cluster.
* ARGUMENTS         : outClusterResult - reference to result vector of vectors.
*
* RETURNS      :
* NOTES             :
* CHANGE HISTROY
* Author            Date                Description of change
*************************************************************************************/
void getClusterResult(vector<vector<int> >& outClusterResult) const
{
     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Entering: "
          <<"LTKHierarchicalClustering::getClusterResult()"<<endl;

     for(int v=0;v<m_intermediateCG.size();v++)
     {

          outClusterResult.push_back(m_intermediateCG[v]);
     }

     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Exiting: "
          <<"LTKHierarchicalClustering::getClusterResult()"<<endl;
}

/**********************************************************************************
* AUTHOR       : Bharath A
* DATE              : 22-FEB-2005
* NAME              : computeProximityMatrix
* DESCRIPTION  : Populates the argument (vector of vectors) with data objects indices.
*                     Each inner vector corresponds to a cluster.
* ARGUMENTS         : distanceClassPtr - pointer to the class that has the distance definition
*                     distFuncPtr - function pointer to the distance function
* RETURNS      : error code
* NOTES             :
* CHANGE HISTROY
* Author            Date                Description of change
*************************************************************************************/

//void computeProximityMatrix(ComputeDistanceFunc computeDistFuncObj)
int computeProximityMatrix(DistanceClass* distanceClassPtr,
                                 FN_PTR_DISTANCE distFuncPtr)
{
     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Entering: "
          <<"LTKHierarchicalClustering::computeProximityMatrix()"<<endl;

     m_distancePtr=distFuncPtr;
     m_distClassPtr=distanceClassPtr;

     int errorCode;

     if((errorCode=computeDistances())!=SUCCESS)
     {
           LOG(LTKLogger::LTK_LOGLEVEL_ERR)
               <<"Error: LTKHierarchicalClustering::computeProximityMatrix()"<<endl;

          LTKReturnError(errorCode);
     }

     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Exiting: "
          <<"LTKHierarchicalClustering::computeProximityMatrix()"<<endl;

     return SUCCESS;
}



private:

/**********************************************************************************
* AUTHOR       : Bharath A
* DATE              : 22-FEB-2005
* NAME              : computeDistances
* DESCRIPTION  : Computes inter-object distances and puts them in the distance matrix
* ARGUMENTS         :
* RETURNS      : error code
* NOTES             :
* CHANGE HISTROY
* Author            Date                Description of change
*************************************************************************************/

int computeDistances()
{

     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Entering: "
          <<"LTKHierarchicalClustering::computeDistances()"<<endl;

     for(int i=0;i<(m_data.size()-1);++i)
     {
          vector<float> eachRow((m_data.size()-i)-1);//added -1 at the end

          int c=0;

          for(int j=i+1;j<m_data.size();++j)
          {
               //external distance function called
               int errorCode = (m_distClassPtr->*m_distancePtr)(m_data[i],m_data[j], eachRow[c]);

               if (errorCode != SUCCESS )
               {
                    LOG(LTKLogger::LTK_LOGLEVEL_ERR)
                         <<"Error while calling distance function"<<endl;

                    LOG(LTKLogger::LTK_LOGLEVEL_ERR)
                         <<"Error: LTKHierarchicalClustering::computeDistances()"<<endl;

                    LTKReturnError(errorCode);
               }

               ++c;

          }

          m_proximityMatrix.push_back(eachRow);

     }

     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Exiting: "
          <<"LTKHierarchicalClustering::computeDistances()"<<endl;

    return SUCCESS;

}



/**********************************************************************************
* AUTHOR       : Bharath A
* DATE              : 22-FEB-2005
* NAME              : clusterToFindNumClusters
* DESCRIPTION  : Clusters the data objects hierarchically (agglomerative)
*                     till the desired number of
*                     clusters and also evaluates the stopping criterion selected.
* ARGUMENTS         :
* RETURNS      : error code
* NOTES             :
* CHANGE HISTROY
* Author            Date                Description of change
*************************************************************************************/

int clusterToFindNumClusters()
{

     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Entering: "
          <<"LTKHierarchicalClustering::clusterToFindNumClusters()"<<endl;

   if(m_stoppingCriterion==LMETHOD)
   {
          //Number of clusters needs to be determined
          if(m_determineClusters)
          {
               //map for number of clusters vs. merging distance
               m_mergingDist.reserve(m_data.size());
          }
   }
   else if(m_stoppingCriterion==AVG_SIL)
   {
          if(m_writeHTML==false && m_cachedResult.size()>0)
          {
               m_intermediateCG=m_cachedResult;

               return SUCCESS;
          }
   }

     for(int i=0;i<m_data.size();i++)
     {
          vector<int> v;
          v.push_back(i);

          //To begin with, each data object is cluster by itself
          m_intermediateCG.push_back(v);
     }

     if(m_writeHTML)  //If output is needed as html
     {
          string outputFilePath=m_outputDir+"/"+OUTPUT_HTML_FILE_NAME;

          m_output.open(outputFilePath.c_str()); //Cluster output file is created

          if(m_output.fail())
          {
               LOG(LTKLogger::LTK_LOGLEVEL_ERR)
                    <<"Unable to create file:"
                    <<outputFilePath<<endl;

               LOG(LTKLogger::LTK_LOGLEVEL_ERR)
                    <<"Error : "<< EFILE_CREATION_FAILED
                    <<":"<< getErrorMessage(EFILE_CREATION_FAILED)
                <<" LTKHierarchicalClustering::clusterToFindNumClusters()" <<endl;

               LTKReturnError(EFILE_CREATION_FAILED);
          }

          /*Html tags are written*/
          m_output<<"<html>\n";
          m_output<<"<body>\n";
          m_output<<"<table border='1' bordercolor='black'>\n";


          m_output<<"<tr>\n";


          for(int v=0;v<m_intermediateCG.size();v++)
          {

               int clusterSize=m_intermediateCG[v].size();

               m_output<<"<td colspan=\""<<clusterSize<<"\">";

               for(int w=0;w<clusterSize;w++)
               {
                    if(m_hyperlinksVec.size()>0)
                    {
                         m_output<<"<a href='"
                                   <<m_hyperlinksVec[m_intermediateCG[v][w]]
                                   <<"'>"<<m_intermediateCG[v][w]<<"</a>&nbsp;";
                    }
                    else
                    {
                         m_output<<m_intermediateCG[v][w]<<"&nbsp;";
                    }

                    //if there is an image file corresponding to each data object
                    if(!m_imageFileExtn.empty())
                    {
                         m_output<<"<img src=\""
                                   <<m_intermediateCG[v][w]<<"."<<m_imageFileExtn
                                   <<"\" border=\"0\"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                    }


               }
          }

          m_output<<"<td><b>";
          m_output<<"Inter-cluster Dist";
          m_output<<"</b></td>";

          m_output<<"</tr>\n";

     }

     if(m_numOfClusters<m_data.size() || m_determineClusters==true)
     {

          int currNumOfClusters = m_data.size();

          //this local variable is used only for Average Silhouette method
          float minSil=FLT_MAX;


          for(int it=0;it<(m_data.size()-m_numOfClusters);++it)
          {
               vector<int> toCluster;

               //to find the clusters that need to be merged
               float interClusterDistance=findGroup(toCluster);

               currNumOfClusters=m_data.size()-it-1;

               if(m_stoppingCriterion==AVG_SIL)
               {
                    float silDiff=computeAvgSil(toCluster[0],toCluster[1]);

                    if(silDiff<minSil)
                    {
                         minSil=silDiff;
                         if(currNumOfClusters > 2)
                         {
                              m_numBySil=currNumOfClusters+1;
                              m_cachedResult=m_intermediateCG;
                         }

                    }
               }
               else if(m_stoppingCriterion==LMETHOD && m_determineClusters==true)
               {
                         m_mergingDist[currNumOfClusters]=interClusterDistance;
               }


               //clusters are merged
               m_intermediateCG[toCluster[0]].insert(m_intermediateCG[toCluster[0]].end(),
                                                              m_intermediateCG[toCluster[1]].begin(),
                                                              m_intermediateCG[toCluster[1]].end());

               //old cluster deleted
               m_intermediateCG.erase(m_intermediateCG.begin()+ toCluster[1]);



                    if(m_writeHTML)
                    {
                         if(!m_showAllLevels)
                         {
                              if(currNumOfClusters==m_numOfClusters)
                              {
                                   writeClustersAsHTML(interClusterDistance);
                              }
                         }
                         else
                         {
                              writeClustersAsHTML(interClusterDistance);
                         }

                    }


          }


     }


     //closing the html tags
     if(m_writeHTML)
     {
          m_output<<"</table>\n";
          m_output<<"</body>\n";
          m_output<<"</html>";

          m_output.close();
     }

     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Exiting: "
          <<"LTKHierarchicalClustering::clusterToFindNumClusters()"<<endl;

     return SUCCESS;

}







/**********************************************************************************
* AUTHOR       : Bharath A
* DATE              : 22-FEB-2005
* NAME              : getInterObjectDistance
* DESCRIPTION  : Returns the distance between two data objects from the distance matrix
* ARGUMENTS         : firstObjIndex - index of the first data object
*                     secondObjIndex -  index of the second data object
* RETURNS      : distance (float)
* NOTES             :
* CHANGE HISTROY
* Author            Date                Description of change
*************************************************************************************/
float getInterObjectDistance(int firstObjIndex,int secondObjIndex) const
{
     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Entering: "
          <<"LTKHierarchicalClustering::getInterObjectDistance()"<<endl;

     int row = 0;
     int col = 0;

     if(firstObjIndex < secondObjIndex)
     {
          row=firstObjIndex;
          col=secondObjIndex;
     }
     else
     {
          row=secondObjIndex;
          col=firstObjIndex;
     } //lesser index is made as row and the other as column

     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Exiting: "
          <<"LTKHierarchicalClustering::getInterObjectDistance()"<<endl;

     return m_proximityMatrix[row][col-row-1];
}

/**********************************************************************************
* AUTHOR       : Bharath A
* DATE              : 22-FEB-2005
* NAME              : findGroup
* DESCRIPTION  : Finds the indices in the m_intermediateCG (clusters) that
*                     need to be merged
* ARGUMENTS         : pairToCombine - vector for storing the cluster indices
* RETURNS      : inter cluster distance (float)
* NOTES             :
* CHANGE HISTROY
* Author            Date                Description of change
*************************************************************************************/
//double findGroup(vector<int> pairToCombine)
float findGroup(vector<int>& pairToCombine) const
{
     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Entering: "
          <<"LTKHierarchicalClustering::findGroup()"<<endl;

     float minDistance=FLT_MAX;

     pairToCombine.clear();

     pairToCombine.resize(2);

     for(int i=0;i<m_intermediateCG.size();i++)
     {
          for(int j=i+1;j<m_intermediateCG.size();j++)
          {
               float tempDist=findInterClusterDistance(m_intermediateCG[i],
                                                                  m_intermediateCG[j]);

               if(tempDist<minDistance)
               {

                    minDistance=tempDist;
                    pairToCombine[0]=i;
                    pairToCombine[1]=j;
               }
          }

     }

     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Exiting: "
          <<"LTKHierarchicalClustering::findGroup()"<<endl;


     return minDistance;

}


/**********************************************************************************
* AUTHOR       : Bharath A
* DATE              : 22-FEB-2005
* NAME              : findInterClusterDistance
* DESCRIPTION  : Finds the inter-cluster distance.
*                     The contents of each cluster are in the vectors.
* ARGUMENTS         : v1 cluster one
*                     v2 cluster two
* RETURNS      : inter cluster distance
* NOTES             :
* CHANGE HISTROY
* Author            Date                Description of change
*************************************************************************************/

//double findInterClusterDistance(const vector<int>& v1,const vector<int>& v2)
float findInterClusterDistance(const vector<int>& cluster1, const vector<int>& cluster2) const
{
     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Entering: "
          <<"LTKHierarchicalClustering::findInterClusterDistance()"<<endl;

     float groupDistance=0.0;

     /*For single-linkage algorithm*/
     if(m_method==SINGLE_LINKAGE)
     {
          groupDistance= FLT_MAX;

          for(int i=0;i<cluster1.size();i++)
          {
               for(int j=0;j<cluster2.size();j++)
               {
                    float temp=getInterObjectDistance(cluster1[i],cluster2[j]);

                    if(temp < groupDistance)
                    {
                         groupDistance=temp;
                    }
               }
          }
     }


     /*For average-linkage algorithm*/
     if(m_method==AVERAGE_LINKAGE)
     {
          groupDistance=0.0;

          for(int i=0;i<cluster1.size();i++)
          {
               for(int j=0;j<cluster2.size();j++)
               {

                    groupDistance+=getInterObjectDistance(cluster1[i],cluster2[j]);
               }
          }

          groupDistance/=((float)(cluster1.size()*cluster2.size()));
     }


     /*For complete-linkage algorithm*/
     if(m_method==COMPLETE_LINKAGE)
     {
          groupDistance=0.0;

          for(int i=0;i<cluster1.size();i++)
          {
               for(int j=0;j<cluster2.size();j++)
               {
                    float temp=getInterObjectDistance(cluster1[i],cluster2[j]);

                    if(temp > groupDistance)
                    {
                         groupDistance=temp;
                    }
               }
          }
     }

     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Exiting: "
          <<"LTKHierarchicalClustering::findInterClusterDistance()"<<endl;


     return groupDistance;


}

/**********************************************************************************
* AUTHOR       : Bharath A
* DATE              : 22-FEB-2005
* NAME              : writeClustersAsHTML
* DESCRIPTION  : Writes the cluster results as html with data objects' and clusters' ids.
*                     If hyperlinks vector is set, provides links to actual files.
* ARGUMENTS         : interClustDist - merging distance of the new cluster formed
* RETURNS      :
* NOTES             :
* CHANGE HISTROY
* Author            Date                Description of change
*************************************************************************************/

void writeClustersAsHTML(float interClustDist)
{

     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Entering: "
          <<"LTKHierarchicalClustering::writeClustersAsHTML()"<<endl;

     m_output<<"<tr>\n";

     for(int v=0;v<m_intermediateCG.size();v++)
     {
          int clusterSize=m_intermediateCG[v].size();

          m_output<<"<td colspan=\""<<clusterSize<<"\">";

          m_output<<"("<<v<<")<br>";

          for(int w=0;w<clusterSize;w++)
          {
               if(m_hyperlinksVec.size()>0)
               {
                    m_output<<"<a href='"<<m_hyperlinksVec[m_intermediateCG[v][w]]
                            <<"'>"<<m_intermediateCG[v][w]<<"</a>&nbsp;";
               }
               else
               {
                    m_output<<m_intermediateCG[v][w]<<"&nbsp;";
               }
               if(!m_imageFileExtn.empty())
               {
                    m_output<<"<img src=\""<<m_intermediateCG[v][w]<<"."
                            <<m_imageFileExtn
                            <<"\" border=\"0\"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
               }

          }
     }

     m_output<<"<td>";

     m_output<<"("<<m_intermediateCG.size()
               <<")&nbsp;&nbsp;&nbsp;<b>"<<interClustDist<<"</b>";

     m_output<<"</td>";

     m_output<<"</tr>\n";

     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Exiting: "
          <<"LTKHierarchicalClustering::writeClustersAsHTML()"<<endl;

}

/**********************************************************************************
* AUTHOR       : Bharath A
* DATE              : 22-FEB-2005
* NAME              : determineNumOfClusters
* DESCRIPTION  : Determines the number of clusters to be formed using
*                     iterative refinement of L-method.
*                     REFERENCE:S. Salvador and P. Chan. Determining the number of clusters/
*                     segments in hierarchical clustering/segmentation algorithms.
*                     Proceedings of 16th IEEE International Conference
*                     on Tools with Artificial Intelligence, 3:1852-1857, 2004.
* ARGUMENTS         :
* RETURNS      : number of clusters
* NOTES             :
* CHANGE HISTROY
* Author            Date                Description of change
*************************************************************************************/

int determineNumOfClusters() const
{
     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Entering: "
          <<"LTKHierarchicalClustering::determineNumOfClusters()"<<endl;

     int cutOff=(int)m_mergingDist.capacity()-1;

     int lastKnee=0;
     int currentKnee=0;

     lastKnee=cutOff;

     currentKnee=lastKnee;

     bool trueCutOff=false;

     /*Iterative refinement of the L-method result*/

     while(true)
     {

          lastKnee=currentKnee;

          currentKnee=determineKnee(cutOff);

          if(trueCutOff)
          {

               if(currentKnee >= lastKnee)
               {

                    break;
               }
          }

          int temp=currentKnee*2;

          if(temp>cutOff)
          {
               --cutOff;

               trueCutOff=false;
          }
          else
          {
               cutOff=temp;

               trueCutOff=true;
          }


          if(cutOff < MIN_CUTOFF)
          {

               break;
          }


     }

     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)
          <<"Number of clusters determined by iterative refinement:"
          <<currentKnee<<endl;

     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Exiting: "
          <<"LTKHierarchicalClustering::determineNumOfClusters()"<<endl;

     return currentKnee;
}




/**********************************************************************************
* AUTHOR       : Bharath A
* DATE              : 22-FEB-2005
* NAME              : determineKnee
* DESCRIPTION  : Determines the knee of the given number of clusters vs. merging distance curve
* ARGUMENTS         : maxNumClusters - maximum number of clusters
* RETURNS      : knee point of the curve
* NOTES             :
* CHANGE HISTROY
* Author            Date                Description of change
*************************************************************************************/
int determineKnee(int maxNumClusters) const
{
     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Entering: "
          <<"LTKHierarchicalClustering::determineKnee()"<<endl;

     int result=0;

     float minRMSE = FLT_MAX;

     //atleast two points are required to fit lines, hence c ranges
     //from 3 to maxNumClusters-2
     for(int c=3;c<maxNumClusters-2;c++)
     {

          float lRMSE=0,rRMSE=0;

          findRMSE(c,maxNumClusters,lRMSE,rRMSE);

          float     cRMSE=(((float)(c-1)/(float)(maxNumClusters-1))*lRMSE)
                           +(((float)(maxNumClusters-c)/(float)(maxNumClusters-1))*rRMSE);

          if(cRMSE<minRMSE)
          {

               minRMSE=cRMSE;

               result=c;
          }
     }

     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Exiting: "
          <<"LTKHierarchicalClustering::determineKnee()"<<endl;

     return result+1;
}




/**********************************************************************************
* AUTHOR       : Bharath A
* DATE              : 22-FEB-2005
* NAME              : determineKnee
* DESCRIPTION  : Determines left and right RMSE values of the given point
*                     on the no. of clusters vs. merging distance curve.
*                     It fits two regression lines on either side of the point to find RMSEs
* ARGUMENTS         : candidateKnee - candidata knee point
*                     maxNumClusters - upper bound on number of clusters
*                     lRMSE - output RMSE on the left of c
*                     rRMSE - output RMSE on the right of c
* RETURNS      :
* NOTES             :
* CHANGE HISTROY
* Author            Date                Description of change
*************************************************************************************/
void findRMSE(int candidateKnee,int maxNumClusters,float& outLRMSE,float& outRRMSE) const
{
     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Entering: "
          <<"LTKHierarchicalClustering::findRMSE()"<<endl;

     float avgXLeft = 0;
     float avgYLeft = 0;
     float avgXRight = 0;
     float avgYRight = 0;

     /*Regression line coefficients*/
     float beta0Left = 0;
     float beta1Left = 0;
     float beta0Right = 0;
     float beta1Right = 0;

     int i = 0;
     int j = 0;

     for(i=2;i<=candidateKnee;i++)
     {
          avgYLeft+=m_mergingDist[i];

          avgXLeft+=i;
     }


     avgYLeft /= (candidateKnee-1);
     avgXLeft /= (candidateKnee-1);


     for(j=candidateKnee+1;j<=maxNumClusters;j++)
     {

          avgYRight += m_mergingDist[j];
          avgXRight += j;
     }

     avgYRight /= (maxNumClusters-candidateKnee);
     avgXRight /= (maxNumClusters-candidateKnee);

     float numer=0;
     float denom=0;

     for(i=2;i<=candidateKnee;i++)
     {

          numer += ((i-avgXLeft)*(m_mergingDist[i]-avgYLeft));
          denom += ((i-avgXLeft)*(i-avgXLeft));
     }

     beta1Left = numer/denom;
     beta0Left = avgYLeft-(beta1Left*avgXLeft);

     numer=0;denom=0;

     for(j=candidateKnee+1;j<=maxNumClusters;j++)
     {
          numer += ((j-avgXRight)*(m_mergingDist[j]-avgYRight));
          denom += ((j-avgXRight)*(j-avgXRight));
     }

    if(denom > EPS)
    {
          beta1Right = numer / denom;
     }
     else
     {
          beta1Right = 0;
     }

     beta0Right = avgYRight-(beta1Right*avgXRight);

     float errorSOS=0;

     for(i=2;i<=candidateKnee;i++)
     {

          float yCap = (beta0Left+(beta1Left*i));

          errorSOS += ((m_mergingDist[i]-yCap)*(m_mergingDist[i]-yCap));

     }

     outLRMSE=sqrt(errorSOS/(candidateKnee-2));

     errorSOS=0;

     for(j=candidateKnee+1;j<=maxNumClusters;j++)
     {

          float yCap = beta0Right + (beta1Right*j);

          errorSOS += (m_mergingDist[j]-yCap)*(m_mergingDist[j]-yCap);

     }

     outRRMSE=sqrt(errorSOS/(maxNumClusters-candidateKnee-1));

     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Exiting: "
          <<"LTKHierarchicalClustering::findRMSE()"<<endl;

}




/**********************************************************************************
* AUTHOR       : Bharath A
* DATE              : 22-FEB-2005
* NAME              : computeAvgSil
* DESCRIPTION  : Funtion that determines the change in the ratio of
*                     intra and inter cluster similarity before and after merging
* ARGUMENTS         : clust1Index - index of cluster one
*                     clust2Index - index of cluster two
* RETURNS      : average silhouette computed
* NOTES             :
* CHANGE HISTROY
* Author            Date                Description of change
*************************************************************************************/
float computeAvgSil(int clust1Index,int clust2Index) const
{
     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Entering: "
          <<"LTKHierarchicalClustering::computeAvgSil()"<<endl;

     const vector<int>& clust1=m_intermediateCG[clust1Index];

     const vector<int>& clust2=m_intermediateCG[clust2Index];

     vector<int> combinedClust;

     combinedClust.insert(combinedClust.end(),clust1.begin(),clust1.end());

     combinedClust.insert(combinedClust.end(),clust2.begin(),clust2.end());

     float clust1TotalSils=0.0f,clust2TotalSils=0.0f,combinedClustTotalSils=0.0f;

     for(int i=0;i<clust1.size();i++)
     {
          int dataObj=clust1[i];

          float avgIntraDist=0.0;

          if(clust1.size()>1)
          {
               for(int j=0;j<clust1.size();j++)
               {
                    if(clust1[j]!=dataObj)
                    {
                         avgIntraDist+=getInterObjectDistance(dataObj,clust1[j]);

                    }
               }

               avgIntraDist/=((float)(clust1.size()-1));
          }

          float minInterDist= FLT_MAX;

          for(int r=0;r<m_intermediateCG.size();r++)
          {
               float avgInterDist=0.0;

               if(r!=clust1Index)
               {
                    for(int c=0;c<m_intermediateCG[r].size();c++)
                    {
                         avgInterDist+=getInterObjectDistance(dataObj,m_intermediateCG[r][c]);
                    }

                    avgInterDist/=((float)m_intermediateCG[r].size());

                    if(avgInterDist<minInterDist)
                    {
                         minInterDist=avgInterDist;
                    }
               }

          }

          float dataObjSil=0.0;

          if(minInterDist > avgIntraDist && minInterDist > EPS)
          {

               dataObjSil=(minInterDist-avgIntraDist)/minInterDist;

          }
          else if(avgIntraDist > EPS)
          {

               dataObjSil=(minInterDist-avgIntraDist)/avgIntraDist;

          }

          clust1TotalSils+=dataObjSil;
     }

     for(int ii=0;ii<clust2.size();ii++)
     {
          int dataObj=clust2[ii];

          float avgIntraDist=0.0;

          if(clust2.size()>1)
          {
               for(int j=0;j<clust2.size();j++)
               {
                    if(clust2[j]!=dataObj)
                    {

                         avgIntraDist+=getInterObjectDistance(dataObj,clust2[j]);

                    }
               }

               avgIntraDist/=((float)(clust2.size()-1));
          }

          float minInterDist= FLT_MAX;

          for(int r=0;r<m_intermediateCG.size();r++)
          {
               float avgInterDist=0.0;

               if(r!=clust2Index)
               {
                    for(int c=0;c<m_intermediateCG[r].size();c++)
                    {
                         avgInterDist+=getInterObjectDistance(dataObj,
                                                                       m_intermediateCG[r][c]);
                    }

                    avgInterDist/=((float)m_intermediateCG[r].size());

                    if(avgInterDist < minInterDist)
                    {
                         minInterDist=avgInterDist;
                    }
               }

          }
          float dataObjSil=0.0;

          if(minInterDist > avgIntraDist && minInterDist > EPS)
          {
               dataObjSil=(minInterDist-avgIntraDist)/minInterDist;
          }
          else if(avgIntraDist > EPS)
          {
               dataObjSil=(minInterDist-avgIntraDist)/avgIntraDist;
          }

          clust2TotalSils+=dataObjSil;
     }


     for(int iii=0;iii<combinedClust.size();iii++)
     {
          int dataObj=combinedClust[iii];

          float avgIntraDist=0.0;

          if(combinedClust.size()>1)
          {
               for(int j=0;j<combinedClust.size();j++)
               {
                    if(combinedClust[j]!=dataObj)
                    {
                         avgIntraDist+=getInterObjectDistance(dataObj,combinedClust[j]);

                    }
               }
               avgIntraDist/=((float)(combinedClust.size()-1));
          }

          float minInterDist=FLT_MAX;

          for(int r=0;r<m_intermediateCG.size();r++)
          {

               if(r!=clust1Index && r!=clust2Index)
               {
                    float avgInterDist=0.0f;

                    for(int c=0;c<m_intermediateCG[r].size();c++)
                    {
                         avgInterDist+=getInterObjectDistance(dataObj,m_intermediateCG[r][c]);
                    }

                    avgInterDist = (float)avgInterDist/ ((float)m_intermediateCG[r].size());

                    if(avgInterDist<minInterDist)
                    {
                         minInterDist=avgInterDist;

                    }
               }

          }

          float dataObjSil=0.0;

          if(minInterDist>avgIntraDist && minInterDist > EPS)
          {

               dataObjSil=(minInterDist-avgIntraDist)/minInterDist;

          }
          else if(avgIntraDist > EPS)
          {

               dataObjSil=(minInterDist-avgIntraDist)/avgIntraDist;

          }

          combinedClustTotalSils+=dataObjSil;
     }


     LOG(LTKLogger::LTK_LOGLEVEL_DEBUG)<<"Exiting: "
          <<"LTKHierarchicalClustering::computeAvgSil()"<<endl;


     return (combinedClustTotalSils-clust1TotalSils-clust2TotalSils);

}



};
#endif