Beispiel #1
0
 def networkx_sp_tree(self, source, target):
     # compute source-rooted SP tree
     (preds_ab, self.dist_map_ab) = nx.dijkstra_predecessor_and_distance(
         self.graph, source, weight="weight")
     # transform because we want only one predecessor for each
     self.pred_map_ab = {
         key: int(next(iter(pred_list), key))
         for key, pred_list in preds_ab.items()
     }
     # reverse edge directions
     self.graph = self.graph.reverse(copy=False)
     # compute target-rooted SP tree
     (preds_ba, self.dist_map_ba) = nx.dijkstra_predecessor_and_distance(
         self.graph, target, weight="weight")
     # fill the ones that are not in dictionary yet
     (self.pred_map_ba, self.pred_map_ba) = {}, {}
     vertices = np.unique(self.pos2node)[1:]
     for v in vertices:
         try:
             self.pred_map_ba[v] = int(next(iter(preds_ba[v]), v))
         except KeyError:
             self.pred_map_ba[v] = v
             self.dist_map_ba[v] = np.inf
         try:
             self.pred_map_ab[v] = int(next(iter(preds_ab[v]), v))
         except KeyError:
             self.pred_map_ab[v] = v
             self.dist_map_ab[v] = np.inf
     self.graph = self.graph.reverse(copy=False)
Beispiel #2
0
    def test_dijkstra_predecessor(self):
        G = nx.path_graph(4)
        assert_equal(nx.dijkstra_predecessor_and_distance(G, 0), ({
            0: [],
            1: [0],
            2: [1],
            3: [2]
        }, {
            0: 0,
            1: 1,
            2: 2,
            3: 3
        }))
        G = nx.grid_2d_graph(2, 2)
        pred, dist = nx.dijkstra_predecessor_and_distance(G, (0, 0))
        assert_equal(sorted(pred.items()), [((0, 0), []), ((0, 1), [(0, 0)]),
                                            ((1, 0), [(0, 0)]),
                                            ((1, 1), [(0, 1), (1, 0)])])
        assert_equal(sorted(dist.items()), [((0, 0), 0), ((0, 1), 1),
                                            ((1, 0), 1), ((1, 1), 2)])

        XG = nx.DiGraph()
        XG.add_weighted_edges_from([
            ('s', 'u', 10), ('s', 'x', 5), ('u', 'v', 1), ('u', 'x', 2),
            ('v', 'y', 1), ('x', 'u', 3), ('x', 'v', 5), ('x', 'y', 2),
            ('y', 's', 7), ('y', 'v', 6)
        ])
        (P, D) = nx.dijkstra_predecessor_and_distance(XG, 's')
        assert_equal(P['v'], ['u'])
        assert_equal(D['v'], 9)
        (P, D) = nx.dijkstra_predecessor_and_distance(XG, 's', cutoff=8)
        assert_false('v' in D)
Beispiel #3
0
    def test_dijkstra_predecessor(self):
        G = nx.path_graph(4)
        assert_equal(
            nx.dijkstra_predecessor_and_distance(G, 0), ({0: [], 1: [0], 2: [1], 3: [2]}, {0: 0, 1: 1, 2: 2, 3: 3})
        )
        G = nx.grid_2d_graph(2, 2)
        pred, dist = nx.dijkstra_predecessor_and_distance(G, (0, 0))
        assert_equal(
            sorted(pred.items()), [((0, 0), []), ((0, 1), [(0, 0)]), ((1, 0), [(0, 0)]), ((1, 1), [(0, 1), (1, 0)])]
        )
        assert_equal(sorted(dist.items()), [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 2)])

        XG = nx.DiGraph()
        XG.add_weighted_edges_from(
            [
                ("s", "u", 10),
                ("s", "x", 5),
                ("u", "v", 1),
                ("u", "x", 2),
                ("v", "y", 1),
                ("x", "u", 3),
                ("x", "v", 5),
                ("x", "y", 2),
                ("y", "s", 7),
                ("y", "v", 6),
            ]
        )
        (P, D) = nx.dijkstra_predecessor_and_distance(XG, "s")
        assert_equal(P["v"], ["u"])
        assert_equal(D["v"], 9)
Beispiel #4
0
def dijkstra_plan_networkX(product, beta=10):
    # requires a full construct of product automaton
    start = time.time()
    runs = {}
    loop = {}
    # minimal circles
    for prod_target in product.graph['accept']:
        #print 'prod_target', prod_target
        # accepting state in self-loop
        if prod_target in product.predecessors(prod_target):
            loop[prod_target] = (
                product.edge[prod_target][prod_target]["weight"],
                [prod_target, prod_target])
            continue
        else:
            cycle = {}
            loop_pre, loop_dist = dijkstra_predecessor_and_distance(
                product, prod_target)
            for target_pred in product.predecessors_iter(prod_target):
                if target_pred in loop_dist:
                    cycle[target_pred] = product.edge[target_pred][
                        prod_target]["weight"] + loop_dist[target_pred]
            if cycle:
                opti_pred = min(cycle, key=cycle.get)
                suffix = compute_path_from_pre(loop_pre, opti_pred)
                loop[prod_target] = (cycle[opti_pred], suffix)
    # shortest line
    if not product.graph['initial']:
        print 'Initial set empty'
    for prod_init in product.graph['initial']:
        line = {}
        line_pre, line_dist = dijkstra_predecessor_and_distance(
            product, prod_init)
        for target in loop.iterkeys():
            if target in line_dist:
                line[target] = line_dist[target] + beta * loop[target][0]
        if line:
            opti_targ = min(line, key=line.get)
            prefix = compute_path_from_pre(line_pre, opti_targ)
            precost = line_dist[opti_targ]
            runs[(prod_init,
                  opti_targ)] = (prefix, precost, loop[opti_targ][1],
                                 loop[opti_targ][0])
    # best combination
    if runs:
        prefix, precost, suffix, sufcost = min(
            runs.values(), key=lambda p: p[1] + beta * p[3])
        run = ProdAut_Run(product, prefix, precost, suffix, sufcost,
                          precost + beta * sufcost)
        print '=================='
        print 'Dijkstra_plan_networkX done within %.2fs: precost %.2f, sufcost %.2f' % (
            time.time() - start, precost, sufcost)
        return run, time.time() - start
        #print '\n==================\n'
    print '=================='
    print 'No accepting run found in optimal planning!'
    return None, None
Beispiel #5
0
 def test_dijkstra_predecessor3(self):
     XG = nx.DiGraph()
     XG.add_weighted_edges_from([('s', 'u', 10), ('s', 'x', 5),
                                 ('u', 'v', 1), ('u', 'x', 2),
                                 ('v', 'y', 1), ('x', 'u', 3),
                                 ('x', 'v', 5), ('x', 'y', 2),
                                 ('y', 's', 7), ('y', 'v', 6)])
     (P, D) = nx.dijkstra_predecessor_and_distance(XG, 's')
     assert_equal(P['v'], ['u'])
     assert_equal(D['v'], 9)
     (P, D) = nx.dijkstra_predecessor_and_distance(XG, 's', cutoff=8)
     assert_false('v' in D)
Beispiel #6
0
 def test_dijkstra_predecessor3(self):
     XG = nx.DiGraph()
     XG.add_weighted_edges_from([('s', 'u', 10), ('s', 'x', 5),
                                 ('u', 'v', 1), ('u', 'x', 2),
                                 ('v', 'y', 1), ('x', 'u', 3),
                                 ('x', 'v', 5), ('x', 'y', 2),
                                 ('y', 's', 7), ('y', 'v', 6)])
     (P, D) = nx.dijkstra_predecessor_and_distance(XG, 's')
     assert_equal(P['v'], ['u'])
     assert_equal(D['v'], 9)
     (P, D) = nx.dijkstra_predecessor_and_distance(XG, 's', cutoff=8)
     assert_false('v' in D)
Beispiel #7
0
 def test_dijkstra_predecessor3(self):
     XG = nx.DiGraph()
     XG.add_weighted_edges_from([
         ('s', 'u', 10), ('s', 'x', 5), ('u', 'v', 1), ('u', 'x', 2),
         ('v', 'y', 1), ('x', 'u', 3), ('x', 'v', 5), ('x', 'y', 2),
         ('y', 's', 7), ('y', 'v', 6)
     ])
     (P, D) = nx.dijkstra_predecessor_and_distance(XG, 's')
     assert P['v'] == ['u']
     assert D['v'] == 9
     (P, D) = nx.dijkstra_predecessor_and_distance(XG, 's', cutoff=8)
     assert 'v' not in D
def subtours(n, dist, model, x):
    # construindo grafo auxiliar (apenas uma vez)
    global F
    if not F:
        F = []
        G = nx.DiGraph()
        for ((i, j), val) in dist.items():
            G.add_edge(i, j, weight=val)
        for i in range(n):
            P, D = nx.dijkstra_predecessor_and_distance(G, source=i)
            DS = list(D.items())
            DS.sort(key=lambda x: x[1])
            F.append((i, DS[-1][0]))

    G = nx.DiGraph()
    for (i, j) in x.keys():
        if x[(i,j)].x > EPS:
            G.add_edge(i, j, capacity=x[i,j].x)

    cycles = set()
    for (u, v) in F:
        val, (S, NS) = nx.minimum_cut(G, u, v)
        if len(S) > 1 and len(S) < n and val <= 0.99:
            arcs_S = [(i,j) for (i,j) in dist if i in S and j in S]
            if sum(x[arc].x for arc in arcs_S) >= len(S) - 1 + EPS:
                cycles.add(tuple(S))

    return cycles
Beispiel #9
0
    def dijkstra(self, v_inicial):
        if(self.vertices.count(v_inicial) == 0):
            print("El nodo que ha ingresado no pertenece al grafo")
        else:
            filas = columnas = len(self.matriz)
            #Matriz de peso con enteros
            matriz = [[0] * (filas) for i in range(columnas)]
            for f in range(filas):
                for c in range(columnas):
                    if(self.matriz[f][c] is None):
                        matriz[f][c] = 0
                    else:
                        matriz[f][c] = int(self.matriz[f][c])

            #Creo un array de numpy para analizar la matriz mas facilmente
            matriz = np.array(matriz)
            #Creo el grafico de la libreria networkx para usar sus metodos (Dijkstra)
            G = nx.from_numpy_matrix(matriz, create_using=nx.DiGraph())
            pred, dist = nx.dijkstra_predecessor_and_distance(G, self.vertices.index(v_inicial))
            dist = dist.items()
            # print(pred) #Antecesores como diccionario
            # print(pred.items()) #Antecesores como arreglo
            for i in dist:
                #Rearmando la ruta
                #Codigo del rearme de ruta (In progress...)
                
                #Distancias (working...)
                print("Distancia menor de " + v_inicial + "->" + self.vertices[i[0]] + ": " + str(i[1]))
def estimate(graph, runs):
    it = 0
    max_id = max(graph.nodes())
    it_since_last_update = 0
    seen = set()

    est = {'src': -1, 'dst': -1, 'distance': 0, 'edges': 0}

    src = npr.randint(max_id)

    while not graph.has_node(src):
        src = npr.randint(max_id)

    while it_since_last_update < runs:
        seen.add(src)
        pred, dists = nx.dijkstra_predecessor_and_distance(graph, src)
        dst, dist = max(dists.items(), key=lambda x: x[1])
        if dist > est['distance']:
            est['src'] = src
            est['dst'] = dst
            est['distance'] = dist
            edges = 0
            x = dst
            while x != src:
                edges += 1
                x = pred[x][0]
            est['edges'] = edges
            it_since_last_update = 0
        print "{} | {} -- {} : {} (cur estimate {} standing {})".format(
            it, src, dst, dist, est, it_since_last_update)
        it += 1
        src = npr.randint(max_id) if dst in seen else dst
        it_since_last_update += 1
    return est
Beispiel #11
0
 def test_dijkstra_pred_distance_multigraph(self):
     G = nx.MultiGraph()
     G.add_edge('a', 'b', key='short', foo=5, weight=100)
     G.add_edge('a', 'b', key='long', bar=1, weight=110)
     p, d = nx.dijkstra_predecessor_and_distance(G, 'a')
     assert_equal(p, {'a': [], 'b': ['a']})
     assert_equal(d, {'a': 0, 'b': 100})
Beispiel #12
0
 def test_dijkstra_pred_distance_multigraph(self):
     G = nx.MultiGraph()
     G.add_edge("a", "b", key="short", foo=5, weight=100)
     G.add_edge("a", "b", key="long", bar=1, weight=110)
     p, d = nx.dijkstra_predecessor_and_distance(G, "a")
     assert_equal(p, {"a": [], "b": ["a"]})
     assert_equal(d, {"a": 0, "b": 100})
Beispiel #13
0
 def test_dijkstra_pred_distance_multigraph(self):
     G = nx.MultiGraph()
     G.add_edge('a', 'b', key='short',foo=5, weight=100)
     G.add_edge('a', 'b', key='long',bar=1, weight=110)
     p,d= nx.dijkstra_predecessor_and_distance(G, 'a')
     assert_equal(p,{'a': [], 'b': ['a']})
     assert_equal(d,{'a': 0, 'b': 100})
Beispiel #14
0
def list_dist(G, list_data, user, list_nodes):
    """Returns the list of distance between the user node and the other system nodes
    
    Parameters :
    ===========================================================================

    list_nodes :list of node object
    
    G : NetworkX graph
    
    user : string (user node label)
        
    Returns :
    ===========================================================================
        data_list : list of int 
    
    """
    l_dist = []
    path = nx.dijkstra_predecessor_and_distance(G, user)[1]
    l_node = []

    if user in list_nodes:
        list_nodes.remove(user)
    for node in list_nodes:

        l_dist.append(path[node])
    l_dist.sort()
    for dist in l_dist:
        for node in list_node:
            if path[node] == dist:
                l_node.append(node)

    return l_node
Beispiel #15
0
def dijkstra_plan_networkX_suffix(product, beta=10):
    # requires a full construct of product automaton
    start = time.time()
    runs = {}
    loop = {}
    # minimal circles
    for prod_target in product.graph['accept']:
        #print 'prod_target', prod_target
        # accepting state in self-loop
        if prod_target in product.predecessors(prod_target):
            loop[prod_target] = (
                product.edge[prod_target][prod_target]["weight"],
                [prod_target, prod_target])
            continue
        else:
            cycle = {}
            loop_pre, loop_dist = dijkstra_predecessor_and_distance(
                product, prod_target)
            for target_pred in product.predecessors_iter(prod_target):
                if target_pred in loop_dist:
                    cycle[target_pred] = product.edge[target_pred][
                        prod_target]["weight"] + loop_dist[target_pred]
                    print 'one suffix found, cost', cycle[target_pred]
            if cycle:
                opti_pred = min(cycle, key=cycle.get)
                suffix = compute_path_from_pre(loop_pre, opti_pred)
                loop[prod_target] = (cycle[opti_pred], suffix)
                print 'optimal suffix found, cost', cycle[opti_pred]
                print '=================='
                print 'Dijkstra_plan_networkX_Suffix done within %.2fs: sufcost %.2f' % (
                    time.time() - start, cycle[opti_pred])
    print '=================='
    print 'No accepting run found in optimal planning!'
    return None, None
Beispiel #16
0
def dijkstra_all_shortest_paths(G, source, target, weight=None):
    ''' This function is the networkX's implementation of the "all-shortest-paths-problem" algorithm
        and is used as ground truth for our implementation. It uses a modified version of the 
        dijkstra algorithm that compute  the shortest path length and predecessors 
        on shortest paths.'''
        
    if weight is not None:
        pred,dist = nx.dijkstra_predecessor_and_distance(G,source,weight=weight)
    else:
        pred = nx.predecessor(G,source)
    if target not in pred:
        raise nx.NetworkXNoPath()
    stack = [[target,0]]
    top = 0
    while top >= 0:
        node,i = stack[top]
        if node == source:
            yield [p for p,n in reversed(stack[:top+1])]
        if len(pred[node]) > i:
            top += 1
            if top == len(stack):
                stack.append([pred[node][i],0])
            else:
                stack[top] = [pred[node][i],0]
        else:
            stack[top-1][1] += 1
            top -= 1
Beispiel #17
0
 def test_dijkstra_pred_distance_multigraph(self):
     G = nx.MultiGraph()
     G.add_edge("a", "b", key="short", foo=5, weight=100)
     G.add_edge("a", "b", key="long", bar=1, weight=110)
     p, d = nx.dijkstra_predecessor_and_distance(G, "a")
     assert p == {"a": [], "b": ["a"]}
     assert d == {"a": 0, "b": 100}
Beispiel #18
0
def compute_mst(G, main_stem, nodes):
    # Set weights proportional to distance to node
    # (for computing minimum spanning tree)
    G = G.copy()
    distances = {}
    for i in nodes:
        _, distances[i] = nx.dijkstra_predecessor_and_distance(G, i)

    distance_to_node = {}
    for n in G.nodes():
        distance_to_node[n] = min(distances[i][n] for i in nodes)

    def node_penalty(u, v):
        if u in main_stem or v in main_stem:
            return 0
        if len(list(nx.neighbors(G, u))) > 2 or len(list(nx.neighbors(G,
                                                                      v))) > 2:
            print(">2", u, v)
            return 10000 + distance_to_node[u] + distance_to_node[v]
        return (distance_to_node[u] + distance_to_node[v])

    for u, v in G.edges():
        G[u][v]['weight'] = node_penalty(u, v)

    # Compute minimum spanning tree
    T = nx.minimum_spanning_tree(G)
    return T
Beispiel #19
0
def phase_from_node_shortest(gg1, startnode):
  hap0=[]
  hap1=[]
  if len(gg1)==1:
    hap0.append(get_phased_allele(gg1, startnode, 0))
    hap1.append(get_phased_allele(gg1, startnode, 1))
  else:
    dp=nx.dijkstra_predecessor_and_distance(gg1, startnode, weight='tot')
    kk=list(dp[0].keys())
    for ii in range(len(kk)):
      if ii==0:
        curnode=startnode
        hap0.append(get_phased_allele(gg1, curnode, 0))
        hap1.append(get_phased_allele(gg1, curnode, 1))
      else:
        curnode=kk[ii]
        prevnode=dp[0][kk[ii]][0]
        edata=gg1.edges[curnode, prevnode]
        if 'phased_all' in gg1.nodes[prevnode]:
          alleles=gg1.nodes[prevnode]['phased_all']
          oddsratio=(edata['cts'][0]+1.0)*(edata['cts'][3]+1.0)/((edata['cts'][1]+1.0)*(edata['cts'][2]+1.0))
          if oddsratio>1:
            gg1.nodes[curnode]['phased_all']=alleles
          else:
            gg1.nodes[curnode]['phased_all']=[alleles[1], alleles[0]] 
          hap0.append(get_phased_allele(gg1, curnode, 0))
          hap1.append(get_phased_allele(gg1, curnode, 1))
  return [hap0, hap1]
Beispiel #20
0
def _node_betweenness(G,
                      source,
                      cutoff=False,
                      normalized=True,
                      weighted_edges=False):
    """Node betweenness helper:
    see betweenness_centrality for what you probably want.

    This actually computes "load" and not betweenness.
    See https://networkx.lanl.gov/ticket/103

    This calculates the load of each node for paths from a single source.
    (The fraction of number of shortests paths from source that go
    through each node.)

    To get the load for a node you need to do all-pairs shortest paths.

    If weighted_edges is True then use Dijkstra for finding shortest paths.
    In this case a cutoff is not implemented and so is ignored.

    """

    # get the predecessor and path length data
    if weighted_edges:
        (pred, length) = nx.dijkstra_predecessor_and_distance(G, source)
    else:
        (pred, length) = nx.predecessor(G,
                                        source,
                                        cutoff=cutoff,
                                        return_seen=True)

    # order the nodes by path length
    onodes = [(l, vert) for (vert, l) in length.items()]
    onodes.sort()
    onodes[:] = [vert for (l, vert) in onodes if l > 0]

    # intialize betweenness
    between = {}.fromkeys(length, 1.0)

    while onodes:
        v = onodes.pop()
        if v in pred:
            num_paths = len(pred[v])  # Discount betweenness if more than
            for x in pred[v]:  # one shortest path.
                if x == source:  # stop if hit source because all remaining v
                    break  #  also have pred[v]==[source]
                between[x] += between[v] / float(num_paths)
    #  remove source
    for v in between:
        between[v] -= 1
    # rescale to be between 0 and 1
    if normalized:
        l = len(between)
        if l > 2:
            scale = 1.0 / float(
                (l - 1) * (l - 2))  # 1/the number of possible paths
            for v in between:
                between[v] *= scale
    return between
Beispiel #21
0
def make_paths_tree(nodes,origin):
    pred, length = nx.dijkstra_predecessor_and_distance(G, origin, cutoff=None, weight='length')
    tree = build_paths_tree(pred,nodes,origin)
    N = len(nodes)
    dist = np.empty(N)
    for i in range(N):
        dist[i] = length[nodes[i]]
    return tree, dist
def explore_shortestpath(G,K):
    cx,cy = position(entiers=True)
    _ , dist = nx.dijkstra_predecessor_and_distance( G,(cx,cy) )
    dist = {ij:dist[ij] for ij in dist if ij not in K}
    if dist:
        closest, _ = min(dist.items(), key=itemgetter(1))
        p = nx.shortest_path(G,(cx,cy),closest,weight='weight')
        suivre_chemin(p,aller)
def _node_betweenness(G, source, cutoff=False, weight=None, destIdentifier='destinations'):
    """Node betweenness_centrality helper:

    See betweenness_centrality for what you probably want.
    This actually computes "partial centrality" and not betweenness.
    See https://networkx.lanl.gov/ticket/103

    This calculates the load of each node for paths from a single source.
    (The fraction of number of shortests paths from source that go
    through each node.)

    To get the load for a node you need to do all-pairs shortest paths.

    If weight is not None then use Dijkstra for finding shortest paths.
    """
    # get the predecessor and path length data
    if weight is None:
        (pred, length) = nx.predecessor(G, source, cutoff=cutoff,
                                        return_seen=True)
    else:
        (pred, length) = nx.dijkstra_predecessor_and_distance(G, source,
                                                              cutoff, weight)

    for predecessor in pred:
        newlist = []
        if len(pred[predecessor]) > 0:
            minimo = pred[predecessor][0]
            for elem in pred[predecessor]:
                if int(elem) < int(minimo):
                    minimo = elem
            newlist.append(minimo)
            pred[predecessor][:] = newlist

    onodes = [(l, vert) for (vert, l) in length.items()]
    onodes.sort()
    onodes[:] = [vert for (l, vert) in onodes if l > 0]

    between = {}.fromkeys(length, 1.0)
    for node in G.nodes:
        if destIdentifier not in G.nodes[node]:
            between[node] = 0.0  # No stub nodes does not propagate any contribute
        else:
            between[node] = 1.0  # Stub nodes propagate 1 contribute

    while onodes:
        v = onodes.pop()
        if v in pred:
            num_paths = len(pred[v])  # Discount betweenness if more than
            for x in pred[v]:  # one shortest path.
                if x == source:  # stop if hit source
                    break  # also have pred[v]==[source]
                between[x] += between[v] / float(num_paths)

    for node in G.nodes:
        if destIdentifier in G.nodes[node]:
            between[node] -= 1.0

    return between
Beispiel #24
0
def dijkstra_plan_networkX(product, beta=10):
	# requires a full construct of product automaton
	start = time.time()
	runs = {}
	loop = {}
	# minimal circles
	for prod_target in product.graph['accept']:
                #print 'prod_target', prod_target
                # accepting state in self-loop
                if prod_target in product.predecessors(prod_target):
                        loop[prod_target] = (product.edges[prod_target,prod_target]["weight"], [prod_target, prod_target])
                        continue
                else:
                        cycle = {}
                        loop_pre, loop_dist = dijkstra_predecessor_and_distance(product, prod_target)
                        for target_pred in product.predecessors(prod_target):
                                if target_pred in loop_dist:
                                        cycle[target_pred] = product.edges[target_pred,prod_target]["weight"] + loop_dist[target_pred]
                        if cycle:
                                opti_pred = min(cycle, key = cycle.get)
                                suffix = compute_path_from_pre(loop_pre, opti_pred)
                                loop[prod_target] = (cycle[opti_pred], suffix)
	# shortest line
	for prod_init in product.graph['initial']:
                line = {}
		line_pre, line_dist = dijkstra_predecessor_and_distance(product, prod_init)
		for target in loop.iterkeys():
			if target in line_dist:
				line[target] = line_dist[target]+beta*loop[target][0]
		if line:
			opti_targ = min(line, key = line.get)
			prefix = compute_path_from_pre(line_pre, opti_targ)
			precost = line_dist[opti_targ]
			runs[(prod_init, opti_targ)] = (prefix, precost, loop[opti_targ][1], loop[opti_targ][0])
	# best combination
	if runs:
		prefix, precost, suffix, sufcost = min(runs.values(), key = lambda p: p[1] + beta*p[3])
		run = ProdAut_Run(product, prefix, precost, suffix, sufcost, precost+beta*sufcost)
		print '=================='
		print 'Dijkstra_plan_networkX done within %.2fs: precost %.2f, sufcost %.2f' %(time.time()-start, precost, sufcost)
		return run, time.time()-start
		#print '\n==================\n'
	print '=================='        
	print 'No accepting run found in optimal planning!'
        return None, None
Beispiel #25
0
 def test_dijkstra_predecessor2(self):
     # 4-cycle
     G = nx.Graph([(0, 1), (1, 2), (2, 3), (3, 0)])
     pred, dist = nx.dijkstra_predecessor_and_distance(G, (0))
     assert_equal(pred[0], [])
     assert_equal(pred[1], [0])
     assert_true(pred[2] in [[1, 3], [3, 1]])
     assert_equal(pred[3], [0])
     assert_equal(dist, {0: 0, 1: 1, 2: 2, 3: 1})
Beispiel #26
0
 def test_dijkstra_predecessor2(self):
     # 4-cycle
     G = nx.Graph([(0, 1), (1, 2), (2, 3), (3, 0)])
     pred, dist = nx.dijkstra_predecessor_and_distance(G, (0))
     assert pred[0] == []
     assert pred[1] == [0]
     assert pred[2] in [[1, 3], [3, 1]]
     assert pred[3] == [0]
     assert dist == {0: 0, 1: 1, 2: 2, 3: 1}
Beispiel #27
0
 def test_dijkstra_predecessor2(self):
     # 4-cycle
     G = nx.Graph([(0,1),(1,2),(2,3),(3,0)])
     pred, dist = nx.dijkstra_predecessor_and_distance(G, (0))
     assert_equal(pred[0],[])
     assert_equal(pred[1],[0])
     assert_true(pred[2] in [[1,3],[3,1]])
     assert_equal(pred[3],[0])
     assert_equal(dist, {0: 0, 1: 1, 2: 2, 3: 1})
Beispiel #28
0
 def test_dijkstra_predecessor3(self):
     XG = nx.DiGraph()
     XG.add_weighted_edges_from([
         ("s", "u", 10),
         ("s", "x", 5),
         ("u", "v", 1),
         ("u", "x", 2),
         ("v", "y", 1),
         ("x", "u", 3),
         ("x", "v", 5),
         ("x", "y", 2),
         ("y", "s", 7),
         ("y", "v", 6),
     ])
     (P, D) = nx.dijkstra_predecessor_and_distance(XG, "s")
     assert P["v"] == ["u"]
     assert D["v"] == 9
     (P, D) = nx.dijkstra_predecessor_and_distance(XG, "s", cutoff=8)
     assert "v" not in D
Beispiel #29
0
def Part1_4(house_nd,object_nd):
    N = len(house_nd)
    M = len(object_nd)
    tree_weights = np.empty(M)
    for j in range(M):
        pred, length_object2house = nx.dijkstra_predecessor_and_distance(G, object_nd[j], cutoff=None, weight='length')
        tree = build_paths_tree(pred,house_nd,object_nd[j])
        tree_weights[j] = tree.size(weight='length')

    arg = np.argmin(tree_weights)
    return arg 
Beispiel #30
0
def test_dijkstra_all_digraph(testgraph):
    """
    Testing dijkstra_all function for directed graphs.
    """

    a, b = testgraph[2:]
    s = randint(0, 99)
    nx_dijk =  nx.dijkstra_predecessor_and_distance(a, s)
    nx_dijk = nx_dijk[1]
    sg_dijk = sg.dijkstra.dijkstra_all(b, s, directed = True)
    for i in range(len(nx_dijk)):
        assert sg_dijk[1][i] == nx_dijk[sg_dijk[0][i]]
Beispiel #31
0
def shortest_path_ts(ts, f_ts_node, t_ts_node):
    if (f_ts_node not in ts) or (t_ts_node not in ts):
        print 'either nodes not in ts'
        return None, None
    else:
        path_pre, path_dist = dijkstra_predecessor_and_distance(ts, f_ts_node)
        if t_ts_node not in path_dist:
            print 'destination not reached'
        else:
            path = compute_path_from_pre(path_pre, t_ts_node)
            cost = path_dist[t_ts_node]
        return (path, cost)
    def test_dijkstra_predecessor(self):
        G=nx.path_graph(4)
        assert_equal(nx.dijkstra_predecessor_and_distance(G,0),
                     ({0: [], 1: [0], 2: [1], 3: [2]}, {0: 0, 1: 1, 2: 2, 3: 3}))
        G=nx.grid_2d_graph(2,2)
        pred,dist=nx.dijkstra_predecessor_and_distance(G,(0,0))
        assert_equal(sorted(pred.items()),
                     [((0, 0), []), ((0, 1), [(0, 0)]), 
                      ((1, 0), [(0, 0)]), ((1, 1), [(0, 1), (1, 0)])])
        assert_equal(sorted(dist.items()),
                     [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 2)])

        XG=nx.DiGraph()
        XG.add_weighted_edges_from([('s','u',10) ,('s','x',5) ,
                                    ('u','v',1) ,('u','x',2) ,
                                    ('v','y',1) ,('x','u',3) ,
                                    ('x','v',5) ,('x','y',2) ,
                                    ('y','s',7) ,('y','v',6)])
        (P,D)= nx.dijkstra_predecessor_and_distance(XG,'s')
        assert_equal(P['v'],['u'])
        assert_equal(D['v'],9)
Beispiel #33
0
def _node_betweenness(G, source, cutoff=False, normalized=True, weight=None):
    """Node betweenness_centrality helper:

    See betweenness_centrality for what you probably want.
    This actually computes "load" and not betweenness.
    See https://networkx.lanl.gov/ticket/103

    This calculates the load of each node for paths from a single source.
    (The fraction of number of shortests paths from source that go
    through each node.)

    To get the load for a node you need to do all-pairs shortest paths.

    If weight is not None then use Dijkstra for finding shortest paths.
    """

    # get the predecessor and path length data
    if weight is None:
        (pred, length) = nx.predecessor(G, source, cutoff=cutoff,
                                        return_seen=True)
    else:
        (pred, length) = nx.dijkstra_predecessor_and_distance(G, source,
                                                              cutoff, weight)

    # order the nodes by path length
    onodes = [(l, vert) for (vert, l) in length.items()]
    onodes.sort()
    onodes[:] = [vert for (l, vert) in onodes if l > 0]

    # intialize betweenness
    between = {}.fromkeys(length, 1.0)

    while onodes:
        v = onodes.pop()
        if v in pred:
            num_paths = len(pred[v])  # Discount betweenness if more than
            for x in pred[v]:         # one shortest path.
                if x == source:  # stop if hit source because all remaining v
                    break        # also have pred[v]==[source]
                between[x] += between[v] / float(num_paths)
    #  remove source
    for v in between:
        between[v] -= 1
    # rescale to be between 0 and 1
    if normalized:
        l = len(between)
        if l > 2:
            # scale by 1/the number of possible paths
            scale = 1.0 / float((l - 1) * (l - 2))
            for v in between:
                between[v] *= scale
    return between
Beispiel #34
0
    def get_farthest_point_list(self):

        # computing farthest point for each point, these will be checked first for
        # isolated subtours

        F = []
        for i in self.graph.nodes():
            P, D = nx.dijkstra_predecessor_and_distance(self.graph, source=i)
            DS = list(D.items())
            farthest_point = max(DS, key=lambda x: x[1])[0]
            F.append((i, farthest_point))

        return F
Beispiel #35
0
 def test_dijkstra_predecessor1(self):
     G = nx.path_graph(4)
     assert (nx.dijkstra_predecessor_and_distance(G, 0) == ({
         0: [],
         1: [0],
         2: [1],
         3: [2]
     }, {
         0: 0,
         1: 1,
         2: 2,
         3: 3
     }))
Beispiel #36
0
def perform_tests(files):
    Time_nx = []
    Time_custom = []
    Num = []
    for file in files:
        input_data = pd.read_csv(file, index_col=0)
        G = nx.DiGraph(input_data.values)
        N = len(G.nodes())
        Num.append(N)
        #D_truth = np.empty([N,N])
        #D = np.empty([N,N])
        D_truth = []
        D = []
        t0 = tm.time()
        for i in range(N):
            D_truth.append(
                nx.dijkstra_predecessor_and_distance(G, i, weight='weight')[1])
        t1 = tm.time()
        Time_nx.append(t1 - t0)

        t0 = tm.time()
        for i in range(N):
            D.append(custom_dijkstra(G, i, weight='weight')[1])
        t1 = tm.time()
        Time_custom.append(t1 - t0)
        Dist = np.zeros([N, N])
        Dist_truth = np.zeros([N, N])
        for i in range(N):
            for e in D[i]:
                Dist[i, e] = D[i][e]
        for i in range(N):
            for e in D_truth[i]:
                Dist_truth[i, e] = D_truth[i][e]

        print(np.max(Dist - Dist_truth) == 0.0)
        Dist = np.append([np.arange(N)], Dist, axis=0)
        Dist = np.append(np.transpose([np.concatenate(([0], np.arange(N)))]),
                         Dist,
                         axis=1)

        np.savetxt(
            file[0:-4] + '_result.csv',
            Dist.astype(int),
            delimiter=',',
            fmt='%5.0f',
        )

    return Time_nx, Time_custom, Num
Beispiel #37
0
 def nx_dijkstra(
     graph: NetworkXGraph,
     source_node: NodeID  # , max_path_length: float
 ) -> Tuple[PythonNodeMap, PythonNodeMap]:
     predecessors_map, distance_map = nx.dijkstra_predecessor_and_distance(
         graph.value,
         source_node,  # cutoff=max_path_length,
     )
     single_parent_map = {
         child: parents[0] if len(parents) > 0 else source_node
         for child, parents in predecessors_map.items()
     }
     return (
         PythonNodeMap(single_parent_map, ),
         PythonNodeMap(distance_map, ),
     )
Beispiel #38
0
def checkMetricCompatibility(G, system, weights, strict=False):
    N = len(G.nodes)

    #This defines edge weight function
    def wghtFxn(i, j, dictEdge):
        edge = (i, j) if i < j else (j, i)
        return weights[edge]

    #Given a path gives its weight
    def pathWeight(p):
        sum = 0
        for i in range(0, len(p) - 1):
            sum = sum + wghtFxn(p[i], p[i + 1], [])
        return sum

    #Get all the shortest distances between vtxs
    len_path = dict(nx.all_pairs_dijkstra_path_length(G, weight=wghtFxn))

    #We check is all the paths in the system are geodesics wrt to weightStrings
    for i in range(1, N):

        for j in range(0, i):

            #shortest distance between ij wrt weights
            ijDist = len_path[i][j]
            #weight of ij path in the path system
            pthSysDist = pathWeight(system[i][j])

            #If the actual disance is smaller than that of ij path from the system return false
            if ijDist < pthSysDist:
                return False

    #In the strict case we need to also check each path is unique
    if strict:
        for i in range(1, N):
            #pred is a dictionary which contains all the predeccesors of all paths with source i
            pred, _ = nx.dijkstra_predecessor_and_distance(G,
                                                           i,
                                                           weight=wghtFxn)
            for j in range(0, i):
                #If j has two predeccesors on the shortest ij path then it is not unique

                if len(pred[j]) > 1:
                    return False

    return True
Beispiel #39
0
def get_main_stem_and_nodes(G, root_node):
    # Get main stem as shortest path to point furthest from root
    predecessors, distances_to_root = nx.dijkstra_predecessor_and_distance(
        G, root_node)
    i = max(distances_to_root.items(), key=operator.itemgetter(1))[0]
    main_stem = [i]
    current_node = i
    while current_node != root_node:
        current_node = predecessors[current_node][0]
        main_stem.append(current_node)
    main_stem = np.array(main_stem, dtype=int)

    # Get nodes, sorted from closest to furthest to the root
    n_neighbors = np.array([len(list(nx.neighbors(G, g))) for g in main_stem],
                           dtype=int)
    nodes = main_stem[n_neighbors > 2]
    nodes = nodes[::-1]
    return main_stem[::-1], nodes
def all_shortest_paths(G, source, target, weight=None):
    if weight is not None:
        pred,dist = nx.dijkstra_predecessor_and_distance(G,source,weight=weight)
    else:
        pred = nx.predecessor(G,source)
    if target not in pred:
        raise nx.NetworkXNoPath()
    stack = [[target,0]]
    top = 0
    while top >= 0:
        node,i = stack[top]
        if node == source:
            yield [p for p,n in reversed(stack[:top+1])]
        if len(pred[node]) > i:
            top += 1
            if top == len(stack):
                stack.append([pred[node][i],0])
            else:
                stack[top] = [pred[node][i],0]
        else:
            stack[top-1][1] += 1
            top -= 1
Beispiel #41
0
def all_shortest_paths(G, source, target, weight=None):
    """Compute all shortest paths in the graph.

    Parameters
    ----------
    G : NetworkX graph

    source : node
       Starting node for path.

    target : node
       Ending node for path.

    weight : None or string, optional (default = None)
       If None, every edge has weight/distance/cost 1.
       If a string, use this edge attribute as the edge weight.
       Any edge attribute not present defaults to 1.

    Returns
    -------
    paths: generator of lists
        A generator of all paths between source and target.

    Examples
    --------
    >>> G=nx.Graph()
    >>> G.add_path([0,1,2])
    >>> G.add_path([0,10,2])
    >>> print([p for p in nx.all_shortest_paths(G,source=0,target=2)])
    [[0, 1, 2], [0, 10, 2]]

    Notes
    -----
    There may be many shortest paths between the source and target.

    See Also
    --------
    shortest_path()
    single_source_shortest_path()
    all_pairs_shortest_path()
    """
    if weight is not None:
        pred,dist = nx.dijkstra_predecessor_and_distance(G,source,weight=weight)
    else:
        pred = nx.predecessor(G,source)
    if target not in pred:
        raise nx.NetworkXNoPath()
    stack = [[target,0]]
    top = 0
    while top >= 0:
        node,i = stack[top]
        if node == source:
          yield [p for p,n in reversed(stack[:top+1])]
        if len(pred[node]) > i:
            top += 1
            if top == len(stack):
                stack.append([pred[node][i],0])
            else:
                stack[top] = [pred[node][i],0]
        else:
            stack[top-1][1] += 1
            top -= 1
Beispiel #42
0
	def dijkstra_plan_networkX(self, beta=10):
		# requires a full construct of product automaton
		start = time.time()
		runs = {}
		loop = {}

		# minimal circles
		for prod_target in self.graph['accept']:
			cycle = {}
			loop_pre, loop_dist = nx.dijkstra_predecessor_and_distance(self, prod_target)
			#print "\nTEST",prod_target
			for target_pred in self.predecessors_iter(prod_target):
				if target_pred in loop_dist:
					#print target_pred, prod_target
					cycle[target_pred] = self.edge[target_pred][prod_target]["weight"] + loop_dist[target_pred]
			if cycle:
				opti_pred = min(cycle, key = cycle.get)
				suffix = compute_path_from_pre(loop_pre, opti_pred)
				#print opti_pred,prod_target,suffix
				loop[prod_target] = (cycle[opti_pred], suffix)

		# print "loops"
		# for p in loop.keys():
		# 	print p,"\t>>",loop[p]
		# shortest line
		for prod_init in self.graph['initial']:
			line = {}
			line_pre, line_dist = nx.dijkstra_predecessor_and_distance(self, prod_init)

			# print
			# print prod_init
			# print "line_dist"
			# for l,m in line_dist.items():
			# 	print l,m

			# print "line_pre"
			# for l,m in line_pre.items():
			# 	print l,m
			# print "loop"
			# for n in loop.iterkeys():
			# 	print n
			# print "\n<<<<<<<<<<<<"
			for target in loop.iterkeys():
				if target in line_dist.iterkeys():
					line[target] = line_dist[target]+beta*loop[target][0]
					# print prod_init,target,line[target]
			# print "<<<<<<<<<<<<\n"
			if line:
				opti_targ = min(line, key = line.get)
				prefix = compute_path_from_pre(line_pre, opti_targ)
				precost = line_dist[opti_targ]
				runs[(prod_init, opti_targ)] = (prefix, precost, loop[opti_targ][1], loop[opti_targ][0])
				# print prod_init,">>",opti_targ, ">>",loop[opti_targ][1]

		# print "Runs\n...................................."
		# for r,p in runs.items():
		# 	print
		# 	print r
		# 	print p
		# print "...................................."
		# best combination
		if runs:
			prefix, precost, suffix, sufcost = min(runs.values(), key = lambda p: p[1] + beta*p[3])
			#print '\n==================\n'
			return prefix, precost, suffix, sufcost
			#print '\n==================\n'
		print 'no accepting run found in optimal planning!'
Beispiel #43
0
 def test_dijkstra_predecessor1(self):
     G = nx.path_graph(4)
     assert_equal(nx.dijkstra_predecessor_and_distance(G, 0),
                  ({0: [], 1: [0], 2: [1], 3: [2]}, {0: 0, 1: 1, 2: 2, 3: 3}))