initial working version with folding.
diff --git a/sim.py b/sim.py --- a/sim.py +++ b/sim.py @@ -19,14 +19,13 @@ def generateflat(nodes, connectionsperno """generate a randomly connected network with the given connectionspernode.""" net = defaultdict(list) for node in nodes: - connections = [] for n in range(connectionspernode - len(net[node])): conn = choice(nodes) while (conn == node or node in net[conn] or - net[conn][connectionspernode-1:]): + net[conn][connectionspernode:]): conn = choice(nodes) - connections.append(conn) + net[node].append(conn) net[conn].append(node) for node, conns in net.items(): net[node] == sorted(conns) @@ -52,17 +51,61 @@ def findroute(target, start, net): while not best == target: prev = best best = closest(target, net[prev]) - # never repeat a route + # never repeat a route deterministically if best in seen: best = choice(net[prev]) route.append(best) seen.add(best) return route +def checkfold(target, prev, net, probability=0.07): + """switch to the target location with some probability""" + if random() > probability: + return + # do not switch to exactly the target to avoid duplicate entries + # (implementation detail) + while target in net: + target = (target + (random()-0.5)*1.e-9) % 1 + conns = net[prev] + # never switch with a neighbour + if target in conns: + return + net[target] = conns + del net[prev] + for conn in conns: + net[conn].remove(prev) + net[conn] = sorted(net[conn] + [target]) + +def fold(net, num=10): + """do num path foldings.""" + for i in range(num): + nodes = list(net.keys()) + start = choice(nodes) + target = choice(nodes) + while target == start: + target = choice(nodes) + + route = findroute(target, start, net) + for prev in route: + checkfold(target, prev, net) + +def linklengths(net): + """calculate the lengthsof all links""" + lengths = [] + for node, targets in net.items(): + for t in targets: + lengths.append(abs(t-node)) + return lengths + if __name__ == "__main__": + import numpy as np nodes = randomnodes() net = generateflat(nodes) - start = choice(nodes) - target = choice(nodes) - route = findroute(target, start, net) - print (route) + print (np.mean(linklengths(net))) + fold(net) + print (np.mean(linklengths(net))) + fold(net) + print (np.mean(linklengths(net))) + fold(net) + print (np.mean(linklengths(net))) +