/
NiceGraph.cpp
executable file
·1367 lines (1173 loc) · 38.9 KB
/
NiceGraph.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
/*******************************************************************************
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
********************************************************************************/
/* FILE: NiceGraph.cpp
* DESCRIPTION: Implementation of a class to manage the graphs
* AUTHOR: Gary Weissman
* DATE: August 2008
* CONTACT: gary@babelgraph.org
* URL: http://www.babelgraph.org/
*/
#include "NiceGraph.hpp"
// Graph initialization
//------------------------------------------------------------------------------
NiceGraph::NiceGraph()
{
edgeIDCounter = 0;
vertexIDCounter = 0;
isDirected = true; // the default is a directed graph
// call makeUndirected() to change this
}
//------------------------------------------------------------------------------
NiceGraph::~NiceGraph()
{
// destroy vertices
for (map<int,Vertex*>::iterator iter = vertexList.begin(); iter != vertexList.end(); iter++)
{
if (iter->second != NULL) delete iter->second;
}
// destroy edges
for (map<int,Edge*>::iterator iter = edgeList.begin(); iter != edgeList.end(); iter++)
{
if (iter->second != NULL) delete iter->second;
}
}
// Graph create/manipulate structure
//------------------------------------------------------------------------------
void NiceGraph::makeEmptyGraph(int numVertices)
{
for (int index = 0; index < numVertices; index++)
{
addVertex();
}
}
//------------------------------------------------------------------------------
void NiceGraph::makeCompleteGraph(int numVertices)
{
makeEmptyGraph(numVertices); // first initialize all the vertices
// now loop through all possible edges and create them
for (int froms = 0; froms < numVertices; froms++)
{
for (int tos = 0; tos < numVertices; tos++)
{
if ((froms != tos) && (froms < tos))
{
addEdge(froms,tos);
addEdge(tos,froms);
}
}
}
}
//------------------------------------------------------------------------------
void NiceGraph::makeRandomGraph(int numVertices, float density)
{
makeEmptyGraph(numVertices); // first initialize all the vertices
int total = density * (float) numVertices * (numVertices - 1.0);
// bounds checking
if ((density > 0) && (total < 1))
total = 1;
while (total > 0)
{
int v1 = rand() % numVertices;
int v2 = rand() % numVertices;
if (isDirected) // directed graph
{
if (!testFromToConnected(v1,v2))
{
addEdge(v1,v2);
total--;
}
}
else // undirected graph
{
if (!testConnected(v1,v2))
{
addEdge(v1,v2);
addEdge(v2,v1);
total--; total--;
}
}
}
}
//------------------------------------------------------------------------------
void NiceGraph::makeKRegularGraph (int numVertices, int k)
{
makeEmptyGraph(numVertices); // first initialize all the vertices
int maxIndex = numVertices - 1;
if (k % 2 != 0) // k is an odd number, can't have an odd k-2 regular lattice graph
k++; // just round k up one
// special case k = 1?
// now add k-neighbors to each one
for (int i = 0; i < numVertices; i++)
{
for (int r = 1; r <= k/2; r++)
{
int next = i + r;
if ( next > maxIndex)
next = next - maxIndex - 1;
addEdge (i, next);
addEdge (next , i);
}
}
}
//------------------------------------------------------------------------------
void NiceGraph::makeStrangersBanquetGraph(int numVertices, int groups, float density, float mu)
{
makeEmptyGraph(numVertices); // first initialize all the vertices
makeUndirected(); // the SB is only undirected for now...
if (groups > numVertices) // bounds checking on number of groups
groups = numVertices;
for (int c = 0; c < numVertices; c++) // now subdivide into groups
{
for (int g = 0; g < groups; g++)
{
if (c % groups == g)
setVertexColor(c,g);
}
}
// make declining edge scheme to speed things up
int total_edges = numVertices * (numVertices - 1) / 2;
vector<Edge> proposals (total_edges);
int edgeIndex = 0;
for (int froms = 0; froms < numVertices; froms++)
{
for (int tos = 0; tos < numVertices; tos++)
{
if ((froms != tos) && (froms < tos))
{
proposals[edgeIndex].from = vertexList[froms];
proposals[edgeIndex].to = vertexList[tos];
edgeIndex++;
}
}
}
// propose connections and build graph
int num_edges = (int) (density * (float) total_edges);
int edge_counter = 0;
while (edge_counter < num_edges)
{
// use declining proposal list to speed things up...
int randIndex = rand() % proposals.size();
// choose two vertices to make the proposal
int vertex1 = proposals[randIndex].from->vID;
int vertex2 = proposals[randIndex].to->vID;
if ((vertex1 != vertex2) && (!testConnected(vertex1,vertex2))) // if isn't itself, and aren't already connected
{
// now check to see if they are accepted
if (vertexList[vertex1]->vColor == vertexList[vertex2]->vColor)
{
// if same color approve match
addEdge(vertex1, vertex2); // add edge
edge_counter++;
if (!proposals.empty())
proposals.erase(proposals.begin()+randIndex); // remove from list
}
else // if different colors check against mu
{
float chance1 = rand() / (RAND_MAX+1.0);
float chance2 = rand() / (RAND_MAX+1.0);
if ((chance1 < mu) || (chance2 < mu))
continue; // if either one rejects the connection do nothing
else
{ // approve the connection
addEdge(vertex1, vertex2); // add edge
edge_counter++;
if (!proposals.empty())
proposals.erase(proposals.begin()+randIndex); // remove from list
}
}
}
}
}
//------------------------------------------------------------------------------
void NiceGraph::makeBinaryTreeGraph(int numVertices)
{
makeEmptyGraph(numVertices); // first initialize all the vertices
queue<int> parents;
for (int q = 0; q < numVertices; q++) // initialize queue with vertex indices
{
parents.push(q);
}
while (!parents.empty())
{
int baby1 = 2*parents.front()+1 ;
int baby2 = 2*parents.front()+2 ;
if (baby1 < numVertices)
addEdge(parents.front(), baby1);
if (baby2 < numVertices)
addEdge(parents.front(), baby2);
parents.pop();
}
}
//------------------------------------------------------------------------------
void NiceGraph::addVertex()
{
vertexList[vertexIDCounter] = new Vertex();
vertexList[vertexIDCounter]->vName = " ";
vertexList[vertexIDCounter]->vColor = YELLOW;
vertexList[vertexIDCounter]->vID = vertexIDCounter;
vertexIDCounter++;
}
//------------------------------------------------------------------------------
void NiceGraph::addVertex(string newName)
{
addVertex();
vertexList[vertexIDCounter - 1]->vName = newName;
}
//------------------------------------------------------------------------------
void NiceGraph::removeVertex (int vertexID)
{
// first make sure the vertex exists
// then remove all neighboring edges (including those stored by the neighbors)
// then remove the vertex itself
// delete the pointer to the vertex for memory then delete the vertex from the map
vertexList.erase(vertexID);
// update everyone else's edgeIDs for no confusioN!!
}
//------------------------------------------------------------------------------
void NiceGraph::addEdge (int fromID, int toID)
{
// if not already connected, add the edge
// otherwise do nothing
// also, can't connect to self
bool goFlag;
if (isDirected) // directed graph
goFlag = !testFromToConnected(fromID,toID);
else // undirected graph
goFlag = !testConnected(fromID,toID);
if (fromID == toID)
goFlag = false;
if (goFlag)
{
Vertex *vFrom = vertexList[fromID];
Vertex *vTo = vertexList[toID];
Edge *newEdge = new Edge();
edgeList[edgeIDCounter] = newEdge;
edgeList[edgeIDCounter]->from = vFrom;
edgeList[edgeIDCounter]->to = vTo;
edgeList[edgeIDCounter]->eID = edgeIDCounter;
// DEFAULT WEIGHT UNLESS OTHERWISE SPECIFIED
edgeList[edgeIDCounter]->weight = 1.0;
// also add the edge to the vertex neighbor list
vFrom->out[edgeIDCounter] = newEdge;
vTo->in[edgeIDCounter] = newEdge;
if (!isDirected) // add the reciprocal edge if the graph is not directed
addEdge(toID,fromID);
edgeIDCounter++;
}
}
//------------------------------------------------------------------------------
void NiceGraph::removeEdge (int from, int to)
{
bool okflag;
if (isDirected)
okflag = testFromToConnected(from,to);
else
okflag = testConnected(from,to);
// test connected first to make sure the connection exists
if (okflag)
{
int edgeID = getEdgeID(from,to);
removeEdge(edgeID);
if (!isDirected)
removeEdge(to,from);
}
}
//------------------------------------------------------------------------------
void NiceGraph::removeEdge (int edgeID)
{
// does this edge exist?
bool okflag = validEID(edgeID);
if (okflag)
{
Vertex * vfrom, *vto;
vfrom = edgeList[edgeID]->from;
vto = edgeList[edgeID]->to;
// remove edge from neighbors vectors of both from and to
vfrom->out.erase(edgeID);
vto->in.erase(edgeID);
if (!isDirected)
{
vfrom->in.erase(edgeID);
vto->out.erase(edgeID);
}
// remove edge from the MAP edgeList
edgeList.erase(edgeID);
}
// also what about the memory leak aspect of the edge, does that get erased, too?
}
//------------------------------------------------------------------------------
int NiceGraph::getEdgeID(int vertexID1, int vertexID2)
{
// NOTE: for undirected graphs there will be two distint EDGE IDs representing
// basically the same thing.
int edgeID = -1;
// make sure it even exists, return -1 as an error code if we can't find it
if (!testFromToConnected(vertexID1, vertexID2) && isDirected)
return -1;
if (!testFromToConnected(vertexID1, vertexID2) && isDirected)
return -1;
// now find the associated edgeid
Vertex *vFrom = vertexList[vertexID1];
map<int,Edge*> *temp = &vFrom->out;
for (map<int,Edge*>::iterator iter = temp->begin(); iter != temp->end(); iter++)
{
Edge* eTemp = iter->second;
if (eTemp->to->vID == vertexID2)
edgeID = iter->first;
}
return edgeID; // return edge id
}
//------------------------------------------------------------------------------
int NiceGraph::getNumVertices()
{
return vertexList.size();
}
//------------------------------------------------------------------------------
int NiceGraph::getNumEdges()
{
return edgeList.size();
}
//------------------------------------------------------------------------------
int NiceGraph::getDegree (int vertexID)
{
return getInDegree(vertexID) + getOutDegree(vertexID);
}
//------------------------------------------------------------------------------
int NiceGraph::getInDegree (int vertexID)
{
return vertexList[vertexID]->in.size();
}
//------------------------------------------------------------------------------
int NiceGraph::getOutDegree (int vertexID)
{
return vertexList[vertexID]->out.size();
}
//------------------------------------------------------------------------------
float NiceGraph::getWeight(int from, int to)
{
int eID = getEdgeID(from,to);
return edgeList[eID]->weight;
}
//------------------------------------------------------------------------------
bool NiceGraph::testConnected (int vertexID1, int vertexID2)
{
// if it's an undirected graph, only need to check on vertex's neighborhood
vector<int> temp = getNeighborList(vertexID1);
if (temp.empty())
return false; // if vertex doesn't have any neighors
else
{
vector<int>::iterator it;
it = find(temp.begin(), temp.end(), vertexID2);
if (it != temp.end())
return true; // found the neighbor!
}
return false; // default, didn't find anything
}
//------------------------------------------------------------------------------
bool NiceGraph::testFromToConnected (int vertexID1, int vertexID2)
{
// on a directed graph, only check the outgoing neighbors
vector<int> temp = getOutNeighborList(vertexID1);
if (temp.empty())
return false; // if vertex doesn't have any neighors
else
{
vector<int>::iterator it;
it = find(temp.begin(), temp.end(), vertexID2);
if (it != temp.end())
return true; // found the neighbor!
}
return false; // default, didn't find anything
}
//------------------------------------------------------------------------------
bool NiceGraph::checkDirected()
{
return isDirected;
}
//------------------------------------------------------------------------------
void NiceGraph::makeUndirected()
{
isDirected = false;
// now make matrix symmetric
for (map<int,Edge*>::iterator iter = edgeList.begin(); iter != edgeList.end(); iter++)
{
Edge *e = iter->second;
int id1 = e->from->vID;
int id2 = e->to->vID;
// error checking to make sure they don't already exist happens automatically
addEdge(id2,id1);
}
}
// Neighbor(hood) related functions
//------------------------------------------------------------------------------
vector<int> NiceGraph::getNeighborList(int vertexID)
{
vector<int> total, in, out;
in = getInNeighborList(vertexID);
out = getOutNeighborList(vertexID);
total = in; // added in, now add outs, but check for duplicates
// check for duplicates
for (vector<int>::iterator I = out.begin(); I != out.end(); I++)
{
vector<int>::iterator it;
it = find(total.begin(), total.end(), *I);
if (it == total.end())
total.push_back(*I); // found the neighbor in ANOTHER SPOT! remove it!
}
return total;
}
//---------------------------------------------------------------------------------
vector<int> NiceGraph::getInNeighborList(int vertexID)
{
map<int,Edge*> inList = vertexList[vertexID]->in;
vector<int> tempList;
for (map<int,Edge*>::iterator iter = inList.begin(); iter != inList.end(); iter++)
{
Edge *tEdge = iter->second;
tempList.push_back(tEdge->from->vID);
}
return tempList;
}
//---------------------------------------------------------------------------------
vector<int> NiceGraph::getOutNeighborList(int vertexID)
{
map<int,Edge*> outList = vertexList[vertexID]->out;
vector<int> tempList;
for (map<int,Edge*>::iterator iter = outList.begin(); iter != outList.end(); iter++)
{
Edge*tEdge = iter->second;
tempList.push_back(tEdge->to->vID);
}
return tempList;
}
// Graph Extrinsic properties
//---------------------------------------------------------------------------------
string NiceGraph::getVertexName(int vertexID)
{
return vertexList[vertexID]->vName;
}
//---------------------------------------------------------------------------------
void NiceGraph::setVertexName(int vertexID, string newName)
{
vertexList[vertexID]->vName = newName;
}
//---------------------------------------------------------------------------------
int NiceGraph::getVertexColor (int vertexID)
{
return vertexList[vertexID]->vColor;
}
//---------------------------------------------------------------------------------
void NiceGraph::setVertexColor (int vertexID, int newColor)
{
vertexList[vertexID]->vColor = newColor;
}
// Graph Analysis
//---------------------------------------------------------------------------------
void NiceGraph::avgShortestPathMatrix(map<int,float> &paths )
{
// this approach based on Floyd-Warshall shortest paths algorithm (iterative!)
// returns -1 if the graph if some nodes are not reachable
int size = vertexList.size();
unsigned long int distance[size][size];
// initialize all values
for (int q = 0; q < size; q++)
{
for (int r = 0; r < size; r++)
{
if (testFromToConnected(q,r))
distance[q][r] = getWeight(q,r);
else if (q == r)
distance[q][r] = 0; // zero distance to self
else
distance[q][r] = INT_MAX; // set distance to infinity if not connected directly
}
}
// now iterate over and over to update shortest paths...
for (int k = 0; k < size; k++){
for (int i = 0; i < size; i++){
for (int j = 0; j < size; j++){
unsigned int sum = distance[i][k] + distance[k][j];
if (sum < distance[i][j]){
distance[i][j] = sum; }
}
}
}
// now compute averages for each guy distance matrix
for (int m = 0; m < size; m++) {
long double sum = 0;
for (int n = 0; n < size; n++) {
sum += distance[m][n];
}
sum = sum / (size-1);
if (sum >=getNumVertices())
sum = -1;
paths[m] = sum;
}
}
//---------------------------------------------------------------------------------
float NiceGraph::avgShortestPathofGraph_FW()
{
// this approach based on Floyd-Warshall shortest paths algorithm (iterative!)
// returns -1 if the graph if some nodes are not reachable
int size = vertexList.size();
unsigned long int distance[size][size];
// initialize all values
for (int q = 0; q < size; q++)
{
for (int r = 0; r < size; r++)
{
if (testFromToConnected(q,r))
distance[q][r] = getWeight(q,r);
else if (q == r)
distance[q][r] = 0; // zero distance to self
else
distance[q][r] = INT_MAX; // set distance to infinity if not connected directly
}
}
// now iterate over and over to update shortest paths...
for (int k = 0; k < size; k++){
for (int i = 0; i < size; i++){
for (int j = 0; j < size; j++){
unsigned int sum = distance[i][k] + distance[k][j];
if (sum < distance[i][j]){
distance[i][j] = sum; }
}
}
}
// now compute averages using distance matrix
long double sum = 0;
for (int m = 0; m < size; m++) {
for (int n = 0; n < size; n++) {
sum += distance[m][n];
}
}
float value = (sum / (size * (size - 1)));
if (value >= getNumVertices()) // the case where the graph is disconnected
value=-1;
return value ; // return the average over all values not including distance to self
}
//---------------------------------------------------------------------------------
// works but is SLOW!! WHY??
float NiceGraph::avgShortestPathofGraph_BFS()
{
// This approach based on a breadth first search --> better for undirected graphs?
int size = vertexList.size();
unsigned long int distance[size][size];
// initialize all values
for (int q = 0; q < size; q++)
{
for (int r = 0; r < size; r++)
{
distance[q][r] = INT_MAX; // set distance to infinity if not connected directly
}
}
for (int q =0; q < size; q++)
{
vector<bool> visited (size, false); // initialize all visited values to true so far
visited[q] = true; // has already visited self
distance[q][q] = 0; // distance to self is always zero
queue<int> Q;
Q.push(q);
do {
visited[Q.front()] = true;
vector<int> temp = getOutNeighborList(Q.front());
if (!temp.empty())
{
for (unsigned int t = 0; t < temp.size(); t++)
{
distance[Q.front()][temp[t]] = getWeight(Q.front(),temp[t]);
if (!visited[temp[t]])
Q.push(temp[t]);
unsigned int newPath = distance[q][Q.front()] + distance[Q.front()][temp[t]];
if (newPath < distance[q][temp[t]]) {
distance[q][temp[t]] = newPath;
}
}
}
Q.pop(); // pop off the neighbor just examined
} while (!Q.empty());
}
// now compute averages using distance matrix
long double sum = 0;
for (int m = 0; m < size; m++) {
for (int n = 0; n < size; n++) {
sum += distance[m][n];
}
}
float value = (sum / (size * (size - 1)));
if (value >= getNumVertices()) // the case where the graph is disconnected
value=-1;
return value ; // return the average over all values not including distance to self
}
//---------------------------------------------------------------------------------
float NiceGraph::getHomophilicDyadDensity()
{
// define HDD = s_i / (s_i + d_i), i.e. the fraction of homophilic edges over all edges
int same = 0, different = 0;
for (map<int,Edge*>::iterator iter = edgeList.begin(); iter != edgeList.end(); iter++)
{
Edge* eTemp;
eTemp = iter->second;
if (eTemp->from->vColor == eTemp->to->vColor)
same++;
else
different++;
}
float HDD = (float) same / ((float) same + (float) different);
return HDD;
}
//------------------------------------------------------------------------------
void NiceGraph::getPageRank(map<int,float> &pageRank, int iterations, float damping)
{
int total = getNumVertices();
// set initial page ranks
for (map<int,Vertex*>::iterator vIter = vertexList.begin(); vIter != vertexList.end(); vIter++)
{
pageRank[vIter->first] = 1.0/(float)total;
}
// run arbitrary number of iterations
for (int i = 0; i < iterations; i++)
{
for (map<int,Vertex*>::iterator vIter = vertexList.begin(); vIter != vertexList.end(); vIter++)
{
float votes = 0;
int id = vIter->first;
vector<int> inList = getInNeighborList(id);
for (vector<int>::iterator nIter = inList.begin(); nIter != inList.end(); nIter++)
{
votes+=pageRank[(*nIter)]/(float)getOutDegree(*nIter);
}
pageRank[id] = (1.0-damping) + damping * votes;
}
}
}
//------------------------------------------------------------------------------
float NiceGraph::getClusteringCoefficient(int index)
{
vector<int> ns = getNeighborList(index);
int size = ns.size();
int max = size * (size - 1) ;
int cnxs = 0;
float cc = 0;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
int from = ns[i];
int to = ns[j];
if (from!=to) // don't connect to self
{
if (testFromToConnected(from,to)) cnxs++;
}
}
}
if (max<1)
cc = 0;
else
cc = (float)cnxs / (float)max;
return cc;
}
//------------------------------------------------------------------------------
void NiceGraph::getClosenessCentrality(map<int,float> &cCentrality)
{
// this approach based on Floyd-Warshall shortest paths algorithm (iterative!)
// almost the same as avg shortest paths, but only calculates against reachable vertices
// therefore always returns a normal value even if the graph is partially disconnected
unsigned int size = vertexList.size();
unsigned long int distance[size][size];
// initialize all values
for (unsigned int q = 0; q < size; q++)
{
for (unsigned int r = 0; r < size; r++)
{
if (testFromToConnected(q,r))
distance[q][r] = getWeight(q,r);
else if (q == r)
distance[q][r] = 0; // zero distance to self
else
distance[q][r] = INT_MAX; // set distance to infinity if not connected directly
}
}
// now iterate over and over to update shortest paths...
for (unsigned int k = 0; k < size; k++){
for (unsigned int i = 0; i < size; i++){
for (unsigned int j = 0; j < size; j++){
unsigned int sum = distance[i][k] + distance[k][j];
if (sum < distance[i][j]){
distance[i][j] = sum; }
}
}
}
// now compute averages for each guy distance matrix
for (unsigned int m = 0; m < size; m++) {
long double sum = 0;
int reachable = 0;
for (unsigned int n = 0; n < size; n++) {
if (distance[m][n] < size) // ie. if the vertex is reachable
{
sum += distance[m][n]; reachable++;}
}
if (!(reachable == 1)) // ie can only get to itself
sum = sum / (reachable-1);
else sum = 0;
if (sum >=getNumVertices()) // should never happen here
sum = -1;
cCentrality[m] = sum;
}
}
//------------------------------------------------------------------------------
void NiceGraph::setXYZPos(int vertexID, float x, float y, float z)
{
vertexList[vertexID]->posX = x;
vertexList[vertexID]->posY = y;
vertexList[vertexID]->posZ = z;
}
//------------------------------------------------------------------------------
// takes a reference to 3-vector and returns it full of coordinates
void NiceGraph::getXYZPos(int vertexID, vector<float> & xyz)
{
xyz[0]= vertexList[vertexID]->posX;
xyz[1]= vertexList[vertexID]->posY;
xyz[2]= vertexList[vertexID]->posZ;
}
//---------------------------------------------------------------------------------
// return endpoints of an edge
void NiceGraph::getEndpoints (int edgeID, vector<float> & v1, vector<float> &v2)
{
if (validEID(edgeID))
{
Vertex *vert1 = edgeList[edgeID]->from;
Vertex *vert2 = edgeList[edgeID]->to;
v1[0] = vert1->posX;
v1[1] = vert1->posY;
v1[2] = vert1->posZ;
v2[0] = vert2->posX;
v2[1] = vert2->posY;
v2[2] = vert2->posZ;
}
}
//---------------------------------------------------------------------------------
void NiceGraph::randomLayoutAll(float xmin, float xmax, float ymin, float ymax, float zmin, float zmax)
{
for (unsigned int vIndex = 0; vIndex < vertexList.size(); vIndex++)
{
randomLayout (vIndex, xmin, xmax, ymin, ymax, zmin, zmax);
}
}
//---------------------------------------------------------------------------------
void NiceGraph::randomLayout(int vertexID, float xmin, float xmax, float ymin, float ymax, float zmin, float zmax)
{
float randX = (rand() / (RAND_MAX+1.0)) * (xmax - xmin) + xmin;
float randY = (rand() / (RAND_MAX+1.0)) * (ymax - ymin) + ymin;
float randZ = (rand() / (RAND_MAX+1.0)) * (zmax - zmin) + zmin;
setXYZPos(vertexID, randX, randY, randZ);
}
//---------------------------------------------------------------------------------
void NiceGraph::selfOrganize(float force, float min, float max)
{
// this function only self organizes 1 step, must be called multiple times for continous updating
// the force value ranges from [0,1] and is the fraction of the final step to take
// min and max values are protected distances for the various edges
if (force > 1)
force = 1;
else if (force <=0)
force = 0.001;
// iterate over edges, attract and check bounds, rearrange as necessary
for (map<int,Edge*>::iterator iter = edgeList.begin(); iter != edgeList.end(); iter++)
{
int e = iter->first;
vector<float> v1 (3), v2 (3);
float attraction = 0, dx = 0, dy = 0, dz = 0;
int id1 = edgeList[e]->from->vID;
int id2 = edgeList[e]->to->vID;
getEndpoints (e, v1, v2);
float vx = v2[0] - v1[0];
float vy = v2[1] - v1[1];
float vz = v2[2] - v1[2];
float dr = sqrt ( vx*vx + vy*vy + vz*vz );
attraction = -1.0 * (max - dr) / (100 * (max - min)/2);
dx += 0.5 * attraction * vx;
dy += 0.5 * attraction * vy;
dz += 0.5 * attraction * vz;
float scale = 1.0;
setXYZPos (id1, v1[0] + scale * dx, v1[1] + scale * dy, v1[2] + scale * dz);
setXYZPos (id2, v2[0] - scale * dx, v2[1] - scale * dy, v2[2] - scale * dz);
}
for (map<int,Vertex*>::iterator iter = vertexList.begin(); iter != vertexList.end(); iter++)
{
int self = iter->first;
float dx = 0, dy = 0, dz = 0, repulsion = 0;
float px = vertexList[self]->posX;
float py = vertexList[self]->posY;
float pz = vertexList[self]->posZ;
// sum repulsion from other vertices
for (map<int,Vertex*>::iterator iter2 = vertexList.begin(); iter2 != vertexList.end(); iter2++)
{
int other = iter2->first;
if (self == other) // don't need to repel self, too!
continue;
float vx = vertexList[other]->posX - px;
float vy = vertexList[other]->posY - py;
float vz = vertexList[other]->posZ - pz;
float dr = sqrt (vx * vx + vy * vy + vz * vz);
// let the repulsion go as 1/r^2, like the electrostatic force
repulsion = -0.01 * force*force / (sqrt(dr) * dr);
dx += repulsion * vx;
dy += repulsion * vy;
dz += repulsion * vz;
}
// update position
setXYZPos (self, px + dx, py + dy, pz + dz);
}
}