예제 #1
0
def main():
    """ Reads in a value of k and a graph and prints an approximate k-centers solution """

    k = int(sys.argv[1])
    graph_file_path = sys.argv[2]

    input_graph = nx.read_weighted_edgelist(graph_file_path)

    # sort the edges of G by nondecreasing weight
    all_edges = list(input_graph.edges.items())
    all_edges.sort(key=lambda pair: pair[1]['weight'])

    # Construct the squares of the edge-induced subgraphs for each edge subset [1..i]
    power_graphs = []
    for i in range(0, len(all_edges)):
        edges_to_remove = list(map(lambda pair: pair[0], all_edges[i + 1:]))
        induced_graph = nx.restricted_view(input_graph, [], edges_to_remove)
        power_graphs.append(nx.power(induced_graph, 2))

    # Compute a maximal independent set for each power graph
    # If its size is less than k, return it as our approximate solution
    for pow_graph in power_graphs:
        indep_set = nx.maximal_independent_set(pow_graph)
        if len(indep_set) <= k:
            print("k centers are:", indep_set)
            break
예제 #2
0
 def average_degree_of_power(self, k):
     power_graph = networkx.power(self.graph, k)
     vertex_degree_tuples = list(power_graph.degree)
     if len(vertex_degree_tuples) == 0:
         return 0
     return sum([
         vertex_degree_tuple[1]
         for vertex_degree_tuple in vertex_degree_tuples
     ]) / len(vertex_degree_tuples)
def power_graph(G, vertices, power):
    # for i in range(len(vertices)):
    # 	for j in range(len(vertices)):
    # 		if i != j:
    # 			e = find_edge(G,i,j)
    # 			#ean den uparxei connection
    # 			if e is None:
    # 				dist = shortest_distance(G, i,j)
    # 				if dist == power:
    # 					G.add_edge(i,j)
    return nx.power(G, power)
    return G
예제 #4
0
def sparse_mx_to_khopsgraph(sp_mx):

    graph = nx.from_scipy_sparse_matrix(sp_mx)
    twohops_graph = nx.power(graph, 2)
    threehops_graph = nx.power(graph, 3)
    fourhops_graph = nx.power(graph, 4)
    assert (len(graph) == len(twohops_graph))
    print('graph has nodes: ', len(graph))
    print('one hop graph has edges: ', len(graph.edges()))
    print('two hop graph has edges: ', len(twohops_graph.edges()))
    assert (len(graph) == len(threehops_graph))
    print('three hop graph has edges:', len(threehops_graph.edges()))
    print('four hop graph has edges:', len(fourhops_graph.edges()))
    nodes_num = len(graph.nodes())
    onehops_dict= {}
    twohops_dict = {}
    threehops_dict = {}
    fourhops_dict = {}
    degree_dict_prob = graph.degree()
    degree_list_prob = []
    all_degrees = sum(degree_dict_prob.values())
    for (k,v) in degree_dict_prob.items():
        val = v / all_degrees
        degree_dict_prob[k] = val
        degree_list_prob.append(val)

    for i in range(len(graph)):
        onehops_dict[i] = graph.neighbors(i)

    for i in range(len(twohops_graph)):
        twohops_dict[i] = twohops_graph.neighbors(i)

    for i in range(len(threehops_graph)):
        threehops_dict[i] = threehops_graph.neighbors(i)
    #with open("{}/ind.{}.{}.{}".format(data_folder, dataset_str, str(cmd_args.n_hops), 'khops_graph'), 'wb') as f:
        #pkl.dump(khops_dict, f)
    for i in range(len(fourhops_graph)):
        fourhops_dict[i] = fourhops_graph.neighbors(i)

    return onehops_dict, twohops_dict, threehops_dict, fourhops_dict, degree_list_prob
예제 #5
0
def test_graph_power():
    # wikipedia example for graph power
    G = nx.cycle_graph(7)
    G.add_edge(6, 7)
    G.add_edge(7, 8)
    G.add_edge(8, 9)
    G.add_edge(9, 2)
    H = nx.power(G, 2)

    assert_edges_equal(list(H.edges()),
                       [(0, 1), (0, 2), (0, 5), (0, 6), (0, 7), (1, 9), (1, 2),
                        (1, 3), (1, 6), (2, 3), (2, 4), (2, 8), (2, 9), (3, 4),
                        (3, 5), (3, 9), (4, 5), (4, 6), (5, 6), (5, 7), (6, 7),
                        (6, 8), (7, 8), (7, 9), (8, 9)])
예제 #6
0
def test_graph_power():
    # wikipedia example for graph power
    G = nx.cycle_graph(7)
    G.add_edge(6, 7)
    G.add_edge(7, 8)
    G.add_edge(8, 9)
    G.add_edge(9, 2)
    H = nx.power(G, 2)
    assert_equal(list(H.edges()), [(0, 1), (0, 2), (0, 5), (0, 6), (0, 7), (1, 9),
                             (1, 2), (1, 3), (1, 6), (2, 3), (2, 4), (2, 8),
                             (2, 9), (3, 4), (3, 5), (3, 9), (4, 5), (4, 6),
                             (5, 6), (5, 7), (6, 7), (6, 8), (7, 8), (7, 9),
                             (8, 9)])
    assert_raises(ValueError, nx.power, G, -1)
예제 #7
0
def test_graph_power_negative():
    nx.power(nx.Graph(), -1)
예제 #8
0
def test_graph_power_raises():
    nx.power(nx.MultiDiGraph(), 2)
예제 #9
0
def test_graph_power_raises():
    nx.power(nx.MultiDiGraph(), 2)
예제 #10
0
def test_graph_power_negative():
    with pytest.raises(ValueError):
        nx.power(nx.Graph(), -1)
예제 #11
0
def test_graph_power_raises():
    with pytest.raises(nx.NetworkXNotImplemented):
        nx.power(nx.MultiDiGraph(), 2)
예제 #12
0
 def powerGraph(self, p):
     self.main_graph = nx.power(self.main_graph, p)
예제 #13
0
def test_graph_power_negative():
    nx.power(nx.Graph(), -1)
예제 #14
0
def wl2_encode(
  g,
  dim_node_features=None, dim_edge_features=None,
  num_node_labels=None, num_edge_labels=None,
  neighborhood=1, with_indices=False, compact=False):
  """
    Takes a graph with node and edge features and converts it
    into a edge + row/col ref list for sparse WL2 implementations.
  """
  g_p = nx.power(g, neighborhood) if neighborhood > 1 else g

  if dim_node_features is None:
    dim_node_features = 0

  if dim_edge_features is None:
    dim_edge_features = 0

  if num_node_labels is None:
    dim_edge_features = 0

  if num_edge_labels is None:
    num_edge_labels = 0

  dim_node_wl2 = dim_node_features + num_node_labels
  dim_edge_wl2 = dim_edge_features + num_edge_labels
  n_zero_f = np.zeros(dim_node_features)
  n_zero_l = np.zeros(num_node_labels)
  e_zero_f = np.zeros(dim_edge_features)
  e_zero_l = np.zeros(num_edge_labels)
  I_n = np.eye(num_node_labels)
  I_e = np.eye(num_edge_labels)

  for node, data in g.nodes(data=True):
    g_p.add_edge(node, node)
    g.add_edge(
      node, node,
      features=data.get("features", n_zero_f),
      label=data.get("label"))

  x = []
  ref_a = []
  ref_b = []
  backref = []
  max_ref_dim = 0
  e_ids = {}

  for i, edge in enumerate(g_p.edges):
    e_ids[edge] = i

  for i, edge in enumerate(g_p.edges):
    a, b = edge
    in_g = g.has_edge(a, b)
    if not in_g:
      f = e_zero_f
      lab = e_zero_l
    elif (
      (a != b and dim_edge_wl2 == 0)
      or (a == b and dim_node_wl2 == 0)):
      f = []
      lab = []
    else:
      d = g.get_edge_data(a, b)
      f = d.get("features", e_zero_f)
      if a == b and num_node_labels > 0:
        lab = I_n[d["label"] - 1]
      elif a != b and num_edge_labels > 0:
        lab = I_e[d["label"] - 1]
      else:
        lab = []

    nbs = (
      ([a] if a == b else [a, b])
      + list(nx.common_neighbors(g_p, a, b)))
    n_a = [eid_lookup(e_ids, a, k) for k in nbs]
    n_b = [eid_lookup(e_ids, b, k) for k in nbs]
    nbs_count = len(nbs)

    x.append(np.concatenate(
      ([1, 0, 0], lab, f, e_zero_l, e_zero_f) if a == b else
      ([0], [1, 0] if in_g else [0, 1], n_zero_l, n_zero_f, lab, f)))

    if compact:
      ref_a += n_a
      ref_b += n_b
      backref += [e_ids[edge]] * nbs_count
    else:
      if nbs_count > max_ref_dim:
        max_ref_dim = nbs_count

      ref_a.append(np.array(n_a))
      ref_b.append(np.array(n_b))

  n = g.order()
  res = (
    np.array(x),
    np.array(ref_a), np.array(ref_b),
    np.array(backref if compact else max_ref_dim),
    n)

  if with_indices:
    res += (list(g_p.edges),)

  return res