def test_already_branching(self): """Tests that a directed acyclic graph that is already a branching produces an isomorphic branching as output. """ T1 = nx.balanced_tree(2, 2, create_using=nx.DiGraph()) T2 = nx.balanced_tree(2, 2, create_using=nx.DiGraph()) G = nx.disjoint_union(T1, T2) B = nx.dag_to_branching(G) assert_true(nx.is_isomorphic(G, B))
def setUp(self): G=nx.Graph(); G.add_edge(0,1,weight=3) G.add_edge(0,2,weight=2) G.add_edge(0,3,weight=6) G.add_edge(0,4,weight=4) G.add_edge(1,3,weight=5) G.add_edge(1,5,weight=5) G.add_edge(2,4,weight=1) G.add_edge(3,4,weight=2) G.add_edge(3,5,weight=1) G.add_edge(4,5,weight=4) self.G=G self.exact_weighted={0: 4.0, 1: 0.0, 2: 8.0, 3: 6.0, 4: 8.0, 5: 0.0} self.K = nx.krackhardt_kite_graph() self.P3 = nx.path_graph(3) self.P4 = nx.path_graph(4) self.K5 = nx.complete_graph(5) self.C4=nx.cycle_graph(4) self.T=nx.balanced_tree(r=2, h=2) self.Gb = nx.Graph() self.Gb.add_edges_from([(0,1), (0,2), (1,3), (2,3), (2,4), (4,5), (3,5)]) F = nx.florentine_families_graph() self.F = F
def gen_data(): """ generates test metrics and network, where the network is a balanced graph of height 2 and branch factor 2 """ network = nx.balanced_tree(2, 2) metrics = DataFrame(network.node).T metrics['Demand'] = [np.nan, 100, 50, 25, 12, 6, 3] metrics['Population'] = [np.nan, 100, 50, 25, 12, 6, 3] #level 0 metrics['coords'] = [np.array([125,10]) for x in metrics.index] #level 2 metrics['coords'].ix[1] = metrics['coords'].ix[0] + [-.5, -.25] metrics['coords'].ix[2] = metrics['coords'].ix[0] + [+.5, -.25] #level 3 metrics['coords'].ix[3] = metrics['coords'].ix[1] + [-.25, -.25] metrics['coords'].ix[4] = metrics['coords'].ix[1] + [+.25, -.25] metrics['coords'].ix[5] = metrics['coords'].ix[2] + [-.25, -.25] metrics['coords'].ix[6] = metrics['coords'].ix[2] + [+.25, -.25] metrics['coords'] = metrics['coords'].apply(tuple) nx.set_node_attributes(network, 'coords', metrics.coords.to_dict()) #nx.draw(network, nx.get_node_attributes(network, 'coords')) return metrics, network.to_directed()
def test_get_geoff_digraph(self): truth = [{'body': {}, 'id': 0, 'method': 'POST', 'to': '/node'}, {'body': {}, 'id': 1, 'method': 'POST', 'to': '/node'}, {'body': {'debug': 'test'}, 'id': 2, 'method': 'POST', 'to': '/node'}, {'body': "ITEM", 'method': 'POST', 'to': '{0}/labels'}, {'body': "ITEM", 'method': 'POST', 'to': '{1}/labels'}, {'body': "ITEM", 'method': 'POST', 'to': '{2}/labels'}, {'body': {'data': {'debug': False}, 'to': '{1}', 'type': 'LINK_TO'}, 'method': 'POST', 'to': '{0}/relationships'}, {'body': {'data': {}, 'to': '{2}', 'type': 'LINK_TO'}, 'method': 'POST', 'to': '{0}/relationships'}] graph = nx.balanced_tree(2, 1, create_using=nx.DiGraph()) graph.node[2]['debug'] = 'test' graph[0][1]['debug'] = False result = generate_data(graph, "LINK_TO", "ITEM", json.JSONEncoder()) self.assertEqual(json.loads(result), truth) httpretty.register_uri(httpretty.GET, "http://localhost:7474/db/data/", body=BATCH_URL) httpretty.register_uri(httpretty.POST, "http://localhost:7474/db/data/batch", body='["Dummy"]') result = write_to_neo("http://localhost:7474/db/data/", graph, "LINKS_TO", "ITEM") self.assertEqual(result, ["Dummy"])
def gen_data(): """ generates test metrics and network, where the network is a balanced graph of height 2 and branch factor 2 """ network = nx.balanced_tree(2, 2) metrics = DataFrame() metrics['Demand'] = [100, 50, 25, 12, 6, 3] metrics['Population'] = [100, 50, 25, 12, 6, 3] #level 0 base_coord = np.array([125, 10]) coord_dict = {0: np.array([125, 10])} coord_dict[1] = coord_dict[0] + [-.5, -.25] coord_dict[2] = coord_dict[0] + [+.5, -.25] coord_dict[3] = coord_dict[1] + [-.25, -.25] coord_dict[4] = coord_dict[1] + [+.25, -.25] coord_dict[5] = coord_dict[2] + [-.25, -.25] coord_dict[6] = coord_dict[2] + [+.25, -.25] # assign x, y metrics['X'] = [coord_dict[i][0] for i in range(1, 7)] metrics['Y'] = [coord_dict[i][1] for i in range(1, 7)] nx.set_node_attributes(network, 'coords', coord_dict) #nx.draw(network, nx.get_node_attributes(network, 'coords')) return metrics, network.to_directed()
def create_tree(r, h): G = nx.balanced_tree(r, h) return G #nx.draw_networkx(G, pos = nx.spring_layout(G)) #nx.draw_spring(G) for i in range(7): G.node[i]['color'] = 'white' ####### Visualization with graphviz ######## #write_dot(G,'test.dot') # same layout using matplotlib with no labels #plt.title("draw_networkx") pos=graphviz_layout(G,prog='dot') nx.draw(G,pos,with_labels=True,arrows=False, node_color = 'lightgray') plt.show() return G
def test_tree(self): for sz in range(1,5): G = nx.balanced_tree(2,sz,nx.DiGraph()).reverse() G = nx.relabel_nodes(G,dict(zip(G.nodes(),reversed(G.nodes()))),True) G.name = 'Complete binary tree of height {}'.format(sz) F = PebblingFormula(G) self.checkFormula(sys.stdin,F, ["cnfgen","-q","peb", "--tree", sz])
def balanced_tree_N(r,N): h = math.ceil( np.log(r*N-N+1)/np.log(r) -1 ) Nbis = int((r**(h+1)-1)/(r-1)) G = nx.balanced_tree(r,h) for n in range(N,Nbis): G.remove_node(n) return G
def test_balanced_tree(self): """Edge betweenness centrality: balanced tree""" G = nx.balanced_tree(r=2, h=2) b = nx.edge_betweenness_centrality(G, weight="weight", normalized=False) b_answer = {(0, 1): 12, (0, 2): 12, (1, 3): 6, (1, 4): 6, (2, 5): 6, (2, 6): 6} for n in sorted(G.edges()): assert_almost_equal(b[n], b_answer[n])
def generate_topology(self, topo_type, node_count, branches = None): if topo_type == TopologyType.LADDER: total_nodes = node_count/2 graph = networkx.ladder_graph(total_nodes) elif topo_type == TopologyType.LINEAR: graph = networkx.path_graph(node_count) elif topo_type == TopologyType.MESH: graph = networkx.complete_graph(node_count) elif topo_type == TopologyType.TREE: h = math.log(node_count + 1)/math.log(2) - 1 graph = networkx.balanced_tree(2, h) elif topo_type == TopologyType.STAR: graph = networkx.Graph() graph.add_node(0) nodesinbranch = (node_count - 1)/ BRANCHES c = 1 for i in xrange(BRANCHES): prev = 0 for n in xrange(1, nodesinbranch + 1): graph.add_node(c) graph.add_edge(prev, c) prev = c c += 1 return graph
def create_tree(r, h=None, num_nodes=None): #need to have either height or num_nodes assert xor(bool(h),bool(num_nodes)) to_remove=0 if num_nodes != None: if r==1: h=num_nodes else: h=ceil(log(num_nodes*(r-1)+1, r)-1) init_size=(r**(h+1)-1)/(r-1) to_remove=int(init_size-num_nodes) #branching factor of 1 does not seem to work for nx.balanced_tree result_graph = semGODiGraph(None, Aspects.BP) if r ==1: for u in range(0,h): v=u+1 result_graph.add_edge(GN(nodetype=GN.TERM_TYPE,dbid=v),GN(nodetype=GN.TERM_TYPE,dbid=u)) else: internal_graph=nx.balanced_tree(r=r,h=h,create_using=nx.DiGraph()) #gnp_random_graph(10,0.5,directed=True) current=internal_graph.number_of_nodes() remove_nodes=range(current-to_remove,current) for r in remove_nodes: internal_graph.remove_node(r) if num_nodes != None: assert num_nodes == internal_graph.number_of_nodes() for u,v in internal_graph.edges_iter(): result_graph.add_edge(GN(nodetype=GN.TERM_TYPE,dbid=u),GN(nodetype=GN.TERM_TYPE,dbid=v)) nx.reverse(result_graph, copy=False) #make the edges point up not down root_list=[n for n,d in result_graph.out_degree().items() if d==0] result_graph.root=root_list[0] result_graph.semMakeGraph() return result_graph
def _getGraph(self, values): r = values['Branching'] h = values['Height'] G = nx.balanced_tree(r ,h, create_using=nx.DiGraph()) nodes = layout.circularTree(h, r, 25) return G, nodes
def test_already_arborescence(self): """Tests that a directed acyclic graph that is already an arborescence produces an isomorphic arborescence as output. """ A = nx.balanced_tree(2, 2, create_using=nx.DiGraph()) B = nx.dag_to_branching(A) assert_true(nx.is_isomorphic(A, B))
def main(): simconfig.branching_factor = 4 simconfig.depth_factor = 4 stats = analysis.BalancedTreeAutomorphismStatistics(simconfig) g2 = nx.balanced_tree(simconfig.branching_factor, simconfig.depth_factor) r2 = stats.calculate_graph_symmetries(g2) log.info("results: %s", r2)
def generate_graph(self): #nodes n = int(self.lineEdit_2.text()) self.graph = nx.balanced_tree(2, n) self.graph = nx.bfs_tree(self.graph, 0) #self.pos = nx.circular_layout(self.graph) self.pos = nx.graphviz_layout(self.graph, prog='dot') self.draw_graph()
def test_get_geoff_digraph(self): today = datetime.date(2012, 1, 1) graph = nx.balanced_tree(2, 1, create_using=nx.DiGraph()) graph.node[2]["debug"] = 'test"' graph[0][1]["debug"] = today self.assertRaises(TypeError, get_geoff, (graph, "LINK_TO"))
def comparison(): r""" CommandLine: python -m utool.experimental.dynamic_connectivity comparison --profile python -m utool.experimental.dynamic_connectivity comparison """ n = 12 a, b = 9, 20 num = 3 import utool for timer in utool.Timerit(num, 'old bst version (PY)'): g = nx.balanced_tree(2, n) self = TestETT.from_tree(g, version='bst', fast=False) with timer: self.delete_edge_bst_version(a, b, bstjoin=False) import utool for timer in utool.Timerit(num, 'new bst version (PY) (with join)'): g = nx.balanced_tree(2, n) self = TestETT.from_tree(g, version='bst', fast=False) with timer: self.delete_edge_bst_version(a, b, bstjoin=True) import utool for timer in utool.Timerit(num, 'old bst version (C)'): g = nx.balanced_tree(2, n) self = TestETT.from_tree(g, version='bst', fast=True) with timer: self.delete_edge_bst_version(a, b, bstjoin=False) import utool for timer in utool.Timerit(num, 'new bst version (C) (with join)'): g = nx.balanced_tree(2, n) self = TestETT.from_tree(g, version='bst', fast=True) with timer: self.delete_edge_bst_version(a, b, bstjoin=True) import utool for timer in utool.Timerit(num, 'list version'): g = nx.balanced_tree(2, n) self = TestETT.from_tree(g, version='list') with timer: self.delete_edge_list_version(a, b) pass
def test_graph2geoff_digraph_fail(): today = datetime.date(2012, 1, 1) graph = nx.balanced_tree(2, 1, create_using=nx.DiGraph()) graph.node[2]['debug'] = 'test"' graph[0][1]['debug'] = today with pytest.raises(TypeError) as excinfo: graph2geoff(graph, 'LINK_TO')
def __init__(self, **kwargs): # super super(BalancedTree, self).__init__() r = kwargs.get('r', 2) h = kwargs.get('h', 2) # mn_nx's topology view of the network self.ref_g = nx.balanced_tree(r,h) # nx topology definition self.build_nx_topo(self.ref_g)
def create_graph(self): integer_graph = nx.balanced_tree(2, 2, nx.DiGraph()) package_mapping = { i: 'm.' + ('X' if i % 2 == 0 else 'Y') + '.' + letter for (i, letter) in enumerate(string.ascii_lowercase) } # Edges: [(X.a, Y.b), (X.a, X.c), (Y.b, Y.d), (Y.b, X.e), (X.c, Y.f), (X.c, X.g)] return nx.relabel_nodes(integer_graph, package_mapping)
def generate_product_graph(): """Generates k cuts for cartesian product of a path and a double tree""" k = int(input("k for product of tree & path:")) trials = int(input("number of trials:")) prodfname = input("output file:") prodfname = "hard_instances/" + prodfname prodfile = open(prodfname, "wb", 0) h = int(input("height of the tree: ")) H1 = nx.balanced_tree(2, h) H2 = nx.balanced_tree(2, h) H = nx.disjoint_union(H1, H2) n = H.number_of_nodes() p = math.pow(2, h + 1) - 1 H.add_edge(0, p) n = 4 * math.sqrt(n) n = math.floor(n) print("Length of path graph: " + str(n)) G = nx.path_graph(n) tmpL = nx.normalized_laplacian_matrix(G).toarray() T = nx.cartesian_product(G, H) A = nx.adjacency_matrix(T).toarray() L = nx.normalized_laplacian_matrix(T).toarray() (tmpw, tmpv) = la.eigh(L) tmp = 2 * math.sqrt(tmpw[1]) print("cheeger upperbound:" + str(tmp)) (w, v) = spectral_projection(L, k) lambda_k = w[k - 1] tmp_str = "Cartesian product of balanced tree of height " + str(h) tmp_str += " and path of length " + str(n - 1) + "\n" tmp_str += "k = " + str(k) + ", " tmp_str += "trials = " + str(trials) + "\n\n\n" tmp_str = tmp_str.encode("utf-8") prodfile.write(tmp_str) k_cuts_list = lrtv(A, v, k, lambda_k, trials, prodfile) plotname = prodfname + "plot" plot(k_cuts_list, plotname) for i in range(len(k_cuts_list)): k_cuts = k_cuts_list[i] tmp_str = list(map(str, k_cuts)) tmp_str = " ".join(tmp_str) tmp_str += "\n\n" tmp_str = tmp_str.encode("utf-8") prodfile.write(tmp_str)
def _generate_initial_graph(self): # Generated a simple ordered tree height = floor(log(self._num_nodes) / log(2)) graph = balanced_tree(2, height, DiGraph()) for node in graph.nodes(): if int(node) >= self._num_nodes: graph.remove_node(node) # We rename the nodes according to the target bayesian # network we are trying to learn return self._rename_nodes(graph)
def test_graph2geoff_digraph(): result = """(0) (1) (2 {"debug": "test\\""}) (0)-[:LINK_TO {"debug": false}]->(1) (0)-[:LINK_TO]->(2)""" graph = nx.balanced_tree(2, 1, create_using=nx.DiGraph()) graph.node[2]['debug'] = 'test"' graph[0][1]['debug'] = False assert graph2geoff(graph, 'LINK_TO') == result
def test_get_geoff_digraph(self): result = """(0) (1) (2 {"debug": "test\\""}) (0)-[:LINK_TO {"debug": false}]->(1) (0)-[:LINK_TO]->(2)""" graph = nx.balanced_tree(2, 1, create_using=nx.DiGraph()) graph.node[2]["debug"] = 'test"' graph[0][1]["debug"] = False self.assertEqual(get_geoff(graph, "LINK_TO"), result)
def test_balanceds(): r = [2, 3, 4] h = [5, 6] for i in r: for j in h: G = nx.balanced_tree(i, j) G.graph['name'] = 'Balanced Tree {},{}'.format(i, j) total_time, sizes = test_graph(G) with open('trees.csv', 'a') as f: f.write('{},{},{},{},{}'.format(i, j, len(G.nodes()), len(G.edges()), total_time)) for size in sizes: f.write(',{}'.format(size)) f.write('\n')
def test_get_geoff_digraph_custom(self): today = datetime.date(2012, 1, 1) result = """(0) (1) (2 {"debug": "test\\""}) (0)-[:LINK_TO {"debug": "2012-01-01"}]->(1) (0)-[:LINK_TO]->(2)""" graph = nx.balanced_tree(2, 1, create_using=nx.DiGraph()) graph.node[2]["debug"] = 'test"' graph[0][1]["debug"] = today data = get_geoff(graph, "LINK_TO", DateEncoder()) self.assertEqual(data, result)
def test_graph2geoff_digraph_custom(): today = datetime.date(2012, 1, 1) result = """(0) (1) (2 {"debug": "test\\""}) (0)-[:LINK_TO {"debug": "2012-01-01"}]->(1) (0)-[:LINK_TO]->(2)""" graph = nx.balanced_tree(2, 1, create_using=nx.DiGraph()) graph.node[2]['debug'] = 'test"' graph[0][1]['debug'] = today data = graph2geoff(graph, 'LINK_TO', DateEncoder()) assert data == result
def setUp(self): self.P3 = nx.path_graph(3) self.P4 = nx.path_graph(4) self.K5 = nx.complete_graph(5) self.C4 = nx.cycle_graph(4) self.C5 = nx.cycle_graph(5) self.T = nx.balanced_tree(r=2, h=2) self.Gb = nx.DiGraph() self.Gb.add_edges_from([(0, 1), (0, 2), (0, 4), (2, 1), (2, 3), (4, 3)])
def setUp(self): G=nx.Graph(); G.add_edge(0,1,weight=3) G.add_edge(0,2,weight=2) G.add_edge(0,3,weight=6) G.add_edge(0,4,weight=4) G.add_edge(1,3,weight=5) G.add_edge(1,5,weight=5) G.add_edge(2,4,weight=1) G.add_edge(3,4,weight=2) G.add_edge(3,5,weight=1) G.add_edge(4,5,weight=4) self.G=G self.exact_weighted={0: 4.0, 1: 0.0, 2: 8.0, 3: 6.0, 4: 8.0, 5: 0.0} self.K = nx.krackhardt_kite_graph() self.P3 = nx.path_graph(3) self.P4 = nx.path_graph(4) self.K5 = nx.complete_graph(5) self.C4=nx.cycle_graph(4) self.T=nx.balanced_tree(r=2, h=2) self.Gb = nx.Graph() self.Gb.add_edges_from([(0,1), (0,2), (1,3), (2,3), (2,4), (4,5), (3,5)]) F = nx.Graph() # Florentine families F.add_edge('Acciaiuoli','Medici') F.add_edge('Castellani','Peruzzi') F.add_edge('Castellani','Strozzi') F.add_edge('Castellani','Barbadori') F.add_edge('Medici','Barbadori') F.add_edge('Medici','Ridolfi') F.add_edge('Medici','Tornabuoni') F.add_edge('Medici','Albizzi') F.add_edge('Medici','Salviati') F.add_edge('Salviati','Pazzi') F.add_edge('Peruzzi','Strozzi') F.add_edge('Peruzzi','Bischeri') F.add_edge('Strozzi','Ridolfi') F.add_edge('Strozzi','Bischeri') F.add_edge('Ridolfi','Tornabuoni') F.add_edge('Tornabuoni','Guadagni') F.add_edge('Albizzi','Ginori') F.add_edge('Albizzi','Guadagni') F.add_edge('Bischeri','Guadagni') F.add_edge('Guadagni','Lamberteschi') self.F = F
def test_balanced_tree(self): # balanced_tree(r,h) is a tree with (r**(h+1)-1)/(r-1) edges for r, h in [(2, 2), (3, 3), (6, 2)]: t = nx.balanced_tree(r, h) order = t.order() assert order == (r**(h + 1) - 1) / (r - 1) assert nx.is_connected(t) assert t.size() == order - 1 dh = nx.degree_histogram(t) assert dh[0] == 0 # no nodes of 0 assert dh[1] == r**h # nodes of degree 1 are leaves assert dh[r] == 1 # root is degree r assert dh[r + 1] == order - r**h - 1 # everyone else is degree r+1 assert len(dh) == r + 2
def setUp(self): self.K = nx.krackhardt_kite_graph() self.P3 = nx.path_graph(3) self.P4 = nx.path_graph(4) self.K5 = nx.complete_graph(5) self.C4 = nx.cycle_graph(4) self.T = nx.balanced_tree(r=2, h=2) self.Gb = nx.Graph() self.Gb.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (2, 4), (4, 5), (3, 5)]) F = nx.florentine_families_graph() self.F = F
def test_balanced_tree_initial_partition(): graph = nx.balanced_tree(2, 3, create_using=nx.DiGraph) initial_partition = [ (0, 1, 2), (3, 4), (5, 6), (7, 8, 9, 10), (11, 12, 13), (14, ), ] assert to_set( dovier_piazza_policriti( graph, initial_partition=initial_partition)) == to_set( paige_tarjan(graph, initial_partition=initial_partition))
def _init_balanced_tree(self, branch_factor=2, height=4, max_weight=10): """ Uses networkx to quickly initialize a balanced tree. Then we randomly add weights to the edges. :param branch_factor: Split nodes by :param height: How many layers in the tree :param max_weight: When randomly initializing edge weights, what is the max weight :return: """ graph = nx.balanced_tree(branch_factor, height) pos = nx.spring_layout(graph) for edge in graph.edges: graph[edge[0]][edge[1]]['weight'] = random.randint(1, max_weight) return graph, pos
def test_modularity_communities_weighted(func): G = nx.balanced_tree(2, 3) for (a, b) in G.edges: if ((a == 1) or (a == 2)) and (b != 0): G[a][b]["weight"] = 10.0 else: G[a][b]["weight"] = 1.0 expected = [{0, 1, 3, 4, 7, 8, 9, 10}, {2, 5, 6, 11, 12, 13, 14}] assert func(G, weight="weight") == expected assert func(G, weight="weight", resolution=0.9) == expected assert func(G, weight="weight", resolution=0.3) == expected assert func(G, weight="weight", resolution=1.1) != expected
def setup_class(cls): cls.P3 = nx.path_graph(3) cls.P4 = nx.path_graph(4) cls.K5 = nx.complete_graph(5) cls.C4 = nx.cycle_graph(4) cls.C4_directed = nx.cycle_graph(4, create_using=nx.DiGraph) cls.C5 = nx.cycle_graph(5) cls.T = nx.balanced_tree(r=2, h=2) cls.Gb = nx.DiGraph() cls.Gb.add_edges_from([(0, 1), (0, 2), (0, 4), (2, 1), (2, 3), (4, 3)])
def get_test_graphs() -> List[nx.Graph]: # return nx.graph_atlas_g()[1:100] names = [ "Path graph (10)", "Complete graph (30)", "Balanced Tree (2, 3)", "Barbell graph (5, 1)", "Binomial tree (4)", "Circular ladder graph (5)", "Cycle graph (10)", "Star graph (10)", "Wheel graph (6)" ] optimal_colorings = [2, 30, 2, 5, 2, 3, 2, 2, 4] graphs = [ nx.path_graph(10), nx.complete_graph(30), nx.balanced_tree(2, 3), nx.barbell_graph(5, 1), nx.binomial_tree(4), nx.circular_ladder_graph(5), nx.cycle_graph(10), nx.star_graph(10), nx.wheel_graph(6) ] # load graph instances for file in os.listdir("./instances"): new_graph = nx.Graph() with open(os.path.join("instances", file), "r") as f: # data = f.read() edges = [] line = f.readline() line.strip() while line: if " " not in line: break # need indexes to be from 0 edges.append([int(x) - 1 for x in line.split(" ")]) line = f.readline() line.strip() # last line is the optimal coloring if line == '?': continue # ignore graphs for which we don't know the optimal coloring new_graph.add_edges_from(edges) if len(new_graph.nodes) > 200 or len(new_graph.edges) > 5000: continue names.append(file) optimal_colorings.append(line) graphs.append(new_graph) for i, g in enumerate(graphs): g.name = names[i] return graphs, optimal_colorings
def test_balanced_tree(self): """Edge betweenness centrality: balanced tree""" G = nx.balanced_tree(r=2, h=2) b = nx.edge_betweenness_centrality(G, weight=None, normalized=False) b_answer = { (0, 1): 12, (0, 2): 12, (1, 3): 6, (1, 4): 6, (2, 5): 6, (2, 6): 6 } for n in sorted(G.edges()): assert_almost_equal(b[n], b_answer[n])
def construct_doubled_tree(m = 2,k = 3): G = nx.balanced_tree(m,k) H = nx.balanced_tree(m,k) G = add_level_data(m,G) H = add_level_data(m,H) G_leaves = [] for x in G.nodes: if G.degree(x) == 1: G_leaves.append(x) H_leaves = [] for x in H.nodes: if H.degree(x) == 1: H_leaves.append(x) H.node[x]["half"] = "H" G_not_leaves = [] for y in G.nodes(): if y not in G_leaves: G_not_leaves.append(y) nodes_to_add = [str(y) + "G" for y in G_not_leaves] H.add_nodes_from(nodes_to_add) for n in G_not_leaves: H.node[str(n) + "G"]["level"] = G.node[n]["level"] H.node[str(n) + "G"]["half"] = "G" for y in G_not_leaves: for x in G.neighbors(y): if x in G_leaves: H.add_edge( x, str(y) + "G") else: H.add_edge(str(x) + "G", str(y) + "G") H.graph["depth"] = k H.name = "doubled_tree" roots = [H.graph["root"], str(G.graph["root"]) + "G"] H.graph["roots"] = roots return H
def setUp(self): G = nx.Graph() G.add_edge(0, 1, weight=3) G.add_edge(0, 2, weight=2) G.add_edge(0, 3, weight=6) G.add_edge(0, 4, weight=4) G.add_edge(1, 3, weight=5) G.add_edge(1, 5, weight=5) G.add_edge(2, 4, weight=1) G.add_edge(3, 4, weight=2) G.add_edge(3, 5, weight=1) G.add_edge(4, 5, weight=4) self.G = G self.exact_weighted = {0: 4.0, 1: 0.0, 2: 8.0, 3: 6.0, 4: 8.0, 5: 0.0} self.K = nx.krackhardt_kite_graph() self.P3 = nx.path_graph(3) self.P4 = nx.path_graph(4) self.K5 = nx.complete_graph(5) self.C4 = nx.cycle_graph(4) self.T = nx.balanced_tree(r=2, h=2) self.Gb = nx.Graph() self.Gb.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (2, 4), (4, 5), (3, 5)]) F = nx.Graph() # Florentine families F.add_edge('Acciaiuoli', 'Medici') F.add_edge('Castellani', 'Peruzzi') F.add_edge('Castellani', 'Strozzi') F.add_edge('Castellani', 'Barbadori') F.add_edge('Medici', 'Barbadori') F.add_edge('Medici', 'Ridolfi') F.add_edge('Medici', 'Tornabuoni') F.add_edge('Medici', 'Albizzi') F.add_edge('Medici', 'Salviati') F.add_edge('Salviati', 'Pazzi') F.add_edge('Peruzzi', 'Strozzi') F.add_edge('Peruzzi', 'Bischeri') F.add_edge('Strozzi', 'Ridolfi') F.add_edge('Strozzi', 'Bischeri') F.add_edge('Ridolfi', 'Tornabuoni') F.add_edge('Tornabuoni', 'Guadagni') F.add_edge('Albizzi', 'Ginori') F.add_edge('Albizzi', 'Guadagni') F.add_edge('Bischeri', 'Guadagni') F.add_edge('Guadagni', 'Lamberteschi') self.F = F
def setUp(self): integer_graph = nx.balanced_tree(2, 2, nx.DiGraph()) package_mapping = { i: 'm.' + ('X' if i % 2 == 0 else 'Y') + '.' + letter for (i, letter) in enumerate(string.ascii_lowercase) } # Edges: [(X.a, Y.b), (X.a, X.c), (Y.b, Y.d), (Y.b, X.e), (X.c, Y.f), (X.c, X.g)] self.package_graph = nx.relabel_nodes(integer_graph, package_mapping) for node in self.package_graph: self.package_graph.node[node]['fqn'] = node.split('.')[1:] self.project = self.get_project()
def test_multi_stage(self): G = networkx.balanced_tree(3, 2, networkx.DiGraph()) model = ScenarioTreeModelFromNetworkX(G, edge_probability_attribute=None) self.assertEqual(sorted(list(model.Stages)), sorted(['Stage1', 'Stage2', 'Stage3'])) self.assertEqual(sorted(list(model.Nodes)), sorted([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])) self.assertEqual(sorted(list(model.Children[0])), sorted([1, 2, 3])) self.assertEqual(sorted(list(model.Children[1])), sorted([4, 5, 6])) self.assertEqual(sorted(list(model.Children[2])), sorted([7, 8, 9])) self.assertEqual(sorted(list(model.Children[3])), sorted([10, 11, 12])) self.assertEqual(sorted(list(model.Children[4])), sorted([])) self.assertEqual(sorted(list(model.Children[5])), sorted([])) self.assertEqual(sorted(list(model.Children[6])), sorted([])) self.assertEqual(sorted(list(model.Children[7])), sorted([])) self.assertEqual(sorted(list(model.Children[8])), sorted([])) self.assertEqual(sorted(list(model.Children[9])), sorted([])) self.assertEqual(sorted(list(model.Children[10])), sorted([])) self.assertEqual(sorted(list(model.Children[11])), sorted([])) self.assertEqual(sorted(list(model.Children[12])), sorted([])) self.assertEqual( sorted(list(model.Scenarios)), sorted([ 'Scenario_u4', 'Scenario_u5', 'Scenario_u6', 'Scenario_u7', 'Scenario_u8', 'Scenario_u9', 'Scenario_u10', 'Scenario_u11', 'Scenario_u12' ])) self.assertEqual(model.ConditionalProbability[0], 1.0) self.assertAlmostEqual(model.ConditionalProbability[1], 1.0 / 3) self.assertAlmostEqual(model.ConditionalProbability[2], 1.0 / 3) self.assertAlmostEqual(model.ConditionalProbability[3], 1.0 / 3) self.assertAlmostEqual(model.ConditionalProbability[4], 1.0 / 3) self.assertAlmostEqual(model.ConditionalProbability[5], 1.0 / 3) self.assertAlmostEqual(model.ConditionalProbability[6], 1.0 / 3) self.assertAlmostEqual(model.ConditionalProbability[7], 1.0 / 3) self.assertAlmostEqual(model.ConditionalProbability[8], 1.0 / 3) self.assertAlmostEqual(model.ConditionalProbability[9], 1.0 / 3) self.assertAlmostEqual(model.ConditionalProbability[10], 1.0 / 3) self.assertAlmostEqual(model.ConditionalProbability[11], 1.0 / 3) self.assertAlmostEqual(model.ConditionalProbability[12], 1.0 / 3) model.StageCost['Stage1'] = 'c1' model.StageCost['Stage2'] = 'c2' model.StageCost['Stage3'] = 'c3' model.StageVariables['Stage1'].add('x') model.StageVariables['Stage2'].add('y') model.StageVariables['Stage3'].add('y') ScenarioTree(scenariotreeinstance=model)
def main(): if (len(sys.argv) < 4): printUsage(sys.argv[0]) exit() # Size r = int(sys.argv[1]) height = int(sys.argv[2]) # Generate graph = nx.balanced_tree(r, height) # Write to file writeFile(graph, sys.argv[3])
def tree(start, height, r=2, role_start=0): """Builds a balanced r-tree of height h INPUT: ------------- start : starting index for the shape height : int height of the tree r : int number of branches per node role_start : starting index for the roles OUTPUT: ------------- graph : a tree shape graph, with ids beginning at start roles : list of the roles of the nodes (indexed starting at role_start) """ graph = nx.balanced_tree(r, height) roles = [0] * graph.number_of_nodes() return graph, roles
def test_failure_json(self): graph = nx.balanced_tree(2, 1) httpretty.register_uri(httpretty.GET, "http://localhost:7474/db/data/", body=BATCH_URL) httpretty.register_uri(httpretty.POST, "http://localhost:7474/db/data/batch", body='{"exception": "Error", "stacktrace": 1}', status=500, content_type='application/json; charset=UTF-8') f = lambda: write_to_neo("http://localhost:7474/db/data/", graph, 'LINK_TO') self.assertRaises(Exception, f)
def __init__(self, parent=None): super(CircularTree, self).__init__() # self.other_plt = plt print("reached in init?") G = nx.balanced_tree(3, 5) pos = graphviz_layout(G, prog='twopi', args='') self.plt2.figure(figsize=(8, 8)) nx.draw(G, pos, node_size=100, alpha=0.5, node_color="blue", with_labels=False) self.plt2.axis('equal') print("done with init?") self.plt2.show()
def test_failure_500(self): graph = nx.balanced_tree(2, 1) httpretty.register_uri(httpretty.GET, "http://localhost:7474/db/data/", body=BATCH_URL) httpretty.register_uri(httpretty.POST, "http://localhost:7474/db/data/batch", body='Server Error', status=500, content_type='text/html') f = lambda: write_to_neo("http://localhost:7474/db/data/", graph, 'LINK_TO', "ITEM") self.assertRaises(Exception, f)
def plot(self): ''' plot some random stuff ''' G = nx.balanced_tree(3, 5) pos = graphviz_layout(G, prog='twopi', args='') # self.plt2.figure(figsize=(8, 8)) nx.draw(G, pos, node_size=100, alpha=0.5, node_color="blue", with_labels=False) # data = [random.random() for i in range(25)] # ax = self.figure.add_subplot(111) # ax.hold(False) # ax.plot(data, '*-') self.canvas.draw()
def test_tree_multiple_sources_tree_critical(self): # tests D to be a tree, whole tree is critical # There are multiple sources in the graphs, including two # covering all the vertices. However, the optimal solution is # still of size 1. In addition to test_tree_multiple_sources_leafs_critical(), # this test also tests correctness of the deletion procedure. # If it proceeds correctly, it does not consider the newly added sources # as critical sinks, so the solution is still of size 1. D: nx.DiGraph = nx.balanced_tree(2, 5, nx.DiGraph()) critical = set(D.nodes) D.add_edges_from({(65, 1), (65, 2), (66, 15), (65, 29), (66, 38), (67, 58)}) cover = source_cover(D, critical) assert_true( cover == {0} ) # All others are reachable from a critical vertex, so this is only viable option.
def test_directed_tree_str(): # Create a directed forest with labels graph = nx.balanced_tree(r=2, h=2, create_using=nx.DiGraph) for node in graph.nodes: graph.nodes[node]["label"] = "node_" + chr(ord("a") + node) node_target = dedent(""" ╙── 0 ├─╼ 1 │ ├─╼ 3 │ └─╼ 4 └─╼ 2 ├─╼ 5 └─╼ 6 """).strip() label_target = dedent(""" ╙── node_a ├─╼ node_b │ ├─╼ node_d │ └─╼ node_e └─╼ node_c ├─╼ node_f └─╼ node_g """).strip() # Basic node case ret = nx.forest_str(graph, with_labels=False) print(ret) assert ret == node_target # Basic label case ret = nx.forest_str(graph, with_labels=True) print(ret) assert ret == label_target # Custom write function case lines = [] ret = nx.forest_str(graph, write=lines.append, with_labels=False) assert ret is None assert lines == node_target.split("\n") # Smoke test to ensure passing the print function works. To properly test # this case we would need to capture stdout. (for potential reference # implementation see :class:`ubelt.util_stream.CaptureStdout`) ret = nx.forest_str(graph, write=print) assert ret is None
def test_compute(): graph = nx.balanced_tree(2, 3, create_using=nx.DiGraph) initial_partition = [ (0, 1, 2), (3, 4), (5, 6), (7, 8, 9, 10), (11, 12, 13), (14,) ] assert to_set(compute_maximum_bisimulation( graph, initial_partition )) == to_set(paige_tarjan(graph, initial_partition)) assert to_set(compute_maximum_bisimulation( graph, initial_partition, algorithm=Algorithms.DovierPiazzaPolicriti )) == to_set(paige_tarjan(graph, initial_partition)) assert to_set(compute_maximum_bisimulation( graph, initial_partition, algorithm=Algorithms.PaigeTarjan )) == to_set(paige_tarjan(graph, initial_partition))
def generate_forest_balanced_trees(r, h, n): graphs = [] roots = [] num_nodes = stats.num_nodes_balanced_tree(r, h) starting_num = 0 for i in range(0, n): #log.debug("building tree with starting root: %s", starting_num) g = nx.balanced_tree(r, h) g = nx.convert_node_labels_to_integers(g, first_label=starting_num) #log.debug("nodes: %s", pp.pformat(g.nodes())) graphs.append(g) roots.append(starting_num) starting_num += num_nodes trees = nx.union_all(graphs) return (trees, roots)
def test_multi_stage(self): G = networkx.balanced_tree(3, 2, networkx.DiGraph()) model = ScenarioTreeModelFromNetworkX(G, edge_probability_attribute=None) self.assertEqual(sorted(list(model.Stages)), sorted(["Stage1", "Stage2", "Stage3"])) self.assertEqual(sorted(list(model.Nodes)), sorted([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])) self.assertEqual(sorted(list(model.Children[0])), sorted([1, 2, 3])) self.assertEqual(sorted(list(model.Children[1])), sorted([4, 5, 6])) self.assertEqual(sorted(list(model.Children[2])), sorted([7, 8, 9])) self.assertEqual(sorted(list(model.Children[3])), sorted([10, 11, 12])) self.assertEqual(sorted(list(model.Children[4])), sorted([])) self.assertEqual(sorted(list(model.Children[5])), sorted([])) self.assertEqual(sorted(list(model.Children[6])), sorted([])) self.assertEqual(sorted(list(model.Children[7])), sorted([])) self.assertEqual(sorted(list(model.Children[8])), sorted([])) self.assertEqual(sorted(list(model.Children[9])), sorted([])) self.assertEqual(sorted(list(model.Children[10])), sorted([])) self.assertEqual(sorted(list(model.Children[11])), sorted([])) self.assertEqual(sorted(list(model.Children[12])), sorted([])) self.assertEqual(sorted(list(model.Scenarios)), sorted([4, 5, 6, 7, 8, 9, 10, 11, 12])) self.assertEqual(model.ConditionalProbability[0], 1.0) self.assertAlmostEqual(model.ConditionalProbability[1], 1.0 / 3) self.assertAlmostEqual(model.ConditionalProbability[2], 1.0 / 3) self.assertAlmostEqual(model.ConditionalProbability[3], 1.0 / 3) self.assertAlmostEqual(model.ConditionalProbability[4], 1.0 / 3) self.assertAlmostEqual(model.ConditionalProbability[5], 1.0 / 3) self.assertAlmostEqual(model.ConditionalProbability[6], 1.0 / 3) self.assertAlmostEqual(model.ConditionalProbability[7], 1.0 / 3) self.assertAlmostEqual(model.ConditionalProbability[8], 1.0 / 3) self.assertAlmostEqual(model.ConditionalProbability[9], 1.0 / 3) self.assertAlmostEqual(model.ConditionalProbability[10], 1.0 / 3) self.assertAlmostEqual(model.ConditionalProbability[11], 1.0 / 3) self.assertAlmostEqual(model.ConditionalProbability[12], 1.0 / 3) model.StageCost["Stage1"] = "c1" model.StageCost["Stage2"] = "c2" model.StageCost["Stage3"] = "c3" model.StageVariables["Stage1"].add("x") model.StageVariables["Stage2"].add("y") model.StageVariables["Stage3"].add("y") self.assertEqual(model.Bundling.value, False) self.assertEqual(list(model.Bundles), []) self.assertEqual(len(model.BundleScenarios), 0) ScenarioTree(scenariotreeinstance=model)
def build_tree(N, wavefunc, filename): G = nx.balanced_tree(2, N) # define empty binary tree probs = abs(wavefunc)**2 # get probabilities from wavefunction mapping_dict = {} # assign leaves to probabilities of basis states for idx in range(len(probs)): bfs_idx = 2**N # since nodes are assigned numbers breadth-first mapping_dict[idx + bfs_idx - 1] = round(probs[idx], 3) # map other nodes to sum of probabilities of children for layer in range(N - 1, 0, -1): for idx in range(2**layer): bfs_idx = 2**layer # since nodes are assigned numbers breadth-first mapping_dict[bfs_idx + idx - 1] = round( mapping_dict[2 * bfs_idx + 2 * idx - 1] + mapping_dict[2 * bfs_idx + 2 * idx], 3, ) mapping_dict[0] = round(mapping_dict[1] + mapping_dict[2], 3) # add root node # label edges with spins edge_labels_dict = {} spin = 0 for edge in G.edges(): edge_labels_dict[edge] = spin spin = (spin + 1) % 2 # alternate spins since edges are ordered # make directed binary tree graph write_dot(G, "temp.dot") plt.subplots(figsize=(20, 5)) pos = graphviz_layout(G, prog="dot") nx.draw(G, pos, with_labels=False, arrows=True, node_size=1000) nx.draw_networkx_labels(G, pos, mapping_dict) nx.draw_networkx_edge_labels(G, pos, edge_labels_dict) plt.tight_layout() plt.savefig("{0}.png".format(filename)) os.remove("temp.dot")
def graphGenerator(): if args.graph_type == "erdos_renyi": return networkx.erdos_renyi_graph(args.graph_size,args.graph_p) if args.graph_type == "balanced_tree": ndim = int(np.ceil(np.log(args.graph_size)/np.log(args.graph_degree))) return networkx.balanced_tree(args.graph_degree,ndim) if args.graph_type == "cicular_ladder": ndim = int(np.ceil(args.graph_size*0.5)) return networkx.circular_ladder_graph(ndim) if args.graph_type == "cycle": return networkx.cycle_graph(args.graph_size) if args.graph_type == 'grid_2d': ndim = int(np.ceil(np.sqrt(args.graph_size))) return networkx.grid_2d_graph(ndim,ndim) if args.graph_type == 'lollipop': ndim = int(np.ceil(args.graph_size*0.5)) return networkx.lollipop_graph(ndim,ndim) if args.graph_type =='expander': ndim = int(np.ceil(np.sqrt(args.graph_size))) return networkx.margulis_gabber_galil_graph(ndim) if args.graph_type =="hypercube": ndim = int(np.ceil(np.log(args.graph_size)/np.log(2.0))) return networkx.hypercube_graph(ndim) if args.graph_type =="star": ndim = args.graph_size-1 return networkx.star_graph(ndim) if args.graph_type =='barabasi_albert': return networkx.barabasi_albert_graph(args.graph_size,args.graph_degree) if args.graph_type =='watts_strogatz': return networkx.connected_watts_strogatz_graph(args.graph_size,args.graph_degree,args.graph_p) if args.graph_type =='regular': return networkx.random_regular_graph(args.graph_degree,args.graph_size) if args.graph_type =='powerlaw_tree': return networkx.random_powerlaw_tree(args.graph_size) if args.graph_type =='small_world': ndim = int(np.ceil(np.sqrt(args.graph_size))) return networkx.navigable_small_world_graph(ndim) if args.graph_type =='geant': return topologies.GEANT() if args.graph_type =='dtelekom': return topologies.Dtelekom() if args.graph_type =='abilene': return topologies.Abilene() if args.graph_type =='servicenetwork': return topologies.ServiceNetwork()
def disabled_random(self): import networkx as nx for (r,h) in [ (2,2), (2,5), (3,5) ]: G = nx.balanced_tree(r, h) t = tf.Transformer(True, rospy.Duration(10.0)) for n in G.nodes(): if n != 0: # n has parent p p = min(G.neighbors(n)) setT(t, str(p), str(n), rospy.Time(0), 1) for n in G.nodes(): ((x,_,_), _) = t.lookupTransform("0", str(n), rospy.Time(0)) self.assert_(x == nx.shortest_path_length(G, 0, n)) for i in G.nodes(): for j in G.nodes(): ((x,_,_), _) = t.lookupTransform(str(i), str(j), rospy.Time()) self.assert_(abs(x) == abs(nx.shortest_path_length(G, 0, i) - nx.shortest_path_length(G, 0, j)))
def test_stress_min(): #n = 5 #n = 10 #X = torch.rand(n, 2, requires_grad = True) #G = nx.path_graph(n) #G = nx.cycle_graph(n) r = 2 h = 5 #h = 8 # torch.cuda.init() X = torch.rand(r**(h + 1) - 1, 2, requires_grad=True, device=cuda) # torch.cuda.synchronize() G = nx.balanced_tree(r, h) D = dict(nx.all_pairs_shortest_path_length(G)) D = dict2tensor(D) # print('X:', X) # print('D:', D) stress_minimization(X, D, max_iter=1000)
def balanced_tree(): branching = 3 depth = 5 g = nx.balanced_tree(branching, depth) print('Number of edges: ', g.number_of_edges()) g = ricciCurvature(g, alpha=0.99, method='OTD') g = formanCurvature(g) o_curvatures, f_curvatures = get_edge_curvatures(g) plot_curvatures(o_curvatures, 'balanced_tree_ollivier') plot_curvatures(f_curvatures, 'balanced_tree_forman') # this shows that the positively curved edges are on the last layer for limit in range(1, depth + 1): curvatures = [] for u, v in nx.bfs_edges(g, 0, depth_limit=limit): curvatures.append(g[u][v]['ricciCurvature']) plot_curvatures(np.array(curvatures), '{}_balanced'.format(limit))
def generate_tree(branch, height): G = nx.balanced_tree(branch, height) vertex = G.number_of_nodes() edgelist = G.edges() weightdict = {} incidence = [[0 for col in range(vertex)] for row in range(vertex)] for edge in edgelist: incidence[edge[0]][edge[1]] = 1 nodelist = list(G.nodes()) for i in range(vertex): weightdict[nodelist[i] + 1] = random.randint(5, 30) edgelist = [(edge[0] + 1, edge[1] + 1) for edge in edgelist] return incidence, weightdict, edgelist
def Tree(): try: import pygraphviz from networkx.drawing.nx_agraph import graphviz_layout except ImportError: try: import pydot from networkx.drawing.nx_pydot import graphviz_layout except ImportError: raise ImportError("This example needs Graphviz and either " "PyGraphviz or pydot") G = nx.balanced_tree(3, 3) plt.figure(figsize=(8, 8)) nx.draw(G, node_size=20, alpha=0.5, node_color="blue", with_labels=False) plt.axis('equal') plt.show() return