-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathGraph.cpp
2693 lines (2464 loc) · 87.5 KB
/
Graph.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
#include "Graph.h"
// Graph: a generic graph model to represent RDF graphs
#include <sstream>
#include <fstream>
#include <algorithm>
#include <time.h>
#include <iterator>
#include <list>
#include <deque>
#include <assert.h>
#include <utility>
#include <cmath>
#include <iomanip>
#ifndef _MSC_VER
#include <sys/time.h>
#endif
#include "SimMatrix.h"
#include "Conf.h"
/****
Graph file format:
Please see Graph.h file for the graph file format description.
*/
Graph::Graph() {
//graph = GRA();
conf = Conf();
vl = GRA();
tl = TripleList();
}
Graph::Graph(int size) {
conf = Conf();
vsize = size;
vl = GRA(size);
tl = TripleList();
}
Graph::Graph(GRA& g) {
conf = Conf();
vsize = g.size();
vl = g;
tl = TripleList();
}
//mehmet, this is being called from the main
Graph::Graph(Conf &conf, istream& in, string GraphFileName_, string format, string NoiseLabelsFileName, string NoiseWordsFileName, string MapGraphFileName) {
this->conf = conf;
GraphFileName = GraphFileName_;
if(NoiseLabelsFileName != "")
readNoiseLabels(NoiseLabelsFileName);
if (NoiseWordsFileName != "")
readNoiseWords(NoiseWordsFileName);
if (format == "flat")
readReverseMapping(MapGraphFileName);
readGraph(in,format);
}
Graph::~Graph() {}
/*
* Printing details about the graph. Not much use.
* called when verbose option specified. If you want to print more about the graph enchance writeGraph method
*/
void Graph::printGraph() {
writeGraph(cout);
}
/*
* Printing the pairs that share common property(s)
*/
void Graph::PrintCommonPairs(ostream& out, int prec)
{
cout << "Writing similarities to the file ..."<<endl;
float num;
int i, j;
cout<< "\nSorting the common pair list ..."<<endl;
sort(pairOList.begin(), pairOList.end());//sorting by pair(i,j) similarity DESC
cout<< "Sorted the common pair list."<<endl;
for ( auto it = pairOList.begin(); it != pairOList.end(); ++it )
{
//i>j
i = it->i;
j = it->j;
//num = val(i,j); //mod by mehmet later
num = (1 - it->DisSimilarity);
out<<"("<<i<<","<<j<<"): ";
out<< fixed << setprecision(prec) << num <<endl;
out<<"("<<vrmap[i]<<","<<vrmap[j]<<"): ";
out<< fixed << setprecision(prec) << num <<endl;
}
}
/*
Prints property importancy by pair
Note that property importancy changes by each pair based on definition of the term frequency inverted index
*/
void Graph::PrintPropertyImportancyByPairs(ostream& out, int prec)
{
cout << "Writing property importancies by pair to the file ..."<<endl;
float num, property_importancy;
int i, j, ref_i, ref_j, k, common_O_label;
for ( auto it = pairOList.begin(); it != pairOList.end(); ++it )
{
//i>j
i = it->i;
j = it->j;
ref_i = it->ref_i;
ref_j = it->ref_j;
num = (1 - it->DisSimilarity);
if (!(vl[i].valueNode && vl[j].valueNode))
out<<"("<<vrmap[i]<<","<<vrmap[j]<<") "<<"("<<i<<","<<j<<") :";
else
out << "(" << vrmap[ref_i] << "." << vrmap[i] << " , " << vrmap[ref_j] << "." << vrmap[j] << ") " << "(" << i << "," << j << ") :";
out<<" sim: " << fixed << setprecision(prec) << num <<endl;
for(k = 0;k< it->O_lb_intersect.size(); k++)
{
common_O_label = it->O_lb_intersect[k];
property_importancy = it->pairCommonLabelImportancyMap[common_O_label];
out << " " << lrmap[common_O_label] << " ( " << common_O_label << " ) : " << fixed << setprecision(prec) << property_importancy << "\t" << setprecision(1) << 100 * property_importancy << "%" << "\tRatio: " << fixed << setprecision(prec) << it->prop_importance_ratio * property_importancy << "\t" << setprecision(1) << 100 * it->prop_importance_ratio * property_importancy << "%" << endl;
}
}
}
/*
not being used. Discontinued since we decided to use tf-idf
mehmet, added
this will calculate the labels weight, importancy to be used in the similarity calculation
*/
void Graph::calculateLabelsSimWeight()
{
//find a better place to define these constants
float DEF_label_sim_disfrequency_weight = 0.5;
float DEF_label_sim_uniqeness_weight = 0.5;
cout<<"Calculating label weights which will be used in similarity calculation ..."<<endl;
Label *lobj;
//based on pure frequency and uniqueness
int i;
for(i =0;i< ll.size();i++)
{
lobj = &ll.at(i);
//Label &lobj = ll[common_label_id];
lobj->TotDiffObjects = lobj->IV.size();
lobj->frequency = (float)(lobj->NumOfOccurence)/ (float)Triple_Count_From_Triple_File;
lobj->uniqueness = (float)(lobj->TotDiffObjects) / (float)(lobj->NumOfOccurence);
//Serkan - uniqueness here is defined as lack of uniqness and given higher weight for less discriminative properties. We might want to substract from 1, like frequency measure
lobj->user_given_sim_weight = 0;//for now automate things
lobj->calculated_sim_weight = (1-lobj->frequency)*DEF_label_sim_disfrequency_weight + lobj->uniqueness*DEF_label_sim_uniqeness_weight;
//To disable the property(label) importancy enable the line below
//lobj->calculated_sim_weight = 1;//disabling label importancy
}
}
/*
Applying property importancy by Pair using a measure similar to tf_idf
*/
void Graph::setLabelImportanciesForPairs()
{
cout << "Setting properties importancies (tf-idf) per pair" << endl;
float importancy_weight, pair_tf_id, l_idf, i_tf, j_tf, i_tf_idf, j_tf_idf, tot_common_importancy_weights, tot_importancy_weights;
int i,j,k, common_label_id, label_id;
for ( auto it = pairOList.begin(); it != pairOList.end() && it->include_in_sim_iterations; ++it )
{
//i>j
i = it->i;
j = it->j;
if (conf.autoWeights())
{
//auto-calculating property importancy
//mod- first calculate for the common props
tot_common_importancy_weights = 0;
for (k = 0; k < it->O_lb_intersect.size(); k++)
{
common_label_id = it->O_lb_intersect[k];
Label &lobj = ll[common_label_id];
//calculating tf-idf for the pair and the common property
//Note: getting division by zero error. figure out which one you need to use . look above
l_idf = log(((float)vl.size() / (float)lobj.OV.size())); // inverse document frequency - frequency of the common label(property) in the dataset
i_tf = ((float)vl[i].edge_out_map[common_label_id].dest.size() / (float)vl[i].degree); // term frequency - frequency of the property in the node i
i_tf_idf = (i_tf * l_idf); //term frequency-inverse document frequency for the property(common_label_id) and node i
j_tf = ((float)vl[j].edge_out_map[common_label_id].dest.size() / (float)vl[j].degree);
j_tf_idf = (j_tf * l_idf);
pair_tf_id = (float)(i_tf_idf + j_tf_idf) / 2; //average tf_idf for the common label in the pair
importancy_weight = pair_tf_id;//if you want to add more importancy calculations then calculate and weights them
tot_common_importancy_weights += importancy_weight;
it->pairCommonLabelImportancyMap[common_label_id] = importancy_weight;
}
for (auto it2 = it->pairCommonLabelImportancyMap.begin(); it2 != it->pairCommonLabelImportancyMap.end(); ++it2)
{
it2->second = it2->second / tot_common_importancy_weights;
}
//mod- first then calculate for the union props
tot_importancy_weights = 0;
for (k = 0; k < it->O_lb_union.size(); k++)
{
label_id = it->O_lb_union[k];
//common label
if (vl[i].edge_out_map.find(label_id) != vl[i].edge_out_map.end() && vl[j].edge_out_map.find(label_id) != vl[j].edge_out_map.end()){
continue;
}
i_tf_idf = 0;//need to initialize
j_tf_idf = 0;
Label &lobj = ll[label_id];
l_idf = log(((float)vl.size() / (float)lobj.OV.size())); // inverse document frequency - frequency of the label(property) in the dataset
if (vl[i].edge_out_map.find(label_id) != vl[i].edge_out_map.end()){
//in [i - j]
i_tf = ((float)vl[i].edge_out_map[label_id].dest.size() / (float)vl[i].degree); // term frequency - frequency of the property in the node i
i_tf_idf = (i_tf * l_idf); //term frequency-inverse document frequency for the property(label_id) and node i
}
else if (vl[j].edge_out_map.find(label_id) != vl[j].edge_out_map.end()){
//in [j - i]
j_tf = ((float)vl[j].edge_out_map[label_id].dest.size() / (float)vl[j].degree);
j_tf_idf = (j_tf * l_idf);
}
pair_tf_id = (float)(i_tf_idf + j_tf_idf) / 2; //average tf_idf for the label in the pair
importancy_weight = pair_tf_id;//if you want to add more importancy calculations then calculate and weights them
tot_importancy_weights += importancy_weight;
}
tot_importancy_weights = tot_importancy_weights + tot_common_importancy_weights;
it->prop_importance_ratio = tot_common_importancy_weights / tot_importancy_weights;
}
else
{
//all properties have equal weight = 1/size_o_lb_intersect
for (k = 0; k < it->O_lb_intersect.size(); k++)
{
common_label_id = it->O_lb_intersect[k];
it->pairCommonLabelImportancyMap[common_label_id] = (float)( 1.0 / (float)it->O_lb_intersect.size());
it->prop_importance_ratio = (float)((float)it->O_lb_intersect.size() / (float)it->size_O_lb_union);
}
}
}
}
/*
Applying property importancy of each string literals in each vertex by using a measure similar to tf_idf to be used in String similarity calculation( jaccard )
*/
void Graph::setStringLiteralImportanciesForVertexes()
{
cout << "Setting string literal importancies for vertexes" << endl;
std::set<string>::iterator it;
string word;
float importancy_weight, word_tf_idf, word_idf, word_tf, tot_importancy_weights;
int vid, i;
for (vid = 0; vid < vl.size(); vid++){
if (conf.autoWeights()) //here add if using string sim
{
//auto-calculating string word importancies
Vertex &v = vl[vid];
tot_importancy_weights = 0;
set<string> &v_words = vl[vid].words;
for (it = v_words.begin(); it != v_words.end(); ++it){
word = *it;
StringWord &string_word = stringWords[word];
word_idf = log(((float)vl.size() / (float)string_word.NumOfOccurence_InDataset)); // inverse document frequency - frequency of the literal in the dataset
word_tf = ((float)string_word.NumOfOccurence_PerVertex[vid] / (float)vl[vid].totalNumWord_Occurences); // term frequency - frequency of the property in the node i
word_tf_idf = (word_idf * word_tf);
importancy_weight = word_tf_idf;//if you want to add more importancy calculations then calculate and weights them
tot_importancy_weights += importancy_weight;
string_word.Importancy_PerVertex[vid] = importancy_weight;
}
v.tot_literal_importance_weight = tot_importancy_weights;
for (it = v_words.begin(); it != v_words.end(); ++it){
word = *it;
StringWord &string_word = stringWords[word];
string_word.Importancy_PerVertex[vid] = string_word.Importancy_PerVertex[vid] / tot_importancy_weights;
}
}
else{
Vertex &v = vl[vid];
set<string> &v_words = vl[vid].words;
//equalizes each string words importancies
for (it = v_words.begin(); it != v_words.end(); ++it){
word = *it;
StringWord &string_word = stringWords[word];
string_word.Importancy_PerVertex[vid] = (float)(1.0 / (float)v_words.size());
}
}
}
}
/*
Prints property importancy of each string literals in each vertex by using a measure similar to tf_idf to be used in String similarity calculation( jaccard )
*/
void Graph::PrintStringLiteralImportanciesForVertexes(ostream& out, int prec)
{
std::set<string>::iterator it;
string word;
int vid, i;
for (vid = 0; vid < vl.size(); vid++){
Vertex &v = vl[vid];
if (v.valueNode)
continue;
out << "(" << vrmap[vid] << ") " << "(" << vid << ") :" << endl;
set<string> &v_words = vl[vid].words;
for (it = v_words.begin(); it != v_words.end(); ++it){
word = *it;
StringWord &string_word = stringWords[word];
out << " " << word << " : " << setprecision(prec) << string_word.Importancy_PerVertex[vid] << " - " << setprecision(prec) << string_word.Importancy_PerVertex[vid] * 100 << "%" << endl;
}
}
}
void Graph::setStringLiteralCounts(){
cout << "Setting string literal counts" << endl;
string word;
int vid, v_label_id, k, dest_vertex_id;
for (vid = 0; vid < vl.size(); vid++){
Vertex &v = vl[vid];
EdgeOutMap &v_edge_out_map = vl[vid].edge_out_map;
for (auto it = v_edge_out_map.begin(); it != v_edge_out_map.end(); ++it)
{
v_label_id = it->first;// vertex triple label id
EdgeOut &v_edge_out = it->second;//vertex triple edge outgoing
//it->first; //label_id
//it->second;//EdgeOut struct
for (k = 0; k < it->second.dest.size(); k++)
{
dest_vertex_id = it->second.dest[k]; //neighbor vertex id
Vertex &v_dest = vl[dest_vertex_id];
if (v_dest.valueNode && (v_dest.valueNode_data_type.find("string") != std::string::npos || v_dest.valueNode_data_type == "unknown")){
stringstream ssin(v_dest.valueNode_label_clean); //removing punctuations like . , ! etc
while (ssin.good()){
ssin >> word;
if (Nw.find(word) != Nw.end()) //the word is a noise word, do not count it
continue;
v.words.insert(word);
v.totalNumWord_Occurences++;
if (!stringWords.count(word)){//string_word for the word has not been initialized before
stringWords[word] = StringWord();
}
stringWords[word].NumOfOccurence_InDataset++;
stringWords[word].NumOfOccurence_PerVertex[vid]++;
}
}
}
}
}
}
/*
calculates 2 strings similarity based on their jaccard and importancy(by vertexes) in the data set
this was cauising issues when inside the StringSim
*/
double Graph::similJACCARD_WITH_TFIDF(int vid1, int vid2, string s1, string s2){
set<string> set1;
set<string> set2;
float tot_importancy_set1 = 0;
float tot_importancy_set2 = 0;
stringstream ssin1( s1);
stringstream ssin2( s2);
string word;
float imp;
while (ssin1.good()){
ssin1 >> word;
if (Nw.find(word) != Nw.end())//noise word, don't count
continue;
set1.insert(word);
imp = stringWords[word].Importancy_PerVertex[vid1];
tot_importancy_set1 += imp;
}
while (ssin2.good()){
ssin2 >> word;
if (Nw.find(word) != Nw.end())//noise word, don't count
continue;
set2.insert(word);
imp = stringWords[word].Importancy_PerVertex[vid2];
tot_importancy_set2 += imp;
}
std::set<string>::iterator it;
float nom = 0.0;
//float denom = set1.size() + set2.size();
float denom = (vl[vid1].tot_literal_importance_weight + vl[vid2].tot_literal_importance_weight) / 2;
//cout << vl[vid1].tot_literal_importance_weight << endl;
//cout << vl[vid2].tot_literal_importance_weight << endl;
float num_common = 0.0;
for (it = set1.begin(); it != set1.end(); ++it){
word = *it;
if (set2.find(word) != set2.end()){
//cout << stringWords[word].Importancy_PerVertex[vid1] << endl;
//cout << stringWords[word].Importancy_PerVertex[vid2] << endl;
num_common++;
//common word on both
if (!conf.autoWeights()){
nom += ((stringWords[word].Importancy_PerVertex[vid1]) * vl[vid1].tot_literal_importance_weight +
(stringWords[word].Importancy_PerVertex[vid2]) * vl[vid2].tot_literal_importance_weight) / 2.0;
}
}
}
if (!conf.autoWeights())
{
//not using auto wights
denom = (float)set1.size() + (float)set2.size() - num_common;
nom = num_common;
}
if (denom == 0)
return 0.0;
return (nom / denom);
//used to be this
//return nom; // I think the previous word importancy calculation already included some kind of jaccard
}
/*
Given two vertex ids get the list of their common outgoing labels(properties)
*/
vector<int> Graph::getOLbIntersect(int i, int j)
{
vector<int> result ;
map<int,EdgeOut>::iterator f1 = vl[i].edge_out_map.begin();
map<int,EdgeOut>::iterator f2 = vl[j].edge_out_map.begin();
map<int,EdgeOut>::iterator l1 = vl[i].edge_out_map.end();
map<int,EdgeOut>::iterator l2 = vl[j].edge_out_map.end();
while (f1!=l1 && f2!=l2)
{
if (f1->first<f2->first) ++f1;
else if (f2->first<f1->first) ++f2;
else {
//*result++ = *f1++;
result.push_back(f1->first);
f2++;
}
}
return result;
}
/*
Given two vertex ids get the list of their merged outgoing labels(properties)
*/
vector<int> Graph::getOLbUnion(int i, int j)
{
vector<int> result;
map<int,EdgeOut>::iterator f1 = vl[i].edge_out_map.begin();
map<int,EdgeOut>::iterator f2 = vl[j].edge_out_map.begin();
map<int,EdgeOut>::iterator l1 = vl[i].edge_out_map.end();
map<int,EdgeOut>::iterator l2 = vl[j].edge_out_map.end();
while (f1!=l1 && f2!=l2)
{
if (f1->first < f2->first) result.push_back( f1++->first );
else if (f2->first<f1->first) result.push_back( f2++->first);
else {
result.push_back(f1++->first);
f2++;
}
}
while(f1 != l1)
result.push_back(f1++->first);
while(f2 != l2)
result.push_back(f2++->first);
return result;
}
/*
Given two vertex ids get the list of their common incoming labels(properties)
*/
vector<int> Graph::getILbIntersect(int i, int j)
{
vector<int> result ;
map<int,EdgeIn>::iterator f1 = vl[i].edge_in_map.begin();
map<int,EdgeIn>::iterator f2 = vl[j].edge_in_map.begin();
map<int,EdgeIn>::iterator l1 = vl[i].edge_in_map.end();
map<int,EdgeIn>::iterator l2 = vl[j].edge_in_map.end();
while (f1!=l1 && f2!=l2)
{
if (f1->first<f2->first) ++f1;
else if (f2->first<f1->first) ++f2;
else {
result.push_back(f1++->first);
f2++;
}
}
return result;
}
/*
Given two vertex ids get the list of their merged incoming labels(properties)
*/
vector<int> Graph::getILbUnion(int i, int j)
{
vector<int> result;
map<int,EdgeIn>::iterator f1 = vl[i].edge_in_map.begin();
map<int,EdgeIn>::iterator f2 = vl[j].edge_in_map.begin();
map<int,EdgeIn>::iterator l1 = vl[i].edge_in_map.end();
map<int,EdgeIn>::iterator l2 = vl[j].edge_in_map.end();
while (f1!=l1 && f2!=l2)
{
if (f1->first < f2->first) result.push_back( f1++->first );
else if (f2->first<f1->first) result.push_back( f2++->first);
else {
result.push_back(f1++->first);
f2++;
}
}
while(f1 != l1)
result.push_back(f1++->first);
while(f2 != l2)
result.push_back(f2++->first);
return result;
}
/*
Write the generated clusters to a defined output(probably to a file)
*/
void Graph::writeClusters(ostream& out, float clustering_success_rate)
{
numEdgesInSummaryGraph = 0;
numGoodEdgesInSummaryGraph = 0;
Cluster *c;
Cluster *c_dest;
int index = 1;
int vid;
string vname;
cout<<"Writing final clusters ..."<<endl;
//out << "YOU ALREADY GENERATED CLUSTER RELATIONS STORED IN THE CLUSTER STRUCT EDGE MAPS. WRITE AND VISUALIZE THOSE TOO"<< endl;
if (clustering_success_rate > 0){
cout << "Clustering success rate: " << clustering_success_rate << "%" << endl << endl;;
out << "Clustering success rate: " << clustering_success_rate << "%" << endl << endl;;
}
out<< "CLUSTER LIST:"<<endl;
for(int i =0;i< setClusters.size();i++)
{
c = &setClusters.at(i);
if(c->members.size() == 0)
continue;
out<<endl<< c->name << endl; //it used to be << index
//cout<< endl<< "CLUSTER: " << i << endl;
index++;
for(int j =0;j<c->members.size();j++)
{
vid = c->members.at(j);
vname = vrmap[vid];
out << "\t"<< vname << " ("<< vid <<")" <<" ("<<vl[vid].edge_out_map.size() << ")" << endl;
// cout << vname << " ("<< vid <<")" << endl;
if (j % 10000 == 0){//progress bar
//cout << ".";
}
}
}
//cout<<endl<<"Writing un-clustered nodes ..."<<endl;
out<<endl<< "Printing Un-clusterred Nodes:" << endl;
for (int i =0;i< vl.size();i++)
{
vid = i;
if (vid == 14)
{
string x = "debug me here";
}
if(!vToClusterMap.count(vid))
{
vname = vrmap[vid];
//out << vname << " ("<< vid <<")" << endl;
out << vname << " ("<< vid <<")" <<" ("<<vl[vid].edge_out_map.size() << ")" << endl;
// cout << vname << " ("<< vid <<")" << endl;
}
if (i % 10000 == 0){//progress bar
//cout << ".";
}
}
out<< "" <<endl;
cout<<endl;
out<< "CLUSTER RELATIONS:"<<endl;
out << "" << endl;
out << "------------" << endl;
cout << "Summary Graph Stability: " << summaryGraphStability << " %" << endl;
out << "Summary Graph Stability: " << summaryGraphStability << " %" << endl;
cout << "summaryGraph_cRMSD: " << summaryGraph_cRMSD << endl;
out << "summaryGraph_cRMSD: " << summaryGraph_cRMSD << endl;
out << "------------" << endl;
cout << endl;
for(int i =0;i< setClusters.size();i++)
{
//i = current cluster index
c = &setClusters.at(i); // current cluster
if (c->members.size() == 0)
continue;
//cout << "" << endl;
out << "" << endl;
//cout<< c->name <<endl;
out<< c->name <<endl;
//cout<<"\tClass Stability Ratio:"<<c->stability_ratio<<" %"<<endl;
out<<"\tClass Stability Ratio:"<<c->stability_ratio<<" %"<<endl;
//cout<<"\tClass Property Coverage Ratio:"<<c->propery_coverage_ratio<<" %"<<endl;
out<<"\tClass Property Coverage Ratio:"<<c->propery_coverage_ratio<<" %"<<endl;
EdgeOutMap &c_edge_out_map = c->edge_out_map;
for ( auto it = c_edge_out_map.begin(); it != c_edge_out_map.end(); ++it )
{
int c_label_id = it->first;// cluster relation (cluster triple) label id
string c_label_name = lrmap[c_label_id];
EdgeOut &c_edge_out = it->second;//cluster relation edge outgoing struct
for( int k = 0; k < c_edge_out.dest.size(); k++ )
{
int dest_cluster_id = c_edge_out.dest[k] ; //neighbor cluster id
c_dest = &setClusters.at(dest_cluster_id);
if (c->size > 1){
numEdgesInSummaryGraph++;
}
if (c->size > 1 && c_dest->size > 1){
numGoodEdgesInSummaryGraph++;
}
//Writing relation
//cout << "\t" << c->name << "\t" << c_label_name << "\t" << c_dest->name << " (stability: " << c->propertyStabilityByRefCluster[c_label_id][dest_cluster_id]*100 << " % )" << endl;
out << "\t" << c->name << "\t" << c_label_name << "\t" << c_dest->name << " (stability: " << c->propertyStabilityByRefCluster[c_label_id][dest_cluster_id]*100 << " % )" << endl;
//out<<"Cluster:"<<i<<"\t"<< c_label_id <<"\t"<<"Cluster:"<<dest_cluster_id<<endl;
}
}
}
cout <<endl<< "Done writing the clusters." <<endl;
}
/*
Write the generated clusters to a defined output(probably to a file)
*/
void Graph::writeClustersJSON(ostream& out, float clustering_success_rate)
{
Cluster *c;
Cluster *c_dest;
int index = 1;
int vid;
string vname;
cout << "Writing final clusters ..." << endl;
//out << "YOU ALREADY GENERATED CLUSTER RELATIONS STORED IN THE CLUSTER STRUCT EDGE MAPS. WRITE AND VISUALIZE THOSE TOO"<< endl;
if (clustering_success_rate > 0){
cout << "Clustering success rate: " << clustering_success_rate << "%" << endl << endl;;
out << "Clustering success rate: " << clustering_success_rate << "%" << endl << endl;;
}
out << "{\"name\":\"root\", \"children\" : [" << endl; //it used to be << index
/*{"name":"root", "children" : [
{"name":"C-Harvard_University>","children": [
{"name":"Harvard_University","size":2600},
{"name":"Yale_University","size":2600}
]
},
*/
for (int i = 0; i< setClusters.size(); i++)
{
c = &setClusters.at(i);
if (c->members.size() == 0)
continue;
out << "{\"name\":\"" + c->name + "\"," + "\"children\"" + ": [" << endl; //it used to be << index
index++;
for (int j = 0; j<c->members.size(); j++)
{
vid = c->members.at(j);
vname = vrmap[vid];
vname.erase(std::remove(vname.begin(), vname.end(), '"'), vname.end());
vname.erase(std::remove(vname.begin(), vname.end(), '>'), vname.end());
//if (vname.find("http://dbpedia.org/resource/")>0)
// vname.erase(0, 29);
//vname.replace(vname.find("http://dbpedia.org/resource/")-1,29, "");
//out << "\t" << vname << " (" << vid << ")" << " (" << vl[vid].edge_out_map.size() << ")" << endl;
out << "{\"name\":\"" + vname << "\"," << "\"size\"" << ":" << vl[vid].edge_out_map.size() * 100 << "}";
if (j == c->members.size() - 1)
out << endl;
else
out << "," << endl;
//{ "name": "<http://dbpedia.org/resource/Barbara_Snyder> ", "size" : 7840 }
// cout << vname << " ("<< vid <<")" << endl;
if (j % 10000 == 0){//progress bar
//cout << ".";
}
}
if (i == setClusters.size() - 1)
out << "]" << endl << "}" << endl;
else
out << "]" << endl << "}," << endl;
}
out << "]" << endl << "}" << endl;
cout << endl << "Done writing the clusters." << endl;
}
/*
given a ClusterVerificationFileName(contains real cluster results), calculate and print how correct your clusters are
*/
float Graph::verifyClusterResults(string ClusterVerificationFileName, float cluster_member_similarity_threshold)
{
//ERROR HERE, vname has not been populated yet. Populate it in the readReverseMapping function. But do not populate it if format = triple
/*cout << "The verification of the clusters planned to be implemented after we do the hieracial clustering." << endl;
return;*/
ifstream in(ClusterVerificationFileName);
if (!in) {
cerr << "Error: Cannot open the cluster verification file: " << ClusterVerificationFileName << endl;
return -1 ;
}
cout << "Reading the cluster verification file..." << endl;
string buf;
vector<int> members;
map<int, int> verifiedClusterMap;
int k1, k2, vid, vid1, vid2, i, j;
string pair_key;
int pairOIndex;
int tot_pairs = 0;
int tot_pairs_correct = 0;
float success_rate1 = 0.0;
float success_rate2 = 0.0;
float success_rate = 0.0;
string vname = "";
int num_verif_clusters = 0;
//1. compare verifCluster with GeneratedClusers = success_rate1
while (getline(in, buf)) {
if (buf.substr(0, 2) != "\t\t"){
num_verif_clusters++;
//cout << "new cluster: " << buf << endl;
if (members.size() > 0){
for (k1 = 0; k1 < members.size(); k1++){
for (k2 = (members.size() > 1 ? k1 + 1 : k1); k2 < members.size(); k2++){ //the for loop also account for the clusters which have only one member
tot_pairs++;
i = members[k1];
j = members[k2];
if (i == 14 || j == 14)
{
string xx = "debug here";
}
if (vToClusterMap.count(i) && vToClusterMap.count(j) && vToClusterMap[i] == vToClusterMap[j]){
tot_pairs_correct++;
}
else{
//cout << vrmap[i] << "\t" << vrmap[j] << "\tsuppose to be in the same cluster!" << endl;
}
}
}
}
members.clear();
//starts of a new cluster
}
else
{
vname = Util::removeChar( Util::removeChar(buf, '\t'), '\t');
//cout << "cluster member" << vname << endl;
vid = vmap[vname];
members.push_back(vid);
verifiedClusterMap[vid] = num_verif_clusters;
}
}
in.close();
success_rate1 = ((float)tot_pairs_correct / (float)tot_pairs) * 100;
tot_pairs_correct = 0;
tot_pairs = 0;
//2. compare GeneratedClusers with verifCluster = success_rate2
Cluster *c;
int i1, j1, j2;
for (i1 = 0; i1 < setClusters.size(); i1++)
{
//i = current cluster index
c = &setClusters.at(i1); // current cluster
for (j1 = 0; j1 < c->size; j1++) // process current cluster's members
{
for (j2 = j1+1; j2 < c->size; j2++){
tot_pairs++;
i = c->members.at(j1); // member vertex id = i
j = c->members.at(j2); // member vertex id = j
if (verifiedClusterMap.count(i) && verifiedClusterMap.count(j) && verifiedClusterMap[i] == verifiedClusterMap[j]){
tot_pairs_correct++;
}
else{
//cout << vrmap[i] << "\t" << vrmap[j] << "\tare NOT suppose to be in the same cluster!" << endl;
}
}
}
}
success_rate2 = ((float)tot_pairs_correct / (float)tot_pairs) * 100;
success_rate = (success_rate1 + success_rate2) / 2;
return success_rate;
}
/*
After generating the clusters also generate the cluster relations.
Similar to creating the RDFS schema
*/
void Graph::generateClusterRelations()
{
Cluster *c;
int vid;
set<int> setForDups;
map<int, bool> setForSourcePredDestCluster; //if a member in c1 making a p connection to a member in c2 more than one time then only count it once , destClusterIndex, true/false of reference
cout<<"Generating cluster relations ..."<<endl;
int allPredicateRefCount = 0;
float allPredicateRefStabilitySum = 0;
numGoodClusteredNodes = 0;
numGoodClusters = 0;
for(int i =0;i< setClusters.size();i++)
{
//i = current cluster index
c = &setClusters.at(i); // current cluster
c->size = c->members.size(); // update current cluster size
if (c->size > 1){
numGoodClusters += 1;
numGoodClusteredNodes += c->size;
}
c->degree = 0;
c->in_degree = 0;
c->stability_ratio = 0;
c->propery_coverage_ratio = 0;
float c_members_total_out_degree = 0;
if(c->size == 0)
continue;
//cout<< endl<< "Processing cluster: " << c->name << endl;
for(int j =0;j<c->size;j++) // process current cluster's members
{
vid = c->members.at(j); // member vertex id
c_members_total_out_degree+= vl[vid].degree;
EdgeOutMap &v_edge_out_map = vl[vid].edge_out_map;
for ( auto it = v_edge_out_map.begin(); it != v_edge_out_map.end(); ++it )
{
int v_label_id = it->first;// vertex triple label id
EdgeOut &v_edge_out = it->second;//vertex triple edge outgoing
//it->first; //label_id
//it->second;//EdgeOut struct
setForSourcePredDestCluster.clear();
for( int k = 0; k < it->second.dest.size() ; k++ )
{
int dest_vertex_id = it->second.dest[k] ; //neighbor vertex id
bool dest_Cluster_exists = vToClusterMap.count(dest_vertex_id);
if(dest_Cluster_exists)
{
int dest_Cluster_Index = vToClusterMap[dest_vertex_id];
Cluster &c_dest = setClusters.at(dest_Cluster_Index);//destination cluster
//adding cluster relation like triples = ( current_cluster_index, connecting_label_id, destination_cluster_index )
//adding out Edge. add the dest cluster to the current cluster outgoings
if(!c->edge_out_map.count(v_label_id))
{
EdgeOut edgeOut = EdgeOut();
edgeOut.src = i;//current cluster index
edgeOut.label_id = v_label_id;
edgeOut.dest = VectIntType();
c->edge_out_map[v_label_id] = edgeOut;
}
//you need to check for uniqueness[ uniqueness checking is at the end by using sets ]
//if (std::find(c->edge_out_map[v_label_id].dest.begin(), c->edge_out_map[v_label_id].dest.end(), dest_Cluster_Index) == c->edge_out_map[v_label_id].dest.end()){
c->edge_out_map[v_label_id].dest.push_back(dest_Cluster_Index);//add the neighboring cluster index
c->degree++;
//}
//adding in Edge. add src to dest's incoming
if(!c_dest.edge_in_map.count(v_label_id))
{
EdgeIn edgeIn = EdgeIn();
edgeIn.src = VectIntType();
edgeIn.label_id = v_label_id;
edgeIn.dest = dest_Cluster_Index; //destination cluster index
c_dest.edge_in_map[v_label_id] = edgeIn;
}
//you need to check for uniqueness[ uniqueness checking is at the end by using sets ]
//if (std::find(c_dest.edge_in_map[v_label_id].src.begin(), c_dest.edge_in_map[v_label_id].src.end(), i) == c_dest.edge_in_map[v_label_id].src.end()){
c_dest.edge_in_map[v_label_id].src.push_back(i);//current cluster index
c_dest.in_degree++;
//}
if (!setForSourcePredDestCluster.count(dest_Cluster_Index)){
setForSourcePredDestCluster[dest_Cluster_Index] = true;
if (!c->propertyStabilityByRefCluster.count(v_label_id)){
map<int, float> refClusterStability;
c->propertyStabilityByRefCluster[v_label_id] = refClusterStability;
}
if (!c->propertyStabilityByRefCluster[v_label_id].count(dest_Cluster_Index)){
c->propertyStabilityByRefCluster[v_label_id][dest_Cluster_Index] = 0;
}
c->propertyStabilityByRefCluster[v_label_id][dest_Cluster_Index] += 1 / (float)c->size; //will add to the stability ratio for c1, p, c2
}
}
}
}
//cout << vname << " ("<< vid <<")" <<" ("<<vl[vid].edge_out_map.size() << ")" << endl;
if (j % 10000 == 0){//progress bar
//cout << ".";
}
}
//Remove dups from the relations, ( triples may contain duplicates )
for ( auto it = c->edge_out_map.begin(); it != c->edge_out_map.end(); ++it )
{
setForDups.clear();
for( int k = 0; k < it->second.dest.size(); k++ )
setForDups.insert( it->second.dest[k]);
it->second.dest.assign( setForDups.begin(), setForDups.end() );
}
for ( auto it = c->edge_in_map.begin(); it != c->edge_in_map.end(); ++it )
{
setForDups.clear();
for( int k = 0; k < it->second.src.size(); k++ )
setForDups.insert( it->second.src[k]);
it->second.src.assign( setForDups.begin(), setForDups.end() );
}
setForDups.clear();
//calculate stability ratio
float predicateStabilitiesSum = 0;
int predicateRefsCount = 0;
for (auto it = c->propertyStabilityByRefCluster.begin(); it != c->propertyStabilityByRefCluster.end(); ++it){
int v_label_id = it->first; //property id, p
for (auto it2 = c->propertyStabilityByRefCluster[v_label_id].begin(); it2 != c->propertyStabilityByRefCluster[v_label_id].end(); ++it2){
int dest_Cluster_Index = it2->first; //destination cluster, c2
predicateStabilitiesSum += it2->second;
predicateRefsCount++;
}
}
allPredicateRefCount += predicateRefsCount;
allPredicateRefStabilitySum += predicateStabilitiesSum;
c->stability_ratio = (predicateRefsCount != 0 ? ((float)predicateStabilitiesSum / (float)predicateRefsCount) * 100 : 100);
c->propery_coverage_ratio = (c_members_total_out_degree != 0 ? ((float)c->degree / (float)c_members_total_out_degree)*100 : 100);
}
//calculating summary graph stability
summaryGraphStability = (allPredicateRefCount != 0 ? ((float)allPredicateRefStabilitySum / (float)allPredicateRefCount) * 100 : 100); //calculated summary graph stability
cout <<endl<< "Done generating cluster relations." <<endl;
}
void Graph::nameClusters()//name the cluster
{
Cluster *c;
int vid, pos1, pos2;
map<string, int> vnameCounts;
map<string, vector<int>> cnameIndexes;
string vname, vname2;
cout << "Generating cluster names ..." << endl;
for (int i = 0; i< setClusters.size(); i++)
{
vnameCounts.clear();
c = &setClusters.at(i); // current cluster
std::stringstream sstm;
sstm << "CLUSTER: " << (i + 1); //default namings
c->name = sstm.str();
//cout << "Processing: " << c->name << endl;
if (c->size == 0)
continue;
//cout << endl << "Processing CLUSTER: " << i << endl;
for (int j = 0; j<c->members.size(); j++) // process current cluster's members
{
vid = c->members.at(j); // member vertex id
vname = vrmap[vid];
pos1 = vname.rfind("/");
if (pos1 < 0)
continue;
vname2 = vname.substr(pos1+1);
pos2 = vname2.rfind(":");
if (pos2 > 0)
vname2 = vname2.substr(0, pos2);
if (!vnameCounts.count(vname2))
vnameCounts[vname2] = 0;
vnameCounts[vname2]++;
//cout << vname << " ("<< vid <<")" <<" ("<<vl[vid].edge_out_map.size() << ")" << endl;
if (j % 10000 == 0){//progress bar