-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathant_find_path.py
1253 lines (1032 loc) · 45.6 KB
/
ant_find_path.py
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
#!/usr/bin/env python
from __future__ import division
import networkx as nx
import time,logging
from optparse import OptionParser
import argparse
import matplotlib as mpl
mpl.use('agg')
from matplotlib import pylab as PP
from numpy.random import seed,choice, random
from numpy import mean,median, array, argmax, where, subtract
import numpy as np
from collections import defaultdict
import os
from matplotlib import animation
from scipy.stats import spearmanr
from scipy.stats import entropy
from graphs import *
from choice_functions import *
from decay_functions import *
import sys
from random import randint
import os
SEED_DEBUG = False
SEED_MAX = 4294967295
SEED_VAL = randint(0, SEED_MAX)
if SEED_DEBUG:
print SEED_VAL
seed(SEED_VAL)
#seed(174069528)
Minv = {} # node tuple -> node id
M = {} # node id -> node tuple
Ninv = {} # edge -> edge id
N = {} # edge id -> edge
AFTER_GRAPH_THRESHOLD = 0.01
pos = {}
node_color,node_size = [],[]
edge_color,edge_width = [],[]
#P = []
EDGE_THICKNESS = 25
pheromone_thickness = 1
ant_thickness = 25
INIT_WEIGHT_FACTOR = 20
MAX_PATH_LENGTH = 38
FRAME_INTERVAL = 1000
global EXPLORE_CHANCES
global EXPLORES
EXPLORE_CHANCES = 0
EXPLORES = 0
DRAW_AND_QUIT = False
DEBUG = False
DEBUG_QUEUES = False
DEBUG_PATHS = False
REINFORCEMENT_RATE = {1 : 1, 2 : 0.5, 3 : 0.33, 4 : 0.25}
REINFORCEMENT_THRESHOLD = 10
ANTI_PHEROMONE = False
WAVES = False
FIRST_WAVE = 5
PERIOD = 100
MAX_PRUNING_STEPS = 10000
""" Difference from tesht2 is that the ants go one at a time + other output variables. """
# PARAMETERS:
# n=number of ants
# delta=pheromone add-decay amount
# choice function=max or probabilistic
# trade-offs=speed of recovery vs. centrality
# backwards-coming ants=ignore.
# TODO: add/decay as a function of n?
# TODO: output path edges taken by each ant to visualize.
# TODO: more memory of history?
# TODO: is [0-1] the right range?
def clear_queues(G):
'''
empties all node and edge queues
'''
for u in G.nodes_iter():
G.node[u]['queue'] = []
for u, v in G.edges():
G[u][v]['forwards_queue'] = []
G[u][v]['backwards_queue'] = []
def init_graph(G):
'''
initializes the graph for drawing
sets all edge weights to 0, and creates mapping between each node and an integer, and
between each edge and an integer
'''
# map each node to an integer
for i,u in enumerate(sorted(G.nodes())):
M[i] = u
Minv[u] = i
if 'road' not in G.graph['name'] and G.graph['name'] != 'subelji':
pos[u] = [u[0],u[1]] # position is the same as the label.
G.node[u]['queue'] = []
if u in G.graph['nests']:
node_size.append(100)
node_color.append('r')
else:
node_size.append(10)
node_color.append('k')
# map each edge to an integer
# since this is an undirected graph, both orientations of an edge map to same integer
# each integer maps to one of the two orientations of the edge
for i, (u,v) in enumerate(sorted(G.edges())):
G[u][v]['weight'] = MIN_PHEROMONE
G[u][v]['forwards'] = tuple(sorted((u, v)))
G[u][v]['forwards_queue'] = []
G[u][v]['backwards'] = tuple(sorted((u, v))[::-1])
G[u][v]['backwards_queue'] = []
Ninv[(u, v)] = i
N[i] = (u, v)
Ninv[(v, u)] = i
edge_color.append('k')
edge_width.append(1)
G[u][v]['anti_pheromone'] = 0
G[u][v]['super_pheromone'] = 0
G.graph['node_map'] = M
G.graph['node_map_inv'] = Minv
G.graph['edge_map'] = N
G.graph['edge_map_inv'] = Ninv
def color_graph(G, c, w, figname, cost=None):
'''
Draws the current graph and colors all the edges with pheromone, to display the
pheromone network the ants have constructed at some point in time
G - the networkx Graph object to be drawn
c - the color to use for pheromone edges
w - the scaling factor for edge weights. If the edge widths are set directly equal to
the edge weights, the edge widths will become prohibitively big and ruin the picture
this scaling factor allows the edge widths to be proportional to the edge weights
while capping the size of the largest edge. Thus, this value should be a constant
factor times the weight of the highest edge in the graph at the time of drawing.
All edge weights and resulting widths are normalized by this factor.
figname - the name to which to save the figure
'''
colors, widths = edge_color[:], edge_width[:]
unique_weights = set()
for u, v in G.edges():
index = None
try:
index = Ninv[(u, v)]
except KeyError:
index = Ninv[(v, u)]
wt = G[u][v]['weight']
width = 0
# don't draw edges with miniscule weight
if wt > AFTER_GRAPH_THRESHOLD:
width = 1 + (wt * w * EDGE_THICKNESS)
colors[index] = c
else:
width = 1
colors[index] = 'k'
widths[index] = width
unique_weights.add(wt)
if 'road' in G.graph['name'] or G.graph['name'] == 'subelji':
nx.draw(G, with_labels=False, node_size=node_size, edge_color=colors,\
node_color=node_color, width=widths, nodelist = sorted(G.nodes()), \
edgelist = sorted(G.edges()))
else:
nx.draw(G, pos=pos, with_labels=False, node_size=node_size, edge_color=colors,\
node_color=node_color, width=widths, nodelist = sorted(G.nodes()), \
edgelist = sorted(G.edges()))
PP.draw()
#PP.show()
PP.savefig(figname + '.png', format='png')
PP.close()
os.system('convert %s.png %s.pdf' % (figname, figname))
def pheromone_subgraph(G, origin=None, destination=None):
'''
Generates the subgraph induced by the edges with pheromone
G - graph with pheromone edges
origin, destination - nest and target vertices that should be included even if not
adjacent to a pheromone edge
'''
G2 = nx.Graph()
for u, v in G.edges_iter():
# need enough pheromone for the ant to be able to detect it on that edge
wt = G[u][v]['weight']
if wt > MIN_DETECTABLE_PHEROMONE:
G2.add_edge(u, v)
G2[u][v]['weight'] = wt
# add the nests to the graph even if not connected anywhere
if origin not in G2:
G2.add_node(origin)
if destination not in G2:
G2.add_node(destination)
return G2
def pheromone_paths(G, origin, destination, limit=15):
'''
computes all paths between the origin and destination that use only pheromone edges
does this by enumerating all paths in the pheromone subgraph
G - graph with pheromone edges
origin, destination - vertices between which to find all paths
'''
G2 = pheromone_subgraph(G, origin, destination)
return list(nx.all_simple_paths(G2, origin, destination, limit))
def has_pheromone_path(G, origin, destination):
'''
Checks whether there exists a pheromone path between origin and destination. Does
this by checking there is a path between origin and destination in the pheromone
subgraph.
G - graph with pheromone edges
origin, destination - vertices between which to check for a path
'''
G2 = pheromone_subgraph(G, origin, destination)
return nx.has_path(G2, origin, destination)
def count_nonzero(G, curr):
'''
Counts the number of neighboring edges with pheromone above the detection threshold
'''
count = 0
for neighbor in G.neighbors(curr):
if G[curr][neighbor]['weight'] > MIN_DETECTABLE_PHEROMONE:
count += 1
return count
def pheromone_cost(G):
'''
Counts the total number of pheromone edges in the graph G
'''
G2 = nx.Graph()
for u, v in G.edges_iter():
if G[u][v]['weight'] > MIN_DETECTABLE_PHEROMONE:
G2.add_edge(u, v)
return G2.number_of_edges()
def path_prob(G, path, explore_prob, strategy='uniform'):
'''
computes the probability of the ant taking a particular path on graph G according to
the edge weights, explore probability, and choice function
G - graph which ant traverses
path - a path on G which the ant traverses
explore_prob - probability that the ant takes an explore step
strategy - the choice function the ant uses to determine its next step
'''
prob = 1
prev = None
for i in xrange(len(path) - 1):
source = path[i]
dest = path[i + 1]
prob *= choice_prob(G, source, dest, explore_prob, prev, strategy)
if prob == 0:
break
prev = source
return prob
def path_prob_no_explore(G, path, strategy='uniform'):
'''
computes the probability of an ant taking a particular path on a graph G when explore
steps are not allowed
'''
return path_prob(G, path, 0, strategy)
def pruning_plot(costs, figname, max_cost=None):
'''
plots the edge cost over time
'''
if max_cost == None:
max_cost = max(costs)
assert max_cost in costs
costs = PP.array(costs)
costs /= float(max_cost)
assert 1 in costs
PP.plot(range(len(costs)), costs)
PP.xlabel('time steps')
PP.ylabel('proportion of edges in use')
PP.savefig(figname + '.png', format='png')
def pheromone_dead_end(G, curr, prev):
'''
Checks if an ant is at a dead end. We define a dead end as such: if the only edge
with pheromone is the edge that the ant traversed on the previous step, then the ant
is at a dead end, i.e. following pheromone did not allow the ant to reach the nest
'''
for n in G.neighbors(curr):
if n != prev and G[curr][n]['weight'] > MIN_DETECTABLE_PHEROMONE:
return False
return True
def walk_to_path(walk):
'''
Converts a walk on a graph to a path by removing all cycles in the path
'''
assert len(walk) >= 2
if walk[0] == walk[-1]:
print walk
assert walk[0] != walk[-1]
path = []
'''
path does not have repeated vertices, so keep track of visited vertices on walk
maps each vertex to the first position in the walk at which that vertex was
visited
'''
visited = {}
for i, node in enumerate(walk):
if node not in visited:
# new node, goes into the path
path.append(node)
visited[node] = len(path) - 1
else:
'''
visited node, meaning our walk has cycled back to a vertex. Thus we excise
all vertices that are part of that cycle from the path.
'''
prev = visited[node]
for j in xrange(prev + 1, len(path)):
del visited[path[j]]
path = path[:prev + 1]
assert len(path) >= 2
assert path[0] == walk[0]
assert path[-1] == walk[-1]
return path
def queue_ant(G, queue_node, ant):
'''
adds an ant to the queue at a particular node in the graph
'''
G.node[queue_node]['queue'].append(ant)
def check_queues(G, queued_nodes, queued_edges, num_ants, verbose=False):
'''
Checks whether the queued nodes are correct. Checks that each queued node has a
non-empty queue; checks that every ant appears in one of the queues, and that no
ant appears in more than one queue
'''
queued_ants = []
for queued_node in sorted(queued_nodes):
queue = G.node[queued_node]['queue']
if verbose:
print "queued node", queued_node, queue
assert len(G.node[queued_node]['queue']) > 0
for ant in queue:
assert ant not in queued_ants
queued_ants += list(queue)
for edge_id in sorted(queued_edges):
u, v = N[edge_id]
directions = ['forwards', 'backwards']
total_size = 0
for direction in directions:
queue = G[u][v][direction + '_queue']
if verbose:
print "queued edge " + direction, edge_id, (u, v), queue
total_size += len(queue)
for ant in queue:
assert ant not in queued_ants
queued_ants += list(queue)
assert total_size > 0
if verbose:
if len(queued_ants) != num_ants:
print len(queued_ants), sorted(queued_ants), num_ants
assert len(queued_ants) == num_ants
def path_to_edges(path):
'''
converts a path represented as a series of vertices to a path represented as a series
of edges
'''
edges = []
for i in xrange(len(path) - 2):
edges.append(Ninv[(path[i], path[i + 1])])
return edges
def wasted_edges(G, useful_edges):
'''
count the number of edges that have pheromone but are not part of the network that the
ants use.
Assumes useful edges is a list of edge ids, rather than actual edges
'''
wasted_edges = 0
wasted_edge_weight = 0
for u, v in G.edges_iter():
wt = G[u][v]['weight']
if wt > MIN_DETECTABLE_PHEROMONE:
edge_id = Ninv[(u, v)]
if edge_id not in useful_edges:
wasted_edges += 1
wasted_edge_weight += wt
return wasted_edges, wasted_edge_weight
def max_neighbors(G, source, prev=None):
'''
Gets all neighbors that are tied for the highest weight among all neighbors. Ignores
ants most previously visited vertex
'''
candidates = G.neighbors(source)
# ignore previous vertex, ant won't consider it
if prev != None:
assert prev in candidates
candidates.remove(prev)
max_wt = float("-inf")
max_neighbors = []
for candidate in candidates:
wt = G[source][candidate]['weight']
if wt <= MIN_DETECTABLE_PHEROMONE:
continue
elif wt > max_wt:
max_wt = wt
max_neighbors = [candidate]
elif wt == max_wt:
max_neighbors.append(candidate)
return max_neighbors
def maximal_paths(G, source, dest, limit=None):
queue = [[source]]
max_paths = []
while len(queue) > 0:
curr_path = queue.pop(0)
if limit != None and len(curr_path) > limit:
continue
curr = curr_path[-1]
prev = None
if len(curr_path) > 1:
prev = curr_path[-2]
max_n = max_neighbors(G, curr, prev)
for max_neighbor in max_n:
new_path = curr_path + [max_neighbor]
if max_neighbor == dest:
max_paths.append(new_path)
elif max_neighbor not in curr_path:
queue.append(new_path)
return max_paths
def maximal_cycles(G, source, limit=None):
return maximal_paths(G, source, source, limit)
def print_queues(G):
for u in sorted(G.nodes()):
if len(G.node[u]['queue']) > 0:
print u, G.node[u]['queue']
for u, v in sorted(G.edges()):
if len(G[u][v]['forwards_queue']) + len(G[u][v]['backwards_queue']) > 0:
print u, v
if len(G[u][v]['forwards_queue']) > 0:
print 'forwards', G[u][v]['forwards_queue']
if len(G[u][v]['backwards_queue']) > 0:
print 'backwards', G[u][v]['backwards_queue']
def check_path(G, path):
for i in xrange(len(path) - 1):
u, v = path[i], path[i + 1]
if u != v:
assert G.has_edge(u, v)
def to_list(nodes):
if nodes == None:
return [None]
if type(nodes) == tuple:
return [nodes]
else:
assert type(nodes) == list
return nodes
def find_path(G, pheromone_add, pheromone_decay, explore_prob, explore2,\
strategy='uniform', num_ants=100, max_steps=10000, num_iters=1,\
print_graph=False, video=False, nframes=200, video2=False, cost_plot=False,\
backtrack=False, decay_type='linear', node_queue_lim=1, edge_queue_lim=1,\
one_way=False):
""" """
graph_name = G.graph['name']
nests = G.graph['nests']
out_items = ['find_path', strategy, graph_name, decay_type]
if backtrack:
out_items.append('backtrack')
if one_way:
out_items.append('one_way')
out_str = '_'.join(out_items)
def next_destination(origin):
idx = nests.index(origin)
idx += 1
idx %= len(nests)
return nests[idx]
num_edges = G.size()
nframes = min(nframes, max_steps)
pher_str = "%d, %f, %f, " % (num_ants, explore_prob, pheromone_decay)
data_file = open('ant_%s%d.csv' % (out_str, max_steps), 'a')
track_pruning = max_steps <= MAX_PRUNING_STEPS
if video:
fig = PP.figure()
for iter in xrange(num_iters):
nonzero_edges = set()
for u, v in G.edges_iter():
G[u][v]['weight'] = MIN_PHEROMONE
G[u][v]['units'] = []
clear_queues(G)
if iter == 0 and print_graph:
pass #color_graph(G, 'g', pheromone_thickness, "graph_before")
print str(iter) + ": " + pher_str
explore = defaultdict(bool)
reinforce = defaultdict(bool)
prevs = {}
prevs2 = {}
prevs3 = {}
currs = {}
paths = {}
walks = {}
destinations = {}
origins = {}
edge_weights = defaultdict(list)
deadend = {}
search_mode = {}
costs = []
path_counts = defaultdict(int)
chosen_walk_counts = defaultdict(int)
max_entropy = None
max_walk_entropy = None
connect_time = -1
queued_nodes = set()
queued_edges = set()
max_cycles = 0
curr_max_cycles = 0
for ant in xrange(num_ants):
origin = nests[ant % len(nests)]
origins[ant] = origin
destinations[ant] = next_destination(origin)
prev = None
curr = None
if one_way:
curr = nests[0]
else:
curr = origin
paths[ant] = [prev, curr]
if destinations[ant] in paths[ant]:
origins[ant], destinations[ant] = destinations[ant], origins[ant]
walks[ant] = [prev, curr]
prevs[ant] = prev
prevs2[ant] = None
prevs3[ant] = None
currs[ant] = curr
deadend[ant] = False
queue_ant(G, curr, ant)
queued_nodes.add(curr)
search_mode[ant] = True
steps = 1
rounds = 1
max_weight = MIN_PHEROMONE
unique_weights = set()
max_cost = 0
costs = []
curr_entropy = None
curr_walk_entropy = None
for u, v in sorted(G.edges()):
index = Ninv[(u, v)]
wt = G[u][v]['weight']
unique_weights.add(wt)
max_weight = max(max_weight, wt)
if wt <= MIN_DETECTABLE_PHEROMONE:
edge_weights[index].append(None)
else:
edge_weights[index].append(wt)
nest_nqls = {}
def reset_nest_nqls(ql=0):
for nest in nests:
nest_nqls[nest] = ql
if WAVES:
reset_nest_nqls(FIRST_WAVE)
while steps <= max_steps:
cost = pheromone_cost(G)
max_cost = max(max_cost, cost)
costs.append(cost)
G2 = G.copy()
empty_nodes = set()
new_queue_nodes = set()
moved_ants = set()
empty_edges = set()
updated_paths_ants = set()
if DEBUG_QUEUES:
check_queues(G2, queued_nodes, queued_edges, num_ants)
for queued_node in queued_nodes:
curr_max_cycles = len(maximal_cycles(G, queued_node))
max_cycles = max(curr_max_cycles, max_cycles)
queue = G2.node[queued_node]['queue']
#queue = G2.node[node]['queue']
#assert len(queue) > 0
qlim = node_queue_lim
if qlim == -1:
qlim = len(queue)
if WAVES:
if queued_node in nests:
qlim = nest_nqls[queued_node]
if steps % PERIOD == 0:
qlim += FIRST_WAVE
next_ants = []
q = 0
while q < len(queue) and len(next_ants) < qlim:
if queue[q] not in moved_ants:
q_ant = queue[q]
next_ants.append(q_ant)
q += 1
for next_ant in next_ants:
queue.remove(next_ant)
for queued_ant in queue:
if queued_ant not in moved_ants:
moved_ants.add(queued_ant)
paths[queued_ant].append(queued_node)
if DEBUG_PATHS:
check_path(G, paths[queued_ant])
walks[queued_ant].append(queued_node)
path = paths[queued_ant]
if len(queue) == 0:
empty_nodes.add(queued_node)
for next_ant in next_ants:
moved_ants.add(next_ant)
curr = currs[next_ant]
prev = prevs[next_ant]
if curr != origins[next_ant] and (not search_mode[next_ant])\
and pheromone_dead_end(G, curr, prev):
search_mode[next_ant] = True
n = G.neighbors(curr)
if curr != prev and prev != None:
for p in to_list(prev):
if p == None:
continue
if p not in n:
print n
print list(prev)
n.remove(p)
candidates = []
for neighbor in n:
if G[curr][neighbor]['anti_pheromone'] <= MIN_DETECTABLE_PHEROMONE:
candidates.append(neighbor)
if G[curr][neighbor]['weight'] >= REINFORCEMENT_THRESHOLD and prev != None:
reinforce[next_ant] = True
if len(candidates) == 0:
deadend[next_ant] = (curr not in nests)
#print curr, deadend[j]
elif len(candidates) > 1:
deadend[next_ant] = False
if (prev == curr):
prev = None
if (curr == origins[next_ant] and not search_mode[next_ant] and not reinforce[next_ant]):
prev = None
exp_prob = explore_prob
if search_mode[next_ant]:
exp_prob = explore2
elif (curr == origins[next_ant] and not search_mode[next_ant]):
exp_prob = 0
next, ex = next_edge(G, curr, exp_prob, strategy, prev, \
destinations[next_ant], search_mode[next_ant],\
backtrack=backtrack, reinforce=reinforce[next_ant])
if ex and (G[curr][next]['weight'] <= MIN_DETECTABLE_PHEROMONE):
queue_ant(G2, curr, next_ant)
new_queue_nodes.add(curr)
empty_nodes.discard(curr)
if WAVES:
if curr in nests:
nest_nqls[curr] += 1
#prevs[next_ant] = curr
#prevs[next_ant] = next
#prevs[next_ant] = prevs[next_ant]
#prevs[next_ant] = [to_list(prevs[next_ant])[0], next]
currs[next_ant] = curr
if video:
paths[next_ant].append(curr)
if track_pruning:
walks[next_ant].append(curr)
if DEBUG_PATHS:
check_path(G, paths[next_ant])
add_amount = 2 * pheromone_add
if 'difficulty' in G[curr][next]:
add_amount *= REINFORCEMENT_RATE[G[curr][next]['difficulty']]
if not deadend[next_ant]:
G2[curr][next]['weight'] += add_amount
if decay_type == 'linear':
G2[curr][next]['units'].append(add_amount)
nonzero_edges.add(Ninv[(curr, next)])
elif ANTI_PHEROMONE:
#G2[curr][next]['weight'] -= add_amount
#G2[curr][next]['weight'] = max(G2[curr][next]['weight'], MIN_PHEROMONE)
#if G2[curr][next]['weight'] > MIN_PHEROMONE:
#nonzero_edges.add(Ninv[(curr, next)])
G2[curr][next]['anti_pheromone'] += 1
else:
if (curr, next) == G[curr][next]['forwards']:
G2[curr][next]['forwards_queue'].append(next_ant)
else:
G2[curr][next]['backwards_queue'].append(next_ant)
queued_edges.add(Ninv[(curr, next)])
queued_nodes.difference_update(empty_nodes)
queued_nodes.update(new_queue_nodes)
if DEBUG_QUEUES:
check_queues(G2, queued_nodes, queued_edges, num_ants)
reset_nest_nqls()
for edge_id in queued_edges:
u, v = N[edge_id]
resulting_size = 0
for direction in ['forwards', 'backwards']:
i = 0
curr, next = G2[u][v][direction]
edge_queue = G2[u][v][direction + '_queue']
eqlim = edge_queue_lim
if edge_queue_lim == -1:
eqlim = len(edge_queue)
while len(edge_queue) > 0 and i < eqlim:
next_ant = edge_queue.pop(0)
if next in nests:
nest_nqls[next] += 1
i += 1
queue_ant(G2, next, next_ant)
new_queue_nodes.add(next)
empty_nodes.discard(next)
prevs[next_ant] = curr
currs[next_ant] = next #curr
add_amount = pheromone_add
if 'difficulty' in G[curr][next]:
add_amount *= REINFORCEMENT_RATE[G[curr][next]['difficulty']]
if not deadend[next_ant]:
G2[curr][next]['weight'] += add_amount
if decay_type == 'linear':
G2[curr][next]['units'].append(add_amount)
nonzero_edges.add(Ninv[(curr, next)])
elif ANTI_PHEROMONE:
#G2[curr][next]['weight'] -= add_amount
#G2[curr][next]['weight'] = max(G2[curr][next]['weight'], MIN_PHEROMONE)
#if G2[curr][next]['weight'] > MIN_PHEROMONE:
#nonzero_edges.add(Ninv[(curr, next)])
G2[curr][next]['anti_pheromone'] += 1
if video:
paths[next_ant].append(next)
if track_pruning:
walks[next_ant].append(next)
if DEBUG_PATHS:
check_path(G, paths[next_ant])
if next == destinations[next_ant]:
orig, dest = origins[next_ant], destinations[next_ant]
origins[next_ant], destinations[next_ant] = dest, orig
search_mode[next_ant] = False
reinforce[next_ant] = True
if track_pruning:
walk = walks[next_ant]
if walk[0] == orig and walk[-1] == dest:
chosen_walk_counts[tuple(walk)] += 1
path = walk_to_path(walk)
start = path[0]
end = path[-1]
idx1 = nests.index(orig)
idx2 = nests.index(dest)
if idx2 > idx1:
path = path[::-1]
path_counts[tuple(path)] += 1
curr_entropy = entropy(path_counts.values())
curr_walk_entropy = entropy(chosen_walk_counts.values())
if max_entropy == None:
max_entropy = curr_entropy
else:
max_entropy = max(max_entropy, curr_entropy)
if max_walk_entropy == None:
max_walk_entropy = curr_walk_entropy
else:
max_walk_entropy = max(max_walk_entropy, curr_walk_entropy)
walks[next_ant] = [origins[next_ant]]
elif next == origins[next_ant]:
search_mode[next_ant] = True
for j in xrange(len(edge_queue)):
next_ant = edge_queue[j]
paths[next_ant].append(curr)
if DEBUG_PATHS:
check_path(G, paths[next_ant])
walks[next_ant].append(curr)
resulting_size += 1
if resulting_size == 0:
empty_edges.add(edge_id)
queued_nodes.difference_update(empty_nodes)
queued_nodes.update(new_queue_nodes)
queued_edges.difference_update(empty_edges)
if DEBUG_QUEUES:
check_queues(G2, queued_nodes, queued_edges, num_ants)
decay_func = get_decay_func_edges(decay_type)
zero_edges = decay_func(G2, nonzero_edges, pheromone_decay, time=1, min_pheromone=MIN_PHEROMONE)
nonzero_edges.difference_update(zero_edges)
G = G2
if video:
for u, v in sorted(G.edges()):
index = Ninv[(u, v)]
wt = G[u][v]['weight']
unique_weights.add(wt)
max_weight = max(max_weight, wt)
if wt <= MIN_DETECTABLE_PHEROMONE:
edge_weights[index].append(None)
else:
edge_weights[index].append(wt)
if connect_time == -1 and has_pheromone_path(G, nests[0], nests[1]):
connect_time = steps
steps += 1
cost = 0
max_wt = 0
for u, v in G.edges_iter():
wt = G[u][v]['weight']
if wt > MIN_PHEROMONE:
cost += 1
max_wt = max(wt, max_wt)
e_colors = edge_color[:]
e_widths = edge_width[:]
n_colors = node_color[:]
n_sizes = node_size[:]
for nest in nests:
n_colors[Minv[nest]] = 'm'
n_sizes[Minv[nest]] = 100
def init():
nx.draw(G, pos=pos, with_labels=False, node_size=n_sizes, edge_color=e_colors,\
node_color=n_colors, width=e_widths, nodelist = sorted(G.nodes()), \
edgelist = sorted(G.edges()))
def redraw(frame):
PP.clf()
print frame
n_colors = ['r'] * len(node_color)
n_sizes = [10] * len(node_size)
ax = PP.gca()
for n in xrange(num_ants):
node = paths[n][frame + 1]
index = Minv[node]
n_colors[index] = 'k'
n_sizes[index] += ant_thickness
#if frame > 0:
# frame -= 1
max_units = max_weight / pheromone_add
e_colors = []
e_widths = []
for u, v in sorted(G.edges()):
index = Ninv[(u, v)]
edge_wt = edge_weights[index][frame]
if edge_wt == None:
if 'difficulty' in G[u][v]:
e_colors.append(DIFFICULTY_COLORS[G[u][v]['difficulty']])
elif 'plant' in G.node[u] and 'plant' in G.node[v]:
if G.node[u]['plant'] == G.node[v]['plant']:
e_colors.append('k')
else:
e_colors.append('b')
else:
e_colors.append('k')
e_widths.append(1)
else:
e_colors.append('g')
e_widths.append(1 + 25 * (edge_wt / max_weight))
for nest in nests:
n_colors[Minv[nest]] = 'm'
#n_sizes[Minv[nest]] = min(n_sizes[Minv[nest]], 100)
#print nest, n_sizes[Minv[nest]]