/
community.c
3845 lines (3386 loc) · 145 KB
/
community.c
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
/* -*- mode: C -*- */
/* vim:set ts=4 sw=4 sts=4 et: */
/*
IGraph library.
Copyright (C) 2007-2012 Gabor Csardi <csardi.gabor@gmail.com>
334 Harvard street, Cambridge, MA 02139 USA
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 2 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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA
*/
#include "igraph_community.h"
#include "igraph_constructors.h"
#include "igraph_memory.h"
#include "igraph_random.h"
#include "igraph_arpack.h"
#include "igraph_adjlist.h"
#include "igraph_interface.h"
#include "igraph_interrupt_internal.h"
#include "igraph_components.h"
#include "igraph_dqueue.h"
#include "igraph_progress.h"
#include "igraph_stack.h"
#include "igraph_spmatrix.h"
#include "igraph_statusbar.h"
#include "igraph_types_internal.h"
#include "igraph_conversion.h"
#include "igraph_centrality.h"
#include "igraph_structural.h"
#include "config.h"
#include <string.h>
#include <math.h>
#ifdef USING_R
#include <R.h>
#endif
static int igraph_i_rewrite_membership_vector(igraph_vector_t *membership) {
long int no = (long int) igraph_vector_max(membership) + 1;
igraph_vector_t idx;
long int realno = 0;
long int i;
long int len = igraph_vector_size(membership);
IGRAPH_VECTOR_INIT_FINALLY(&idx, no);
for (i = 0; i < len; i++) {
long int t = (long int) VECTOR(*membership)[i];
if (VECTOR(idx)[t]) {
VECTOR(*membership)[i] = VECTOR(idx)[t] - 1;
} else {
VECTOR(idx)[t] = ++realno;
VECTOR(*membership)[i] = VECTOR(idx)[t] - 1;
}
}
igraph_vector_destroy(&idx);
IGRAPH_FINALLY_CLEAN(1);
return 0;
}
static int igraph_i_community_eb_get_merges2(const igraph_t *graph,
const igraph_vector_t *edges,
const igraph_vector_t *weights,
igraph_matrix_t *res,
igraph_vector_t *bridges,
igraph_vector_t *modularity,
igraph_vector_t *membership) {
igraph_vector_t mymembership;
long int no_of_nodes = igraph_vcount(graph);
long int i;
igraph_real_t maxmod = -1;
long int midx = 0;
igraph_integer_t no_comps;
IGRAPH_VECTOR_INIT_FINALLY(&mymembership, no_of_nodes);
if (membership) {
IGRAPH_CHECK(igraph_vector_resize(membership, no_of_nodes));
}
if (modularity || res || bridges) {
IGRAPH_CHECK(igraph_clusters(graph, 0, 0, &no_comps,
IGRAPH_WEAK));
if (modularity) {
IGRAPH_CHECK(igraph_vector_resize(modularity,
no_of_nodes - no_comps + 1));
}
if (res) {
IGRAPH_CHECK(igraph_matrix_resize(res, no_of_nodes - no_comps,
2));
}
if (bridges) {
IGRAPH_CHECK(igraph_vector_resize(bridges,
no_of_nodes - no_comps));
}
}
for (i = 0; i < no_of_nodes; i++) {
VECTOR(mymembership)[i] = i;
}
if (membership) {
igraph_vector_update(membership, &mymembership);
}
IGRAPH_CHECK(igraph_modularity(graph, &mymembership, &maxmod, weights));
if (modularity) {
VECTOR(*modularity)[0] = maxmod;
}
for (i = igraph_vector_size(edges) - 1; i >= 0; i--) {
long int edge = (long int) VECTOR(*edges)[i];
long int from = IGRAPH_FROM(graph, edge);
long int to = IGRAPH_TO(graph, edge);
long int c1 = (long int) VECTOR(mymembership)[from];
long int c2 = (long int) VECTOR(mymembership)[to];
igraph_real_t actmod;
long int j;
if (c1 != c2) { /* this is a merge */
if (res) {
MATRIX(*res, midx, 0) = c1;
MATRIX(*res, midx, 1) = c2;
}
if (bridges) {
VECTOR(*bridges)[midx] = i + 1;
}
/* The new cluster has id no_of_nodes+midx+1 */
for (j = 0; j < no_of_nodes; j++) {
if (VECTOR(mymembership)[j] == c1 ||
VECTOR(mymembership)[j] == c2) {
VECTOR(mymembership)[j] = no_of_nodes + midx;
}
}
IGRAPH_CHECK(igraph_modularity(graph, &mymembership, &actmod, weights));
if (modularity) {
VECTOR(*modularity)[midx + 1] = actmod;
if (actmod > maxmod) {
maxmod = actmod;
if (membership) {
igraph_vector_update(membership, &mymembership);
}
}
}
midx++;
}
}
if (membership) {
IGRAPH_CHECK(igraph_i_rewrite_membership_vector(membership));
}
igraph_vector_destroy(&mymembership);
IGRAPH_FINALLY_CLEAN(1);
return 0;
}
/**
* \function igraph_community_eb_get_merges
* \brief Calculating the merges, i.e. the dendrogram for an edge betweenness community structure
*
* </para><para>
* This function is handy if you have a sequence of edge which are
* gradually removed from the network and you would like to know how
* the network falls apart into separate components. The edge sequence
* may come from the \ref igraph_community_edge_betweenness()
* function, but this is not necessary. Note that \ref
* igraph_community_edge_betweenness can also calculate the
* dendrogram, via its \p merges argument.
*
* \param graph The input graph.
* \param edges Vector containing the edges to be removed from the
* network, all edges are expected to appear exactly once in the
* vector.
* \param weights An optional vector containing edge weights. If null,
* the unweighted modularity scores will be calculated. If not null,
* the weighted modularity scores will be calculated. Ignored if both
* \p modularity and \p membership are nulls.
* \param res Pointer to an initialized matrix, if not NULL then the
* dendrogram will be stored here, in the same form as for the \ref
* igraph_community_walktrap() function: the matrix has two columns
* and each line is a merge given by the ids of the merged
* components. The component ids are number from zero and
* component ids smaller than the number of vertices in the graph
* belong to individual vertices. The non-trivial components
* containing at least two vertices are numbered from \c n, \c n is
* the number of vertices in the graph. So if the first line
* contains \c a and \c b that means that components \c a and \c b
* are merged into component \c n, the second line creates
* component \c n+1, etc. The matrix will be resized as needed.
* \param bridges Pointer to an initialized vector or NULL. If not
* null then the index of the edge removals which split the network
* will be stored here. The vector will be resized as needed.
* \param modularity If not a null pointer, then the modularity values
* for the different divisions, corresponding to the merges matrix,
* will be stored here.
* \param membership If not a null pointer, then the membership vector
* for the best division (in terms of modularity) will be stored
* here.
* \return Error code.
*
* \sa \ref igraph_community_edge_betweenness().
*
* Time complexity: O(|E|+|V|log|V|), |V| is the number of vertices,
* |E| is the number of edges.
*/
int igraph_community_eb_get_merges(const igraph_t *graph,
const igraph_vector_t *edges,
const igraph_vector_t *weights,
igraph_matrix_t *res,
igraph_vector_t *bridges,
igraph_vector_t *modularity,
igraph_vector_t *membership) {
long int no_of_nodes = igraph_vcount(graph);
igraph_vector_t ptr;
long int i, midx = 0;
igraph_integer_t no_comps;
if (membership || modularity) {
return igraph_i_community_eb_get_merges2(graph, edges, weights, res,
bridges, modularity,
membership);
}
IGRAPH_CHECK(igraph_clusters(graph, 0, 0, &no_comps, IGRAPH_WEAK));
IGRAPH_VECTOR_INIT_FINALLY(&ptr, no_of_nodes * 2 - 1);
if (res) {
IGRAPH_CHECK(igraph_matrix_resize(res, no_of_nodes - no_comps, 2));
}
if (bridges) {
IGRAPH_CHECK(igraph_vector_resize(bridges, no_of_nodes - no_comps));
}
for (i = igraph_vector_size(edges) - 1; i >= 0; i--) {
igraph_integer_t edge = (igraph_integer_t) VECTOR(*edges)[i];
igraph_integer_t from, to, c1, c2, idx;
igraph_edge(graph, edge, &from, &to);
idx = from + 1;
while (VECTOR(ptr)[idx - 1] != 0) {
idx = (igraph_integer_t) VECTOR(ptr)[idx - 1];
}
c1 = idx - 1;
idx = to + 1;
while (VECTOR(ptr)[idx - 1] != 0) {
idx = (igraph_integer_t) VECTOR(ptr)[idx - 1];
}
c2 = idx - 1;
if (c1 != c2) { /* this is a merge */
if (res) {
MATRIX(*res, midx, 0) = c1;
MATRIX(*res, midx, 1) = c2;
}
if (bridges) {
VECTOR(*bridges)[midx] = i + 1;
}
VECTOR(ptr)[c1] = no_of_nodes + midx + 1;
VECTOR(ptr)[c2] = no_of_nodes + midx + 1;
VECTOR(ptr)[from] = no_of_nodes + midx + 1;
VECTOR(ptr)[to] = no_of_nodes + midx + 1;
midx++;
}
}
igraph_vector_destroy(&ptr);
IGRAPH_FINALLY_CLEAN(1);
return 0;
}
/* Find the smallest active element in the vector */
static long int igraph_i_vector_which_max_not_null(const igraph_vector_t *v,
const char *passive) {
long int which, i = 0, size = igraph_vector_size(v);
igraph_real_t max;
while (passive[i]) {
i++;
}
which = i;
max = VECTOR(*v)[which];
for (i++; i < size; i++) {
igraph_real_t elem = VECTOR(*v)[i];
if (!passive[i] && elem > max) {
max = elem;
which = i;
}
}
return which;
}
/**
* \function igraph_community_edge_betweenness
* \brief Community finding based on edge betweenness
*
* Community structure detection based on the betweenness of the edges
* in the network. The algorithm was invented by M. Girvan and
* M. Newman, see: M. Girvan and M. E. J. Newman: Community structure in
* social and biological networks, Proc. Nat. Acad. Sci. USA 99, 7821-7826
* (2002).
*
* </para><para>
* The idea is that the betweenness of the edges connecting two
* communities is typically high, as many of the shortest paths
* between nodes in separate communities go through them. So we
* gradually remove the edge with highest betweenness from the
* network, and recalculate edge betweenness after every removal.
* This way sooner or later the network falls off to two components,
* then after a while one of these components falls off to two smaller
* components, etc. until all edges are removed. This is a divisive
* hierarchical approach, the result is a dendrogram.
* \param graph The input graph.
* \param result Pointer to an initialized vector, the result will be
* stored here, the ids of the removed edges in the order of their
* removal. It will be resized as needed. It may be NULL if
* the edge IDs are not needed by the caller.
* \param edge_betweenness Pointer to an initialized vector or
* NULL. In the former case the edge betweenness of the removed
* edge is stored here. The vector will be resized as needed.
* \param merges Pointer to an initialized matrix or NULL. If not NULL
* then merges performed by the algorithm are stored here. Even if
* this is a divisive algorithm, we can replay it backwards and
* note which two clusters were merged. Clusters are numbered from
* zero, see the \p merges argument of \ref
* igraph_community_walktrap() for details. The matrix will be
* resized as needed.
* \param bridges Pointer to an initialized vector of NULL. If not
* NULL then all edge removals which separated the network into
* more components are marked here.
* \param modularity If not a null pointer, then the modularity values
* of the different divisions are stored here, in the order
* corresponding to the merge matrix. The modularity values will
* take weights into account if \p weights is not null.
* \param membership If not a null pointer, then the membership vector,
* corresponding to the highest modularity value, is stored here.
* \param directed Logical constant, whether to calculate directed
* betweenness (i.e. directed paths) for directed graphs. It is
* ignored for undirected graphs.
* \param weights An optional vector containing edge weights. If null,
* the unweighted edge betweenness scores will be calculated and
* used. If not null, the weighted edge betweenness scores will be
* calculated and used.
* \return Error code.
*
* \sa \ref igraph_community_eb_get_merges(), \ref
* igraph_community_spinglass(), \ref igraph_community_walktrap().
*
* Time complexity: O(|V||E|^2), as the betweenness calculation requires
* O(|V||E|) and we do it |E|-1 times.
*
* \example examples/simple/igraph_community_edge_betweenness.c
*/
int igraph_community_edge_betweenness(const igraph_t *graph,
igraph_vector_t *result,
igraph_vector_t *edge_betweenness,
igraph_matrix_t *merges,
igraph_vector_t *bridges,
igraph_vector_t *modularity,
igraph_vector_t *membership,
igraph_bool_t directed,
const igraph_vector_t *weights) {
long int no_of_nodes = igraph_vcount(graph);
long int no_of_edges = igraph_ecount(graph);
double *distance, *tmpscore;
unsigned long long int *nrgeo;
long int source, i, e;
igraph_inclist_t elist_out, elist_in, fathers;
igraph_inclist_t *elist_out_p, *elist_in_p;
igraph_vector_int_t *neip;
long int neino;
igraph_vector_t eb;
long int maxedge, pos;
igraph_integer_t from, to;
igraph_bool_t result_owned = 0;
igraph_stack_t stack = IGRAPH_STACK_NULL;
igraph_real_t steps, steps_done;
char *passive;
/* Needed only for the unweighted case */
igraph_dqueue_t q = IGRAPH_DQUEUE_NULL;
/* Needed only for the weighted case */
igraph_2wheap_t heap;
if (result == 0) {
result = igraph_Calloc(1, igraph_vector_t);
if (result == 0) {
IGRAPH_ERROR("edge betweenness community structure failed", IGRAPH_ENOMEM);
}
IGRAPH_FINALLY(igraph_free, result);
IGRAPH_VECTOR_INIT_FINALLY(result, 0);
result_owned = 1;
}
directed = directed && igraph_is_directed(graph);
if (directed) {
IGRAPH_CHECK(igraph_inclist_init(graph, &elist_out, IGRAPH_OUT));
IGRAPH_FINALLY(igraph_inclist_destroy, &elist_out);
IGRAPH_CHECK(igraph_inclist_init(graph, &elist_in, IGRAPH_IN));
IGRAPH_FINALLY(igraph_inclist_destroy, &elist_in);
elist_out_p = &elist_out;
elist_in_p = &elist_in;
} else {
IGRAPH_CHECK(igraph_inclist_init(graph, &elist_out, IGRAPH_ALL));
IGRAPH_FINALLY(igraph_inclist_destroy, &elist_out);
elist_out_p = elist_in_p = &elist_out;
}
distance = igraph_Calloc(no_of_nodes, double);
if (distance == 0) {
IGRAPH_ERROR("edge betweenness community structure failed", IGRAPH_ENOMEM);
}
IGRAPH_FINALLY(igraph_free, distance);
nrgeo = igraph_Calloc(no_of_nodes, unsigned long long int);
if (nrgeo == 0) {
IGRAPH_ERROR("edge betweenness community structure failed", IGRAPH_ENOMEM);
}
IGRAPH_FINALLY(igraph_free, nrgeo);
tmpscore = igraph_Calloc(no_of_nodes, double);
if (tmpscore == 0) {
IGRAPH_ERROR("edge betweenness community structure failed", IGRAPH_ENOMEM);
}
IGRAPH_FINALLY(igraph_free, tmpscore);
if (weights == 0) {
IGRAPH_DQUEUE_INIT_FINALLY(&q, 100);
} else {
if (igraph_vector_min(weights) <= 0) {
IGRAPH_ERROR("weights must be strictly positive", IGRAPH_EINVAL);
}
if (membership != 0) {
IGRAPH_WARNING("Membership vector will be selected based on the lowest "\
"modularity score.");
}
if (modularity != 0 || membership != 0) {
IGRAPH_WARNING("Modularity calculation with weighted edge betweenness "\
"community detection might not make sense -- modularity treats edge "\
"weights as similarities while edge betwenness treats them as "\
"distances");
}
IGRAPH_CHECK(igraph_2wheap_init(&heap, no_of_nodes));
IGRAPH_FINALLY(igraph_2wheap_destroy, &heap);
IGRAPH_CHECK(igraph_inclist_init_empty(&fathers,
(igraph_integer_t) no_of_nodes));
IGRAPH_FINALLY(igraph_inclist_destroy, &fathers);
}
IGRAPH_CHECK(igraph_stack_init(&stack, no_of_nodes));
IGRAPH_FINALLY(igraph_stack_destroy, &stack);
IGRAPH_CHECK(igraph_vector_resize(result, no_of_edges));
if (edge_betweenness) {
IGRAPH_CHECK(igraph_vector_resize(edge_betweenness, no_of_edges));
if (no_of_edges > 0) {
VECTOR(*edge_betweenness)[no_of_edges - 1] = 0;
}
}
IGRAPH_VECTOR_INIT_FINALLY(&eb, no_of_edges);
passive = igraph_Calloc(no_of_edges, char);
if (!passive) {
IGRAPH_ERROR("edge betweenness community structure failed", IGRAPH_ENOMEM);
}
IGRAPH_FINALLY(igraph_free, passive);
/* Estimate the number of steps to be taken.
* It is assumed that one iteration is O(|E||V|), but |V| is constant
* anyway, so we will have approximately |E|^2 / 2 steps, and one
* iteration of the outer loop advances the step counter by the number
* of remaining edges at that iteration.
*/
steps = no_of_edges / 2.0 * (no_of_edges + 1);
steps_done = 0;
for (e = 0; e < no_of_edges; steps_done += no_of_edges - e, e++) {
IGRAPH_PROGRESS("Edge betweenness community detection: ",
100.0 * steps_done / steps, NULL);
igraph_vector_null(&eb);
if (weights == 0) {
/* Unweighted variant follows */
/* The following for loop is copied almost intact from
* igraph_edge_betweenness_estimate */
for (source = 0; source < no_of_nodes; source++) {
IGRAPH_ALLOW_INTERRUPTION();
memset(distance, 0, (size_t) no_of_nodes * sizeof(double));
memset(nrgeo, 0, (size_t) no_of_nodes * sizeof(unsigned long long int));
memset(tmpscore, 0, (size_t) no_of_nodes * sizeof(double));
igraph_stack_clear(&stack); /* it should be empty anyway... */
IGRAPH_CHECK(igraph_dqueue_push(&q, source));
nrgeo[source] = 1;
distance[source] = 0;
while (!igraph_dqueue_empty(&q)) {
long int actnode = (long int) igraph_dqueue_pop(&q);
neip = igraph_inclist_get(elist_out_p, actnode);
neino = igraph_vector_int_size(neip);
for (i = 0; i < neino; i++) {
igraph_integer_t edge = (igraph_integer_t) VECTOR(*neip)[i], from, to;
long int neighbor;
igraph_edge(graph, edge, &from, &to);
neighbor = actnode != from ? from : to;
if (nrgeo[neighbor] != 0) {
/* we've already seen this node, another shortest path? */
if (distance[neighbor] == distance[actnode] + 1) {
nrgeo[neighbor] += nrgeo[actnode];
}
} else {
/* we haven't seen this node yet */
nrgeo[neighbor] += nrgeo[actnode];
distance[neighbor] = distance[actnode] + 1;
IGRAPH_CHECK(igraph_dqueue_push(&q, neighbor));
IGRAPH_CHECK(igraph_stack_push(&stack, neighbor));
}
}
} /* while !igraph_dqueue_empty */
/* Ok, we've the distance of each node and also the number of
shortest paths to them. Now we do an inverse search, starting
with the farthest nodes. */
while (!igraph_stack_empty(&stack)) {
long int actnode = (long int) igraph_stack_pop(&stack);
if (distance[actnode] < 1) {
continue; /* skip source node */
}
/* set the temporary score of the friends */
neip = igraph_inclist_get(elist_in_p, actnode);
neino = igraph_vector_int_size(neip);
for (i = 0; i < neino; i++) {
long int edge = (long int) VECTOR(*neip)[i];
long int neighbor = IGRAPH_OTHER(graph, edge, actnode);
if (distance[neighbor] == distance[actnode] - 1 &&
nrgeo[neighbor] != 0) {
tmpscore[neighbor] +=
(tmpscore[actnode] + 1) * nrgeo[neighbor] / nrgeo[actnode];
VECTOR(eb)[edge] +=
(tmpscore[actnode] + 1) * nrgeo[neighbor] / nrgeo[actnode];
}
}
}
/* Ok, we've the scores for this source */
} /* for source <= no_of_nodes */
} else {
/* Weighted variant follows */
/* The following for loop is copied almost intact from
* igraph_i_edge_betweenness_estimate_weighted */
for (source = 0; source < no_of_nodes; source++) {
/* This will contain the edge betweenness in the current step */
IGRAPH_ALLOW_INTERRUPTION();
memset(distance, 0, (size_t) no_of_nodes * sizeof(double));
memset(nrgeo, 0, (size_t) no_of_nodes * sizeof(unsigned long long int));
memset(tmpscore, 0, (size_t) no_of_nodes * sizeof(double));
igraph_2wheap_push_with_index(&heap, source, 0);
distance[source] = 1.0;
nrgeo[source] = 1;
while (!igraph_2wheap_empty(&heap)) {
long int minnei = igraph_2wheap_max_index(&heap);
igraph_real_t mindist = -igraph_2wheap_delete_max(&heap);
igraph_stack_push(&stack, minnei);
neip = igraph_inclist_get(elist_out_p, minnei);
neino = igraph_vector_int_size(neip);
for (i = 0; i < neino; i++) {
long int edge = VECTOR(*neip)[i];
long int to = IGRAPH_OTHER(graph, edge, minnei);
igraph_real_t altdist = mindist + VECTOR(*weights)[edge];
igraph_real_t curdist = distance[to];
igraph_vector_int_t *v;
if (curdist == 0) {
/* This is the first finite distance to 'to' */
v = igraph_inclist_get(&fathers, to);
igraph_vector_int_resize(v, 1);
VECTOR(*v)[0] = edge;
nrgeo[to] = nrgeo[minnei];
distance[to] = altdist + 1.0;
IGRAPH_CHECK(igraph_2wheap_push_with_index(&heap, to, -altdist));
} else if (altdist < curdist - 1) {
/* This is a shorter path */
v = igraph_inclist_get(&fathers, to);
igraph_vector_int_resize(v, 1);
VECTOR(*v)[0] = edge;
nrgeo[to] = nrgeo[minnei];
distance[to] = altdist + 1.0;
IGRAPH_CHECK(igraph_2wheap_modify(&heap, to, -altdist));
} else if (altdist == curdist - 1) {
/* Another path with the same length */
v = igraph_inclist_get(&fathers, to);
igraph_vector_int_push_back(v, edge);
nrgeo[to] += nrgeo[minnei];
}
}
} /* igraph_2wheap_empty(&Q) */
while (!igraph_stack_empty(&stack)) {
long int w = (long int) igraph_stack_pop(&stack);
igraph_vector_int_t *fatv = igraph_inclist_get(&fathers, w);
long int fatv_len = igraph_vector_int_size(fatv);
for (i = 0; i < fatv_len; i++) {
long int fedge = (long int) VECTOR(*fatv)[i];
long int neighbor = IGRAPH_OTHER(graph, fedge, w);
tmpscore[neighbor] += (tmpscore[w] + 1) * nrgeo[neighbor] / nrgeo[w];
VECTOR(eb)[fedge] += (tmpscore[w] + 1) * nrgeo[neighbor] / nrgeo[w];
}
tmpscore[w] = 0;
distance[w] = 0;
nrgeo[w] = 0;
igraph_vector_int_clear(fatv);
}
} /* source < no_of_nodes */
}
/* Now look for the smallest edge betweenness */
/* and eliminate that edge from the network */
maxedge = igraph_i_vector_which_max_not_null(&eb, passive);
VECTOR(*result)[e] = maxedge;
if (edge_betweenness) {
VECTOR(*edge_betweenness)[e] = VECTOR(eb)[maxedge];
if (!directed) {
VECTOR(*edge_betweenness)[e] /= 2.0;
}
}
passive[maxedge] = 1;
igraph_edge(graph, (igraph_integer_t) maxedge, &from, &to);
neip = igraph_inclist_get(elist_in_p, to);
neino = igraph_vector_int_size(neip);
igraph_vector_int_search(neip, 0, maxedge, &pos);
VECTOR(*neip)[pos] = VECTOR(*neip)[neino - 1];
igraph_vector_int_pop_back(neip);
neip = igraph_inclist_get(elist_out_p, from);
neino = igraph_vector_int_size(neip);
igraph_vector_int_search(neip, 0, maxedge, &pos);
VECTOR(*neip)[pos] = VECTOR(*neip)[neino - 1];
igraph_vector_int_pop_back(neip);
}
IGRAPH_PROGRESS("Edge betweenness community detection: ", 100.0, NULL);
igraph_free(passive);
igraph_vector_destroy(&eb);
igraph_stack_destroy(&stack);
IGRAPH_FINALLY_CLEAN(3);
if (weights == 0) {
igraph_dqueue_destroy(&q);
IGRAPH_FINALLY_CLEAN(1);
} else {
igraph_2wheap_destroy(&heap);
igraph_inclist_destroy(&fathers);
IGRAPH_FINALLY_CLEAN(2);
}
igraph_free(tmpscore);
igraph_free(nrgeo);
igraph_free(distance);
IGRAPH_FINALLY_CLEAN(3);
if (directed) {
igraph_inclist_destroy(&elist_out);
igraph_inclist_destroy(&elist_in);
IGRAPH_FINALLY_CLEAN(2);
} else {
igraph_inclist_destroy(&elist_out);
IGRAPH_FINALLY_CLEAN(1);
}
if (merges || bridges || modularity || membership) {
IGRAPH_CHECK(igraph_community_eb_get_merges(graph, result, weights, merges,
bridges, modularity,
membership));
}
if (result_owned) {
igraph_vector_destroy(result);
igraph_Free(result);
IGRAPH_FINALLY_CLEAN(2);
}
return 0;
}
/**
* \function igraph_community_to_membership
* \brief Create membership vector from community structure dendrogram
*
* This function creates a membership vector from a community
* structure dendrogram. A membership vector contains for each vertex
* the id of its graph component, the graph components are numbered
* from zero, see the same argument of \ref igraph_clusters() for an
* example of a membership vector.
*
* </para><para>
* Many community detection algorithms return with a \em merges
* matrix, \ref igraph_community_walktrap() and \ref
* igraph_community_edge_betweenness() are two examples. The matrix
* contains the merge operations performed while mapping the
* hierarchical structure of a network. If the matrix has \c n-1 rows,
* where \c n is the number of vertices in the graph, then it contains
* the hierarchical structure of the whole network and it is called a
* dendrogram.
*
* </para><para>
* This function performs \p steps merge operations as prescribed by
* the \p merges matrix and returns the current state of the network.
*
* </para><para>
* If \p merges is not a complete dendrogram, it is possible to
* take \p steps steps if \p steps is not bigger than the number
* lines in \p merges.
* \param merges The two-column matrix containing the merge
* operations. See \ref igraph_community_walktrap() for the
* detailed syntax.
* \param nodes The number of leaf nodes in the dendrogram
* \param steps Integer constant, the number of steps to take.
* \param membership Pointer to an initialized vector, the membership
* results will be stored here, if not NULL. The vector will be
* resized as needed.
* \param csize Pointer to an initialized vector, or NULL. If not NULL
* then the sizes of the components will be stored here, the vector
* will be resized as needed.
*
* \sa \ref igraph_community_walktrap(), \ref
* igraph_community_edge_betweenness(), \ref
* igraph_community_fastgreedy() for community structure detection
* algorithms.
*
* Time complexity: O(|V|), the number of vertices in the graph.
*/
int igraph_community_to_membership(const igraph_matrix_t *merges,
igraph_integer_t nodes,
igraph_integer_t steps,
igraph_vector_t *membership,
igraph_vector_t *csize) {
long int no_of_nodes = nodes;
long int components = no_of_nodes - steps;
long int i, found = 0;
igraph_vector_t tmp;
if (steps > igraph_matrix_nrow(merges)) {
IGRAPH_ERROR("`steps' to big or `merges' matrix too short", IGRAPH_EINVAL);
}
if (membership) {
IGRAPH_CHECK(igraph_vector_resize(membership, no_of_nodes));
igraph_vector_null(membership);
}
if (csize) {
IGRAPH_CHECK(igraph_vector_resize(csize, components));
igraph_vector_null(csize);
}
IGRAPH_VECTOR_INIT_FINALLY(&tmp, steps);
for (i = steps - 1; i >= 0; i--) {
long int c1 = (long int) MATRIX(*merges, i, 0);
long int c2 = (long int) MATRIX(*merges, i, 1);
/* new component? */
if (VECTOR(tmp)[i] == 0) {
found++;
VECTOR(tmp)[i] = found;
}
if (c1 < no_of_nodes) {
long int cid = (long int) VECTOR(tmp)[i] - 1;
if (membership) {
VECTOR(*membership)[c1] = cid + 1;
}
if (csize) {
VECTOR(*csize)[cid] += 1;
}
} else {
VECTOR(tmp)[c1 - no_of_nodes] = VECTOR(tmp)[i];
}
if (c2 < no_of_nodes) {
long int cid = (long int) VECTOR(tmp)[i] - 1;
if (membership) {
VECTOR(*membership)[c2] = cid + 1;
}
if (csize) {
VECTOR(*csize)[cid] += 1;
}
} else {
VECTOR(tmp)[c2 - no_of_nodes] = VECTOR(tmp)[i];
}
}
if (membership || csize) {
for (i = 0; i < no_of_nodes; i++) {
long int tmp = (long int) VECTOR(*membership)[i];
if (tmp != 0) {
if (membership) {
VECTOR(*membership)[i] = tmp - 1;
}
} else {
if (csize) {
VECTOR(*csize)[found] += 1;
}
if (membership) {
VECTOR(*membership)[i] = found;
}
found++;
}
}
}
igraph_vector_destroy(&tmp);
IGRAPH_FINALLY_CLEAN(1);
return 0;
}
/**
* \function igraph_modularity
* \brief Calculate the modularity of a graph with respect to some vertex types
*
* The modularity of a graph with respect to some division (or vertex
* types) measures how good the division is, or how separated are the
* different vertex types from each other. It is defined as
* Q=1/(2m) * sum((Aij - ki*kj / (2m)) delta(ci,cj), i, j), here `m' is the
* number of edges, `Aij' is the element of the `A' adjacency matrix
* in row `i' and column `j', `ki' is the degree of `i', `kj' is the
* degree of `j', `ci' is the type (or component) of `i', `cj' that of
* `j', the sum goes over all `i' and `j' pairs of vertices, and
* `delta(x,y)' is one if x=y and zero otherwise.
*
* </para><para>
* Modularity on weighted graphs is also meaningful. When taking edge
* weights into account, `Aij' becomes the weight of the corresponding
* edge (or 0 if there is no edge), `ki' is the total weight of edges
* incident on vertex `i', `kj' is the total weight of edges incident
* on vertex `j' and `m' is the total weight of all edges.
*
* </para><para>
* See also Clauset, A.; Newman, M. E. J.; Moore, C. Finding
* community structure in very large networks, Physical Review E,
* 2004, 70, 066111.
* \param graph The input graph. It must be undirected; directed graphs are
* not supported yet.
* \param membership Numeric vector which gives the type of each
* vertex, i.e. the component to which it belongs.
* It does not have to be consecutive, i.e. empty communities are
* allowed.
* \param modularity Pointer to a real number, the result will be
* stored here.
* \param weights Weight vector or NULL if no weights are specified.
* \return Error code.
*
* Time complexity: O(|V|+|E|), the number of vertices plus the number
* of edges.
*/
int igraph_modularity(const igraph_t *graph,
const igraph_vector_t *membership,
igraph_real_t *modularity,
const igraph_vector_t *weights) {
igraph_vector_t e, a;
long int types = (long int) igraph_vector_max(membership) + 1;
long int no_of_edges = igraph_ecount(graph);
long int i;
igraph_integer_t from, to;
igraph_real_t m;
long int c1, c2;
if (igraph_is_directed(graph)) {
#ifndef USING_R
IGRAPH_ERROR("modularity is implemented for undirected graphs", IGRAPH_EINVAL);
#else
REprintf("Modularity is implemented for undirected graphs only.\n");
#endif
}
if (igraph_vector_size(membership) < igraph_vcount(graph)) {
IGRAPH_ERROR("cannot calculate modularity, membership vector too short",
IGRAPH_EINVAL);
}
if (igraph_vector_min(membership) < 0) {
IGRAPH_ERROR("Invalid membership vector", IGRAPH_EINVAL);
}
IGRAPH_VECTOR_INIT_FINALLY(&e, types);
IGRAPH_VECTOR_INIT_FINALLY(&a, types);
if (weights) {
if (igraph_vector_size(weights) < no_of_edges)
IGRAPH_ERROR("cannot calculate modularity, weight vector too short",
IGRAPH_EINVAL);
m = igraph_vector_sum(weights);
for (i = 0; i < no_of_edges; i++) {
igraph_real_t w = VECTOR(*weights)[i];
if (w < 0) {
IGRAPH_ERROR("negative weight in weight vector", IGRAPH_EINVAL);
}
igraph_edge(graph, (igraph_integer_t) i, &from, &to);
c1 = (long int) VECTOR(*membership)[from];
c2 = (long int) VECTOR(*membership)[to];
if (c1 == c2) {
VECTOR(e)[c1] += 2 * w;
}
VECTOR(a)[c1] += w;
VECTOR(a)[c2] += w;
}
} else {
m = no_of_edges;
for (i = 0; i < no_of_edges; i++) {
igraph_edge(graph, (igraph_integer_t) i, &from, &to);
c1 = (long int) VECTOR(*membership)[from];
c2 = (long int) VECTOR(*membership)[to];
if (c1 == c2) {
VECTOR(e)[c1] += 2;
}
VECTOR(a)[c1] += 1;
VECTOR(a)[c2] += 1;
}
}
*modularity = 0.0;
if (m > 0) {
for (i = 0; i < types; i++) {
igraph_real_t tmp = VECTOR(a)[i] / 2 / m;
*modularity += VECTOR(e)[i] / 2 / m;
*modularity -= tmp * tmp;
}
}
igraph_vector_destroy(&e);
igraph_vector_destroy(&a);
IGRAPH_FINALLY_CLEAN(2);
return 0;
}
/**
* \function igraph_modularity_matrix
* \brief Calculate the modularity matrix
*
* This function returns the modularity matrix defined as
* `B_ij = A_ij - k_i k_j * / 2 m`
* where `A_ij` denotes the adjacency matrix, `k_i` is the degree of node `i`
* and `m` is the total weight in the graph. Note that self-loops are multiplied
* by 2 in this implementation. If weights are specified, the weighted
* counterparts are used.
*
* \param graph The input graph
* \param modmat Pointer to an initialized matrix in which the modularity
* matrix is stored.