Пример #1
0
def solve(G):
    """
    Args:
        G: networkx.Graph

    Returns:
        T: networkx.Graph
    """

    end_time = datetime.now() + timedelta(seconds=TIMEOUT)

    graphs_to_consider = []
    graphs_to_consider.append(minimum_spanning_tree(G))
    index = 0
    while datetime.now() < end_time and index < len(G.nodes):
        resulting_graph = create_graph_from_dominating_set(
            G, dominating_set(G, start_with=index))
        #print( average_pairwise_distance(resulting_graph))
        #resulting_graph = optimize_pairwise_distances(G, resulting_graph, average_pairwise_distance(resulting_graph))

        if not nx.is_empty(resulting_graph) and nx.is_connected(
                resulting_graph):
            graphs_to_consider.append(resulting_graph)
        index += 1
    return min(graphs_to_consider, key=average_pairwise_distance)
Пример #2
0
def gen_mst_len_dataset(size: int, min_num_node: int, max_num_node: int)-> TSPDataset:
    dataset = TSPDataset(size=size, min_num_node=min_num_node, max_num_node=max_num_node, transform=Distance(cat=False))
    datalist = []
    for graph in dataset:
        ng = to_networkx(graph, edge_attrs=["edge_attr"], to_undirected=True)
        ng_mst = mst.minimum_spanning_tree(ng, "edge_attr")
        mst_len = sum([edge_value["edge_attr"] for edge_value in ng_mst.edges.values()])
        graph.mst_len = torch.tensor([mst_len], dtype=torch.float)
        datalist.append(graph)

    dataset.__data_list__ = datalist
    dataset.data, dataset.slices = dataset.collate(datalist)

    return dataset
Пример #3
0
L = nx.Graph()
L.add_weighted_edges_from(mas)

#веса связного графа
fin = open('graphsv.txt', 'r')
mas = [[0] * 3 for i in range(82)]
for i in range(82):
    s = fin.readline()
    k = s.split()
    for j in range(2):
        mas[i][j] = k[j]
    mas[i][2] = int(k[2])
G = nx.Graph()
G.add_weighted_edges_from(mas)
#b
print("rad(G) = ", nx.radius(G), ", diam(G) = ", nx.diameter(G),
      ", girth(G) = ", len(min(nx.cycle_basis(G))), ", center(G) = ",
      nx.center(G), ", k_node_connectivity = ", nx.node_connectivity(G),
      ", k_edge_connectivity = ", nx.edge_connectivity(G))
print()

#maxmatching g
print("M =", nx.max_weight_matching(L))
print()

#mst о
MST = nx.Graph(mst.minimum_spanning_tree(G))
print("MST = ", MST.edges)
print("MST =", sum(c for (a, b, c) in (MST.edges.data('weight'))))
print()
import random
from networkx.classes.graph import Graph

G = nx.Graph()
G = nx.random_graphs.gnp_random_graph(100, 0.50)
for (u, v, w) in G.edges(data=True):
    w['weight'] = random.randint(1, 100)

# positions for all nodes

edge_labels = dict([((
    u,
    v,
), d['weight']) for u, v, d in G.edges(data=True)])

a = minimum_spanning_tree(G, algorithm='prim')

pos = nx.spring_layout(G, k=100, scale=33)

nx.draw_networkx_nodes(a, pos, node_size=125, node_color='red')

labels = nx.get_edge_attributes(a, 'weight')

nx.draw_networkx_edge_labels(a,
                             pos,
                             edge_labels=labels,
                             label_pos=0.5,
                             font_size=8,
                             font_color='blue')

nx.draw_networkx_edges(a, pos, width=1)
Пример #5
0
                      if len(g3[u]) == 1])  #убираем висячие ребра
print("The shortest closed path that visits every vertex")
print(tournament.hamiltonian_path(
    g3))  #ищем гамильтонов путь и добавляем в него высячие ребра

#k
print("The shortest closed path that visits every edge")
print(list(euler.eulerian_circuit(
    g3)))  #ищем эйлеров путь и добавляем в него ребра-мосты к висячим вершинам

#m
print("2-edge-connected components")
print(list(edge_kcomponents.bridge_components(g)))

#o
mstree = nx.Graph(mst.minimum_spanning_tree(g2))
print("MST")
print(mstree.edges)
print("Weight of MST")
print(sum(c for (a, b, c) in (mstree.edges.data('weight'))))
nx.draw_planar(mstree, with_labels=True)
plt.savefig("mst.png")
plt.clf()

#q
print("Renamed vertices for Prufer code")
names = {}
for k, v in enumerate(mstree):
    names[v] = k
print(names)
mstree = nx.relabel_nodes(mstree, names)