forked from waynebhayes/BLANT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
blant.c
2485 lines (2330 loc) · 89.1 KB
/
blant.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
#include <sys/file.h>
#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <sys/mman.h>
#include "misc.h"
#include "tinygraph.h"
#include "graph.h"
#include "heap.h"
#include "blant.h"
#include "queue.h"
#include "multisets.h"
#include "sorts.h"
#define PARANOID_ASSERTS 1 // turn on paranoid checking --- slows down execution by a factor of 2-3
#define SPARSE true // do not try false at the moment, it's broken
// Enable the code that uses C++ to parse input files?
#define SHAWN_AND_ZICAN 0
static int *_pairs, _numNodes, _numEdges, _maxEdges=1024, _seed;
char **_nodeNames, _supportNodeNames = true;
#define USE_MarsenneTwister 0
#if USE_MarsenneTwister
#include "libwayne/MT19937/mt19937.h"
#define RandomSeed /*nothing*/
static MT19937 *_mt19937;
double RandomUniform(void) {
if(!_mt19937) _mt19937 = Mt19937Alloc(_seed);
return Mt19937NextDouble(_mt19937);
}
#else
#include "rand48.h"
#define RandomUniform drand48
#define RandomSeed srand48
#endif
int _sampleMethod = -1;
FILE *_sampleFile; // if _sampleMethod is SAMPLE_FROM_FILE
char *_sampleFileName;
char _sampleFileEOF;
// Below are the sampling methods
#define SAMPLE_FROM_FILE 0
#define SAMPLE_ACCEPT_REJECT 1 // makes things REALLY REALLY slow. Like 10-100 samples per second rather than a million.
#define SAMPLE_NODE_EXPANSION 2 // sample using uniform node expansion; about 100,000 samples per second
#define SAMPLE_EDGE_EXPANSION 3 // Fastest, up to a million samples per second
#define SAMPLE_RESERVOIR 4 // Lu Bressan's reservoir sampler, reasonably but not entirely unbiased.
#define SAMPLE_MCMC 5 // MCMC Algorithm estimates graphlet frequency with a random walk
#ifndef RESERVOIR_MULTIPLIER
// this*k is the number of steps in the Reservoir walk. 8 seems to work best, empirically.
#define RESERVOIR_MULTIPLIER 8
#endif
static Boolean _MCMC_UNIFORM = false; // Should MCMC restart at each edge
#define SAMPLE_FAYE 6
#define MAX_TRIES 100 // max # of tries in cumulative sampling before giving up
#define ALLOW_DISCONNECTED_GRAPHLETS 0
#define USE_INSERTION_SORT 0
// The following is the most compact way to store the permutation between a non-canonical and its canonical representative,
// when k=8: there are 8 entries, and each entry is a integer from 0 to 7, which requires 3 bits. 8*3=24 bits total.
// For simplicity we use the same 3 bits per entry, and assume 8 entries, even for k<8. It wastes memory for k<4, but
// makes the coding much simpler.
typedef unsigned char kperm[3]; // The 24 bits are stored in 3 unsigned chars.
static unsigned int _Bk, _k; // _k is the global variable storing k; _Bk=actual number of entries in the canon_map for given k.
static int _numCanon, _canonList[MAX_CANONICALS];
static SET *_connectedCanonicals;
static int _numOrbits, _orbitList[MAX_CANONICALS][maxK];
static int _orbitCanonMapping[MAX_ORBITS]; // Maps orbits to canonical (including disconnected)
//windowRep global Variables
#define WINDOW_SAMPLE_MIN 1 // Find the k-graphlet with minimal canonicalInt
#define WINDOW_SAMPLE_MAX 2 // Find the k-graphlet with maximal canonicalInt
#define WINDOW_SAMPLE_MIN_D 3 // Find the k-graphlet with minimal canonicalInt and balanced numEdges
#define WINDOW_SAMPLE_MAX_D 4 // Find the k-graphlet with maximal canonicalInt and balanced numEdges
#define WINDOW_SAMPLE_LEAST_FREQ_MIN 5 // Find the k-graphlet with least fequent cacnonicalInt. IF there is a tie, pick the minimal one
#define WINDOW_SAMPLE_LEAST_FREQ_MAX 6 // Find the k-graphlet with least fequent cacnonicalInt. IF there is a tie, pick the maximial one
int _windowSampleMethod = -1;
#define WINDOW_COMBO 0 // Turn on for using Combination method to sample k-graphlets in Window. Default is DFS-like way.
static int _windowSize = 0;
static Boolean _window = false;
static int** _windowReps;
static int _MAXnumWindowRep = 0;
static int _numWindowRep = 0;
enum OutputMode {undef, indexGraphlets, kovacsPairs, indexOrbits, graphletFrequency, outputODV, outputGDV};
static enum OutputMode _outputMode = undef;
static unsigned long int _graphletCount[MAX_CANONICALS];
enum CanonicalDisplayMode {undefined, ordinal, decimal, binary, orca, jesse};
static enum CanonicalDisplayMode _displayMode = undefined;
enum FrequencyDisplayMode {freq_display_mode_undef, count, concentration};
static enum FrequencyDisplayMode _freqDisplayMode = freq_display_mode_undef;
static int _magicTable[MAX_CANONICALS][12]; //Number of canonicals for k=8 by number of columns in magic table
static int _outputMapping[MAX_CANONICALS];
// A bit counter-intuitive: we need to allocate this many vectors each of length [_numNodes],
// and then the degree for node v, graphlet/orbit g is _degreeVector[g][v], NOT [v][g].
// We do this simply because we know the length of MAX_CANONICALS so we pre-know the length of
// the first dimension, otherwise we'd need to get more funky with the pointer allocation.
// Only one of these actually get allocated, depending upon outputMode.
static unsigned long int *_graphletDegreeVector[MAX_CANONICALS];
static unsigned long int *_orbitDegreeVector[MAX_ORBITS];
static double *_doubleOrbitDegreeVector[MAX_ORBITS];
static int _orca_orbit_mapping[58]; // Mapping from orbit indices in orca_ordering to our orbits
static int _connectedOrbits[MAX_ORBITS];
static int _numConnectedOrbits;
// If you're squeemish then use this one to access the degrees:
#define ODV(node,orbit) _orbitDegreeVector[orbit][node]
#define GDV(node,graphlet) _graphletDegreeVector[graphlet][node]
// number of parallel threads to run. This must be global because we may get called from C++.
static int _THREADS;
// Here's where we're lazy on saving memory, and we could do better. We're going to allocate a static array
// that is big enough for the 256 million permutations from non-canonicals to canonicals for k=8, even if k<8.
// So we're allocating 256MBx3=768MB even if we need much less. I figure anything less than 1GB isn't a big deal
// these days. It needs to be aligned to a page boundary since we're going to mmap the binary file into this array.
//static kperm Permutations[maxBk] __attribute__ ((aligned (8192)));
kperm *Permutations = NULL; // Allocating memory dynamically
// Here's the actual mapping from non-canonical to canonical, same argument as above wasting memory, and also mmap'd.
// So here we are allocating 256MB x sizeof(short int) = 512MB.
// Grand total statically allocated memory is exactly 1.25GB.
//static short int _K[maxBk] __attribute__ ((aligned (8192)));
short int *_K = NULL; // Allocating memory dynamically
//The number of edges required to walk a *Hamiltonion* path
static unsigned _MCMC_L; // walk length for MCMC algorithm. k-d+1 with d almost always being 2.
static int _alphaList[MAX_CANONICALS];
static double _graphletConcentration[MAX_CANONICALS];
static int _alphaList[MAX_CANONICALS];
/* AND NOW THE CODE */
// You provide a permutation array, we fill it with the permutation extracted from the compressed Permutation mapping.
// There is the inverse transformation, called "EncodePerm", in createBinData.c.
static void ExtractPerm(char perm[_k], int i)
{
int j, i32 = 0;
for(j=0;j<3;j++) i32 |= (Permutations[i][j] << j*8);
for(j=0;j<_k;j++)
perm[j] = (i32 >> 3*j) & 7;
}
// Given the big graph G and a set of nodes in V, return the TINY_GRAPH created from the induced subgraph of V on G.
static TINY_GRAPH *TinyGraphInducedFromGraph(TINY_GRAPH *Gv, GRAPH *G, int *Varray)
{
unsigned i, j;
TinyGraphEdgesAllDelete(Gv);
for(i=0; i < Gv->n; i++) for(j=i+1; j < Gv->n; j++)
if(GraphAreConnected(G, Varray[i], Varray[j]))
TinyGraphConnect(Gv, i, j);
return Gv;
}
// return how many nodes found. If you call it with startingNode == 0 then we automatically clear the visited array
static TSET _visited;
static int NumReachableNodes(TINY_GRAPH *g, int startingNode)
{
if(startingNode == 0) TSetEmpty(_visited);
TSetAdd(_visited,startingNode);
unsigned int j, Varray[maxK], numVisited = 0;
int numNeighbors = TSetToArray(Varray, g->A[startingNode]);
assert(numNeighbors == g->degree[startingNode]);
for(j=0; j<numNeighbors; j++)if(!TSetIn(_visited,Varray[j])) numVisited += NumReachableNodes(g,Varray[j]);
return 1+numVisited;
}
static unsigned int _numConnectedComponents;
static unsigned int *_whichComponent; // will be an array of size G->n specifying which CC each node is in.
static unsigned int *_componentSize; // number of nodes in each CC
static unsigned int **_componentList; // list of lists of components, largest to smallest.
static double _totalCombinations, *_combinations, *_probOfComponent, *_cumulativeProb;
static SET **_componentSet;
void PrintNode(int v) {
#if SHAWN_AND_ZICAN
printf("%s", _nodeNames[v]);
#else
if(_supportNodeNames)
printf("%s", _nodeNames[v]);
else
printf("%d", v);
#endif
}
static int InitializeConnectedComponents(GRAPH *G)
{
static unsigned int v, *Varray, j, i;
assert(!Varray); // we only can be called once.
assert(_numConnectedComponents == 0);
SET *visited = SetAlloc(G->n);
Varray = Calloc(G->n, sizeof(int));
_whichComponent = Calloc(G->n, sizeof(int));
_componentSize = Calloc(G->n, sizeof(int)); // probably bigger than it needs to be but...
_componentList = Calloc(G->n, sizeof(int*)); // probably bigger...
_combinations = Calloc(G->n, sizeof(double*)); // probably bigger...
_probOfComponent = Calloc(G->n, sizeof(double*)); // probably bigger...
_cumulativeProb = Calloc(G->n, sizeof(double*)); // probably bigger...
_componentSet = Calloc(G->n, sizeof(SET*));
int nextStart = 0;
_componentList[0] = Varray;
for(v=0; v < G->n; v++) if(!SetIn(visited, v))
{
_componentSet[_numConnectedComponents] = SetAlloc(G->n);
_componentList[_numConnectedComponents] = Varray + nextStart;
GraphVisitCC(G, v, _componentSet[_numConnectedComponents], Varray + nextStart, _componentSize + _numConnectedComponents);
SetUnion(visited, visited, _componentSet[_numConnectedComponents]);
for(j=0; j < _componentSize[_numConnectedComponents]; j++)
{
assert(_whichComponent[Varray[nextStart + j]] == 0);
_whichComponent[Varray[nextStart + j]] = _numConnectedComponents;
}
nextStart += _componentSize[_numConnectedComponents];
++_numConnectedComponents;
}
assert(nextStart == G->n);
_totalCombinations = 0.0;
for(i=0; i< _numConnectedComponents; i++)
{
//find the biggest one
int biggest = i;
for(j=i+1; j<_numConnectedComponents;j++)
if(_componentSize[j] > _componentSize[biggest])
biggest = j;
// Now swap the biggest one into position i;
for(j=0; j < _componentSize[biggest]; j++)
_whichComponent[_componentList[biggest][j]] = i;
int itmp, *pitmp;
SET * stmp;
itmp = _componentSize[i];
_componentSize[i] = _componentSize[biggest];
_componentSize[biggest] = itmp;
pitmp = _componentList[i];
_componentList[i] = _componentList[biggest];
_componentList[biggest] = pitmp;
stmp = _componentSet[i];
_componentSet[i] = _componentSet[biggest];
_componentSet[biggest] = stmp;
_combinations[i] = CombinChooseDouble(_componentSize[i], _k);
_totalCombinations += _combinations[i];
}
double cumulativeProb = 0.0;
for(i=0; i< _numConnectedComponents; i++)
{
_probOfComponent[i] = _combinations[i] / _totalCombinations;
_cumulativeProb[i] = cumulativeProb + _probOfComponent[i];
cumulativeProb = _cumulativeProb[i];
if(cumulativeProb > 1)
{
assert(cumulativeProb - 1.0 < _numConnectedComponents * 1e-15); // allow some roundoff error
cumulativeProb = _cumulativeProb[i] = 1.0;
}
//printf("Component %d has %d nodes and probability %lf, cumulative prob %lf\n", i, _componentSize[i], _probOfComponent[i], _cumulativeProb[i]);
}
return _numConnectedComponents;
}
// Given the big graph G and an integer k, return a k-graphlet from G
// in the form of a SET of nodes called V. When complete, |V| = k.
// Caller is responsible for allocating the set V and its array Varray.
// The algorithm works by maintaining the exact set of edges that are
// emanating out of the graphlet-in-construction. Then we pick one of
// these edges uniformly at random, add the node at the endpoint of that
// edge to the graphlet, and then add all the outbound edges from that
// new node (ie., edges that are not going back inside the graphlet).
// So the "outset" is the set of edges going to nodes exactly distance
// one from the set V, as V is being built.
static SET *SampleGraphletNodeBasedExpansion(SET *V, int *Varray, GRAPH *G, int k, int whichCC)
{
static SET *outSet;
static int numIsolatedNodes;
if(!outSet)
outSet = SetAlloc(G->n); // we won't bother to free this since it's static.
else if(G->n > outSet->n)
SetResize(outSet, G->n);
else
SetEmpty(outSet);
int v1, v2, i;
int nOut = 0, outbound[G->n]; // vertices one step outside the boundary of V
assert(V && V->n >= G->n);
SetEmpty(V);
int edge;
do {
edge = G->numEdges * RandomUniform();
v1 = G->edgeList[2*edge];
} while(!SetIn(_componentSet[whichCC], v1));
v2 = G->edgeList[2*edge+1];
SetAdd(V, v1); Varray[0] = v1;
SetAdd(V, v2); Varray[1] = v2;
// The below loops over neighbors can take a long time for large graphs with high mean degree. May be faster
// with bit operations if we stored the adjacency matrix... which may be too big to store for big graphs. :-(
for(i=0; i < G->degree[v1]; i++)
{
int nv1 = G->neighbor[v1][i];
if(nv1 != v2)
{
assert(!SetIn(V, nv1)); // assertion to ensure we're in line with faye
SetAdd(outSet, (outbound[nOut++] = nv1));
}
}
for(i=0; i < G->degree[v2]; i++)
{
int nv2 = G->neighbor[v2][i];
if(nv2 != v1 && !SetIn(outSet, nv2))
{
assert(!SetIn(V, nv2)); // assertion to ensure we're in line with faye
SetAdd(outSet, (outbound[nOut++] = nv2));
}
}
for(i=2; i<k; i++)
{
int j;
if(nOut == 0) // the graphlet has saturated it's connected component
{
assert(SetCardinality(outSet) == 0);
assert(SetCardinality(V) < k);
#if ALLOW_DISCONNECTED_GRAPHLETS
while(SetIn(V, (j = G->n*RandomUniform())))
; // must terminate since k <= G->n
outbound[nOut++] = j;
j = 0;
#else
static int depth;
depth++;
// must terminate eventually as long as there's at least one connected component with >=k nodes.
assert(depth < MAX_TRIES); // graph is too disconnected
V = SampleGraphletNodeBasedExpansion(V, Varray, G, k, whichCC);
depth--;
// Ensure the damn thing really *is* connected.
TINY_GRAPH *T = TinyGraphAlloc(k);
TinyGraphInducedFromGraph(T, G, Varray);
assert(NumReachableNodes(T,0) == k);
TinyGraphFree(T);
return V;
#endif
}
else
j = nOut * RandomUniform();
v1 = outbound[j];
SetDelete(outSet, v1);
SetAdd(V, v1); Varray[i] = v1;
outbound[j] = outbound[--nOut]; // nuke v1 from the list of outbound by moving the last one to its place
for(j=0; j<G->degree[v1];j++) // another loop over neighbors that may take a long time...
{
v2 = G->neighbor[v1][j];
if(!SetIn(outSet, v2) && !SetIn(V, v2))
SetAdd(outSet, (outbound[nOut++] = v2));
}
}
assert(i==k);
#if PARANOID_ASSERTS
assert(SetCardinality(V) == k);
assert(nOut == SetCardinality(outSet));
#endif
return V;
}
// modelled after faye by Tuong Do
static SET *SampleGraphletFaye(SET *V, int *Varray, GRAPH *G, int k, int whichCC)
{
/* Faye: Add a visited array to keep track of nodes. Initialize to 0 */
int visited[G->n];
int m = 0;
for (m = 0; m < G->n; m++) {
visited[m] = 0;
}
static SET *outSet;
static int numIsolatedNodes;
if(!outSet)
outSet = SetAlloc(G->n); // we won't bother to free this since it's static.
else if(G->n > outSet->n)
SetResize(outSet, G->n);
else
SetEmpty(outSet);
int v1, v2, i;
int nOut = 0, outbound[G->n]; // vertices one step outside the boundary of V
assert(V && V->n >= G->n);
SetEmpty(V);
int edge;
do {
edge = G->numEdges * RandomUniform();
v1 = G->edgeList[2*edge];
} while(!SetIn(_componentSet[whichCC], v1));
v2 = G->edgeList[2*edge+1];
SetAdd(V, v1); Varray[0] = v1;
SetAdd(V, v2); Varray[1] = v2;
/* Faye: Mark v1 and v2 as visited */
visited[v1] = 1;
visited[v2] = 1;
// The below loops over neighbors can take a long time for large graphs with high mean degree. May be faster
// with bit operations if we stored the adjacency matrix... which may be too big to store for big graphs. :-(
for(i=0; i < G->degree[v1]; i++)
{
int nv1 = G->neighbor[v1][i];
if(nv1 != v2)
{
assert(!SetIn(V, nv1)); // assertion to ensure we're in line with faye
if (!visited[nv1]) { /* Faye: Check if it's visited */
SetAdd(outSet, (outbound[nOut++] = nv1));
visited[nv1] = 1;
}
}
}
for(i=0; i < G->degree[v2]; i++)
{
int nv2 = G->neighbor[v2][i];
if(nv2 != v1 && !SetIn(outSet, nv2))
{
assert(!SetIn(V, nv2)); // assertion to ensure we're in line with faye
if (!visited[nv2]) { /* Faye: Check if it's visited */
SetAdd(outSet, (outbound[nOut++] = nv2));
visited[nv2] = 1;
}
}
}
for(i=2; i<k; i++)
{
int j;
if(nOut == 0) // the graphlet has saturated it's connected component
{
assert(SetCardinality(outSet) == 0);
assert(SetCardinality(V) < k);
#if ALLOW_DISCONNECTED_GRAPHLETS
/* Faye: check if the random node is visited instead
*while(SetIn(V, (j = G->n*RandomUniform()))
*/
while(visited[(j = G->n*RandomUniform())])
; // must terminate since k <= G->n
outbound[nOut++] = j;
j = 0;
#else
static int depth;
depth++;
// must terminate eventually as long as there's at least one connected component with >=k nodes.
assert(depth < MAX_TRIES); // graph is too disconnected
V = SampleGraphletFaye(V, Varray, G, k, whichCC);
depth--;
// Ensure the damn thing really *is* connected.
TINY_GRAPH *T = TinyGraphAlloc(k);
TinyGraphInducedFromGraph(T, G, Varray);
assert(NumReachableNodes(T,0) == k);
TinyGraphFree(T);
return V;
#endif
}
else
j = nOut * RandomUniform();
v1 = outbound[j];
SetDelete(outSet, v1);
SetAdd(V, v1); Varray[i] = v1;
outbound[j] = outbound[--nOut]; // nuke v1 from the list of outbound by moving the last one to its place
for(j=0; j<G->degree[v1];j++) // another loop over neighbors that may take a long time...
{
v2 = G->neighbor[v1][j];
/* Faye: check if it's invisted instead
* if(!SetIn(outSet, v2) && !SetIn(V, v2)) */
if (!visited[v2]) {
SetAdd(outSet, (outbound[nOut++] = v2));
visited[v2] = 1;
}
}
}
assert(i==k);
#if PARANOID_ASSERTS
assert(SetCardinality(V) == k);
assert(nOut == SetCardinality(outSet));
#endif
return V;
}
// Returns NULL if there are no more samples
static SET *SampleGraphletFromFile(SET *V, int *Varray, GRAPH *G, int k)
{
SetEmpty(V);
int i, numRead;
char line[BUFSIZ];
char *s = fgets(line, sizeof(line), _sampleFile);
if(!s){
_sampleFileEOF = 1; // forces exit below
return NULL;
}
switch(k)
{
case 3: numRead = sscanf(line, "%d%d%d",Varray,Varray+1,Varray+2); break;
case 4: numRead = sscanf(line, "%d%d%d%d",Varray,Varray+1,Varray+2,Varray+3); break;
case 5: numRead = sscanf(line, "%d%d%d%d%d",Varray,Varray+1,Varray+2,Varray+3,Varray+4); break;
case 6: numRead = sscanf(line, "%d%d%d%d%d%d",Varray,Varray+1,Varray+2,Varray+3,Varray+4,Varray+5); break;
case 7: numRead = sscanf(line, "%d%d%d%d%d%d%d",Varray,Varray+1,Varray+2,Varray+3,Varray+4,Varray+5,Varray+6); break;
case 8: numRead = sscanf(line, "%d%d%d%d%d%d%d%d",Varray,Varray+1,Varray+2,Varray+3,Varray+4,Varray+5,Varray+6,Varray+7); break;
default: Fatal("unknown k value %d",k);
}
assert(numRead == k);
for(k=0;i<k;i++){
assert(Varray[i] >= 0 && Varray[i] < G->n);
SetAdd(V, Varray[i]);
}
return V;
}
/*
** This is a faster graphlet sampling routine, although it may produce a
** distribution of graphlets that is further from "ideal" than the above.
** The difference is that in the above method we explicitly build and maintain
** the "outset" (the set of nodes one step outside V), but this can expensive
** when the mean degree of the graph G is high, since we have to add all the
** new edges emanating from each new node that we add to V. Instead, here we
** are not going to explicitly maintain this outset. Instead, we're simply
** going to remember the total number of edges emanating from every node in
** V *including* edges heading back into V, which are techically useless to us.
** This sum is just the sum of all the degrees of all the nodes in V. Call this
** number "outDegree". Then, among all the edges emanating out of every node in
** V, we pick a random node from V where the probablity of picking any node v is
** proportional to its degree. Then we pick one of the edges emanating out of v
** uniformly at random. Thus, every edge leaving every node in V has equal
** probability of being chosen---even though some of them lead back into V. If
** that is the case, then we throw away that edge and try the whole process again.
** The advantage here is that for graphs G with high mean degree M, the probability
** of picking an edge leading back into V is bounded by (k-1)/M, which becomes small
** as M gets large, and so we're very unlikely to "waste" samples. Thus, unlike the
** above algorithm that gets *more* expensive with increasing density of G, this
** algorithm actually get cheaper with increasing density.
** Another way of saying this is that we avoid actually building the outSet
** as we do above, we instead simply keep a *estimated* count C[v] of separate
** outSets of each node v in the accumulating graphlet. Then we pick
** an integer in the range [0,..sum(C)), go find out what node that is,
** and if it turns out to be a node already in V, then we simply try again.
** It turns out that even if the mean degree is small, this method is *still*
** faster. In other words, it's *always* faster than the above method. The
** only reason we may prefer the above method is because it's theoretically cleaner
** to describe the distribution of graphlets that comes from it---although
** empirically this one does reasonably well too. However, if the only goal
** is blinding speed at graphlet sampling, eg for building a graphlet database
** index, then this is the preferred method.
*/
static SET *SampleGraphletEdgeBasedExpansion(SET *V, int *Varray, GRAPH *G, int k, int whichCC)
{
int edge, v1, v2;
assert(V && V->n >= G->n);
SetEmpty(V);
int nOut = 0;
do {
edge = G->numEdges * RandomUniform();
v1 = G->edgeList[2*edge];
} while(!SetIn(_componentSet[whichCC], v1));
v2 = G->edgeList[2*edge+1];
SetAdd(V, v1); Varray[0] = v1;
SetAdd(V, v2); Varray[1] = v2;
int vCount = 2;
int outDegree = G->degree[v1] + G->degree[v2];
static int cumulative[maxK];
cumulative[0] = G->degree[v1]; // where v1 = Varray[0]
cumulative[1] = G->degree[v2] + cumulative[0];
static SET *internal; // mark choices of whichNeigh that are discovered to be internal
static int Gn;
if(!internal) {internal = SetAlloc(G->n); Gn = G->n;}
else if(Gn != G->n) {SetFree(internal); internal = SetAlloc(G->n); Gn=G->n;}
else SetEmpty(internal);
int numTries = 0;
while(vCount < k)
{
int i, whichNeigh, newNode = -1;
while(numTries < MAX_TRIES &&
(whichNeigh = outDegree * RandomUniform()) >= 0 && // always true, just setting whichNeigh
SetIn(internal, whichNeigh))
++numTries; // which edge to choose among all edges leaving all nodes in V so far?
if(numTries >= MAX_TRIES) {
#if ALLOW_DISCONNECTED_GRAPHLETS
// get a new node outside this connected component.
// Note this will return a disconnected graphlet.
while(SetIn(V, (newNode = G->n*RandomUniform())))
; // must terminate since k <= G->n
numTries = 0;
outDegree = 0;
int j;
for(j=0; j<vCount; j++) // avoid picking these nodes ever again.
cumulative[j] = 0;
SetEmpty(internal);
#else
static int depth;
depth++;
assert(depth < MAX_TRIES);
V = SampleGraphletEdgeBasedExpansion(V, Varray, G, k, whichCC);
depth--;
return V;
#endif
}
for(i=0; cumulative[i] <= whichNeigh; i++)
; // figure out whose neighbor it is
int localNeigh = whichNeigh-(cumulative[i]-G->degree[Varray[i]]); // which neighbor of node i?
if(newNode < 0) newNode = G->neighbor[Varray[i]][localNeigh];
#if PARANOID_ASSERTS
// really should check some of these a few lines higher but let's group all the paranoia in one place.
assert(i < vCount);
assert(0 <= localNeigh && localNeigh < G->degree[Varray[i]]);
assert(0 <= newNode && newNode < G->n);
#endif
if(SetIn(V, newNode))
{
SetAdd(internal, whichNeigh);
if(++numTries < MAX_TRIES)
continue;
else // graph is too disconnected
{
#if PARANOID_ASSERTS
// We are probably in a connected component with fewer than k nodes.
// Test that hypothesis.
assert(!GraphCCatLeastK(G, v1, k));
#endif
#if ALLOW_DISCONNECTED_GRAPHLETS
// get a new node outside this connected component.
// Note this will return a disconnected graphlet.
while(SetIn(V, (newNode = G->n*RandomUniform())))
; // must terminate since k <= G->n
numTries = 0;
outDegree = 0;
int j;
for(j=0; j<vCount; j++) // avoid picking these nodes ever again.
cumulative[j] = 0;
SetEmpty(internal);
#else
static int depth;
depth++;
assert(depth < MAX_TRIES);
V = SampleGraphletEdgeBasedExpansion(V, Varray, G, k, whichCC);
depth--;
return V;
#endif
}
}
SetAdd(V, newNode);
cumulative[vCount] = cumulative[vCount-1] + G->degree[newNode];
Varray[vCount++] = newNode;
outDegree += G->degree[newNode];
#if PARANOID_ASSERTS
assert(SetCardinality(V) == vCount);
assert(outDegree == cumulative[vCount-1]);
#endif
}
#if PARANOID_ASSERTS
assert(SetCardinality(V) == k);
assert(vCount == k);
#endif
return V;
}
// From the paper: ``Sampling Connected Induced Subgraphs Uniformly at Random''
// Xuesong Lu and Stephane Bressan, School of Computing, National University of Singapore
// {xuesong,steph}@nus.edu.sg
// 24th International Conference on Scientific and Statistical Database Management, 2012
// Note that they suggest *edge* based expansion to select the first k nodes, and then
// use reservoir sampling for the rest. But we know edge-based expansion sucks, so we'll
// start with a better starting guess, which is node-based expansion.
static SET *SampleGraphletLuBressanReservoir(SET *V, int *Varray, GRAPH *G, int k, int whichCC)
{
// Start by getting the first k nodes using a previous method. Once you figure out which is
// better, it's probably best to share variables so you don't have to recompute the outset here.
#if 1 // the following is copied almost verbatim from NodeEdgeExpansion, just changing for loop to while loop.
static SET *outSet;
static int numIsolatedNodes;
if(!outSet)
outSet = SetAlloc(G->n); // we won't bother to free this since it's static.
else if(G->n > outSet->n)
SetResize(outSet, G->n);
else
SetEmpty(outSet);
int v1, v2, i;
int nOut = 0, outbound[G->n]; // vertices one step outside the boundary of V
assert(V && V->n >= G->n);
SetEmpty(V);
int edge;
do {
edge = G->numEdges * RandomUniform();
v1 = G->edgeList[2*edge];
} while(!SetIn(_componentSet[whichCC], v1));
v2 = G->edgeList[2*edge+1];
SetAdd(V, v1); Varray[0] = v1;
SetAdd(V, v2); Varray[1] = v2;
// The below loops over neighbors can take a long time for large graphs with high mean degree. May be faster
// with bit operations if we stored the adjacency matrix... which may be too big to store for big graphs. :-(
for(i=0; i < G->degree[v1]; i++)
{
int nv1 = G->neighbor[v1][i];
if(nv1 != v2) SetAdd(outSet, (outbound[nOut++] = nv1));
}
for(i=0; i < G->degree[v2]; i++)
{
int nv2 = G->neighbor[v2][i];
if(nv2 != v1 && !SetIn(outSet, nv2)) SetAdd(outSet, (outbound[nOut++] = nv2));
}
i=2;
// while(i<k || nOut > 0) // always do the loop at least k times, but i>=k is the reservoir phase.
while(i < RESERVOIR_MULTIPLIER*k) // value of 8 seems to work best from empirical studies.
{
int candidate;
if(nOut ==0) // the graphlet has saturated its connected component before getting to k, start elsewhere
{
#if ALLOW_DISCONNECTED_GRAPHLETS
if(i < k)
{
int tries=0;
while(SetIn(V, (v1 = G->n*RandomUniform())))
assert(tries++<MAX_TRIES); // graph is too disconnected
outbound[nOut++] = v1; // recall that nOut was 0 to enter this block, so now it's 1
candidate = 0; // representing v1 as the 0'th entry in the outbound array
}
else
assert(i==k); // we're done because i >= k and nOut == 0... but we shouldn't get here.
#else
static int depth;
depth++;
assert(depth < MAX_TRIES); // graph is too disconnected
V = SampleGraphletLuBressanReservoir(V, Varray, G, k, whichCC);
depth--;
return V;
#endif
}
else
{
candidate = nOut * RandomUniform();
v1 = outbound[candidate];
}
assert(v1 == outbound[candidate]);
SetDelete(outSet, v1);
outbound[candidate] = outbound[--nOut];// nuke v1 by moving the last one to its place
if(i < k)
{
Varray[i] = v1;
SetAdd(V, v1);
int j;
for(j=0; j<G->degree[v1];j++) // another loop over neighbors that may take a long time...
{
v2 = G->neighbor[v1][j];
if(!SetIn(outSet, v2) && !SetIn(V, v2))
SetAdd(outSet, (outbound[nOut++] = v2));
}
}
else
{
double reservoir_alpha = RandomUniform();
if(reservoir_alpha < k/(double)i)
{
static TINY_GRAPH *T;
if(!T) T = TinyGraphAlloc(k);
static int graphetteArray[maxK], distArray[maxK];
#if PARANOID_ASSERTS
// ensure it's connected before we do the replacement
TinyGraphEdgesAllDelete(T);
TinyGraphInducedFromGraph(T, G, Varray);
#if 0
printf("NRN = %d\n", NumReachableNodes(T, 0));
printf("BFS = %d\n", TinyGraphBFS(T, 0, k, graphetteArray, distArray));
#endif
assert(NumReachableNodes(T, 0) == TinyGraphBFS(T, 0, k, graphetteArray, distArray));
assert(NumReachableNodes(T, 0) == k);
#endif
int memberToDelete = k*RandomUniform();
v2 = Varray[memberToDelete]; // remember the node delated from V in case we need to revert
Varray[memberToDelete] = v1; // v1 is the outbound candidate.
TinyGraphEdgesAllDelete(T);
TinyGraphInducedFromGraph(T, G, Varray);
assert(NumReachableNodes(T,0) == TinyGraphBFS(T, 0, k, graphetteArray, distArray));
if(NumReachableNodes(T, 0) < k)
Varray[memberToDelete] = v2; // revert the change because the graph is not connected
else // add the new guy and delete the old
{
#if PARANOID_ASSERTS
assert(SetCardinality(V) == k);
#endif
SetDelete(V, v2);
SetAdd(V, v1);
#if PARANOID_ASSERTS
assert(SetCardinality(V) == k);
#endif
int j;
for(j=0; j<G->degree[v1];j++) // another loop over neighbors that may take a long time...
{
v2 = G->neighbor[v1][j];
if(!SetIn(outSet, v2) && !SetIn(V, v2))
SetAdd(outSet, (outbound[nOut++] = v2));
}
}
}
}
i++;
}
#else
SampleGraphletEdgeBasedExpansion(V, Varray, G, k, whichCC);
#endif
return V;
}
int alphaListPopulate(char *BUF, int *alpha_list, int k) {
sprintf(BUF, "%s/%s/alpha_list_mcmc%d.txt", _BLANT_DIR, CANON_DIR, k);
FILE *fp_ord=fopen(BUF, "r");
if(!fp_ord) Fatal("cannot find %s\n", BUF);
int numAlphas, i;
assert(1==fscanf(fp_ord, "%d",&numAlphas));
assert(numAlphas == _numCanon);
for(i=0; i<numAlphas; i++) assert(1==fscanf(fp_ord, "%d", &alpha_list[i]));
fclose(fp_ord);
return numAlphas;
}
// Update the most recent d-graphlet to a random neighbor of it
int *MCMCGetNeighbor(int *Xcurrent, GRAPH *G)
{
if (mcmc_d == 2)
{
int oldu = Xcurrent[0];
int oldv = Xcurrent[1];
int numTries = 0;
while (oldu == Xcurrent[0] && oldv == Xcurrent[1]) {
#if PARANOID_ASSERTS
assert(++numTries < MAX_TRIES);
#endif
double p = RandomUniform();
// if 0 < p < 1, p < deg(u) + deg(v) then
if (p < ((double)G->degree[Xcurrent[0]])/(G->degree[Xcurrent[0]] + G->degree[Xcurrent[1]])) {
// select randomly from Neigh(u) and swap
int neighbor = (int) (G->degree[Xcurrent[0]] * RandomUniform());
Xcurrent[1] = G->neighbor[Xcurrent[0]][neighbor];
}
else {
// select randomly from Neigh(v) and swap
int neighbor = (int) (G->degree[Xcurrent[1]] * RandomUniform());
Xcurrent[0] = G->neighbor[Xcurrent[1]][neighbor];
}
}
#if PARANOID_ASSERTS
assert(Xcurrent[0] != Xcurrent[1]);
assert(oldu != Xcurrent[0] || oldv != Xcurrent[1]);
assert(oldu != Xcurrent[1] || oldv != Xcurrent[0]);
#endif
}
else Fatal("Not implemented. Set d to 2");
return Xcurrent;
}
// Crawls one step along the graph updating our sliding window
void crawlOneStep(MULTISET *XLS, QUEUE *XLQ, int* X, GRAPH *G) {
int v, i;
for (i = 0; i < mcmc_d; i++) { // Remove oldest d graphlet from sliding window
v = QueueGet(XLQ).i;
MultisetDelete(XLS, v);
}
MCMCGetNeighbor(X, G); // Gets a neighbor graphlet of the most recent d vertices and add to sliding window
for (i = 0; i < mcmc_d; i++) {
MultisetAdd(XLS, X[i]);
QueuePut(XLQ, (foint) X[i]);
}
}
// Initialize a sliding window represented by a multiset and queue of vertices.
// Sliding window is generated from a preselected edge from a predefined connected component and grown through edge walking.
void initializeSlidingWindow(MULTISET *XLS, QUEUE *XLQ, int* X, GRAPH *G, int windowSize, int edge)
{
MultisetEmpty(XLS);
QueueEmpty(XLQ);
if (windowSize < 1) {
Fatal("Window Size must be at least 1");
}
#if PARANOID_ASSERTS
assert(edge >= 0 && edge < G->numEdges);
#endif
X[0] = G->edgeList[2 * edge];
X[1] = G->edgeList[2 * edge + 1];
MultisetAdd(XLS, X[0]); QueuePut(XLQ, (foint) X[0]);
MultisetAdd(XLS, X[1]); QueuePut(XLQ, (foint) X[1]);
// Add windowSize-1 d graphlets to our sliding window. The edge we added is the first d graphlet
int i, j;
for (i = 1; i < windowSize; i++) {
MCMCGetNeighbor(X, G); // After each call latest graphlet is in X array
for (j = 0; j < mcmc_d; j++) {
MultisetAdd(XLS, X[j]);
QueuePut(XLQ, (foint) X[j]);
}
}
}
// WalkLSteps fills XLS, XLQ (the sliding window) with L dgraphlets
// Given an empty sliding window, XLQ, XLS, walk along the graph starting at a random edge
// growing our sliding window until we have L graphlets in it.
// Then, we slide our window until it has k distinct vertices. That represents our initial sampling
// when we start/restart.
void WalkLSteps(MULTISET *XLS, QUEUE *XLQ, int* X, GRAPH *G, int k, int cc, int edge)
{
//For now d must be equal to 2 because we start by picking a random edge
if (mcmc_d != 2) {
Fatal("mcmc_d must be set to 2 in blant.h for now");
}
if (edge < 0 && cc == -1) { // Pick a random edge from anywhere in the graph that has at least k nodes
do {
edge = G->numEdges * RandomUniform();
X[0] = G->edgeList[2*edge];
} while(!(_componentSize[_whichComponent[G->edgeList[2*edge]]] < k));
X[1] = G->edgeList[2*edge+1];
}
else if (edge < 0) { // Pick a random edge from within a chosen connected component
do {
edge = G->numEdges * RandomUniform();
X[0] = G->edgeList[2*edge];
} while(!SetIn(_componentSet[cc], X[0]));
X[1] = G->edgeList[2*edge+1];
}
// else start from the preselected edge
#if PARANOID_ASSERTS
assert(_componentSize[_whichComponent[X[0]]] >= k); // Assert we can fill the window with the prechosen edge.
#endif
initializeSlidingWindow(XLS, XLQ, X, G, _MCMC_L, edge);
// Keep crawling until we have k distinct vertices
static int numTries = 0;
static int depth = 0;
while (MultisetSupport(XLS) < k) {
if (numTries++ > MAX_TRIES) { // If we crawl 100 steps without k distinct vertices restart
assert(depth++ < MAX_TRIES); // If we restart 100 times in a row without success give up
WalkLSteps(XLS,XLQ,X,G,k,cc,edge); // try again
depth = 0; // If we get passed the recursive calls and successfully find a k graphlet, reset our depth
numTries = 0; // And our number of attempts to crawl one step
return;
}
crawlOneStep(XLS, XLQ, X, G);
}
numTries = 0;
}
static int _numSamples = 0;
static int _samplesPerEdge = 0;
/* SampleGraphletMCMC first starts with an edge in Walk L steps.
It then walks along L = k-1 edges with MCMCGetNeighbor until it fills XLQ and XLS with L edges(their vertices are stored).
XLQ and XLS always hold 2L vertices. They represent a window of the last L edges walked. If that window contains k
distinct vertices, a graphlet is returned.
This random walk predictably overcounts graphlets based on the alpha value and multipler.
The alpha value is precomputed per graphlet type and the multiplier is based on the degree of the graphlets inside of it.
After the algorithm is run the frequencies are normalized into concentrations.
*/
static SET *SampleGraphletMCMC(SET *V, int *Varray, GRAPH *G, int k, int whichCC) {
static Boolean setup = false;
static int currSamples = 0; // Counts how many samples weve done at the current starting point
static int currEdge = 0; // Current edge we are starting at for uniform sampling
static MULTISET *XLS = NULL; // A multiset holding L dgraphlets as separate vertex integers
static QUEUE *XLQ = NULL; // A queue holding L dgraphlets as separate vertex integers
static int Xcurrent[mcmc_d]; // holds the most recently walked d graphlet as an invariant
static TINY_GRAPH *g = NULL; // Tinygraph for computing overcounting;
if (!XLQ || !XLS || !g) {
//NON REENTRANT CODE
XLQ = QueueAlloc(k*mcmc_d);
XLS = MultisetAlloc(G->n);
g = TinyGraphAlloc(k);
}
// The first time we run this, or when we restart. We want to find our initial L d graphlets.
if (!setup && !_MCMC_UNIFORM) {
setup = true;
WalkLSteps(XLS, XLQ, Xcurrent, G, k, whichCC, -1);
}
else if (_MCMC_UNIFORM && (!setup || currSamples >= _samplesPerEdge))