Example #1
0
def centrality_opsahl(dg):
    """
    TODO: reverse edges
    """
    print "computing all pairs shortest path"
    ds = all_pairs_shortest_path_length(dg)
    print "done computing all pairs shortest path"
    rank = {}
    progress = 0
    for x in dg.nodes():
        r = 0.
        if x not in ds:
            continue
        for v in ds[x]:
            if ds[x][v] == 0:
                continue
            r += 1. / ds[x][v]
        progress += 1
#        for v in dg.nodes():
#            if x == v:
#                continue
#            if x not in ds:
#                continue
#            if v not in ds[x]:
#                continue
#            r += 1. / ds[x][v]
        rank[x] = r
        if progress % 1000 == 0:
            print "progress...", progress
    return rank
Example #2
0
    def integration(self):
        print('calculate integration at {}'.format(datetime.now()))
        # Calculate shortest path between all nodes in the graph
        path = dict(all_pairs_shortest_path_length(self.graph_pr))
        print("finish to calculate shortest path between all pairs at {}".format(datetime.now()))
        # store the integration index results for each edge
        main_dict = {}
        len_edge = len(self.graph_pr.edges)
        # for each edge, the algorithm goes over all the nodes in graph and store the min shortest path between the node
        # and its two nodes than add it to to int_index.
        # at the end of each loop int_index divide by the number of lines (normalization)
        # is literally the integration for the edge
        for i, edge in enumerate(self.graph_pr.edges):
            print("Progress {:2.1%}".format(i / len_edge))
            int_index = 0
            len_nodes = len(self.graph_pr.nodes)
            for j, node in enumerate(self.graph_pr.nodes):
                print("     Progress {:2.1%}".format(j / len_nodes))
                weight_1 = path[edge[0]][node]
                weight_2 = path[edge[1]][node]
                miny = min(weight_1, weight_2)
                int_index += miny
            main_dict[edge] = int_index / len_edge

        # add the results as a new properties to the edge's graph
        nx.set_edge_attributes(self.graph_pr, main_dict, 'integ')
Example #3
0
 def __call__(self, data):
     """ Compute a coloring such that no node sees twice the same color in its k-hop neighbourhood."""
     k = self.k
     g = torch_geometric.utils.to_networkx(data, to_undirected=True, remove_self_loops=True)
     lengths = all_pairs_shortest_path_length(g, cutoff=2 * k)
     lengths = [l for l in lengths]
     # Graph where 2k hop neighbors are connected
     k_hop_graph = nx.Graph()
     for lengths_tuple in lengths:
         origin = lengths_tuple[0]
         edges = [(origin, dest) for dest in lengths_tuple[1].keys()]
         k_hop_graph.add_edges_from(edges)
     # Color the k-hop graph
     best_n_colors = np.infty
     best_color_dict = None
     # for strategy in ['largest_first', 'random_sequential', 'saturation_largest_first']:
     for strategy in ['largest_first']:
         color_dict = greedy_color(k_hop_graph, strategy)
         n_colors = np.max([color for color in color_dict.values()]) + 1
         if n_colors < best_n_colors:
             best_n_colors = n_colors
             best_color_dict = color_dict
     # Convert back to torch-geometric. The coloring is contained in data.x
     data.coloring = torch.zeros((data.num_nodes, 1), dtype=torch.long)
     for key, val in best_color_dict.items():
         data.coloring[key] = val
     print('Number of nodes: {} - Number of colors: {}'.format(data.num_nodes, data.coloring.max() + 1))
     return data
def get_values(G, G_prime):
    N = len(G.nodes())
    print('Finding sortest paths...')
    sys.stdout.flush()
    SPG = dict(all_pairs_shortest_path_length(G))
    SPG_prime = dict(all_pairs_shortest_path_length(G_prime))
    print('Found sortest paths.')
    sys.stdout.flush()

    print('Generating LP...')
    sys.stdout.flush()
    diameter = 0
    for i in range(0, N):
        for j in range(i + 1, N):
            if SPG[i][j] > diameter:
                diameter = SPG[i][j]
    (AGGP, bGGP) = lp_without_maxs_or_goal(N, SPG, SPG_prime, 1, size - 1)
    print("Length is %s" % (len(bGGP)))
    sys.stdout.flush()
    # (AGGP, bGGP) = alternate_lp_without_maxs_or_goal(N, SPG, SPG_prime)

    print('Generated LP.')
    sys.stdout.flush()
    c = goal_vector(N)
    print('Solving LP...')
    sys.stdout.flush()
    G_with_G_prime = linprog(c,
                             A_ub=AGGP,
                             b_ub=bGGP,
                             method="interior-point",
                             options={
                                 "disp": False,
                                 "maxiter": N * N * N * N * 100
                             })
    print('Solved LP...')
    sys.stdout.flush()
    return G_with_G_prime.x
def fraction_of_connected_node_pairs(G):
    # computes how many pairs of nodes have a path between each other
    if len(G) < 2:
        return None

    pairs_path_lens = all_pairs_shortest_path_length(G)

    n_connected_pairs = 0
    for i, i_p in pairs_path_lens:
        for j, l in i_p.items():
            if l > 0:
                n_connected_pairs += 1

    f_connected_pairs = n_connected_pairs / (len(G) * (len(G) - 1.0))
    return f_connected_pairs
Example #6
0
def centrality_opsahl(dg):
    """
    TODO: reverse edges
    """
    ds = all_pairs_shortest_path_length(dg)
    rank = {}
    for x in dg.nodes():
        r = 0.
        for v in dg.nodes():
            if x == v:
                continue
            if x not in ds:
                continue
            if v not in ds[x]:
                continue
            r += 1. / ds[x][v]
        rank[x] = r
    return rank
    def _calculate(self, include: set):
        # Translating each label to a relevant index to save memory

        labels_map = super(UndirectedNthNeighborNodeHistogramCalculator,
                           self)._calculate(include)

        dists = unweighted.all_pairs_shortest_path_length(
            self._gnx, cutoff=max(self._neighbor_order))
        for i, (node, node_dists) in enumerate(dists):
            for neighbor, neigh_dist in node_dists.items():
                if (node == neighbor) or \
                        (neigh_dist not in self._neighbor_order) or \
                        (neighbor not in include) or \
                        ("label" not in self._gnx.node[neighbor]):
                    continue
                neighbor_color = self._gnx.node[neighbor]["label"]
                if neighbor_color in labels_map:
                    neighbor_color = labels_map[neighbor_color]
                self._features[node][neigh_dist][neighbor_color] += 1
 def ls_rev(self):
     if self.ls_rev_ is None:
         self.ls_rev_ = dict(
             all_pairs_shortest_path_length(self.g.reverse()))
     return self.ls_rev_
 def ls(self):
     if self.ls_ is None:
         self.ls_ = dict(all_pairs_shortest_path_length(self.g))
     return self.ls_