def test_two_component_graph(self): """Test empty graph""" G = nx.Graph() G.add_node(1) G.add_node(2) treewidth, _ = treewidth_min_degree(G) assert_equals(treewidth, 0)
def testOriginaltoCluster(n, c, k): G_test = nx.random_tree(n) setAllNodeAttributes(G_test) G_cluster = buildClusteredSet(G_test, c) #return cluster graph #start tree decomposition tree_decomp = approx.treewidth_min_degree(G_cluster) print("cluster dict:", clusterDict) print("rej node dict", rejectingNodeDict) clearVisitedNodesAndDictionaries(G_cluster) makeMatrix(G_cluster, G_cluster.number_of_nodes()) color_map = [] for nodeID in G_test.nodes(): if G_test.nodes[nodeID]['criticality'] >= c: color_map.append('red') else: color_map.append('green') fig2 = plt.figure(1) G_tree = tree_decomp[1] print( "List of nodes, where each node is a bag, and each bag contains a set of nodes in the bag:\n", list(G_tree.nodes()), "\nList of edges, where each edge is listed:\n", list(G_tree.edges())) nx.draw_networkx(G_tree, pos=nx.spring_layout(G_tree, iterations=200), arrows=False, with_labels=True) for i in G_tree.nodes(): print(list(i)) #nx.draw_networkx(G_cluster, node_color = color_map, pos=nx.spring_layout(G_test, iterations=1000), arrows=False, with_labels=True) return G_cluster
def show_props(graph): print("Nodes: {}, Edges: {}".format(len(graph.nodes), len(graph.edges))) treewidth, decomp = approximation.treewidth_min_degree(graph) print("TreeWidth: {}".format(treewidth)) cluster_ceof = approximation.clustering_coefficient.average_clustering( graph) print("Average Clustering Coefficient: {}".format(cluster_ceof)) print("Is Acyclic: {}".format(nx.is_forest(graph))) node, degree = max([(n, d) for n, d in graph.degree()], key=lambda x: x[1]) print("Max degree: {}".format(degree))
def main(): if len(sys.argv) != 4: print("Usage: dks_ptas.py [graph file] [k value] [epsilon value]") exit(1) G = nx.read_adjlist(sys.argv[1]) k = int(sys.argv[2]) epsilon = float(sys.argv[3]) print("k = " + str(k) + ", ε = " + str(epsilon)) print("Treewidth: " + str(approximation.treewidth_min_degree(G)[0])) print("Density: " + str(densest_k_subgraph_PTAS(G, k, epsilon)))
def get_tree_decomps(subgraphs): trees = [] for G in subgraphs: (w, T) = approximation.treewidth_min_degree(G) trees.append(T) bin_trees = [] for i in range(len(subgraphs)): G = subgraphs[i] T = trees[i] bin_trees.append(hierarchical_tree(G, T)) return bin_trees
def main(): # Testing using networkx's structure: test = Graphs() #initial_graph = nx.grid_2d_graph(10, 10) initial_graph = test.create_partial_ktrees(100, 5, 60) # Add weight 1 in each edge of the grid for i in initial_graph._adj: for j in initial_graph._adj[i]: initial_graph.add_edge(i, j, weight=1) initial_graph = nx.convert_node_labels_to_integers( initial_graph, first_label=0, ordering='default', label_attribute='old_labels') # treewidth_min_degree returns a tuple with treewidth and the corresponding decomposed tree. # Returns: (int, Graph) tuple p = approx.treewidth_min_degree(initial_graph) tree_decomp_graph = nx.convert_node_labels_to_integers( p[1], first_label=0, ordering='default', label_attribute='bags') # Print or not the Tree Decomposition flag = 0 if flag == 1: # print the adjacency list # for line in nx.generate_adjlist(p[1]): # print(line) # write edgelist to grid.edgelist nx.write_edgelist(tree_decomp_graph, path="grid.edgelist", delimiter=":") # read edgelist from grid.edgelist H = nx.read_edgelist(path="grid.edgelist", delimiter=":") nx.draw(H, with_labels=True) plt.show() del flag set_of_nodes = [i for i in range(0, len(tree_decomp_graph._node))] nodes, adj, initial_graph_nodes, initial_graph_adj = test.data_reform( tree_decomp_graph, set_of_nodes, initial_graph) num_of_nodes = len(initial_graph._node) portals_of_A, set_A, set_B, A, B, flag_separator = test.skew_kseparator_tree( num_of_nodes, p[0], nodes, adj, [], initial_graph_adj, tree_decomp_graph) print()
if line[0] == 'p': s = line.split() v = s[2] e = s[3] avg_deg = int(s[3]) / int(s[2]) data = ' '.join([str(file.name), str(v), str(e), str(avg_deg)]) output.write(data + '\n') break # get more detailed information on problem instances with open("detail.txt", 'w') as output: output.write("file_name min_deg max_deg treewidth approx_vc\n") with os.scandir(input_dir) as dir: for file in dir: g = nx.Graph() with open(file, encoding="latin-1") as f: for line in f: if line[0] == 'p': s = line.split() v = int(s[2]) g.add_nodes_from(range(1, v + 1)) elif line[0] != 'c': e = line.split() g.add_edge(int(e[0]), int(e[1])) min_deg = min(d for n, d in g.degree()) max_deg = max(d for n, d in g.degree()) tw = naa.treewidth_min_degree(g)[0] vc = len(naa.min_weighted_vertex_cover(g)) data = ' '.join([str(file.name), str(min_deg), str(max_deg), str(tw), str(vc)]) output.write(data + '\n')
from networkx.algorithms.approximation import treewidth_min_degree G = nx.Graph() f = open("(100,3).txt") f_data = f.readlines() ddaa=[] for line in f_data: line = line.rstrip("\n").split(" ") new_line =[] for n in line: new_line.append(int(n)) ddaa.append(tuple(new_line)) print("ddaa",ddaa) G.add_edges_from(ddaa) a,b = treewidth_min_degree(G) print(a) print(b.nodes) import pandas as pd frozenset_l = [list(i) for i in list(b.nodes)] print(frozenset_l) frozenset_pd = pd.DataFrame(frozenset_l) print(frozenset_pd) frozenset_pd.to_csv("columns.csv", index=None, header=None) frozenset_pd = pd.read_csv("columns.csv", header=None) data = pd.read_csv("H0.1MAF0.2-2locus_EDM-1_001.txt", sep='\t', header=None) for index, row in frozenset_pd.iterrows(): frozenset_l = list(row) frozenset_l.append(100) print(frozenset_l) output_data = data.loc[:, frozenset_l]
def test_petersen_graph(self): """Test Petersen graph tree decomposition result""" G = nx.petersen_graph() _, decomp = treewidth_min_degree(G) is_tree_decomp(G, decomp)
def test_empty_graph(self): """Test empty graph""" G = nx.Graph() _, _ = treewidth_min_degree(G)
cota = randint(20, 40) restantes = randint(0, 40 - cota) for i in range(cota): for j in range(cota): if adyacencia[i + restantes, j + restantes] != 0 and j != cota - 1: n.add_weighted_edges_from([(i, j, randint(20, 40))]) auxiliar = {} for i in range(30): auxiliar[i + 1] = [] tiempo_acumulado = 0 while True: tiempo_inicial = time() for n in (F, G, H, I, J): app.treewidth_min_degree(n) tiempo_final = time() tiempo_ejecucion = tiempo_final - tiempo_inicial tiempo_acumulado += tiempo_ejecucion auxiliar[i + 1].append(10000 * tiempo_ejecucion) if (tiempo_acumulado >= 5): break k = 1 for n in (F, G, H, I, J): dicrio['Tree_ Min Degree'][k] = {} dicrio['Tree_ Min Degree'][k]['nodos'] = len(n.nodes) dicrio['Tree_ Min Degree'][k]['aristas'] = len(n.edges) k += 1 medias_diccionario = []