def test_tensor_product_size(): P5 = nx.path_graph(5) K3 = nx.complete_graph(3) K5 = nx.complete_graph(5) G=tensor_product(P5,K3) assert_equal(nx.number_of_nodes(G),5*3) G=tensor_product(K3,K5) assert_equal(nx.number_of_nodes(G),3*5)
def test_tensor_product_size(): P5 = nx.path_graph(5) K3 = nx.complete_graph(3) K5 = nx.complete_graph(5) G = nx.tensor_product(P5, K3) assert_equal(nx.number_of_nodes(G), 5 * 3) G = nx.tensor_product(K3, K5) assert_equal(nx.number_of_nodes(G), 3 * 5)
def test_tensor_product_classic_result(): K2 = nx.complete_graph(2) G = nx.petersen_graph() G = tensor_product(G,K2) assert_true(nx.is_isomorphic(G,nx.desargues_graph())) G = nx.cycle_graph(5) G = tensor_product(G,K2) assert_true(nx.is_isomorphic(G,nx.cycle_graph(10))) G = nx.tetrahedral_graph() G = tensor_product(G,K2) assert_true(nx.is_isomorphic(G,nx.cubical_graph()))
def test_tensor_product_combinations(): # basic smoke test, more realistic tests would be usefule P5 = nx.path_graph(5) K3 = nx.complete_graph(3) G = tensor_product(P5, K3) assert_equal(nx.number_of_nodes(G), 5 * 3) G = tensor_product(P5, nx.MultiGraph(K3)) assert_equal(nx.number_of_nodes(G), 5 * 3) G = tensor_product(nx.MultiGraph(P5), K3) assert_equal(nx.number_of_nodes(G), 5 * 3) G = tensor_product(nx.MultiGraph(P5), nx.MultiGraph(K3)) assert_equal(nx.number_of_nodes(G), 5 * 3) G = tensor_product(nx.DiGraph(P5), nx.DiGraph(K3)) assert_equal(nx.number_of_nodes(G), 5 * 3)
def product(g1, g2): base = nx.tensor_product(g1, g2) base = nx.convert_node_labels_to_integers(base, first_label=0, ordering='default', label_attribute=None) return base.to_directed()
def videograph_eventnet_tensor_product(videograph): vg_en_tn_prdct=[] for v1 in videograph: vg_en_tn_prdct_row=[] for v2 in videograph: vg_en_tn_prdct_row.append(nx.tensor_product(v1[0].to_undirected(),v2[0].to_undirected())) vg_en_tn_prdct.append(vg_en_tn_prdct_row) print "Videograph EventNet Tensor Product Matrix:",vg_en_tn_prdct return vg_en_tn_prdct
def test_tensor_product_random(): G = nx.erdos_renyi_graph(10,2/10.) H = nx.erdos_renyi_graph(10,2/10.) GH = tensor_product(G,H) for (u_G,u_H) in GH.nodes_iter(): for (v_G,v_H) in GH.nodes_iter(): if H.has_edge(u_H,v_H) and G.has_edge(u_G,v_G): assert_true(GH.has_edge((u_G,u_H),(v_G,v_H))) else: assert_true(not GH.has_edge((u_G,u_H),(v_G,v_H)))
def videograph_eventnet_tensor_product(videograph): vg_en_tn_prdct = [] for v1 in videograph: vg_en_tn_prdct_row = [] for v2 in videograph: vg_en_tn_prdct_row.append( nx.tensor_product(v1[0].to_undirected(), v2[0].to_undirected())) vg_en_tn_prdct.append(vg_en_tn_prdct_row) print "Videograph EventNet Tensor Product Matrix:", vg_en_tn_prdct return vg_en_tn_prdct
def my_tensor_prod(g1, g2): res = nx.tensor_product(g1, g2) killing_list = [] for edge in res.edges: arr1, arr2 = res.edges[edge]['label'] if not intersection(arr1, arr2): killing_list.append(edge) else: res.edges[edge]['label'] = intersection(arr1, arr2) for edge in killing_list: res.remove_edge(edge[0], edge[1]) return nx.DiGraph(res)
def kproduct(graph): ''' Applies the tensor product to graph k-1 times. INPUT: graph: A networkx graph OUTPUT tensor: The graph on which the tensor product has been applied k-1 times. ''' tensor = graph.copy() for i in range(0, k - 1): tensor = nx.tensor_product(tensor, graph) return tensor
def time_expand(self, mu: int) -> nx.DiGraph: """ Time expand the graph :param mu: Number of time expansions :return: Time expanded graph """ # MAPF via Reduction slides, "Compact Formulation" T = nx.tensor_product(self.G, nx.path_graph(mu + 1, create_using=nx.DiGraph)) # Prune vertices not on a start -> goal path for any agent # This finds a union of the MDDs (which are subgraphs of the TEG) keep = set(itertools.chain.from_iterable( (nx.descendants(T, start) | {start}) & (nx.ancestors(T, goal) | {goal}) for start, goal in zip(zip(self.starts, itertools.repeat(0, len(self.starts))), zip(self.goals, itertools.repeat(mu, len(self.goals)))))) T.remove_nodes_from(T.nodes - keep) nx.relabel_nodes(T, {v: (*v[0], v[1]) for v in T.nodes}, copy=False) return T
def test_tensor_product_null(): null=nx.null_graph() empty10=nx.empty_graph(10) K3=nx.complete_graph(3) K10=nx.complete_graph(10) P3=nx.path_graph(3) P10=nx.path_graph(10) # null graph G=tensor_product(null,null) assert_true(nx.is_isomorphic(G,null)) # null_graph X anything = null_graph and v.v. G=tensor_product(null,empty10) assert_true(nx.is_isomorphic(G,null)) G=tensor_product(null,K3) assert_true(nx.is_isomorphic(G,null)) G=tensor_product(null,K10) assert_true(nx.is_isomorphic(G,null)) G=tensor_product(null,P3) assert_true(nx.is_isomorphic(G,null)) G=tensor_product(null,P10) assert_true(nx.is_isomorphic(G,null)) G=tensor_product(empty10,null) assert_true(nx.is_isomorphic(G,null)) G=tensor_product(K3,null) assert_true(nx.is_isomorphic(G,null)) G=tensor_product(K10,null) assert_true(nx.is_isomorphic(G,null)) G=tensor_product(P3,null) assert_true(nx.is_isomorphic(G,null)) G=tensor_product(P10,null) assert_true(nx.is_isomorphic(G,null))
import random import networkx as nx from common import nx_to_ig, show, random_regularize from nd2_construct_non2 import nd2 P = nx.petersen_graph() P.remove_node(P.nodes()[-1]) G = nx.tensor_product(P, nd2(19, 1)) show(G) G.add_node(0) G = random_regularize(G) show(G)
def main(): import sys import networkx as nx import pydot import pygraphviz as pgv import matplotlib.pyplot as plt g1v = [('A1', ['a']), ('A2', ['b', 'a']), ('A3', ['a', 'c'])] g2v = [('B1', ['a']), ('B2', ['b', 'a']), ('B3', ['x', 'y'])] g3v = [('C1', ['a']), ('C2', ['b', 'a']), ('C3', ['a', 'c'])] g4v = [('1', ['a']), ('2', ['a']), ('3', ['a']), ('4', ['a']), ('5', ['a']), ('6', ['a'])] g1e = [('A1', 'A2'), ('A2', 'A3')] g2e = [('B1', 'B2'), ('B2', 'B3')] g3e = [('C1', 'C2'), ('C2', 'C3')] g4e = [('1', '2'), ('1', '5'), ('2', '5'), ('2', '1'), ('2', '3'), ('3', '4'), ('3', '2'), ('4', '3'), ('4', '6'), ('4', '5'), ('5', '4'), ('5', '2'), ('5', '1'), ('6', '4')] g1 = Graph() g2 = Graph() g3 = Graph() g4 = Graph() g1.init(g1v, g1e) g2.init(g2v, g2e) g3.init(g3v, g3e) g4.init(g4v, g4e) ag1 = AssocGraph() ag2 = AssocGraph() ag1.associate(g1, g2) ag2.associate(g1, g3) print g1 print g2 print g3 print ag1 print ag2 sys.stdout.write("%f, %f\n" % ag1.sim_score()) sys.stdout.write("%f, %f\n" % ag2.sim_score()) g4.bron_kerbosch_pivot(r=set(), p=set([i for i in range(len(g4.v))]), x=set()) print "G4 cliques" for c in g4.cliques: for v in c: print g4.v[v][1], print g4.cliques = [] g4.clique_weights = [] g4.bron_kerbosch_deg_order() print "G4 cliques with degenerate order",g4.cliques for c in g4.cliques: for v in c: print g4.v[v][1], print print "NetworkX Tests" nxg1 = nx.Graph() nxg2 = nx.Graph() for n in g1v: nxg1.add_node(n[0], attr_dict={"label": str(n[0])}) for n in g2v: nxg2.add_node(n[0], attr_dict={"label": str(n[0])}) for e in g1e: nxg1.add_edge(*e) for e in g2e: nxg2.add_edge(*e) contrived_ag_nodes = range(9) contrived_ag_edges = [(0,4), (0,8), (1,3), (1,5), (2,6), (2,4), (3,1), (3,7), (4,0), (4,2), (4,6), (4,8), (5,1), (5,7), (6,2), (6,4), (7,3), (7,5), (8,4), (8,0)] nxag1 = nx.Graph() for i, node in enumerate(contrived_ag_nodes): x = float(i * 100 % 300) y = float(i / 3 * 100 % 300) nxag1.add_node(node, attr_dict={"label": str(node), "pos": "%f, %f" % (x,y)}) for edge in contrived_ag_edges: nxag1.add_edge(*edge) pgvag1 = nx.to_agraph(nxag1) pgvag1.graph_attr['overlap'] = 'true' pgvag1.layout() pgvag1.draw("spectragraph.png") #labels = nx.draw_networkx_labels(nxag1, pos=nx.spring_layout(nxag1), labels=dict(zip(range(9), range(9)))) #nx.draw(nxag1, with_labels=True, labels=labels) pydot_ag1 = nx.to_pydot(nxag1) print pydot_ag1.to_string() for c in nx.find_cliques(nxag1): print c tensor = nx.tensor_product(nxg1, nxg2) nx.draw(tensor) pgvag2 = nx.to_agraph(tensor) pgvag2.layout() pgvag2.draw("tensor.png")
def test_tensor_product_raises(): P = tensor_product(nx.DiGraph(), nx.Graph())
def main(): while True: game = rg.read_game() if game == None: break left = game[0] right = game[1] allowed_left = game[2] allowed_right = game[3] final_states = game[4] start_left = game[5] start_right = game[6] k = 1 # number of left players lgraph = left # Take the k-fold categorical product of the graph for i in range(1, k): lgraph = nx.tensor_product(lgraph, left) left = lgraph # Workaround for networkx's built-in categorical product new_labels = {} for n in left.nodes(): new = collections.deque() append_to_new = new.append update_nodes(n, new, append_to_new) new_labels[n] = tuple(new) nx.relabel_nodes(left, new_labels, copy=False) # Put allowed_right in a format that makes sense. a list of (current pos, next pos) rmoves = collections.deque() append_to_rmoves = rmoves.append for move in allowed_right: x = move[0] for m2 in move[1:]: y = m2 append_to_rmoves([(x, y), sys.maxint]) # Construct a dictionary with left's position(s) as keys, right's as values relation_matrix = {} for v in left.nodes(): relation_matrix[v] = [sys.maxint] * len(right) # Initialize the dict with 0's at every final state # when do we have a final stat for key, value in relation_matrix.iteritems(): for f in final_states: if f[0] in key: # there is a left player matching the position for i in range(0, len(value)): if i == f[1]: value[i] = 0 #Run the game, record the winner. winner = fill_matrix(left, right, relation_matrix, allowed_left, allowed_right) print "\nWinner: %s \n" % (winner) strategy = collections.OrderedDict( sorted(relation_matrix.items(), key=lambda t: t[0])) # Left's strategy: How many moves would it take for left to get to a node labelled 0? if winner == 'Left': for key, value in strategy.iteritems(): print key, for entry in value: print entry, print "" # Right's strategy: How many moves would it take for right to get to a node labelled sys.maxint? if winner == 'Right': updated = collections.deque() append_to_updated = updated.append for key, value in strategy.iteritems(): row = [0] * right.number_of_nodes() # best case: 0 moves for i in range(0, len(value)): if value[i] == 0: # right would lose at this point append_to_updated(i) row[i] = -1 if value[i] == sys.maxint: # right would win here append_to_updated(i) row[i] = 0 neighbours = collections.deque() append_to_neighbours = neighbours.append # recursively relabel each of the nodes which have a move leaving into i for j in range(0, len(allowed_right)): for k in range(0, len(allowed_right[j])): if allowed_right[j][k] == i: append_to_neighbours(j) get_nbrs(row, set(neighbours), relation_matrix, allowed_right, updated, 1, append_to_updated) # print out the labels print key, for entry in row: print entry, print "" game = []
def test_tensor_product_raises(): with pytest.raises(nx.NetworkXError): P = nx.tensor_product(nx.DiGraph(), nx.Graph())
def test_tensor_product_null(): null = nx.null_graph() empty10 = nx.empty_graph(10) K3 = nx.complete_graph(3) K10 = nx.complete_graph(10) P3 = nx.path_graph(3) P10 = nx.path_graph(10) # null graph G = nx.tensor_product(null, null) assert_true(nx.is_isomorphic(G, null)) # null_graph X anything = null_graph and v.v. G = nx.tensor_product(null, empty10) assert_true(nx.is_isomorphic(G, null)) G = nx.tensor_product(null, K3) assert_true(nx.is_isomorphic(G, null)) G = nx.tensor_product(null, K10) assert_true(nx.is_isomorphic(G, null)) G = nx.tensor_product(null, P3) assert_true(nx.is_isomorphic(G, null)) G = nx.tensor_product(null, P10) assert_true(nx.is_isomorphic(G, null)) G = nx.tensor_product(empty10, null) assert_true(nx.is_isomorphic(G, null)) G = nx.tensor_product(K3, null) assert_true(nx.is_isomorphic(G, null)) G = nx.tensor_product(K10, null) assert_true(nx.is_isomorphic(G, null)) G = nx.tensor_product(P3, null) assert_true(nx.is_isomorphic(G, null)) G = nx.tensor_product(P10, null) assert_true(nx.is_isomorphic(G, null))
def powerGraph(g, n): base = g.copy() for i in range(0, n - 1): base = nx.tensor_product(base, g) return base.to_directed()
import networkx as nx import numpy as np G = nx.cycle_graph(2) Gi = G for i in xrange(1, 10): Gi = nx.tensor_product(Gi,G) alpha = len(nx.maximal_independent_set(Gi)) theta = alpha**(1/float(i+1)) print i, alpha, theta
def main(): import sys import networkx as nx import pydot import pygraphviz as pgv import matplotlib.pyplot as plt g1v = [('A1', ['a']), ('A2', ['b', 'a']), ('A3', ['a', 'c'])] g2v = [('B1', ['a']), ('B2', ['b', 'a']), ('B3', ['x', 'y'])] g3v = [('C1', ['a']), ('C2', ['b', 'a']), ('C3', ['a', 'c'])] g4v = [('1', ['a']), ('2', ['a']), ('3', ['a']), ('4', ['a']), ('5', ['a']), ('6', ['a'])] g1e = [('A1', 'A2'), ('A2', 'A3')] g2e = [('B1', 'B2'), ('B2', 'B3')] g3e = [('C1', 'C2'), ('C2', 'C3')] g4e = [('1', '2'), ('1', '5'), ('2', '5'), ('2', '1'), ('2', '3'), ('3', '4'), ('3', '2'), ('4', '3'), ('4', '6'), ('4', '5'), ('5', '4'), ('5', '2'), ('5', '1'), ('6', '4')] g1 = Graph() g2 = Graph() g3 = Graph() g4 = Graph() g1.init(g1v, g1e) g2.init(g2v, g2e) g3.init(g3v, g3e) g4.init(g4v, g4e) ag1 = AssocGraph() ag2 = AssocGraph() ag1.associate(g1, g2) ag2.associate(g1, g3) print g1 print g2 print g3 print ag1 print ag2 sys.stdout.write("%f, %f\n" % ag1.sim_score()) sys.stdout.write("%f, %f\n" % ag2.sim_score()) g4.bron_kerbosch_pivot(r=set(), p=set([i for i in range(len(g4.v))]), x=set()) print "G4 cliques" for c in g4.cliques: for v in c: print g4.v[v][1], print g4.cliques = [] g4.clique_weights = [] g4.bron_kerbosch_deg_order() print "G4 cliques with degenerate order", g4.cliques for c in g4.cliques: for v in c: print g4.v[v][1], print print "NetworkX Tests" nxg1 = nx.Graph() nxg2 = nx.Graph() for n in g1v: nxg1.add_node(n[0], attr_dict={"label": str(n[0])}) for n in g2v: nxg2.add_node(n[0], attr_dict={"label": str(n[0])}) for e in g1e: nxg1.add_edge(*e) for e in g2e: nxg2.add_edge(*e) contrived_ag_nodes = range(9) contrived_ag_edges = [ (0, 4), (0, 8), (1, 3), (1, 5), (2, 6), (2, 4), (3, 1), (3, 7), (4, 0), (4, 2), (4, 6), (4, 8), (5, 1), (5, 7), (6, 2), (6, 4), (7, 3), (7, 5), (8, 4), (8, 0) ] nxag1 = nx.Graph() for i, node in enumerate(contrived_ag_nodes): x = float(i * 100 % 300) y = float(i / 3 * 100 % 300) nxag1.add_node(node, attr_dict={ "label": str(node), "pos": "%f, %f" % (x, y) }) for edge in contrived_ag_edges: nxag1.add_edge(*edge) pgvag1 = nx.to_agraph(nxag1) pgvag1.graph_attr['overlap'] = 'true' pgvag1.layout() pgvag1.draw("spectragraph.png") #labels = nx.draw_networkx_labels(nxag1, pos=nx.spring_layout(nxag1), labels=dict(zip(range(9), range(9)))) #nx.draw(nxag1, with_labels=True, labels=labels) pydot_ag1 = nx.to_pydot(nxag1) print pydot_ag1.to_string() for c in nx.find_cliques(nxag1): print c tensor = nx.tensor_product(nxg1, nxg2) nx.draw(tensor) pgvag2 = nx.to_agraph(tensor) pgvag2.layout() pgvag2.draw("tensor.png")
def main(): while True: game = rg.read_game() if game == None: break left = game[0] right = game[1] allowed_left = game[2] allowed_right = game[3] final_states = game[4] start_left = game[5] start_right = game[6] k = 1 # number of left players lgraph = left # Take the k-fold categorical product of the graph for i in range(1,k): lgraph = nx.tensor_product(lgraph,left) left = lgraph # Workaround for networkx's built-in categorical product new_labels = {} for n in left.nodes(): new = collections.deque() append_to_new = new.append update_nodes(n, new, append_to_new) new_labels[n] = tuple(new) nx.relabel_nodes(left, new_labels, copy=False) # Put allowed_right in a format that makes sense. a list of (current pos, next pos) rmoves = collections.deque() append_to_rmoves = rmoves.append for move in allowed_right: x = move[0] for m2 in move[1:]: y = m2 append_to_rmoves([(x,y), sys.maxint]) # Construct a dictionary with left's position(s) as keys, right's as values relation_matrix = {} for v in left.nodes(): relation_matrix[v] = [sys.maxint] * len(right) # Initialize the dict with 0's at every final state # when do we have a final stat for key, value in relation_matrix.iteritems(): for f in final_states: if f[0] in key: # there is a left player matching the position for i in range(0, len(value)): if i == f[1]: value[i] = 0 #Run the game, record the winner. winner = fill_matrix(left, right, relation_matrix, allowed_left, allowed_right) print "\nWinner: %s \n" %(winner) strategy = collections.OrderedDict(sorted(relation_matrix.items(), key = lambda t: t[0])) # Left's strategy: How many moves would it take for left to get to a node labelled 0? if winner == 'Left': for key, value in strategy.iteritems(): print key, for entry in value: print entry, print "" # Right's strategy: How many moves would it take for right to get to a node labelled sys.maxint? if winner == 'Right': updated = collections.deque() append_to_updated = updated.append for key, value in strategy.iteritems(): row = [0]*right.number_of_nodes() # best case: 0 moves for i in range(0, len(value)): if value[i] == 0: # right would lose at this point append_to_updated(i) row[i] = -1 if value[i] == sys.maxint: # right would win here append_to_updated(i) row[i] = 0 neighbours = collections.deque() append_to_neighbours = neighbours.append # recursively relabel each of the nodes which have a move leaving into i for j in range(0, len(allowed_right)): for k in range(0, len(allowed_right[j])): if allowed_right[j][k] == i: append_to_neighbours(j) get_nbrs(row, set(neighbours), relation_matrix, allowed_right, updated, 1, append_to_updated) # print out the labels print key, for entry in row: print entry, print "" game = []