def setUp(self): G1 = cnlti(nx.grid_2d_graph(2, 2), first_label=0, ordering="sorted") G2 = cnlti(nx.lollipop_graph(3, 3), first_label=4, ordering="sorted") G3 = cnlti(nx.house_graph(), first_label=10, ordering="sorted") self.G = nx.union(G1, G2) self.G = nx.union(self.G, G3) self.DG = nx.DiGraph([(1, 2), (1, 3), (2, 3)]) self.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1) self.gc = [] G = nx.DiGraph() G.add_edges_from([(1, 2), (2, 3), (2, 8), (3, 4), (3, 7), (4, 5), (5, 3), (5, 6), (7, 4), (7, 6), (8, 1), (8, 7)]) C = [[3, 4, 5, 7], [1, 2, 8], [6]] self.gc.append((G, C)) G = nx.DiGraph() G.add_edges_from([(1, 2), (1, 3), (1, 4), (4, 2), (3, 4), (2, 3)]) C = [[2, 3, 4],[1]] self.gc.append((G, C)) G = nx.DiGraph() G.add_edges_from([(1, 2), (2, 3), (3, 2), (2, 1)]) C = [[1, 2, 3]] self.gc.append((G,C)) # Eppstein's tests G = nx.DiGraph({0:[1], 1:[2, 3], 2:[4, 5], 3:[4, 5], 4:[6], 5:[], 6:[]}) C = [[0], [1], [2],[ 3], [4], [5], [6]] self.gc.append((G,C)) G = nx.DiGraph({0:[1], 1:[2, 3, 4], 2:[0, 3], 3:[4], 4:[3]}) C = [[0, 1, 2], [3, 4]] self.gc.append((G, C))
def generate_connection_graph(graph_type, params, count): lower_type = graph_type.lower() if lower_type == 'complete': assert (len(params) == 0) return networkx.complete_graph(count) elif lower_type == 'complete-bipartite': assert (len(params) == 2) assert (int(params[0]) > 0.0) assert (int(params[1]) > 0.0) n1 = int(round(count * float(params[0]) / float(params[1]))) n2 = int(round(count * float(params[1]) / float(params[0]))) n1 = 1 if n1 < 1 else n1 n2 = 1 if n2 < 1 else n2 return networkx.complete_bipartite_graph(n1, n2) elif lower_type == 'circular-ladder': assert (len(params) == 0) return networkx.circular_ladder_graph(count) elif lower_type == 'cycle': assert (len(params) == 0) return networkx.cycle_graph(count) elif lower_type == 'periodic-2grid': assert (len(params) == 2) assert (int(params[0]) > 0.0) assert (int(params[1]) > 0.0) width = int(round(math.sqrt(count * float(params[0]) / float(params[1])))) height = int(round(math.sqrt(count * float(params[1]) / float(params[0])))) width = 1 if width < 1 else width height = 1 if height < 1 else height return networkx.grid_2d_graph(width, height, True) elif lower_type == 'nonperiodic-2grid': assert (len(params) == 2) assert (int(params[0]) > 0.0) assert (int(params[1]) > 0.0) width = int(round(math.sqrt(count * float(params[0]) / float(params[1])))) height = int(round(math.sqrt(count * float(params[1]) / float(params[0])))) width = 1 if width < 1 else width height = 1 if height < 1 else height return networkx.grid_2d_graph(width, height, False) elif lower_type == 'hypercube': assert (len(params) == 0) return networkx.hypercube_graph(int(round(math.log(count, 2)))) elif lower_type == 'star': assert (len(params) == 0) return networkx.star_graph(count - 1) elif lower_type == 'wheel': assert (len(params) == 0) return networkx.wheel_graph(count) elif lower_type == 'erdos-reyni': assert (len(params) == 1) return networkx.erdos_renyi_graph(count, float(params[0])) elif lower_type == 'watts-strogatz': assert (len(params) == 2) if int(params[0]) >= count / 2: k = int(count / 2 - 1) else: k = int(params[0]) return networkx.connected_watts_strogatz_graph(count, k, int(params[1])) else: print "Unknown graph type {}".format(lower_type) assert False
def setUp(self): G1=cnlti(nx.grid_2d_graph(2,2),first_label=0,ordering="sorted") G2=cnlti(nx.lollipop_graph(3,3),first_label=4,ordering="sorted") G3=cnlti(nx.house_graph(),first_label=10,ordering="sorted") self.G=nx.union(G1,G2) self.G=nx.union(self.G,G3) self.DG=nx.DiGraph([(1,2),(1,3),(2,3)]) self.grid=cnlti(nx.grid_2d_graph(4,4),first_label=1)
def test_node_input(self): G = nx.grid_2d_graph(4, 2, periodic=True) H = nx.grid_2d_graph(range(4), range(2), periodic=True) assert_true(nx.is_isomorphic(H, G)) H = nx.grid_2d_graph("abcd", "ef", periodic=True) assert_true(nx.is_isomorphic(H, G)) G = nx.grid_2d_graph(5, 6) H = nx.grid_2d_graph(range(5), range(6)) assert_edges_equal(H, G)
def test_periodic(self): G = nx.grid_2d_graph(0, 0, periodic=True) assert_equal(dict(G.degree()), {}) for m, n, H in [(2, 2, nx.cycle_graph(4)), (1, 7, nx.cycle_graph(7)), (7, 1, nx.cycle_graph(7)), (2, 5, nx.circular_ladder_graph(5)), (5, 2, nx.circular_ladder_graph(5)), (2, 4, nx.cubical_graph()), (4, 2, nx.cubical_graph())]: G = nx.grid_2d_graph(m, n, periodic=True) assert_true(nx.could_be_isomorphic(G, H))
def __init__(self, input, theta=0.3, threshold=0.1): self.input = input self.shape = self.input.shape self.theta = theta self.threshold = threshold self.visible = nx.grid_2d_graph(self.shape[0], self.shape[1]) self.hidden = nx.grid_2d_graph(self.shape[0], self.shape[1]) for n in self.nodes(): self.visible[n]['value'] = self.input[n[0], n[1]] f = lambda: np.array([1.0, 1.0]) self.hidden[n]['messages'] = defaultdict(f)
def build_grid(n, m, l=1): """ See Random planar graphs and the London street network by A.P. Masuccia, D. Smith, A. Crooks, and M. Batty for further information. """ result = networkx.grid_2d_graph(n, n) for a in result.nodes(): result.node[a]['pos'] = (l * a[0], l * a[1]) for e in result.edges(): result.edge[e[0]][e[1]]['weight'] = l for i in range(m): e = choice(result.edges()) sigma = result.edge[e[0]][e[1]]['weight'] apos = ( (result.node[e[0]]['pos'][0] + result.node[e[1]]['pos'][0]) / 2, (result.node[e[0]]['pos'][1] + result.node[e[1]]['pos'][1]) / 2 ) a = result.number_of_nodes() bpos = ( apos[0] + (result.node[e[0]]['pos'][1] - result.node[e[1]]['pos'][1]) / 3, apos[1] + (result.node[e[0]]['pos'][0] - result.node[e[1]]['pos'][0]) / 3 ) result.add_node(a, pos=apos) result.add_node(a + 1, pos=bpos) result.add_edge(a, a + 1, weight=sigma / 3) result.add_edge(e[0], a, weight=sigma / 2) result.add_edge(e[1], a, weight=sigma / 2) result.remove_edge(e[0], e[1]) return result
def makeCCGraph_grid2d(self): """Make 2D grid Capacity Constrained Graph""" if (self.seed != None): random.seed(self.seed) self.G = nx.grid_2d_graph(self.graph_shape[0],self.graph_shape[1]) self.makeCCNodes() self.makeCCEdges()
def test_shortest_simple_paths(): G = cnlti(nx.grid_2d_graph(4, 4), first_label=1, ordering="sorted") paths = nx.shortest_simple_paths(G, 1, 12) assert_equal(next(paths), [1, 2, 3, 4, 8, 12]) assert_equal(next(paths), [1, 5, 6, 7, 8, 12]) assert_equal([len(path) for path in nx.shortest_simple_paths(G, 1, 12)], sorted([len(path) for path in nx.all_simple_paths(G, 1, 12)]))
def simulate(): data = get_data() adjacency = data["adjacency"] t = 10 t_f = 100 t = np.linspace(0, t, num=t_f).astype(np.float32) # a = 0. # b = 100. # r = np.array([ # [a, 0.], # [a+2.,0.], # ]) # v = np.array([ # [0.,10.], # [0., -10.], # ]) # # w = np.array([ # [0,1], # [1,0] # ]).astype(np.float32) n = 5 G = nx.grid_2d_graph(n,n) N = 25 w = nx.to_numpy_matrix(G)*10 r = np.random.rand(N,3) d = r.shape[-1] v = r*0. k=1. return sim_particles(t,r,v,w)
def grid_2d(dim): """Creates a 2d grid of dimension dim""" graph = nx.grid_2d_graph(dim, dim) for node in graph: graph.node[node]['asn'] = 1 graph.node[node]['x'] = node[0] * 150 graph.node[node]['y'] = node[1] * 150 graph.node[node]['device_type'] = 'router' graph.node[node]['platform'] = 'cisco' graph.node[node]['syntax'] = 'ios_xr' graph.node[node]['host'] = 'internal' graph.node[node]['ibgp_role'] = "Peer" mapping = {node: "%s_%s" % (node[0], node[1]) for node in graph} # Networkx wipes data if remap with same labels nx.relabel_nodes(graph, mapping, copy=False) for src, dst in graph.edges(): graph[src][dst]['type'] = "physical" # add global index for sorting SETTINGS['General']['deploy'] = True SETTINGS['Deploy Hosts']['internal'] = { 'cisco': { 'deploy': True, }, } return graph
def test_networkx(self): try: import networkx as nx except ImportError: return try: if nx.__version__[0] == "1": # for NetworkX version 1.x GraphSet.converters['to_graph'] = nx.Graph GraphSet.converters['to_edges'] = nx.Graph.edges else: # for NetworkX version 2.x GraphSet.converters['to_graph'] = nx.from_edgelist GraphSet.converters['to_edges'] = nx.to_edgelist g = nx.grid_2d_graph(3, 3) GraphSet.set_universe(g) g = GraphSet.universe() self.assertTrue(isinstance(g, nx.Graph)) self.assertEqual(len(g.edges()), 12) v00, v01, v10 = (0,0), (0,1), (1,0) e1, e2 = (v00, v01), (v00, v10) gs = GraphSet([nx.Graph([e1])]) self.assertEqual(len(gs), 1) g = gs.pop() self.assertEqual(len(gs), 0) self.assertTrue(isinstance(g, nx.Graph)) self.assertTrue(list(g.edges()) == [(v00, v01)] or list(g.edges()) == [(v01, v00)]) gs.add(nx.Graph([e2])) self.assertEqual(len(gs), 1) except: raise finally: GraphSet.converters['to_graph'] = lambda edges: edges GraphSet.converters['to_edges'] = lambda graph: graph
def grid_2d(dim): import networkx as nx graph = nx.grid_2d_graph(dim, dim) for n in graph: graph.node[n]['asn'] = 1 graph.node[n]['x'] = n[0] * 150 graph.node[n]['y'] = n[1] * 150 graph.node[n]['device_type'] = 'router' graph.node[n]['platform'] = 'cisco' graph.node[n]['syntax'] = 'ios_xr' graph.node[n]['host'] = 'internal' graph.node[n]['ibgp_level'] = 0 mapping = {n: "%s_%s" % (n[0], n[1]) for n in graph} nx.relabel_nodes(graph, mapping, copy=False) # Networkx wipes data if remap with same labels for index, (src, dst) in enumerate(graph.edges()): graph[src][dst]['type'] = "physical" graph[src][dst]['edge_id'] = "%s_%s_%s" % (index, src, dst) # add global index for sorting SETTINGS['General']['deploy'] = True SETTINGS['Deploy Hosts']['internal'] = { 'cisco': { 'deploy': True, }, } return graph
def test_dijkstra_predecessor(self): G = nx.path_graph(4) assert_equal( nx.dijkstra_predecessor_and_distance(G, 0), ({0: [], 1: [0], 2: [1], 3: [2]}, {0: 0, 1: 1, 2: 2, 3: 3}) ) G = nx.grid_2d_graph(2, 2) pred, dist = nx.dijkstra_predecessor_and_distance(G, (0, 0)) assert_equal( sorted(pred.items()), [((0, 0), []), ((0, 1), [(0, 0)]), ((1, 0), [(0, 0)]), ((1, 1), [(0, 1), (1, 0)])] ) assert_equal(sorted(dist.items()), [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 2)]) XG = nx.DiGraph() XG.add_weighted_edges_from( [ ("s", "u", 10), ("s", "x", 5), ("u", "v", 1), ("u", "x", 2), ("v", "y", 1), ("x", "u", 3), ("x", "v", 5), ("x", "y", 2), ("y", "s", 7), ("y", "v", 6), ] ) (P, D) = nx.dijkstra_predecessor_and_distance(XG, "s") assert_equal(P["v"], ["u"]) assert_equal(D["v"], 9)
def get_graph(self): lattice_coord_num = 4 side_length = 0 # The lattice size should be a perfect square, ideally, and is sqrt(population size) l = m.sqrt(self.simconfig.popsize) # get the fractional part of the result, because sqrt always returns a float, even if the number is technically an integer # so we have to test the fractional part, not check python types frac, integral = m.modf(l) if frac == 0.0: log.debug("Lattice model: popsize %s, lattice will be %s by %s", self.simconfig.popsize, l, l) side_length = int(l) else: log.error("Lattice model: population size %s is not a perfect square", self.simconfig.popsize) exit(1) if self.simconfig.periodic == 1: p = True log.debug("periodic boundary condition selected") else: p = False model = nx.grid_2d_graph(side_length, side_length, periodic=p) # now convert the resulting graph to have simple nodenames to use as keys # We need to retain the original nodenames, because they're tuples which represent the position # of the node in the lattice. So we first store them as attribution 'pos' and then convert for nodename in model.nodes(): model.node[nodename]['pos'] = nodename g = nx.convert_node_labels_to_integers(model) return g
def generate_graph(type = 'PL', n = 100, seed = 1.0, parameter = 2.1): if type == 'ER': G = nx.erdos_renyi_graph(n, p=parameter, seed=seed, directed=True) G = nx.DiGraph(G) G.remove_edges_from(G.selfloop_edges()) elif type == 'PL': z = nx.utils.create_degree_sequence(n, nx.utils.powerlaw_sequence, exponent = parameter) while not nx.is_valid_degree_sequence(z): z = nx.utils.create_degree_sequence(n, nx.utils.powerlaw_sequence, exponent = parameter) G = nx.configuration_model(z) G = nx.DiGraph(G) G.remove_edges_from(G.selfloop_edges()) elif type == 'BA': G = nx.barabasi_albert_graph(n, 3, seed=None) G = nx.DiGraph(G) elif type == 'grid': G = nx.grid_2d_graph(int(np.ceil(np.sqrt(n))), int(np.ceil(np.sqrt(n)))) G = nx.DiGraph(G) elif type in ['facebook', 'enron', 'twitter', 'students', 'tumblr', 'facebookBig']: #print 'start reading' #_, G, _, _ = readRealGraph(os.path.join("..","..","Data", type+".txt")) _, G, _, _ = readRealGraph(os.path.join("..","Data", type+".txt")) print 'size of graph', G.number_of_nodes() #Gcc = sorted(nx.connected_component_subgraphs(G.to_undirected()), key = len, reverse=True) #print Gcc[0].number_of_nodes() #print 'num of connected components', len(sorted(nx.connected_component_subgraphs(G.to_undirected()), key = len, reverse=True)) #exit() if G.number_of_nodes() > n: G = getSubgraph(G, n) #G = getSubgraphSimulation(G, n, infP = 0.3) #nx.draw(G) #plt.show() return G
def grid_2d(dim): """Creates a 2d grid of dimension dim""" graph = nx.grid_2d_graph(dim, dim) for node in graph: graph.node[node]["asn"] = 1 graph.node[node]["x"] = node[0] * 150 graph.node[node]["y"] = node[1] * 150 graph.node[node]["device_type"] = "router" graph.node[node]["platform"] = "cisco" graph.node[node]["syntax"] = "ios_xr" graph.node[node]["host"] = "internal" graph.node[node]["ibgp_role"] = "Peer" mapping = {node: "%s_%s" % (node[0], node[1]) for node in graph} # Networkx wipes data if remap with same labels nx.relabel_nodes(graph, mapping, copy=False) for src, dst in graph.edges(): graph[src][dst]["type"] = "physical" # add global index for sorting SETTINGS["General"]["deploy"] = True SETTINGS["Deploy Hosts"]["internal"] = {"cisco": {"deploy": True}} return graph
def run_with_q(q): G = nx.grid_2d_graph(N,N) # draw_lattice(G) # Generate traits traits = {} for node in G: trait_values = [] for i in range(F): trait_values.append(random.randint(1,q)) traits[node] = trait_values nx.set_node_attributes(G, 'traits', traits) edges = G.edges() potential_edges = get_potential_edges(G, edges) #print len(potential_edges) reached_stationary = False while not reached_stationary: run_cycle(G,potential_edges) if (len(potential_edges) == 0): reached_stationary = True #else: #print('Still %d more potential edges '% (len(potential_edges))) result = get_cultural_domains(G) print result #print potential_edges draw_lattice(G,q) return result['percentage']
def test_others(self): (P, D) = nx.bellman_ford(self.XG, 's') assert_equal(P['v'], 'u') assert_equal(D['v'], 9) (P, D) = nx.goldberg_radzik(self.XG, 's') assert_equal(P['v'], 'u') assert_equal(D['v'], 9) G = nx.path_graph(4) assert_equal(nx.bellman_ford(G, 0), ({0: None, 1: 0, 2: 1, 3: 2}, {0: 0, 1: 1, 2: 2, 3: 3})) assert_equal(nx.goldberg_radzik(G, 0), ({0: None, 1: 0, 2: 1, 3: 2}, {0: 0, 1: 1, 2: 2, 3: 3})) assert_equal(nx.bellman_ford(G, 3), ({0: 1, 1: 2, 2: 3, 3: None}, {0: 3, 1: 2, 2: 1, 3: 0})) assert_equal(nx.goldberg_radzik(G, 3), ({0: 1, 1: 2, 2: 3, 3: None}, {0: 3, 1: 2, 2: 1, 3: 0})) G = nx.grid_2d_graph(2, 2) pred, dist = nx.bellman_ford(G, (0, 0)) assert_equal(sorted(pred.items()), [((0, 0), None), ((0, 1), (0, 0)), ((1, 0), (0, 0)), ((1, 1), (0, 1))]) assert_equal(sorted(dist.items()), [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 2)]) pred, dist = nx.goldberg_radzik(G, (0, 0)) assert_equal(sorted(pred.items()), [((0, 0), None), ((0, 1), (0, 0)), ((1, 0), (0, 0)), ((1, 1), (0, 1))]) assert_equal(sorted(dist.items()), [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 2)])
def spanning_2d_grid(length): """ Generate a square lattice with auxiliary nodes for spanning detection Parameters ---------- length : int Number of nodes in one dimension, excluding the auxiliary nodes. Returns ------- networkx.Graph A square lattice graph with auxiliary nodes for spanning cluster detection See Also -------- sample_states : spanning cluster detection """ ret = nx.grid_2d_graph(length + 2, length) for i in range(length): # side 0 ret.node[(0, i)]['span'] = 0 ret[(0, i)][(1, i)]['span'] = 0 # side 1 ret.node[(length + 1, i)]['span'] = 1 ret[(length + 1, i)][(length, i)]['span'] = 1 return ret
def test_large(self): try: import networkx as nx except ImportError: return try: GraphSet.converters['to_graph'] = nx.Graph GraphSet.converters['to_edges'] = nx.Graph.edges g = nx.grid_2d_graph(8, 8) v00, v01, v10 = (0,0), (0,1), (1,0) GraphSet.set_universe(g) self.assertEqual(len(GraphSet.universe().edges()), 112) # self.assertEqual(GraphSet.universe().edges()[:2], [(v00, v01), (v00, v10)]) gs = GraphSet({}); gs -= GraphSet([nx.Graph([(v00, v01)]), nx.Graph([(v00, v01), (v00, v10)])]) self.assertEqual(gs.len(), 5192296858534827628530496329220094) i = 0 for g in gs: if i > 100: break i += 1 paths = GraphSet.paths((0, 0), (7, 7)) self.assertEqual(len(paths), 789360053252) except: raise finally: GraphSet.converters['to_graph'] = lambda edges: edges GraphSet.converters['to_edges'] = lambda graph: graph
def topologyInit(N, choice, Beta): '''Initializes a grid with N nodes distributed evenly on the map. The map-file is files/Grid.xyz. The procedure evaluates the best possible coarsness to fit the desired number of nodes. Generates the full grid, associates height and position to the nodes and removes the node from the grid if it has 0 height. It then associates a weight with every link proportinal to 1+|Delta H|^(-40/13) Finally the resulting grid is out''' FRACTION=0.2796296296296296 M=mapInfo("files/Grid.xyz") coarsnes = int(((float(N)/FRACTION)/(WIDTH*HEIGHT))**(0.5)) print "Coarsness is : " + str(coarsnes) G = nx.grid_2d_graph(WIDTH*coarsnes, HEIGHT*coarsnes, True) listOfNodes = G.nodes() totalNum = len(listOfNodes) listOfPositions = M.getAll3dPos(G, coarsnes) listofGPS=[[element[0],element[1]] for element in listOfPositions] listOfHeights=[element[2] for element in listOfPositions] for i,x in enumerate(sorted(sorted(listOfNodes, key=itemgetter(0)), key=itemgetter(1), reverse=True)): G.node[x]['position']=listofGPS[i] G.node[x]['height']=listOfHeights[i] nodeColor=[] listOfNodes=[x for x in listOfNodes if float(G.node[x]['height']) == 0] G.remove_nodes_from(listOfNodes) print "The actual number of agents in this simulation will be " + str(len(G.nodes())) if choice == WEIGHTED: for edge in G.edges(): G[edge[0]][edge[1]]['weight'] = 2.7**(-Beta*abs(G.node[edge[0]]['height'] - G.node[edge[1]]['height'])) if DEBUG: print G[edge[0]][edge[1]]['weight'] #print str(edge) + "\t" + str(G[edge[0]][edge[1]]['weight']) + str(G.node[edge[0]]['height']) + "\t" + str(G.node[edge[1]]['height']) else: for edge in G.edges(): G[edge[0]][edge[1]]['weight']=1 print "the number of edges in this simulation will be " + str(len(G.edges())) for x in G.nodes(): nodeColor.append(int(G.node[x]['height'])) #target = open("node_height", "w") #for x in range(len(nodeColor)): # target.write(str(x)+"\t"+str(nodeColor[x])+"\n") if SHOW == 1: fig=plt.figure() elarge=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] >=0.05] esmall=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] <0.05] nx.draw_networkx_edges(G, pos={i:i for i in G.nodes()}, edgelist=elarge, width=2) nx.draw_networkx_edges(G, pos={i:i for i in G.nodes()}, edgelist=esmall, width=2, alpha=0.5,edge_color='b',style='dashed') nx.draw_networkx_nodes(G, pos={i:i for i in G.nodes()}, node_color=nodeColor, node_cmap=plt.cm.summer, node_size=20) plt.xlabel('X_grid identifier') plt.ylabel('Y_grid identifier') plt.title('The grid\nGenerated on the basis of given DEM') plt.show() # display return G
def ex_1(): '''Example 1 of the paper. A 2-by-20 grid with reflecting boundary condition and an obstacle in the middle. ''' N = 20 G = nx.grid_2d_graph(N,N) n_middle = (N/2, N/2) # Add reflecting boundary condition for i,j in G: if i == 0 or i == N-1 or j == 0 or j == N-1: G.add_edge((i,j), (i,j)) # Remove edges of the node at the middle # (keep one edge, to simplify the bookiping for u,v in sorted(G.edges(n_middle))[:-1]: G.add_edge(v,v) # Add self loop G.remove_edge(u, v) T, _ = get_T(G) savemat('vf_ex1', {'T':T}, oned_as='column') return G
def er_network(p=0.5): G = nx.grid_2d_graph(11, 11) for u in G.nodes(): for v in G.nodes(): if u == nest and v == target: continue if v == nest and u == target: continue if u != v: if random() <= p: G.add_edge(u, v) else: if G.has_edge(u, v): G.remove_edge(u, v) if not nx.has_path(G, nest, target): return None short_path = nx.shortest_path(G, nest, target) if len(short_path) <= 3: return None #print short_path idx = choice(range(1, len(short_path) - 1)) #print idx G.remove_edge(short_path[idx], short_path[idx + 1]) for i in xrange(idx): P.append((short_path[i], short_path[i + 1])) for i in xrange(idx + 1, len(short_path) - 1): P.append((short_path[i], short_path[i + 1])) #print P if not nx.has_path(G, nest, target): return None for i,u in enumerate(G.nodes_iter()): M[i] = u Minv[u] = i pos[u] = [u[0],u[1]] # position is the same as the label. if (u[0] == nest) or (u == target): node_size.append(100) node_color.append('r') else: node_size.append(10) node_color.append('k') for u,v in G.edges_iter(): G[u][v]['weight'] = MIN_PHEROMONE if (u, v) in P or (v, u) in P: edge_color.append('g') edge_width.append(10) else: edge_color.append('k') edge_width.append(1) for i, (u,v) in enumerate(G.edges()): Ninv[(u, v)] = i N[i] = (u, v) Ninv[(v, u)] = i return G
def test_bellman_ford(self): # single node graph G = nx.DiGraph() G.add_node(0) assert_equal(nx.bellman_ford(G, 0), ({0: None}, {0: 0})) assert_raises(KeyError, nx.bellman_ford, G, 1) # negative weight cycle G = nx.cycle_graph(5, create_using=nx.DiGraph()) G.add_edge(1, 2, weight=-7) for i in range(5): assert_raises(nx.NetworkXUnbounded, nx.bellman_ford, G, i) G = nx.cycle_graph(5) # undirected Graph G.add_edge(1, 2, weight=-3) for i in range(5): assert_raises(nx.NetworkXUnbounded, nx.bellman_ford, G, i) # no negative cycle but negative weight G = nx.cycle_graph(5, create_using=nx.DiGraph()) G.add_edge(1, 2, weight=-3) assert_equal(nx.bellman_ford(G, 0), ({0: None, 1: 0, 2: 1, 3: 2, 4: 3}, {0: 0, 1: 1, 2: -2, 3: -1, 4: 0})) # not connected G = nx.complete_graph(6) G.add_edge(10, 11) G.add_edge(10, 12) assert_equal( nx.bellman_ford(G, 0), ({0: None, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0}, {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}) ) # not connected, with a component not containing the source that # contains a negative cost cycle. G = nx.complete_graph(6) G.add_edges_from([("A", "B", {"load": 3}), ("B", "C", {"load": -10}), ("C", "A", {"load": 2})]) assert_equal( nx.bellman_ford(G, 0, weight="load"), ({0: None, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0}, {0: 0, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}), ) # multigraph P, D = nx.bellman_ford(self.MXG, "s") assert_equal(P["v"], "u") assert_equal(D["v"], 9) P, D = nx.bellman_ford(self.MXG4, 0) assert_equal(P[2], 1) assert_equal(D[2], 4) # other tests (P, D) = nx.bellman_ford(self.XG, "s") assert_equal(P["v"], "u") assert_equal(D["v"], 9) G = nx.path_graph(4) assert_equal(nx.bellman_ford(G, 0), ({0: None, 1: 0, 2: 1, 3: 2}, {0: 0, 1: 1, 2: 2, 3: 3})) assert_equal(nx.bellman_ford(G, 3), ({0: 1, 1: 2, 2: 3, 3: None}, {0: 3, 1: 2, 2: 1, 3: 0})) G = nx.grid_2d_graph(2, 2) pred, dist = nx.bellman_ford(G, (0, 0)) assert_equal(sorted(pred.items()), [((0, 0), None), ((0, 1), (0, 0)), ((1, 0), (0, 0)), ((1, 1), (0, 1))]) assert_equal(sorted(dist.items()), [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 2)])
def gen_grid_graph(i): """ Generate a grid graph with about 2**i nodes. """ n = 2**i sn = int(n**(1/2)) # Redefine amount of nodes: return nx.grid_2d_graph(sn,sn)
def test_2d_grid_graph(): # FC article claims 2d grid graph of size n is (3,3)-connected # and (5,9)-connected, but I don't think it is (5,9)-connected G=nx.grid_2d_graph(8,8,periodic=True) assert_true(nx.is_kl_connected(G,3,3)) assert_false(nx.is_kl_connected(G,5,9)) (H,graphOK)=nx.kl_connected_subgraph(G,5,9,same_as_graph=True) assert_false(graphOK)
def test_grid(self): "Approximate current-flow betweenness centrality: 2d grid" G=nx.grid_2d_graph(4,4) b=nx.current_flow_betweenness_centrality(G,normalized=True) epsilon=0.1 ba = approximate_cfbc(G,normalized=True, epsilon=0.5*epsilon) for n in sorted(G): assert_allclose(b[n],ba[n],atol=epsilon)
def __grid_layout__(width, height): # Construct the width + 1 by height + 1 grid with directed edges. G = nx.grid_2d_graph(width + 1, height + 1) G = nx.DiGraph(G) pos = nx.spectral_layout(G) return (G, pos)
def test_predecessor(self): G=nx.path_graph(4) assert_equal(nx.predecessor(G,0),{0: [], 1: [0], 2: [1], 3: [2]}) assert_equal(nx.predecessor(G,0,3),[2]) G=nx.grid_2d_graph(2,2) assert_equal(sorted(nx.predecessor(G,(0,0)).items()), [((0, 0), []), ((0, 1), [(0, 0)]), ((1, 0), [(0, 0)]), ((1, 1), [(0, 1), (1, 0)])])
def __init__(self, agents, width, height): super().__init__(agents) if len(agents) > width * height: raise Exception('there must be enough space for all agents') # seutp grid self.space = nx.grid_2d_graph(width, height) # place agents positions = self.space.nodes() random.shuffle(positions) for agent in self.agents: pos = positions.pop() self.sync(self.place(agent, pos)) # setup vacant positions for pos in positions: self.space.node[pos] = {'agent': None}
def ttrestore(self, entry): player_loc_0, player_loc_1, horizontal_walls, vertical_walls, wall_counts, terminal, index, nplayer = entry self.graph = nx.grid_2d_graph(self.size, self.size) self.players_loc[0] = np.array(player_loc_0) self.players_loc[1] = np.array(player_loc_1) self.horizontal_walls = set(horizontal_walls) self.vertical_walls = set(vertical_walls) for (x, y) in horizontal_walls: self.graph.remove_edges_from(Game.edges(x, y, HORIZONTAL)) for (x, y) in vertical_walls: self.graph.remove_edges_from(Game.edges(x, y, VERTICAL)) self.wall_counts = list(wall_counts) self.index = index self.terminal = terminal self.nplayer = nplayer self.find_special_edges() self.graph.add_edges_from(self.special_edges)
def truncated_grid_2d_graph(m: int, n: int, t: int = None) -> nx.Graph: """Generate a rectangular grid graph (of width `m` and height `n`), with corners removed. It the truncation `t` is not given, then it is set to half the shortest side (rounded down) truncated_grid_graph(12, 11) returns the topology of Google's bristlecone chip. """ G = nx.grid_2d_graph(m, n) if t is None: t = min(m, n) // 2 for mm in range(t): for nn in range(t - mm): G.remove_node((mm, nn)) G.remove_node((m - mm - 1, nn)) G.remove_node((mm, n - nn - 1)) G.remove_node((m - mm - 1, n - nn - 1)) return G
def test_min_weight_simple_path_greedy(): test_graph = nx.grid_2d_graph(4, 4) test_graph.remove_node((3, 0)) test_graph.remove_node((0, 3)) for e in test_graph.edges: test_graph[e[0]][e[1]]['weight'] = np.random.rand() weights = [w for u, v, w in test_graph.edges.data('weight')] # it better return the lowest weight edge for a path consisting of 2 nodes path = min_weight_simple_path_greedy(test_graph, 2) assert path_weight(test_graph, path) == min(weights) # it should return simple paths path = min_weight_simple_path_greedy(test_graph, 5) assert nx.is_simple_path(test_graph, path) # there should not exist a simple path of 14 nodes assert min_weight_simple_path_greedy(test_graph, 14) is None
def torus_graph(N): G=nx.grid_2d_graph(int(N**(1/2)),int(N**(1/2)),periodic=True,create_using=None) for i in G.nodes(): #for each agent # east, west, north, south lst=[i[0]+1,i[0]-1,i[1]+1,i[1]-1] #get a list of the grid neighbor indices for n,j in enumerate(lst): # n is the index "index" j is the index itself # if the index is outside of the range of possible values if j==-1: lst[n]=max(G.nodes())[0] # connect the most southern (?) node with the most northern (?) if j==max(G.nodes())[0]+1: lst[n]=0 # or connect the most northern (?) node to the most southern (?) nneigh=[(lst[1],lst[2]),(lst[0],lst[2])] # list of two tuples, one for each neighbor, change only the northern neighbors for k in nneigh: G.add_edge(i,k) if N <= 100: G=nx.relabel_nodes(G,dict(zip(G.nodes(),[j[0]*10 + j[1] for j in [list(i) for i in G.nodes()]])),copy=False) # the mapping here makes sure that nodes get assigned an integer label that corresponds to their original # positioning tuple (i.e. (3,4) becomes 34) else: G=nx.convert_node_labels_to_integers(G) return(G)
def grid_r(N, M, p): ''' N - height M - width p - rewiring rate ''' g = nx.grid_2d_graph(N, M, periodic=True, create_using=None) g.graph['N'] = N g.graph['M'] = M g.graph['p'] = p for e in g.edges: if random.random() <= p: g.remove_edge(e[0], e[1]) v = random.choice(list(g.nodes())) g.add_edge(e[0], v) return g
def define_grid_graph( N: int = 3, M: int = 3, mapping: dict = DEFAULT_MAP, refSpeed: dict = DEFAULT_SPD, sensors: tuple = SENSORS, selfishness: float = 0.5, ) -> nx.Graph: """ Creates a grid graph for the control algorithm :param N: row number, defaults to 3 :type N: int, optional :param M: column number, defaults to 3 :type M: int, optional :param mapping: mapping option to match symuvia, defaults to DEFAULT_MAP :type mapping: dict, optional :param refSpeed: Individual speed reference per zone :type refSpeed: dict, optional :param selfishness: Weight for self control action cooperative action is then weighted as (1- selfishness) :type selfishness: dict, optional :return: tuple with :rtype: tuple """ # Creating cyclic graph G = nx.grid_2d_graph(N, M) # Adding attributes to graph G.graph["self"] = selfishness # Relabeling nodes mapping = dict(zip(G.nodes(), sensors)) # Explicit G = nx.relabel_nodes(G, mapping) # Set reference speed on node nx.set_node_attributes(G, refSpeed, "freeFlowSpeed") # Plot graph # nx.draw(G, node_color="#A0CBE2", with_labels=True) return G
def draw_grid(n,X): #Draw an n x n grid with edges / nodes from X in red G = nx.grid_2d_graph(n+1,n+1) set_node_colors(G,G.nodes(),'k') set_edge_colors(G,G.edges(),'k') set_edge_weights(G,G.edges(),0.5) set_node_colors(G,edge_subgraph_nodes(X),'r') set_edge_colors(G,X,'r') set_edge_weights(G,X,1) nc = [G.node[n]['color'] for n in G.nodes()] ec = [G[i][j]['color'] for i,j in G.edges()] w = [G[i][j]['weight'] for i,j in G.edges()] nx.draw(G,grid_positions(G,2),node_size=0.5,width=w,node_color=nc,edge_color=ec)
def generate_2D_graph(n, coef_suppr=False, show=False): graph = nx.grid_2d_graph(n, n) # n x n grid if coef_suppr != False: nb_suppr = int(len(list(graph.nodes)) * coef_suppr) random_edge(graph, nb_suppr, delete=True) pos = nx.spring_layout(graph, iterations=100) graph.remove_nodes_from(list(nx.isolates(graph))) graph = graph.to_directed() if show: nx.draw(graph, pos, node_color='b', node_size=20, with_labels=False) plt.title("Road network") plt.show() return graph
def test_get_all_hardware_grid_problems(): device_graph = nx.grid_2d_graph(3, 3) device_graph = nx.relabel_nodes(device_graph, mapping={(r, c): cirq.GridQubit(r, c) for r, c in device_graph.nodes}) problems = get_all_hardware_grid_problems(device_graph, central_qubit=cirq.GridQubit( 1, 1), n_instances=3, rs=np.random.RandomState(52)) keys_should_be = [(n, i) for n in range(2, 9 + 1) for i in range(3)] assert list(problems.keys()) == keys_should_be for (n, i), v in problems.items(): assert isinstance(v, HardwareGridProblem) assert len(v.graph.nodes) == n assert len(v.coordinates) == n for r, c in v.coordinates: assert 0 <= r < 3 assert 0 <= c < 3
def schelling_model(grid_source, threshold, iterations): """ Shows schelling model """ # get max rows and columns from the input grid numrows = len(grid_source) numcols = len(grid_source[0]) # create grid G = nx.grid_2d_graph(numrows, numcols) # map nodes to grid for i, j in G.nodes(): G.nodes[(i, j)]['type'] = grid_source[i][j] # add diagonal edges for ((x, y), d) in G.nodes(data=True): if (x + 1 <= numcols - 1) and (y + 1 <= numrows - 1): G.add_edge((x, y), (x + 1, y + 1)) for ((x, y), d) in G.nodes(data=True): if (x + 1 <= numcols - 1) and (y - 1 >= 0): G.add_edge((x, y), (x + 1, y - 1)) # display initial graph display_graph(G, 'Initial Grid (Please close to continue)') # get boundary and internal nodes boundary_nodes_list = get_boundary_nodes(G, numrows, numcols) internal_nodes_list = list(set(G.nodes()) - set(boundary_nodes_list)) # make calculations according to threshold # accuracy is based on the number of iterations logger.info("Starting Calculations") for i in range(int(iterations)): # get list of unsatisfied nodes first unsatisfied_nodes_list = get_unsatisfied_nodes_list( G, internal_nodes_list, boundary_nodes_list, threshold, numrows, numcols) logger.info("iteration: {}".format(i)) # move an unsatisfied node to an empty cell empty_cells = [n for (n, d) in G.nodes(data=True) if d['type'] == ' '] make_node_satisfied(G, unsatisfied_nodes_list, empty_cells) # display final graph display_graph(G, 'Schelling model Implemented') logger.info("Schelling model Complete")
def generate_grid(m, n, same_weight=None): G = nx.grid_2d_graph(m, n) grid = nx.DiGraph() for e1, e2 in G.edges(): # rand_num = 0.0 # while rand_num == 0.0: # rand_num = random.random() if same_weight is not None: weight = same_weight else: rand_num = random.uniform(1, 2) weight = round(rand_num, 2) grid.add_edge(e1, e2, weight=weight) grid.add_edge(e2, e1, weight=weight) return grid
def generate_squarenoc(orderx=3, ordery=None, with_ipcore=False): """ NoC generator helper: generates a 2D grid NoC object Arguments * orderx: optional X-axis length of the grid. By default build a 3x3 square grid. * ordery: optional Y-axis length of the grid. By default build a square grid of order "orderx". This argument is used to build rectangular grids. * with_ipcore: If True, add ipcores to routers automatically. """ if ordery == None: ordery = orderx # 1. generate a 2d grid basegrid = nx.grid_2d_graph(orderx, ordery) # 2. convert to a graph with ints as nodes convgrid = nx.Graph() for n in basegrid.nodes_iter(): n2 = n[0] + n[1] * orderx convgrid.add_node(n2, coord_x=n[0], coord_y=n[1]) for e in basegrid.edges_iter(): e1 = e[0][0] + e[0][1] * orderx e2 = e[1][0] + e[1][1] * orderx convgrid.add_edge(e1, e2) nocbase = noc(name="NoC grid %dx%d" % (orderx, ordery), data=convgrid) # 2. for each node add router object for n in nocbase.nodes_iter(): cx = nocbase.node[n]["coord_x"] cy = nocbase.node[n]["coord_y"] r = nocbase._add_router_from_node(n, coord_x=cx, coord_y=cy) if with_ipcore: nocbase.add_ipcore(r) # 3. for each edge add channel object for e in nocbase.edges_iter(): nocbase._add_channel_from_edge(e) return nocbase
def get_rand_weight(YP, Y): G = nx.grid_2d_graph(SIZE[0], SIZE[1]) nlabels_dict = dict() for u, v, d in G.edges(data=True): if u[0] == v[0]: #vertical, dy, channel 0 channel = 0 if u[1] == v[1]: #horizontal, dy, channel 1 channel = 1 d['weight'] = (YP[0, u[0], u[1], 0] + YP[0, v[0], v[1], 0]) / 2.0 nlabels_dict[u] = Y[0, u[0], u[1], 0] nlabels_dict[v] = Y[0, v[0], v[1], 0] [posCounts, negCounts, mstEdges, totalPos, totalNeg] = ev.FindRandCounts(G, nlabels_dict) posError = totalPos negError = 0.0 WY = np.zeros((1, SIZE[0], SIZE[1], 1), np.single) SY = np.zeros((1, SIZE[0], SIZE[1], 1), np.single) for i in range(len(posCounts)): posError = posError - posCounts[i] negError = negError + negCounts[i] WS = posError - negError (u, v) = mstEdges[i] if u[0] == v[0]: #vertical, dy, channel 0 channel = 0 if u[1] == v[1]: #horizontal, dy, channel 1 channel = 1 WY[0, u[0], u[1], 0] += abs(WS) / 2.0 WY[0, v[0], v[1], 0] += abs(WS) / 2.0 if WS > 0.0: SY[0, u[0], u[1], 0] += 0.5 SY[0, v[0], v[1], 0] += 0.5 if WS < 0.0: SY[0, u[0], u[1], 0] += -0.5 SY[0, v[0], v[1], 0] += -0.5 # Std normalization totalW = np.sum(WY) if totalW != 0.0: WY = np.divide(WY, totalW) #SY = np.divide(SY, np.max(SY)) return [WY, SY]
def get_rand_weight(YP, YN): G = nx.grid_2d_graph(INPUT_SIZE[0], INPUT_SIZE[1]) nlabels_dict = dict() for u, v, d in G.edges(data=True): d['weight'] = (YP[0, u[0], u[1], 0] + YP[0, v[0], v[1], 0]) / 2.0 nlabels_dict[u] = YN[0, u[0], u[1], 0] nlabels_dict[v] = YN[0, v[0], v[1], 0] [posCounts, negCounts, mstEdges, totalPos, totalNeg] = ev.FindRandCounts(G, nlabels_dict) # start off with every point in own cluster posError = totalPos negError = 0.0 WY = np.zeros((1, INPUT_SIZE[0], INPUT_SIZE[1], 1), np.float32) SY = np.zeros((1, INPUT_SIZE[0], INPUT_SIZE[1], 1), np.float32) for i in range(len(posCounts)): posError = posError - posCounts[i] negError = negError + negCounts[i] WS = posError - negError (u, v) = mstEdges[i] WY[0, u[0], u[1], 0] = abs(WS) / 2.0 WY[0, v[0], v[1], 0] = abs(WS) / 2.0 if WS > 0.0: SY[0, u[0], u[1], 0] = 1.0 SY[0, v[0], v[1], 0] = 1.0 if WS < 0.0: SY[0, u[0], u[1], 0] = -1.0 SY[0, v[0], v[1], 0] = -1.0 # Std normalization totalW = np.sum(WY) if totalW != 0.0: WY = np.divide(WY, totalW) return [WY, SY]
def load_data(dataset): """ Load datasets from tkipf/gae input files :param dataset: 'cora', 'citeseer' or 'pubmed' graph dataset. :return: n*n sparse adjacency matrix and n*f node features matrix """ # Load the data: x, tx, allx, graph if dataset == 'karate': graph = nx.karate_club_graph() graph = nx.grid_2d_graph(10, 10) adj = nx.adjacency_matrix(graph) features = sp.eye(*adj.shape) else: names = ['x', 'tx', 'allx', 'graph'] objects = [] for i in range(len(names)): with open("../data/ind.{}.{}".format(dataset, names[i]), 'rb') as f: if sys.version_info > (3, 0): objects.append(pkl.load(f, encoding='latin1')) else: objects.append(pkl.load(f)) x, tx, allx, graph = tuple(objects) test_idx_reorder = parse_index_file( "../data/ind.{}.test.index".format(dataset)) test_idx_range = np.sort(test_idx_reorder) if dataset == 'citeseer': # Fix citeseer dataset (there are some isolated nodes in the graph) # Find isolated nodes, add them as zero-vecs into the right position test_idx_range_full = range(min(test_idx_reorder), max(test_idx_reorder) + 1) tx_extended = sp.lil_matrix((len(test_idx_range_full), x.shape[1])) tx_extended[test_idx_range - min(test_idx_range), :] = tx tx = tx_extended features = sp.vstack((allx, tx)).tolil() features[test_idx_reorder, :] = features[test_idx_range, :] graph = nx.from_dict_of_lists(graph) adj = nx.adjacency_matrix(graph) return adj, features
def test_simple_lattice(): G = nx.grid_2d_graph(10, 10) def oracle(vert): return ((vert[0] < 3) and (vert[1] < 3)) or ((vert[0] > 6) and (vert[1] > 6)) # enum: 638 ms ± 22.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) # moss: 18.1 ms ± 75.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) G_cut = s2(G, oracle, lambda G, U, V: moss(G, U, V)) fig = plt.figure() fig.add_subplot(121).title.set_text('Ground-truth') draw_labeled_graph(G, oracle) fig.add_subplot(122).title.set_text('$S^2$') draw_labeled_graph(G_cut, lambda v: G_cut.node[v].get('label')) plt.show()
def feature_maker(imgs): #expected 4D arrays NxHxWxC X = np.zeros((NUM_SAMPLES, SIZE[0] * (SIZE[0] - 1) * 2, 3), dtype=np.single) G = nx.grid_2d_graph(SIZE[0], SIZE[1]) for i in range(imgs.shape[0]): #for each sample aimg = np.zeros((SIZE[0] * (SIZE[0] - 1) * 2, 3)) for j in range(imgs.shape[-1]): #for each channel img = imgs[i, :, :, j] img = signal.convolve2d(img, np.ones( (KERNEL_SIZE, KERNEL_SIZE)) / 9.0, mode='same', boundary='symm') upto = 0 for (u, v) in G.edges(): aimg[upto][j] = (img[u] + img[v]) / 2.0 upto = upto + 1 X[i, :, :] = aimg return X
def _get_9q_square_qvm(name: str, noisy: bool, connection: ForestConnection = None) -> QuantumComputer: """ A nine-qubit 3x3 square lattice. This uses a "generic" lattice not tied to any specific device. 9 qubits is large enough to do vaguely interesting algorithms and small enough to simulate quickly. :param name: The name of this QVM :param connection: The connection to use to talk to external services :param noisy: Whether to construct a noisy quantum computer :return: A pre-configured QuantumComputer """ topology = nx.convert_node_labels_to_integers(nx.grid_2d_graph(3, 3)) return _get_qvm_with_topology(name=name, connection=connection, topology=topology, noisy=noisy, requires_executable=True)
def cal_cost_with_maxdist(t): conn = db_connection() G = nx.grid_2d_graph(numCells, numCells) for e in G.edges_iter(): if cell_connected(e[0], e[1], conn): G[e[0]][e[1]]['weight'] = 1 else: G[e[0]][e[1]]['weight'] = 10000 print e maxdist = round(maxspeed * 60 / (float(boundary_size) * 111 * 1000 / numCells) * diff_in_min(*t)) matrix = [[0 for i in range(numCells * numCells)] for j in range(numCells * numCells)] for i in G.nodes_iter(): row_index = rowcol_to_index(*i) for j in G.nodes_iter(): col_index = rowcol_to_index(*j) if row_index < col_index: if manhanton(i, j) <= maxdist: matrix[row_index][col_index] = nx.shortest_path_length( G, i, j, 'weight') else: matrix[row_index][col_index] = 10000 print row_index result_folder = folder_check(t) with open(result_folder + '/costlist.txt', 'w') as f: for i in range(numCells * numCells): orowcol = index_to_rowcol(i) for j in range(numCells * numCells): drowcol = index_to_rowcol(j) if i < j: cost = matrix[i][j] else: cost = matrix[j][i] f.write('''%d,%d,%d,%d,%d\n''' % (orowcol[0], orowcol[1], drowcol[0], drowcol[1], cost)) conn.close()
def get_cohesive_small_world(n=25, threshold=1.5): def build_net(G, edges): nodes = list(G.nodes()) while G.size() < edges: a = random.choice(nodes) b = random.choice(nodes) if a != b: G.add_edge(a, b) return G nedges = nx.grid_2d_graph(int(n**0.5), int(n**0.5)).size() i = 0 swi = 0 while swi < threshold or swi > threshold + 0.1: seed = nx.cycle_graph(n) G = build_net(seed, nedges) swi = get_swi(G) i += 1 msg = 'We needed {:d} runs to obtain a cohesive small world with {:d} nodes and swi={:.2f}' print(msg.format(i, n, threshold)) return G
def initCostMapGrid(self, costMap): cellSize = 16 frameSizeX = 3488 frameSizeY = 2560 cols = int(frameSizeX / cellSize) rows = int(frameSizeY / cellSize) self.n = cols * rows #self.costmapViz = np.reshape(costMap[:,2],(rows,cols)) self.costMap = dict( zip(zip(costMap[:, 0], costMap[:, 1]), costMap[:, 2])) self.G = nx.grid_2d_graph(rows, cols, periodic=False) for e in self.G.edges(): self.G[e[0]][e[1]][ 'weight'] = self.straightWeight #set edge weights for N,S,E,W, neighbors for n in list(self.G.nodes()): r, c = n if 0 < r < rows - 1 and 0 < c < cols - 1: self.G.add_edge(n, (r - 1, c - 1), weight=self.diagWeight) self.G.add_edge(n, (r + 1, c - 1), weight=self.diagWeight) self.G.add_edge(n, (r + 1, c + 1), weight=self.diagWeight) self.G.add_edge(n, (r - 1, c + 1), weight=self.diagWeight)
def test_dijkstra_predecessor(self): G=nx.path_graph(4) assert_equal(nx.dijkstra_predecessor_and_distance(G,0), ({0: [], 1: [0], 2: [1], 3: [2]}, {0: 0, 1: 1, 2: 2, 3: 3})) G=nx.grid_2d_graph(2,2) pred,dist=nx.dijkstra_predecessor_and_distance(G,(0,0)) assert_equal(sorted(pred.items()), [((0, 0), []), ((0, 1), [(0, 0)]), ((1, 0), [(0, 0)]), ((1, 1), [(0, 1), (1, 0)])]) assert_equal(sorted(dist.items()), [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 2)]) XG=nx.DiGraph() XG.add_weighted_edges_from([('s','u',10) ,('s','x',5) , ('u','v',1) ,('u','x',2) , ('v','y',1) ,('x','u',3) , ('x','v',5) ,('x','y',2) , ('y','s',7) ,('y','v',6)]) (P,D)= nx.dijkstra_predecessor_and_distance(XG,'s') assert_equal(P['v'],['u']) assert_equal(D['v'],9)
def get_graph_list(num_factors): graph_list = [] # 2, 3 bipartite graph g = nx.turan_graph(n=5, r=2) graph_list.append(nx.to_numpy_array(g)) g = nx.house_x_graph() graph_list.append(nx.to_numpy_array(g)) g = nx.balanced_tree(r=3, h=2) graph_list.append(nx.to_numpy_array(g)) g = nx.grid_2d_graph(m=3, n=3) graph_list.append(nx.to_numpy_array(g)) g = nx.hypercube_graph(n=3) graph_list.append(nx.to_numpy_array(g)) g = nx.octahedral_graph() graph_list.append(nx.to_numpy_array(g)) return graph_list[:num_factors]
def __init__(self, input): if input[1] = None: # random graph self.num_nodes = input[0] self.primalbound = np.inf self.r1star = np.inf self.finalpath = [] self.graph = nx.DiGraph() self.r1 = 'r1' self.cost = 'cost' H = nx.grid_2d_graph(self.num_nodes/4,4).to_directed() node_dict = {} for (idx, node) in enumerate(H.nodes): node_dict[node] = idx self.graph.add_node(idx,visited=0,r11=np.inf,r12=np.inf,r13=np.inf,c1=np.inf,c2=np.inf,c3=np.inf) for (u, v) in H.edges: res1 = np.random.random() cost = np.random.random() self.graph.add_edge(node_dict[u],node_dict[v]) self.graph[node_dict[u]][node_dict[v]][self.r1] = res1 self.graph[node_dict[u]][node_dict[v]][self.cost] = cost OD = np.random.choice(self.num_nodes, 2, replace=False) self.start = OD[0] self.dest = OD[1] self.R1underbar = nx.shortest_path_length(self.graph, target=self.dest, weight=self.r1) self.Cunderbar = nx.shortest_path_length(self.graph, target=self.dest, weight=self.cost) self.maxR1 = self.R1underbar[self.start]*1.2 self.optimal = None for path in nx.shortest_simple_paths(self.graph, self.start, self.dest, weight=self.cost): cost = 0.0 res1 = 0.0 for (idx, n) in enumerate(path): if idx > 0: cost += self.graph[path[idx-1]][n][self.cost] res1 += self.graph[path[idx-1]][n][self.r1] if res1 < self.maxR1: self.optimal = cost break
def calc_all_pairs_data(self, DSM): SIZE_X = 100 SIZE_Y = 100 G = nx.grid_2d_graph(SIZE_X, SIZE_Y) if NUMBER_OF_ACTIONS >= 8: Diagonals_Weight = 1 # add diagonals edges G.add_edges_from([ ((x, y), (x + 1, y + 1)) for x in range(SIZE_Y - 1) for y in range(SIZE_Y - 1) ] + [ ((x + 1, y), (x, y + 1)) for x in range(SIZE_Y - 1) for y in range(SIZE_Y - 1) ], weight=Diagonals_Weight) # remove obstacle nodes and edges for x in range(SIZE_X): for y in range(SIZE_Y): if DSM[x][y] == 1.: G.remove_node((x, y)) # nx.write_gpickle(G, 'G_' + DSM_name + '.pkl') import bz2 print("starting all_pairs_distances") all_pairs_distances = dict(nx.all_pairs_shortest_path_length(G)) with bz2.open('all_pairs_distances_' + DSM_name + '___' + '.pkl', "wb") as f: f.write(all_pairs_distances) # sfile = bz2.BZ2File('all_pairs_distances_' + DSM_name + '___' + '.pkl', 'wb', 'w') # pickle.dump(all_pairs_distances, sfile) print("finished all_pairs_distances") with bz2.open('all_pairs_distances_' + DSM_name + '___' + '.pkl', "rb") as f: # Decompress data from file content = f.read() print("dist from (5,5) to (5,6) is: ", content[(5,5)][(5,5)])
def draw_path(problem, path): """ Draw the graph and the path from initial_state to goal_state, just for visualization. -- Creates a jpg in $CWD -- Will be able to map multiple goal_src's hopefully. :param problem: An object of type Problem. :param path: The path that AStar's search returns :return: Nothing """ g = nx.grid_2d_graph(0, 0) # Get edges and nodes prev = None for item in path: g.add_node(item) if prev is not None: g.add_edge(item, prev) prev = item path_nodes = {node: node for node in path} all_nodes = {node: node for node in problem.graph} all_edges = problem.graph.edges() path_edges = g.edges() # labels labels = {problem.initial_state: 'Src', problem.goal_state: 'Dst'} # nodes nx.draw(g, all_nodes, nodelist=all_nodes, node_size=20, node_color='b') nx.draw(g, all_nodes, nodelist=path_nodes, node_size=40, node_color='k', labels=labels, with_labels=True) # edges nx.draw_networkx_edges(g, all_nodes, edgelist=all_edges, width=1) nx.draw_networkx_edges(g, all_nodes, edgelist=path_edges, width=2, edge_color='k', style='dotted') plt.axis('off') plt.savefig("simplegrid.png") plt.show() return
def get_maximin_weight(YP, Y): G = nx.grid_2d_graph(SIZE[0], SIZE[1]) nlabels_dict = dict() for u, v, d in G.edges(data=True): if u[0] == v[0]: #vertical, dy, channel 0 channel = 0 if u[1] == v[1]: #horizontal, dy, channel 1 channel = 1 d['weight'] = (YP[0, u[0], u[1], 0] + YP[0, v[0], v[1], 0]) / 2.0 nlabels_dict[u] = Y[0, u[0], u[1], 0] nlabels_dict[v] = Y[0, v[0], v[1], 0] WY = np.zeros((1, SIZE[0], SIZE[1], 1), np.single) SY = np.zeros((1, SIZE[0], SIZE[1], 1), np.single) #build an MST mstEdges = ev.mstEdges(G) MST = nx.Graph() MST.add_edges_from(mstEdges) #get a random pair u,v u = (randint(0, SIZE[0] - 1), randint(0, SIZE[1] - 1)) v = (randint(0, SIZE[0] - 1), randint(0, SIZE[1] - 1)) while u == v: u = (randint(0, SIZE[0] - 1), randint(0, SIZE[1] - 1)) v = (randint(0, SIZE[0] - 1), randint(0, SIZE[1] - 1)) #find the maximin path between u and v on the MST path = nx.shortest_path(MST, source=u, target=v) #the maximin edge (us, vs) = min([edge for edge in nx.utils.pairwise(path)], key=lambda e: G.edges[e]['weight']) WY[0, us[0], us[1], 0] += 0.5 WY[0, vs[0], vs[1], 0] += 0.5 if Y[0, u[0], u[1], 0] == Y[0, v[0], v[1], 0]: SY[0, us[0], us[1], 0] += 0.5 SY[0, vs[0], vs[1], 0] += 0.5 else: SY[0, us[0], us[1], 0] += -0.5 SY[0, vs[0], vs[1], 0] += -0.5 return [WY, SY]
def generate_graph(type='PL', n=100, seed=1.0, parameter=2.1): if type == 'ER': G = nx.erdos_renyi_graph(n, p=parameter, seed=seed, directed=True) G = nx.DiGraph(G) G.remove_edges_from(G.selfloop_edges()) elif type == 'PL': z = nx.utils.create_degree_sequence(n, nx.utils.powerlaw_sequence, exponent=parameter) while not nx.is_valid_degree_sequence(z): z = nx.utils.create_degree_sequence(n, nx.utils.powerlaw_sequence, exponent=parameter) G = nx.configuration_model(z) G = nx.DiGraph(G) G.remove_edges_from(G.selfloop_edges()) elif type == 'BA': G = nx.barabasi_albert_graph(n, 3, seed=None) G = nx.DiGraph(G) elif type == 'grid': G = nx.grid_2d_graph(int(np.ceil(np.sqrt(n))), int(np.ceil(np.sqrt(n)))) G = nx.DiGraph(G) elif type in [ 'facebook', 'enron', 'twitter', 'students', 'tumblr', 'facebookBig' ]: #print 'start reading' #_, G, _, _ = readRealGraph(os.path.join("..","..","Data", type+".txt")) _, G, _, _ = readRealGraph(os.path.join("..", "Data", type + ".txt")) print 'size of graph', G.number_of_nodes() #Gcc = sorted(nx.connected_component_subgraphs(G.to_undirected()), key = len, reverse=True) #print Gcc[0].number_of_nodes() #print 'num of connected components', len(sorted(nx.connected_component_subgraphs(G.to_undirected()), key = len, reverse=True)) #exit() if G.number_of_nodes() > n: G = getSubgraph(G, n) #G = getSubgraphSimulation(G, n, infP = 0.3) #nx.draw(G) #plt.show() return G
def Sample(p='train', ID=None): if ID == None: print('TrainSample needs to know the sample id.') return else: segId = 0 if p == 'train': image = io.imread(TRAIN_IMG_DIR + ID + IMG_EXT) groundTruth = loadmat(TRAIN_GT_DIR + ID + GT_EXT) elif p == 'val': image = io.imread(TRAIN_IMG_DIR + ID + IMG_EXT) groundTruth = loadmat(VAL_GT_DIR + ID + GT_EXT) gtseg = groundTruth['groundTruth'][0, segId]['Segmentation'][0, 0].astype( np.float32) if image.shape[0] < image.shape[1]: image = np.rot90(image, k=1, axes=(0, 1)) gtseg = np.rot90(gtseg, k=1, axes=(0, 1)) #delete one row and one column so the data fits the unet image = np.delete(image, 0, 0) image = np.delete(image, 0, 1) gtseg = np.delete(gtseg, 0, 0) gtseg = np.delete(gtseg, 0, 1) elabels = np.ones((gtseg.shape[0], gtseg.shape[1], 2), np.float32) G = nx.grid_2d_graph(gtseg.shape[0], gtseg.shape[1]) for (u, v, d) in G.edges(data=True): if u[0] == v[0]: channel = 0 else: channel = 1 if abs(gtseg[u] - gtseg[v]) > 0.0: elabels[u[0], u[1], channel] = -1.0 nlabels = np.expand_dims(gtseg, axis=2) return (image, nlabels, elabels)