-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainAlgo.py
More file actions
1286 lines (1112 loc) · 54.4 KB
/
Copy pathMainAlgo.py
File metadata and controls
1286 lines (1112 loc) · 54.4 KB
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
#Experimental Algorithms
import os, copy
import time
import numpy as np
import numpy.random as npr
import random, sys
import networkx as nx
import pdb
import cPickle
import gc
import TestScripts
import UtilityAlloc
import AltAlgo #module might be refered in params['algorithm']
np.seterr(all='raise')
timeNow = lambda : time.strftime('%Y_%m_%d__%H_%M_%S', time.localtime())
random_one = lambda arr: random.sample(arr, 1)[0]
max_int = np.iinfo(np.int32(10)).max
def chart_paths(G, source, new_edge_horizon, search_method='particles', params=None):
#determine the path structure for paths from source a neighbor through a second path with a random walk
#weighted_random = params.get('weighted_random_walk_method', lambda G,src,valid_nodes: random_one(valid_nodes)) #weighted_step
#G_adj = G.adj
#G_neighborsSet = lambda u: set(G_adj[u].keys())
weighted_step = params.get('weighted_step', False)
sm = sum
rds = random.shuffle
find_next = weighted_step_advanced
G_adj = G.adj
G_neighborsSet = lambda u: set(G_adj[u].keys())
estimate_of_paths = np.zeros(new_edge_horizon+1)
num_trial_particles = params.get('num_trial_particles', 50)
if search_method == 'particles': #random walk from a neighbor to find any OTHER nbr
source_nbs = G_neighborsSet(source)
num_misses = 0
for cur_loc in [random_one(source_nbs) for i in xrange(num_trial_particles)]:
blocked = set([source, cur_loc])
for d in xrange(2, new_edge_horizon+1):
cur_loc = find_next(G=G, start_node=cur_loc, weighted_step=weighted_step, blocked=blocked, rds=rds, sm=sm)
if cur_loc == None: #stuck in a self-made corner
# num_misses += 1
#print 'corner'
#assert len(blocked) == d
break
#blocked.add(cur_loc)
if cur_loc in source_nbs:
estimate_of_paths[d] += 1
#print 'reached nb'
#assert len(blocked) == d + 1
break
elif d == new_edge_horizon:
# num_misses += 1
#print 'escaped'
break
if sum(estimate_of_paths) > 0:
estimate_of_paths /= sum(estimate_of_paths)
num_missed_neighbors = None #not applicable
elif search_method == 'particles_shortest': #random walk estimates the shortest alternative path to a neighbor
source_nbs = G_neighborsSet(source)
nb_steps = dict.fromkeys(G_adj[source].keys(), np.inf)
num_misses = 0
#wishlist: the distance depends on the starting nb. we need to be consistent and use the same starting nb
for cur_loc in [random_one(source_nbs) for i in xrange(num_trial_particles)]:
blocked = set([source, cur_loc])
for d in xrange(2, new_edge_horizon+1):
cur_loc = find_next(G=G, start_node=cur_loc, weighted_step=weighted_step, blocked=blocked, rds=rds, sm=sm)
if cur_loc == None: #stuck in a self-made corner
#num_misses += 1
#print 'corner'
#assert len(blocked) == d
break
#blocked.add(cur_loc)
if cur_loc in source_nbs and d <= nb_steps[cur_loc]:
nb_steps[cur_loc] = d
#assert len(blocked) == d + 1
break
elif d == new_edge_horizon:
#num_misses += 1
#print 'escaped'
break
for nb in nb_steps:
d = nb_steps[nb]
if d < np.inf:
estimate_of_paths[d] += 1
if sum(estimate_of_paths) > 0:
estimate_of_paths /= sum(estimate_of_paths)
num_missed_neighbors = None #not applicable
elif search_method == 'particles3': #routes, determines how many neighbors were never reached
source_nbs = dict.fromkeys(G_adj[source].keys(), False) #which neighbors were reached
for cur_loc in [random_one(source_nbs) for i in xrange(num_trial_particles)]:
blocked = set([source, cur_loc])
for d in xrange(2, new_edge_horizon+1):
cur_loc = find_next(G=G, start_node=cur_loc, weighted_step=weighted_step, blocked=blocked, rds=rds, sm=sm)
if cur_loc == None: #stuck in a self-made corner
break
if cur_loc in source_nbs:
estimate_of_paths[d] += 1
source_nbs[cur_loc] = True
break
#blocked.add(next_loc) #self-avoiding
#wishlist: maybe break if find all the neighbors
num_missed_neighbors = sum(1 for nb in source_nbs if not source_nbs[nb])
if sum(estimate_of_paths) > 0:
estimate_of_paths = (source_nbs.__len__() - num_missed_neighbors) * estimate_of_paths / sum(estimate_of_paths)
num_misses = None #N/A
else:
raise ValueError('Unknown search method')
#return estimate_of_paths, num_misses
#WARNING: many of our results were based on setting this to 0.
#we do not correctly estimate the number of misses ...
#print estimate_of_paths, num_misses
#pdb.set_trace()
#return estimate_of_paths, 0
return {'estimate_of_paths':estimate_of_paths,
'num_missed_neighbors':num_missed_neighbors,
'num_attempts':num_trial_particles,
'num_misses':num_misses,
}
def check_and_fix_connectivity(G, params):
new_edges = set()
ccs = [cc for cc in nx.connected_components(G)]
if len(ccs) > 1:
giant_comp = ccs[0]
for cc in ccs[1:]:
u,w = random.sample(giant_comp, 1)[0], random.sample(cc, 1)[0]
G.add_edge(u,w)
new_edges.add((u,w))
return new_edges
def clean_c_data(G, c_data):
#this method serves no function other than trapping bugs: it removes data which should not be used in uncoarsening
aggregates = c_data['aggregates']
trapped_edges = c_data['trapped_edges']
home_nodes = c_data['home_nodes']
merged_edges = c_data['merged_edges']
deleted_seeds = [node for node in aggregates if not G.has_node(node)]
deleted_c_edges = [edge for edge in merged_edges if not G.has_edge(*edge)]
for node in deleted_seeds:
trapped_edges.pop(node)
for guest in aggregates[node]:
home_nodes.pop(guest)
aggregates.pop(node)
for edge in deleted_c_edges:
merged_edges.pop(edge)
return c_data
def compute_topology_data(G, level, params):
#measures statistics of the topology of graph G
#wishlist: for generation of multiple replicas, it would be helpful to do this computation once for the speedup
if params.get('verbose', True):
sys.stdout.write('Topology estimation ... ')
sys.stdout.flush()
tpl_data = {}
tpl_data['enforce_connected'] = nx.is_connected(G)
#estimates the probability of friending a node at distance d
new_edge_horizon = params.get('new_edge_horizon', estimate_horizon(G)) #no edges added to nodes beyond the horizon
num_pairs_to_sample = params.get('num_pairs_to_sample', 100) #revise comment #no edges added to nodes beyond the horizon
locality_algorithm = params.get('locality_algorithm', chart_paths) #which method to use for computing locality
num_nodes_beyond_the_horizon = 0.
overall_estimates = np.zeros(new_edge_horizon+1)
#for each node u in a sample, select one neighbor, and compute the distance up to H steps
# now see how many of the other neighbors of u have been reached.
# those not reached could be a kind of "beyond-the-horizon-edges", which are also possible
for source in random.sample(G.nodes(), min(G.number_of_nodes(), num_pairs_to_sample)):
source_degree = G.degree(source)
if source_degree == 0:
continue
elif source_degree == 1:
#num_nodes_beyond_the_horizon += 1
continue
#WARNING: many of our results are based on setting this to 0
#source_degree==1 is an important indicator that many edges are, in effect, chance edges
else:
#target_nb = random.choice(G.neighbors(source)) #we will pick any one
locality_data = locality_algorithm(G, source, new_edge_horizon, params=params, search_method=params.get('search_method', 'particles'))
#estimate_of_paths (and num_nodes_beyond_the_horizon) should have the norm of the number of nodes actually reached (not reached), b/c the source has different degrees
estimate_of_paths = locality_data['estimate_of_paths']
num_missed_neighbors = locality_data['num_missed_neighbors']
num_attempts = locality_data['num_attempts']
num_misses = locality_data['num_misses']
overall_estimates += estimate_of_paths
if num_missed_neighbors != None:
num_nodes_beyond_the_horizon += num_missed_neighbors
else:
num_nodes_beyond_the_horizon += num_misses
try:
locality_bias_correction = params['locality_bias_correction'][level]
except: locality_bias_correction = 0.
#locality_bias_correction = 0
if locality_bias_correction > 0: #shift weight downward b/c this estimator under-rates correlations between neighbors
overall_estimates[-1] += locality_bias_correction * num_nodes_beyond_the_horizon
num_nodes_beyond_the_horizon *= (1-locality_bias_correction)
for dis in range(len(overall_estimates)-1, 2, -1):
overall_estimates[dis-1] += locality_bias_correction * overall_estimates[dis]
overall_estimates[dis] *= (1-locality_bias_correction)
else: #shift weight upwards b/c this estimator over-rates correlations between neighbors
for dis in range(len(overall_estimates)-1):
overall_estimates[dis+1] += -locality_bias_correction * overall_estimates[dis]
overall_estimates[dis] *= (1+locality_bias_correction)
num_nodes_beyond_the_horizon += -locality_bias_correction * overall_estimates[-1]
overall_estimates[-1] *= (1+locality_bias_correction)
accept_chance_edges = params.get('accept_chance_edges', 1.0)
assert accept_chance_edges >= 0 and accept_chance_edges <= 1.0
if sum(overall_estimates) > 0 or (num_nodes_beyond_the_horizon > 0 and accept_chance_edges > 0):
if accept_chance_edges > 0:
norm = accept_chance_edges*num_nodes_beyond_the_horizon + sum(overall_estimates)
chance_edge_prob = float(accept_chance_edges*num_nodes_beyond_the_horizon)/norm
else:
norm = sum(overall_estimates)
chance_edge_prob = 0.
locality_acceptor = overall_estimates/norm
else: #fallback
locality_acceptor = [0., 0.] + [0.5/(2**d) for d in xrange(1, min(new_edge_horizon,G.number_of_nodes()-2))]
chance_edge_prob = 0.
if G.number_of_edges() > 10 and nx.density(G) > 0.2:
print_warning(params, 'Warning: unable to estimate edge locality.')
print_warning(params, 'Consider setting allow_chance_edges to positive values')
assert locality_acceptor[0] == 0.
assert locality_acceptor[1] == 0.
if locality_bias_correction > 0 and locality_acceptor[2] > 0.8:
print_warning(params, 'Warning: extreme locality at distance 2. Might make it difficult to insert edges')
tpl_data['locality_acceptor'] = locality_acceptor
tpl_data['chance_edge_prob'] = chance_edge_prob
#print tpl_data
if params.get('verbose', True):
sys.stdout.write('Done topology.'+os.linesep)
return tpl_data
def do_coarsen(G, params):
G_coarse = nx.empty_graph()
aggregates = {} #nodes within new nodes. seed->fine_nodes
trapped_edges = {} #edges within new nodes. seed->fine_edges
home_nodes = {} #node->seed
merged_edges = {} #edge->internal edges
algorithm_for_coarsening = params.get('algorithm_for_coarsening', seed_finder_matching) #alt: seed_finder_weight_alg
seeds, home_nodes, aggregates = algorithm_for_coarsening(G, params)
if params.get('verbose', True):
print('nn: %d ne: %d (seeds: %d)' % (G.number_of_nodes(), G.number_of_edges(), len(seeds)))
free_edges = set() #edges not within any coarse node. they will be retained in the coarse graph (many-to-one mapping)
for seed in seeds:
G_coarse.add_node(seed)
G_coarse.node[seed]['weight'] = sum(G.node[nb].get('weight', 1.) for nb in aggregates[seed])
trapped_edges[seed] = G.subgraph(aggregates[seed]).edges(data=False)
for nb in aggregates[seed]:
for nbnb in G.neighbors(nb):
if nbnb in aggregates[seed] or (nbnb,nb) in free_edges:
continue
free_edges.add((nb,nbnb))
for u,v in free_edges:
s1 = home_nodes[u]
s2 = home_nodes[v]
uv_edge_wt = G.edge[u][v].get('weight', 1.0)
if (s1,s2) in merged_edges:
merged_edges[(s1,s2)].append((u,v))
G_coarse.edge[s1][s2]['weight'] += uv_edge_wt
assert (v,u) not in merged_edges[(s1,s2)]
elif (s2,s1) in merged_edges:
merged_edges[(s2,s1)].append((u,v))
G_coarse.edge[s2][s1]['weight'] += uv_edge_wt
assert (v,u) not in merged_edges[(s2,s1)]
else:
G_coarse.add_edge(s1,s2, weight=uv_edge_wt)
merged_edges[(s1,s2)] = [(u,v)]
assert (v,u) not in merged_edges[(s1,s2)]
for u in G:
assert u in home_nodes
assert home_nodes[u] in seeds
for (u,v) in G.edges():
hu = home_nodes[u]
hv = home_nodes[v]
if hu == hv:
assert not G_coarse.has_edge(hu,hv)
assert (u,v) in trapped_edges[hu] or (v,u) in trapped_edges[hv]
else:
assert G_coarse.has_edge(hu,hv)
assert (hu,hv) in merged_edges or (hv,hu) in merged_edges
c_data = {'aggregates':aggregates, 'trapped_edges':trapped_edges, 'home_nodes':home_nodes, 'merged_edges':merged_edges}
if 'do_coarsen_tester' in params:
params['do_coarsen_tester'](G, G_coarse, c_data)
return G_coarse, c_data
def do_uncoarsen(G_coarse, c_data, params):
if callable(params.get('algorithm_for_uncoarsening', False)):
return params['algorithm_for_uncoarsening'](G_coarse, c_data, params)
aggregates = c_data['aggregates']
trapped_edges = c_data['trapped_edges']
home_nodes = c_data['home_nodes']
merged_edges = c_data['merged_edges']
G_fine = nx.empty_graph()
G_fine.add_nodes_from(home_nodes)
for seed in trapped_edges:
for u,v in trapped_edges[seed]:
if u in G_fine and v in G_fine:
G_fine.add_edge(u,v)
#u or v must have been deleted
for s1,s2 in G_coarse.edges_iter():
if (s1,s2) in merged_edges:
s1s2 = merged_edges[(s1,s2)]
else:
s1s2 = merged_edges[(s2,s1)]
for u,v in s1s2:
assert u in G_fine
assert v in G_fine
G_fine.add_edge(u,v)
if 'do_uncoarsen_tester' in params:
params['do_uncoarsen_tester'](G_coarse, G_fine, c_data)
return G_fine
def edit_edges_sequential(G, edge_edit_rate, edge_growth_rate, tpl_data, params):
#edit edges: first delete, then insert
verbose = params.get('verbose', True)
try:
edit_rate = edge_edit_rate != [] and float(edge_edit_rate[0]) or 0.
if edit_rate < 0. or edit_rate > 1.: raise
except:
print_warning(params, 'Bad or truncated edge edit rate information! Defaulting to 0')
edit_rate = 0.
try:
growth_rate = edge_growth_rate != [] and float(edge_growth_rate[0]) or 0.
except:
print_warning(params, 'Bad or truncated edge growth rate information! Defaulting to 0')
growth_rate = 0.
if verbose:
print(' Edge rates: edit %f, growth %f' % (edit_rate, growth_rate))
if G.number_of_nodes() == 0:
if verbose:
print('Num nodes = 0 ... editing canceled')
return G
new_edge_horizon = params.get('new_edge_horizon', estimate_horizon(G)) #no edges added to nodes beyond the horizon
if new_edge_horizon in params and nx.density(G) > 0.2 and G.number_of_nodes() > 500:
print_warning(params, 'Warning: using a large horizon (%d) on a large graph might use a lot of time'%new_edge_horizon)
if 'enforce_connected' in params:
enforce_connected = params['enforce_connected']
else:
enforce_connected = tpl_data['enforce_connected']
dont_cutoff_leafs = params.get('dont_cutoff_leafs', False)
#do we allow leafs to be cut off completely?
# this option should be used sparingly, as it disrupts deferential detachment and decreases clustering
all_nodes = G.nodes()
added_edges_set = set()
deled_edges_set = set()
target_edges_to_delete = npr.binomial(max(G.number_of_edges(), 1), edit_rate)
target_edges_to_add = npr.binomial(max(G.number_of_edges(), 1), edit_rate) #should be here, since NumEdges will change
if growth_rate > 0:
target_edges_to_add += int(round(G.number_of_edges() * growth_rate))
else:
target_edges_to_delete += int(round(G.number_of_edges() * (-growth_rate)))
deprived_nodes = [] #list of nodes that lost edges, including repetitions
deferential_detachment_factor = params.get('deferential_detachment_factor', 0.0)
avg_degree = np.average(nx.degree(G).values()) #inexact deferential detachment, but with a much higher sampling efficiency
num_deletion_trials = params.get('num_deletion_trials', int(round(avg_degree**2)) )
G_adj = G.adj
G_degree = lambda u: G_adj[u].__len__()
G_neighbors = lambda u: G_adj[u].keys()
for trial_num in xrange(max(20, num_deletion_trials*target_edges_to_delete)):
if len(deled_edges_set) == target_edges_to_delete:
break
u = random.choice(all_nodes)
degree_of_u = G_degree(u)
if degree_of_u == 0: #will take care of this later
continue
#too random w = random.choice(G_neighbors(u))
w = find_node_to_unfriend(G, head=u, params=params, existing_nbs=G_neighbors(u))
if w == None:
continue
degree_of_w = G_degree(w)
#perhaps a slight improvement is to multiply not by avg_degree but by avg_nb_degree
if npr.rand()*deferential_detachment_factor > avg_degree/float(degree_of_u*degree_of_w):
continue
if dont_cutoff_leafs and (degree_of_u == 1 or degree_of_w == 1):
continue
#this improves clustering but it is a an unprincipled approach
#if strong_clustering_structure(G, u, w, params):
# continue
G.remove_edge(u,w)
deled_edges_set.add((u,w))
deprived_nodes += [u,w]
if enforce_connected:
new_edges = check_and_fix_connectivity(G, params)
added_edges_set.update(new_edges)
num_remaining_edges_to_add = target_edges_to_add - len(added_edges_set)
edge_welfare_fraction = params.get('edge_welfare_fraction', 0.0)
long_bridging = params.get('long_bridging', False)
#whether it should try to build edges to nodes which lost them; not supported for all edges or for edges lost during node deletion
for trial_num in xrange(max(20, 3*target_edges_to_add)):
if num_remaining_edges_to_add <= 0: #we might overshoot, hence <= 0 not ==
break
if npr.rand() > edge_welfare_fraction or len(deprived_nodes) == 0:
head = random.choice(all_nodes)
else:
head = random.choice(deprived_nodes)
if G_degree(head) == 0 and tpl_data['chance_edge_prob'] == 0.0:
continue
tail = find_node_to_friend_hits(G=G, head=head, tpl_data=tpl_data, params=params, existing_nbs=G_neighbors(head))
if tail == None or tail == head or G.has_edge(head,tail):
continue
#sys.stdout.write('%d,%.3f'%(G_degree(head), nx.clustering(G, head)))
G.add_edge(head,tail)
#sys.stdout.write(',%.3f\n'%nx.clustering(G, head))
added_edges_set.add((head,tail))
num_remaining_edges_to_add -= 1
num_edges_added = len(added_edges_set)
num_edges_deleted = len(deled_edges_set)
#print num_edges_added, num_edges_deleted, G.number_of_edges()
if num_edges_added > 20 and (num_edges_added-target_edges_to_add)/float(num_edges_added)> 0.2:
print_warning(params, 'Warning: Excessive number of edges were added. Is the graph treelike (low AvgDegree and connected)? AvgDegree=%.1f.'%np.average(nx.degree(G).values()))
#this might be caused by node edits. in that case, try minorizing_node_deletion
if num_edges_added > 20 and (target_edges_to_add-num_edges_added)/float(num_edges_added)> 0.2:
print_warning(params, 'Warning: Excessive number of edges failed to add. Consider setting locality_bias_correction to negative values.')
if nx.density(G) > 0.6:
print_warning(params, 'Is the graph too dense? Density=%.2f'%nx.density(G))
if num_edges_deleted > 20 and abs(target_edges_to_delete-num_edges_deleted)/float(num_edges_deleted)> 0.2:
print_warning(params, 'Warning: Excessive number of edges were deleted.')
if nx.density(G) > 0.6:
print_warning(params, 'Is the graph too dense? Density=%.2f'%nx.density(G))
if verbose:
print('\tadded edges: %d, deleted edges: %d' % (num_edges_added, num_edges_deleted))
if 'edit_edges_tester' in params:
params['edit_edges_tester'](G, added_edges_set, deled_edges_set, tpl_data)
return G
def edit_nodes_sequential(G, node_edit_rate, node_growth_rate, tpl_data, params):
verbose = params.get('verbose', True)
if verbose:
print('nn: %d' % G.number_of_nodes())
try:
edit_rate = node_edit_rate != [] and float(node_edit_rate[0]) or 0.
if edit_rate < 0. or edit_rate > 1.: raise
except:
print_warning(params, 'Bad or truncated node edit rate information! Defaulting to 0')
edit_rate = 0.
try:
growth_rate = node_growth_rate != [] and float(node_growth_rate[0]) or 0.
except:
print_warning(params, 'Bad or truncated node growth rate information! Defaulting to 0')
growth_rate = 0.
if verbose:
print(' Node rates: edit %f, growth %f' % (edit_rate, growth_rate))
if G.number_of_nodes() == 0:
if verbose:
print('Num nodes = 0 ... editing canceled')
return G
new_edge_horizon = params.get('new_edge_horizon', estimate_horizon(G)) #no edges added to nodes beyond the horizon
if new_edge_horizon in params and new_edge_horizon > 5 and nx.density(G) > 0.2 and G.number_of_nodes() > 500:
print_warning(params, 'Warning: using a large horizon (%d) on a large graph might use a lot of time'%new_edge_horizon)
num_deleted_nodes = npr.binomial(G.number_of_nodes(), edit_rate)
num_added_nodes = npr.binomial(G.number_of_nodes(), edit_rate)
if growth_rate > 0:
num_added_nodes += int(round(G.number_of_nodes() * growth_rate))
else:
num_deleted_nodes += int(round(G.number_of_nodes() * (-growth_rate)))
if num_deleted_nodes > G.number_of_nodes():
print_warning(params, 'Warning: excess negative growth rate. Deletion of nodes will destroy all the nodes of the graph. Editing aborted at this level.')
return G
G_adj = G.adj
G_degree = lambda u: G_adj[u].__len__()
G_neighbors = lambda u: G_adj[u].keys()
#we cache edges-to-add to avoid skewing these statistics during the editing process
original_nodes = G.nodes()
added_node_info = {}
for i in xrange(num_added_nodes):
source_node = random.choice(original_nodes)
new_node = new_node_label(G)
added_node_info[new_node] = G_degree(source_node)
#G.node[new_node]['resampling_source'] = source_node
num_edges_added = 0
num_edges_deleted = 0
failed_searches = 0
for new_node in added_node_info:
G.add_node(new_node)
num_remaining_nbs_to_add = added_node_info[new_node]
if num_remaining_nbs_to_add == 0:
continue
#uncomment below and use 'enforce_connected':False to see the aggregates. WARNING: comment back when done
#continue
anchor_node = random.choice(original_nodes)
G.add_edge(new_node, anchor_node)
num_edges_added += 1
num_remaining_nbs_to_add -= 1
for trial_num in xrange(max(40, 3*num_remaining_nbs_to_add)):
if num_remaining_nbs_to_add == 0:
break
v = find_node_to_friend_hits(G=G, head=new_node, tpl_data=tpl_data, params=params, existing_nbs=G_neighbors(new_node))
if v == None or v == new_node or v in G_neighbors(new_node):
continue
G.add_edge(new_node, v)
num_edges_added += 1
num_remaining_nbs_to_add -= 1
if num_remaining_nbs_to_add > 0:
failed_searches += 1
added_nodes_set = set(added_node_info.keys())
deled_nodes_set = set()
minorizing_node_deletion = params.get('minorizing_node_deletion', False)
for u in random.sample(G.nodes(), num_deleted_nodes):
num_edges_deleted += G_degree(u)
if minorizing_node_deletion: #connect the neighbors into a tree
nbrs = G_neighbors(u)
random.shuffle(nbrs)
for nb_idx,nb in enumerate(nbrs[:-1]):
new_edge = (nb, nbrs[nb_idx+1])
if not G.has_edge(*new_edge):
#assert new_edge[0] != new_edge[1]
G.add_edge(*new_edge)
num_edges_added += 1
G.remove_node(u)
deled_nodes_set.add(u)
if len(original_nodes) !=0 and len(original_nodes)>10 and (float(failed_searches)/len(original_nodes)) > .2:
print_warning(params, 'Warning: > 20%% of searches failed when attempting to insert edges.')
if nx.density(G) > 0.6:
print_warning(params, 'Is the graph too dense? Density=%.2f'%nx.density(G))
if verbose:
print('\tadded nodes: %d, deleted nodes: %d' % (num_added_nodes, num_deleted_nodes))
print('\tadded edges: %d, deleted edges: %d' % (num_edges_added, num_edges_deleted))
if 'edit_nodes_tester' in params:
params['edit_nodes_tester'](G, added_nodes_set, deled_nodes_set, tpl_data)
return G
def estimate_horizon(G):
density = nx.density(G)
if density == 0 or G.number_of_nodes() < 3:
return 4
return 20
def find_node_to_friend_basic(G, head, tpl_data, params, existing_nbs=None):
locality_acceptor = tpl_data['locality_acceptor']
#implicit: chance_edge_prob = tpl_data['chance_edge_prob']
weighted_step = params.get('weighted_step', False)
sm = sum
rds = random.shuffle
find_next = weighted_step_advanced
all_nodes = None
tail = None
if existing_nbs == None:
existing_nbs = set()
else:
existing_nbs = set(existing_nbs)
G_adj = G.adj
G_neighborsSet = lambda u: set(G_adj[u].keys())
num_insertion_trials = params.get('num_insertion_trials', 30)
num_insertion_searches_per_distance = params.get('num_insertion_searches_per_distance', 20)
for trial in xrange(num_insertion_trials):
#sample from np.random.multinomial()
toss = npr.rand()
for dis, prob in enumerate(locality_acceptor):
toss -= prob
if toss < 0:
break
for search_num in xrange(num_insertion_searches_per_distance):
if toss < 0 and len(existing_nbs) > 0:
cur_loc = find_next(G=G, start_node=head, weighted_step=weighted_step, blocked=(), rds=rds, sm=sm)
blocked = set([head, cur_loc])
next_loc = None
tail = None
for d in xrange(2, dis+1):
next_loc = find_next(G=G, start_node=cur_loc, weighted_step=weighted_step, blocked=blocked, rds=rds, sm=sm)
if next_loc == None: #stuck in a self-made corner
break
#blocked.add(next_loc) #self-avoiding
cur_loc = next_loc
if d == dis and next_loc != None: #sanity tests ensure that no node "None" exists
tail = next_loc
#print 'tail %s at distance %d steps'%(tail,dis)
else:
for i in xrange(G.number_of_nodes()):
if all_nodes == None:
all_nodes = G.nodes()
candidate = random.choice(all_nodes)
if candidate != head and (candidate not in existing_nbs):
tail = candidate
break
#print 'tail %s by RANDOM selection'%(tail,)
if tail != None:
return tail
return tail
def find_node_to_friend_hits(G, head, tpl_data, params, existing_nbs=None):
locality_acceptor = tpl_data['locality_acceptor']
#implicit: chance_edge_prob = tpl_data['chance_edge_prob']
weighted_step = params.get('weighted_step', False)
sm = sum
rds = random.shuffle
find_next = weighted_step_advanced
all_nodes = None
tail = None
if existing_nbs == None:
existing_nbs = set()
else:
existing_nbs = set(existing_nbs)
G_adj = G.adj
G_neighborsSet = lambda u: set(G_adj[u].keys())
#num_insertion_trials = params.get('num_insertion_trials', 10 )
num_insertion_searches_per_distance = params.get('num_insertion_searches_per_distance', 30)
tail = None
hits = {}
if len(existing_nbs) == 0:
return None
#for trial in xrange(num_insertion_trials):
most_hits = -1
most_hits_candidate = None
if True:
#sample from np.random.multinomial()
toss = npr.rand()
for dis, prob in enumerate(locality_acceptor):
toss -= prob
if toss < 0:
break
for search_num in xrange(num_insertion_searches_per_distance):
cur_loc = find_next(G=G, start_node=head, weighted_step=weighted_step, blocked=(), rds=rds, sm=sm)
blocked = set([head, cur_loc])
#hits[cur_loc] = 1
next_loc = None
d = 2 #in case the loop is not even started
for d in xrange(2, dis+1):
cur_loc = find_next(G=G, start_node=cur_loc, weighted_step=weighted_step, blocked=blocked, rds=rds, sm=sm)
if cur_loc == None: #stuck in a self-made corner
break
if d == dis and cur_loc != None:
cur_loc_hits = hits.get(cur_loc, 0) + 1
hits[cur_loc] = cur_loc_hits
if (cur_loc_hits >= most_hits) and (cur_loc not in existing_nbs):
most_hits = cur_loc_hits
most_hits_candidate = cur_loc
#sanity tests ensure that no node "None" exists
#if d == dis and next_loc != None: #sanity tests ensure that no node "None" exists
# tail = next_loc
# #print 'tail %s at distance %d steps'%(tail,dis)
if most_hits_candidate != None:
return most_hits_candidate
hits = hits.items()
hits.sort(lambda x,y: y[1]-x[1])
for candidate, h in hits:
if candidate not in existing_nbs:
return candidate
return None
def find_node_to_unfriend(G, head, params, existing_nbs=None):
if len(existing_nbs) == 0:
return None
else:
return random_one(existing_nbs)
#locality_acceptor = tpl_data['locality_acceptor']
#implicit: chance_edge_prob = tpl_data['chance_edge_prob']
#weighted_step = params.get('weighted_step', False)
#sm = sum #maybe avoid a weighted walk?
#rds = random.shuffle
#find_next = weighted_step_advanced
#tail = None
#if existing_nbs == None:
# existing_nbs = set(existing_nbs)
#G_adj = G.adj
#G_neighborsSet = lambda u: set(G_adj[u].keys())
#num_insertion_searches_per_distance = params.get('num_insertion_searches_per_distance', 30) #wishlist: use a separate parameter
#tail = None
#hits = {}
#new_edge_horizon = params.get('new_edge_horizon', estimate_horizon(G))
#for search_num in xrange(num_insertion_searches_per_distance):
# cur_loc = find_next(G=G, start_node=head, weighted_step=weighted_step, blocked=(), rds=rds, sm=sm)
# blocked = set([head, cur_loc])
# for d in xrange(2, new_edge_horizon+1):
# cur_loc = find_next(G=G, start_node=cur_loc, weighted_step=weighted_step, blocked=blocked, rds=rds, sm=sm)
# if cur_loc == None: #stuck in a self-made corner
# break
# #blocked.add(cur_loc) #self-avoiding
# if cur_loc in hits:
# hits[cur_loc] += 1
# else:
# hits[cur_loc] = 1
##print hits
##hits = hits.items()
##hits.sort(lambda x,y: y[1]-x[1])
##for candidate in hit_nodes:
## if candidate in existing_nbs:
## return candidate
##return None
def flush_graph(G):
#the algorithm relabels the nodes of the graph at random
#-> data on aggregates becomes obsolete and is so never used
node_map = {}
for node in G:
while True:
new_name = new_node_label(G)
if (new_name not in G) and (new_name not in node_map):
break
node_map[node] = new_name
G = nx.relabel_nodes(G, node_map, copy=True)
return G
def generate_graph(original, params=None):
#main entry point
if params == None:
params = {}
print_warning(params, 'WARNING: empty parameter input. Running with default parameters.')
if params.get('algorithm', False):
params2 = params.copy()
alg_info = params2.pop('algorithm')
if callable(alg_info):
alg_method = alg_info
elif type(alg_info) is str:
alg_method = eval(alg_method)
elif (type(alg_info) is list) or (type(alg_info) is tuple):
alg_method = alg_info[0]
params2['algorithm'] = alg_info[1]
else:
raise ValueError(
'algorithm parameter should be either callable, the name of a function, or (func,(nested_algorithm))')
return alg_method(original=original, params=params2)
simpletesters.validate_params(params)
node_edit_rate = params.get('node_edit_rate', [])
edge_edit_rate = params.get('edge_edit_rate', [])
node_growth_rate = params.get('node_growth_rate', [])
edge_growth_rate = params.get('edge_growth_rate', [])
#we might want to convert all nodes to integers for performance reasons
original._musketeer_data = {}
G = original.copy()
if params.get('verbose', True):
sys.stdout.write('Checking original graph ... ')
UtilityAlloc.graph_sanity_test(G, params)
sys.stdout.write('Done.'+os.linesep)
start_time = time.time()
replica, model_map = revise_graph(G=G, level=0,
node_edit_rate=node_edit_rate,
node_growth_rate=node_growth_rate,
edge_edit_rate=edge_edit_rate,
edge_growth_rate=edge_growth_rate,
params=params)
if params.get('verbose', True):
print('replica is finished. nn: %d. time: %.2f sec.' % (replica.number_of_nodes(), time.time() - start_time))
print
replica = resample_attributes(G, replica, model_map, params)
replica.name = getattr(original, 'name', 'graph') + '_replica_' + timeNow()
replica._musketeer_data = original._musketeer_data #WARNING shallow copy, to allow information to be passed from G to replicas
UtilityAlloc.graph_sanity_test(replica, params)
del G
gc.collect()
return replica
def interpolate_edges(G, c_data, model_map, fine_model_map, params):
aggregates = c_data['aggregates']
merged_edges = c_data['merged_edges']
deep_copying = params.get('deep_copying', True)
if not deep_copying: assert len(model_map) == 0
authentic_edges = merged_edges.items()
edited_edges = []
for (s1,s2) in G.edges_iter(): #wishlist: faster loop?
if ((s1,s2) not in merged_edges) and ((s2,s1) not in merged_edges):
edited_edges.append((s1,s2))
for (s1,s2) in edited_edges:
trapped_in_s1 = aggregates[s1]
trapped_in_s2 = aggregates[s2]
model_aggregate_1 = model_map.get(s1, None)
model_aggregate_2 = model_map.get(s2, None)
new_pairs = set()
if deep_copying:
merged_model_edge_contents = merged_edges.get((model_aggregate_1, model_aggregate_2), None)
if merged_model_edge_contents == None:
merged_model_edge_contents = merged_edges.get((model_aggregate_2, model_aggregate_1), None)
exact_interpolation = deep_copying and (merged_model_edge_contents != None)
if exact_interpolation: #occurs only if s1 and s2 are deep-copied from an edge that existed in the original graph
reversed_map = {}
for trapped_node in trapped_in_s1 + trapped_in_s2:
reversed_map[fine_model_map[trapped_node]] = trapped_node
for mA, mB in merged_model_edge_contents:
u = reversed_map[mA]
v = reversed_map[mB]
new_pairs.add((u,v))
else:
if authentic_edges != []:
random_model_edge, random_model_edge_contents = random.choice(authentic_edges)
num_target_edges = len(random_model_edge_contents)
else:
num_target_edges = 1
num_failures = 0
while len(new_pairs) < num_target_edges and num_failures < max(10, 3*num_target_edges):
u = random.choice(trapped_in_s1)
v = random.choice(trapped_in_s2)
if ((u,v) not in new_pairs) and ((v,u) not in new_pairs):
new_pairs.add((u,v))
else:
num_failures += 1
merged_edges[(s1,s2)] = [(u,v) for u,v in new_pairs]
#might optionally pass an attribute 'new' in the edges
return c_data
def interpolate_nodes(G, c_data, model_map, params):
'''
constructs the interior of nodes just added to the graph G, preparing it for uncoarsening
interpolation is of two kinds: (node has just appeared in level i) -> we randomly select a "model node". then we insert its internal structure from the existing graph.
(deep copying: node was part of an aggregate in level i+) -> we refer to model_map to determine the source_node of its internal structure; we copy that structure;
model_map: u in Gi -> v \in original_i
fine_model_map: u in G_{i-1} -> v \in original_{i-1}
at level i, fine_model_map contains information about level i-1, while model_map is the same information about
'''
aggregates = c_data['aggregates']
trapped_edges = c_data['trapped_edges']
home_nodes = c_data['home_nodes']
merged_edges = c_data['merged_edges']
if not params.get('deep_copying', True):
assert len(model_map) == 0
#this_level_node A -> node in G_i original of which is the model of A
fine_model_map = {}
authentic_nodes = aggregates.keys()
assert authentic_nodes != []
edited_nodes = [node for node in G if node not in aggregates]
num_new_nodes = 0
num_new_edges = 0
for node in edited_nodes:
source_aggregate = model_map.get(node, random.choice(authentic_nodes))
sources_edges = trapped_edges[source_aggregate]
sources_nodes = aggregates[source_aggregate]
renamed_nodes = {}
for node_hosted_by_source in sources_nodes:
new_hosted_node = new_node_label(home_nodes)
renamed_nodes[node_hosted_by_source] = new_hosted_node
fine_model_map[new_hosted_node] = node_hosted_by_source
num_new_nodes += 1
my_trapped_nodes = renamed_nodes.values()
my_trapped_edges = []
for edge_hosted_by_source in sources_edges:
my_trapped_edges.append( (renamed_nodes[edge_hosted_by_source[0]], renamed_nodes[edge_hosted_by_source[1]]) )
num_new_edges += 1
aggregates[node] = my_trapped_nodes
trapped_edges[node] = my_trapped_edges
for new_hosted_node in my_trapped_nodes:
home_nodes[new_hosted_node] = node
#might optionally pass an attribute 'new' in the node
#num_added_nodes += len(my_trapped_nodes)
if params.get('verbose', True):
print(' from new aggregates: %d nodes, %d edges' % (num_new_nodes, num_new_edges))
#print 'added: %d'%num_added_nodes
if params.get('deep_copying', True):
return c_data, fine_model_map
else:
return c_data, {}
def musketeer_on_subgraphs(original, params=None):
components = nx.connected_component_subgraphs(original)
merged_G = nx.Graph()
component_is_edited = params.get('component_is_edited', [True]*len(components))
for G_num, G in enumerate(components):
if component_is_edited[G_num]:
replica = generate_graph(original=G, params=params)
else:
replica = G
merged_G = nx.union(merged_G, replica)
merged_G.name = getattr(original, 'name', 'graph') + '_replica_' + timeNow()
return merged_G
def musketeer_snapshots(original, params=None):
#applies replication sequentially, generating snapshots of the original.
#returns the final snapshot.
#snapshots (0 to last) are held in the .snapshot attribute
graphs = [original]
num_snapshots = params['num_snapshots']
for graph_num in xrange(num_snapshots):
G = graphs[-1]
replica = generate_graph(original=G, params=params)
replica.name = 'snapshot_%d'%graph_num
graphs.append(replica)
if params.get('verbose', True):
print('Snapshots complete.')
print
replica.snapshots = graphs
return replica
def musketeer_iterated_cycle(original, params=None):
#applies replication sequentially, and returns the final snapshot.
num_cycles = params['num_v_cycles']
params2 = params.copy()
params2['edge_edit_rate'] = [r/float(num_cycles) for r in params2.get('edge_edit_rate', [])]
params2['edge_growth_rate'] = [r/float(num_cycles) for r in params2.get('edge_growth_rate', [])]
params2['node_edit_rate'] = [r/float(num_cycles) for r in params2.get('node_edit_rate', [])]
params2['node_growth_rate'] = [r/float(num_cycles) for r in params2.get('node_growth_rate', [])]
replica = original
for graph_num in xrange(num_cycles):
replica = generate_graph(original=replica, params=params2)
replica.name = getattr(original, 'name', 'graph') + '_replica_w%d_'%graph_num + timeNow()
return replica
def new_node_label(G):
#G is either a graph or a dict/list of existing labels
num_trials = 100
label = None
for t in xrange(num_trials):
label = npr.randint(max_int)