def obtain_graph(args): """Build a Graph according to command line arguments Arguments: - `args`: command line options """ if hasattr(args,'gnd') and args.gnd: n,d = args.gnd if (n*d)%2 == 1: raise ValueError("n * d must be even") G=networkx.random_regular_graph(d,n) return G elif hasattr(args,'gnp') and args.gnp: n,p = args.gnp G=networkx.gnp_random_graph(n,p) elif hasattr(args,'gnm') and args.gnm: n,m = args.gnm G=networkx.gnm_random_graph(n,m) elif hasattr(args,'grid') and args.grid: G=networkx.grid_graph(args.grid) elif hasattr(args,'torus') and args.torus: G=networkx.grid_graph(args.torus,periodic=True) elif hasattr(args,'complete') and args.complete>0: G=networkx.complete_graph(args.complete) elif args.graphformat: G=readGraph(args.input,args.graphformat) else: raise RuntimeError("Invalid graph specification on command line") # Graph modifications if hasattr(args,'plantclique') and args.plantclique>1: clique=random.sample(G.nodes(),args.plantclique) for v,w in combinations(clique,2): G.add_edge(v,w) # Output the graph is requested if hasattr(args,'savegraph') and args.savegraph: writeGraph(G, args.savegraph, args.graphformat, graph_type='simple') return G
def test_navigable_small_world(self): G = nx.navigable_small_world_graph(5, p=1, q=0) gg = nx.grid_2d_graph(5, 5).to_directed() assert_true(nx.is_isomorphic(G, gg)) G = nx.navigable_small_world_graph(5, p=1, q=0, dim=3) gg = nx.grid_graph([5, 5, 5]).to_directed() assert_true(nx.is_isomorphic(G, gg)) G = nx.navigable_small_world_graph(5, p=1, q=0, dim=1) gg = nx.grid_graph([5]).to_directed() assert_true(nx.is_isomorphic(G, gg))
def obtain_graph(args,suffix=""): """Build a Graph according to command line arguments Arguments: - `args`: command line options """ if getattr(args,'gnd'+suffix) is not None: n,d = getattr(args,'gnd'+suffix) if (n*d)%2 == 1: raise ValueError("n * d must be even") G=networkx.random_regular_graph(d,n) elif getattr(args,'gnp'+suffix) is not None: n,p = getattr(args,'gnp'+suffix) G=networkx.gnp_random_graph(n,p) elif getattr(args,'gnm'+suffix) is not None: n,m = getattr(args,'gnm'+suffix) G=networkx.gnm_random_graph(n,m) elif getattr(args,'grid'+suffix) is not None: G=networkx.grid_graph(getattr(args,'grid'+suffix)) elif getattr(args,'torus'+suffix) is not None: G=networkx.grid_graph(getattr(args,'torus'+suffix),periodic=True) elif getattr(args,'complete'+suffix) is not None: G=networkx.complete_graph(getattr(args,'complete'+suffix)) elif getattr(args,'empty'+suffix) is not None: G=networkx.empty_graph(getattr(args,'empty'+suffix)) elif getattr(args,'graphformat'+suffix) is not None: try: print("INFO: reading simple graph {} from '{}'".format(suffix,getattr(args,"input"+suffix).name), file=sys.stderr) G=readGraph(getattr(args,'input'+suffix), "simple", getattr(args,'graphformat'+suffix)) except ValueError,e: print("ERROR ON '{}'. {}".format( getattr(args,'input'+suffix).name,e), file=sys.stderr) exit(-1)
def GridGraph(dim_list): """ Returns an n-dimensional grid graph. INPUT: - ``dim_list`` - a list of integers representing the number of nodes to extend in each dimension. PLOTTING: When plotting, this graph will use the default spring-layout algorithm, unless a position dictionary is specified. EXAMPLES:: sage: G = graphs.GridGraph([2,3,4]) sage: G.show() # long time :: sage: C = graphs.CubeGraph(4) sage: G = graphs.GridGraph([2,2,2,2]) sage: C.show() # long time sage: G.show() # long time """ import networkx dim = [int(a) for a in dim_list] G = networkx.grid_graph(dim) return graph.Graph(G, name="Grid Graph for %s"%dim)
def graph_example_1(): G = nx.convert_node_labels_to_integers(nx.grid_graph([5, 5]), label_attribute='labels') rlabels = nx.get_node_attributes(G, 'labels') labels = {v: k for k, v in rlabels.items()} for nodes in [(labels[(0, 0)], labels[(1, 0)]), (labels[(0, 4)], labels[(1, 4)]), (labels[(3, 0)], labels[(4, 0)]), (labels[(3, 4)], labels[(4, 4)])]: new_node = G.order() + 1 # Petersen graph is triconnected P = nx.petersen_graph() G = nx.disjoint_union(G, P) # Add two edges between the grid and P G.add_edge(new_node + 1, nodes[0]) G.add_edge(new_node, nodes[1]) # K5 is 4-connected K = nx.complete_graph(5) G = nx.disjoint_union(G, K) # Add three edges between P and K5 G.add_edge(new_node + 2, new_node + 11) G.add_edge(new_node + 3, new_node + 12) G.add_edge(new_node + 4, new_node + 13) # Add another K5 sharing a node G = nx.disjoint_union(G, K) nbrs = G[new_node + 10] G.remove_node(new_node + 10) for nbr in nbrs: G.add_edge(new_node + 17, nbr) G.add_edge(new_node + 16, new_node + 5) G.name = 'Example graph for connectivity' return G
def spanning_1d_chain(length): """ Generate a linear chain with auxiliary nodes for spanning cluster detection Parameters ---------- length : int Number of nodes in the chain, excluding the auxiliary nodes. Returns ------- networkx.Graph A linear chain graph with auxiliary nodes for spanning cluster detection See Also -------- sample_states : spanning cluster detection """ ret = nx.grid_graph(dim=[int(length + 2)]) ret.node[0]['span'] = 0 ret[0][1]['span'] = 0 ret.node[length + 1]['span'] = 1 ret[length][length + 1]['span'] = 1 return ret
def square_lattice_model(D=3, N_side=4): lattice_dimensions = [] for _ in range(D): lattice_dimensions.append(N_side) G = nx.grid_graph(lattice_dimensions) edges = G.edges() G.remove_edges_from(edges) G = G.to_directed() bottom_corner = [] top_corner = [] for _ in range(D): bottom_corner.append(0) top_corner.append(N_side-1) extremes = [bottom_corner, top_corner] for j in range(len(extremes)): extremes[j] = tuple(extremes[j]) for node_a in G.nodes(): for node_b in G.nodes(): if lattice_check(node_a, node_b, D): G.add_edge(node_a, node_b) return [G,extremes]
def anneal_bdst(n=11, depth=10, phases=10, iters=1000): """ MCMC/simulated annealing to generate a random bounded-depth spanning tree Parameters ---------- n : int, size of grid depth : int, optional, target bound on depth Returns ------- T : nx.Graph, spanning tree with T.base_graph, possibly with degree bound satisfied """ beta = pm.Uninformative('beta', value=1.) G = nx.grid_graph([n, n]) root = ((n-1)/2, (n-1)/2) bdst = BDST(G, root, depth, beta) @pm.deterministic def max_depth(T=bdst, root=root): shortest_path_length = nx.shortest_path_length(T, root) T.max_depth = max(shortest_path_length.values()) return T.max_depth mod_mc = pm.MCMC([beta, bdst, max_depth]) mod_mc.use_step_method(STMetropolis, bdst) mod_mc.use_step_method(pm.NoStepper, beta) for i in range(phases): beta.value = i*5 mod_mc.sample(iters, thin=max(1, iters/100)) print('cur depth', max_depth.value) print('pct of trace with max_depth <= depth', np.mean(mod_mc.trace(max_depth)[:] <= depth)) return bdst.value
def setup_space(self): """ Method to setup our space. """ # Initialize a space with a grid network self.g = nx.grid_graph(dim=self.size) self.g=self.g.to_directed() # Set Pheromones print 'Setting up network' capacity_pheromone_list=[self.initial_pheromone]*len(self.capacities[0])*2 capacity_pheromone_list.extend([self.initial_pheromone]*len(self.capacities[1])*2) for e in self.g.edges_iter(): self.g.add_edge(e[0],e[1],max_capacity=self.edge_capacity) self.g.add_edge(e[0],e[1],capacity=0) #initial capacity self.g.add_edge(e[0],e[1],edge_pheromone=[self.initial_pheromone]*2*2) #pheromone per edge self.g.add_edge(e[0],e[1],capacity_pheromone=capacity_pheromone_list) #pheromone per capacity for n in self.g.nodes_iter(): neighbors_n=self.g.neighbors(n) branch_pheromone_list=[] branch_pheromone_list=[self.initial_pheromone] branch_pheromone_list.extend([self.initial_pheromone*.5]*(len(neighbors_n)-1)) self.g.add_node(n,branch_pheromone=branch_pheromone_list*2*2) termination_pheromone_list=[self.initial_termination*0.25,self.initial_termination]*2*2 self.g.add_node(n,termination_pheromone=termination_pheromone_list) # Set layout self.g_layout = nx.spectral_layout(self.g)
def __init__(self, dim=None, phi=np.pi, periodic=True, phases=None): if not dim: dim = [4, 4] dim = copy(dim) self.dim = copy(dim) self.nspins = np.prod(dim) self.G = nx.grid_graph(dim, periodic) if phases is not None: self.phases = phases else: self.phases = dict() binary_disorder = True if binary_disorder: for edge in self.G.edges(): self.phases[edge] = phi * np.random.random_integers(0, 1) else: for edge in self.G.edges(): self.phases[edge] = np.random.uniform(-phi, phi) nx.set_edge_attributes(self.G, "phase", self.phases) self.indices = dict() self.index2node = dict() nodes = sorted(self.G.nodes()) for i, node in enumerate(nodes): self.indices[node] = i self.index2node[i] = node self.num_edges = self.G.number_of_edges() self.set_up_neighborlists()
def make_grid_graph(dim, periodic=True): """ this is a wrapper for nx.grid_graph() which replaces the node definition grid_graph creates a graph where the nodes are tuples (ix, iy, ...) where ix and iy are the x and y positions of the site. It would be more useful to have the nodes be simple integers that could act as indices for lists and arrays. The spatial positions will be returned in a separate dict """ G = nx.grid_graph(dim, periodic=periodic) Gnew = nx.Graph() spatial = dict() node2i = dict() for i, node in enumerate(G.nodes()): Gnew.add_node(i) spatial[i] = node node2i[node] = i for edge in G.edges(data=False): u = node2i[edge[0]] v = node2i[edge[1]] Gnew.add_edge(u, v) return Gnew, spatial
def get_graph_from_image(image): grid = nx.grid_graph(dim=list(image.shape[:2])) for u,v,d in grid.edges(data=True): d['weight'] = np.abs(image[u] - image[v])*255 return grid
def generate_grid_graph(): """Generates k cuts for grid graphs""" k = int(input("k for grid graph:")) trials = int(input("number of trials:")) gridfname = input("output file:") gridfname = "hard_instances/" + gridfname gridfile = open(gridfname, "wb", 0) n = int(input("Number of dimensions: ")) d = [] for i in range(0, n): tmp = int(input("Size of dimension " + str(i + 1) + ": ")) d.append(tmp) G = nx.grid_graph(dim=d) A = nx.adjacency_matrix(G).toarray() L = nx.normalized_laplacian_matrix(G).toarray() (tmpw, tmpv) = la.eigh(L, eigvals=(0, 1)) tmp = 2 * math.sqrt(tmpw[1]) print("cheeger upperbound:" + str(tmp)) (w, v) = spectral_projection(L, k) lambda_k = w[k - 1] k_cuts_list = lrtv(A, v, k, lambda_k, trials, gridfile) plotname = gridfname + "plot" plot(k_cuts_list, plotname) tmp_str = "Grid graph of dimension: " + str(d) + "\n" tmp_str += "k = " + str(k) + ", " tmp_str += "trials = " + str(trials) + "\n\n\n" tmp_str = tmp_str.encode("utf-8") gridfile.write(tmp_str) 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") gridfile.write(tmp_str)
def main(plot=True): # make a graph representing a lattice in two dimensions dim = [10,10] grid_graph = nx.grid_graph(dim, periodic=False) A = [(0,0)] B = [(dim[0]-1, dim[1]-1)] # make some random rates for each of the edges rates = dict() for u, v in grid_graph.edges_iter(): rates[(u,v)] = np.random.rand() rates[(v,u)] = np.random.rand() # set up the graph reduction object reducer = GraphReduction(rates, A, B) # make the kmc graph from the rates kmc_graph = kmcgraph_from_rates(rates) com_prob = reducer.compute_committor_probabilities(kmc_graph.nodes()) if plot: # put it into matrix form and plot P = np.zeros(dim) for node, p in com_prob.iteritems(): x, y = node P[x,y] = p import matplotlib.pyplot as plt plt.imshow(P, cmap="BrBG", vmin=0, vmax=1) plt.title("probability of a trajectory reaching the lower right corner\n before reaching the upper left") plt.colorbar() plt.show()
def generateLattice(self): edgeCounter = 0 maxEdges = self.__dimension * 2 * (self.__size ** self.__dimension) # A grid graph forming the lattices dimGrid = [] for i in range(self.__dimension): dimGrid.append(self.__size) G = nx.grid_graph(dimGrid) print 'Gridgraph constructed! size = ' + str(self.__size) # use a classic Bi-directional graph print 'start adding a Stairway to Heaven ' oldcounter = 0 for e in G.edges_iter(): edgeCounter+=1 ec = edgeCounter/1000 if ec > oldcounter: print '.'; oldcounter += ec self.__GD.add_node(e[0], consumed=False, counter=0) self.__GD.add_node(e[1], consumed=False, counter=0) if self.__GD.has_edge(e[0], e[1]) == False: self.__GD.add_edge(e[0], e[1], vdir=np.array(e[0]) - np.array(e[1]),SA= False,New=True) if self.__GD.has_edge(e[1], e[0]) == False: self.__GD.add_edge(e[1], e[0], vdir=np.array(e[1]) - np.array(e[0]),SA=False,New=True) print 'clearing original graph!' G.clear()
def torrents_and_ferraro_graph(): G = nx.convert_node_labels_to_integers(nx.grid_graph([5, 5]), label_attribute='labels') rlabels = nx.get_node_attributes(G, 'labels') labels = {v: k for k, v in rlabels.items()} for nodes in [(labels[(0, 4)], labels[(1, 4)]), (labels[(3, 4)], labels[(4, 4)])]: new_node = G.order() + 1 # Petersen graph is triconnected P = nx.petersen_graph() G = nx.disjoint_union(G, P) # Add two edges between the grid and P G.add_edge(new_node + 1, nodes[0]) G.add_edge(new_node, nodes[1]) # K5 is 4-connected K = nx.complete_graph(5) G = nx.disjoint_union(G, K) # Add three edges between P and K5 G.add_edge(new_node + 2, new_node + 11) G.add_edge(new_node + 3, new_node + 12) G.add_edge(new_node + 4, new_node + 13) # Add another K5 sharing a node G = nx.disjoint_union(G, K) nbrs = G[new_node + 10] G.remove_node(new_node + 10) for nbr in nbrs: G.add_edge(new_node + 17, nbr) # Commenting this makes the graph not biconnected !! # This stupid mistake make one reviewer very angry :P G.add_edge(new_node + 16, new_node + 8) for nodes in [(labels[(0, 0)], labels[(1, 0)]), (labels[(3, 0)], labels[(4, 0)])]: new_node = G.order() + 1 # Petersen graph is triconnected P = nx.petersen_graph() G = nx.disjoint_union(G, P) # Add two edges between the grid and P G.add_edge(new_node + 1, nodes[0]) G.add_edge(new_node, nodes[1]) # K5 is 4-connected K = nx.complete_graph(5) G = nx.disjoint_union(G, K) # Add three edges between P and K5 G.add_edge(new_node + 2, new_node + 11) G.add_edge(new_node + 3, new_node + 12) G.add_edge(new_node + 4, new_node + 13) # Add another K5 sharing two nodes G = nx.disjoint_union(G, K) nbrs = G[new_node + 10] G.remove_node(new_node + 10) for nbr in nbrs: G.add_edge(new_node + 17, nbr) nbrs2 = G[new_node + 9] G.remove_node(new_node + 9) for nbr in nbrs2: G.add_edge(new_node + 18, nbr) return G
def creaRed(Nodos,TipoNodos): global g,numNodos, numTipoNodos numNodos=Nodos numTipoNodos=TipoNodos g=nx.grid_graph(dim=[numNodos,numNodos], periodic=True) for i in g.nodes_iter(): g.node[i]['tipo']=rd.choice(range(numTipoNodos)) return g
def __init__(self, n): """ Create a new cubic lattice with given linear dimension. Final number of nodes will be n**3. """ self.G = nx.grid_graph([n, n, n]) self.G = nx.convert_node_labels_to_integers(self.G, label_attribute="pos") self._find_cycle_basis() self._find_cycle_dual()
def test_grid_graph(self): """grid_graph([n,m]) is a connected simple graph with the following properties: number_of_nodes = n*m degree_histogram = [0,0,4,2*(n+m)-8,(n-2)*(m-2)] """ for n, m in [(3, 5), (5, 3), (4, 5), (5, 4)]: dim = [n, m] g = nx.grid_graph(dim) assert_equal(len(g), n*m) assert_equal(nx.degree_histogram(g), [0, 0, 4, 2 * (n + m) - 8, (n - 2) * (m - 2)]) for n, m in [(1, 5), (5, 1)]: dim = [n, m] g = nx.grid_graph(dim) assert_equal(len(g), n*m) assert_true(nx.is_isomorphic(g, nx.path_graph(5)))
def anneal_w_graphics(n=11, depth=10): """ Make an animation of the BDST chain walking on an nxn grid and play it """ ni = 5 nj = 100 nk = 5 beta = mc.Uninformative('beta', value=1.) G = nx.grid_graph([n, n]) G.orig_pos = dict([[v, v] for v in G.nodes_iter()]) G.pos = dict([[v, v] for v in G.nodes_iter()]) root = (5,5) bdst = BDST(G, root, depth, beta) mod_mc = mc.MCMC([beta, bdst]) mod_mc.use_step_method(STMetropolis, bdst) mod_mc.use_step_method(mc.NoStepper, beta) for i in range(ni): beta.value = i*5 for j in range(nj): mod_mc.sample(1) T = bdst.value for k in range(nk): if random.random() < .95: delta_pos = nx.spring_layout(T, pos=G.pos, fixed=[root], iterations=1) else: delta_pos = G.orig_pos eps=.01 my_avg = lambda x, y: (x[0]*(1.-eps) + y[0]*eps, x[1]*(1.-eps)+y[1]*eps) for v in G.pos: G.pos[v] = my_avg(G.pos[v], delta_pos[v]) views.plot_graph_and_tree(G, T, time=1.*k/nk) str = '' str += ' beta: %.1f\n' % beta.value str += ' cur depth: %d (target: %d)\n' % (T.depth, depth) sm = mod_mc.step_method_dict[bdst][0] str += ' accepted: %d of %d\n' % (sm.accepted, sm.accepted + sm.rejected) plt.figtext(0, 0, str) plt.figtext(1, 0, 'healthyalgorithms.wordpress.com \n', ha='right') plt.axis([-1, n, -1, n]) plt.axis('off') plt.subplots_adjust(0, 0, 1, 1) plt.savefig('bdst%06d.png' % (i*nj*nk + j*nk + k)) print 'accepted:', mod_mc.step_method_dict[bdst][0].accepted import subprocess subprocess.call('mencoder mf://bdst*.png -mf w=800:h=600 -ovc x264 -of avi -o bdst_G_%d_d_%d.avi' % (n, depth), shell=True) subprocess.call('mplayer -loop 0 bdst_G_%d_d_%d.avi' % (n, depth), shell=True) subprocess.call('rm bdst*.png') return bdst.value
def GridGraph(dim_list): """ Returns an n-dimensional grid graph. INPUT: - ``dim_list`` - a list of integers representing the number of nodes to extend in each dimension. PLOTTING: When plotting, this graph will use the default spring-layout algorithm, unless a position dictionary is specified. EXAMPLES:: sage: G = graphs.GridGraph([2,3,4]) sage: G.show() # long time :: sage: C = graphs.CubeGraph(4) sage: G = graphs.GridGraph([2,2,2,2]) sage: C.show() # long time sage: G.show() # long time TESTS: The graph name contains the dimension:: sage: g = graphs.GridGraph([5, 7]) sage: g.name() 'Grid Graph for [5, 7]' sage: g = graphs.GridGraph([2, 3, 4]) sage: g.name() 'Grid Graph for [2, 3, 4]' sage: g = graphs.GridGraph([2, 4, 3]) sage: g.name() 'Grid Graph for [2, 4, 3]' All dimensions must be positive integers:: sage: g = graphs.GridGraph([2,-1,3]) Traceback (most recent call last): ... ValueError: All dimensions must be positive integers ! """ import networkx dim = [int(a) for a in dim_list] if any(a <= 0 for a in dim): raise ValueError("All dimensions must be positive integers !") # We give a copy of dim to networkx because it modifies the list G = networkx.grid_graph(list(dim)) return graph.Graph(G, name="Grid Graph for " + str(dim))
def __init__(self,initial_grid_size): self.initial_grid_size=initial_grid_size self.ship=nx.grid_graph(dim=initial_grid_size) self.layout=nx.spectral_layout(self.ship) #label streets and penetrations self.dual_streets={} self.geometric_characteristics={'H':'horizontal','L':'longitudinal','T':'transverse'} structural_denotation=['T','L','H'] self.transfer_types={'P':None,'EM_P':None,'C':None,'I':None,'H':None} #self.transfer_types={'E':None,'M':None,'I':None,'H':None} for u,v in self.ship.edges(): self.ship[u][v]['availability']=list(self.transfer_types) for i in range(len(self.initial_grid_size)): for structure in range(self.initial_grid_size[i]+1): s_name='{}{}'.format(structural_denotation[i],structure) self.dual_streets[s_name]={} self.dual_streets[s_name]['orientation']=self.geometric_characteristics[structural_denotation[i]] self.dual_streets[s_name]['availability']=list(self.transfer_types) for u,v in self.ship.edges(): coord_change=[(a is b) for a, b in zip(u,v)].index(False) if coord_change==0: #move in x self.ship[u][v]['penetration']='T{}'.format(max(u[0],v[0])) self.ship[u][v]['streets']=['L{}'.format(u[1]),'L{}'.format((u[1]+1)),'H{}'.format(u[2]),'H{}'.format((u[2]+1))] if coord_change==1: #move in y self.ship[u][v]['penetration']='L{}'.format(max(u[1],v[1])) self.ship[u][v]['streets']=['H{}'.format(u[2]),'H{}'.format((u[2]+1)),'T{}'.format(u[0]),'T{}'.format((u[0]+1))] if coord_change==2: #move in z self.ship[u][v]['penetration']='H{}'.format(max(u[2],v[2])) self.ship[u][v]['streets']=['T{}'.format(u[0]),'T{}'.format((u[0]+1)),'L{}'.format(u[1]),'L{}'.format((u[1]+1))] #print (u,v),self.ship[u][v]['streets'],self.ship[u][v]['penetration'] #generate default information dual self.ship_dual=nx.Graph() for key in self.dual_streets: if self.dual_streets[key]['orientation'] is 'horizontal': for cross_street in self.dual_streets: if self.dual_streets[cross_street]['orientation'] is not 'horizontal': self.ship_dual.add_edge(key,cross_street) if self.dual_streets[key]['orientation'] is 'transverse': for cross_street in self.dual_streets: if self.dual_streets[cross_street]['orientation'] is not 'transverse': self.ship_dual.add_edge(key,cross_street) if self.dual_streets[key]['orientation'] is 'longitudinal': for cross_street in self.dual_streets: if self.dual_streets[cross_street]['orientation'] is not 'longitudinal': self.ship_dual.add_edge(key,cross_street)
def drawLattice(self,labels=None, graph_layout='spring', node_size=1000, node_color='blue', node_alpha=0.3, node_text_size=12, edge_color='blue', edge_alpha=0.3, edge_thickness=2, edge_text_pos=0.3, text_font='sans-serif'): """Method that physically draws the lattice graph based on length, width, and height.""" graph=nx.grid_graph([self.x,self.y,self.z]) # add edges for edge in self.GraphList: graph.add_edge(edge[0], edge[1]) # these are different layouts for the network you may try # shell seems to work best if graph_layout == 'spring': graph_pos=nx.spring_layout(graph) elif graph_layout == 'spectral': graph_pos=nx.spectral_layout(graph) elif graph_layout == 'random': graph_pos=nx.random_layout(graph) else: graph_pos=nx.shell_layout(graph) # draw graph nx.draw_networkx_nodes(graph,graph_pos,node_size=node_size, alpha=node_alpha, node_color=node_color) nx.draw_networkx_edges(graph,graph_pos,width=edge_thickness, alpha=edge_alpha,edge_color=edge_color) nx.draw_networkx_labels(graph, graph_pos,font_size=node_text_size, font_family=text_font) if labels is None: labels = range(len(graph)) edge_labels = dict(zip(graph, labels)) #Nodes prints the coordinates of the node positions #n = nx.nodes(graph) #print(n) #Number of Nodes is helpful nn = nx.number_of_nodes(graph) #print(nn) #Prints <dict_keyiterator object at 0x116fd3318> neighbors = nx.all_neighbors(graph, (0,0,1)) #print(neighbors) #e = nx.edges(graph) #print(e) # show graph plt.show()
def setUp(self): # Construct a weighted 1-D grid graph. self.n = 10 self.g = nx.grid_graph(dim=[self.n]) for i in xrange(self.n-1): self.g[i][i+1]['weight'] = i+1 # Construct fine level 0 and geometric aggregation coarse level 1. self.level0 = level.create_finest_level(relax.create_gauss_seidel_relaxer, self.g) geometric_aggregate_index = np.repeat(np.arange(self.n/2), 2) self.level1 = level.create_coarse_level(relax.create_gauss_seidel_relaxer, self.level0, geometric_aggregate_index)
def test_algebraic_distance(): #TODO: need new tests: edges are always=1 for normal distance #given two start vectors, a mesh should unfold print 'Testing Algebraic distance' #test1: nodes nearby on the path graph should land nearby print 'test path ...' G1 = nx.path_graph(10) distance1 = algebraic_distance(G1, params={'all_pairs_distance':False}) #usual regime true_distance1 = [] alg_distance1 = [] for node1 in G1: for node2 in G1.neighbors(node1): if node1 > node2: continue true_distance1.append(abs(node1-node2)) alg_distance1.append(distance1[node1][node2]) assert distance1[0][1] == distance1[1][0] val1 = np.corrcoef(true_distance1, alg_distance1)[0,1] print 'correlation: %.2f'%val1 assert val1 > 0.8 print 'passed.' print 'test grid' G2=nx.grid_graph(dim=[10,10]) distance2 = algebraic_distance(G2, params={'all_pairs_distance':True}) true_distance2 = [] alg_distance2 = [] for node1 in G2: for node2 in G2: if sum(node1) > sum(node2): continue true_distance2.append(abs(node1[0]-node2[0]) + abs(node1[1]-node2[1])) alg_distance2.append(distance2[node1][node2]) val2 = np.corrcoef(true_distance2, alg_distance2)[0,1] print 'correlation: %.2f'%val2 assert val2 > 0.5 val1 = np.corrcoef(true_distance1, alg_distance1)[0,1] distance2sp = algebraic_distance_sparse(G2, params={'all_pairs_distance':True}) err2 = 0 for node1 in G2: for node2 in G2: if sum(node1) > sum(node2): continue err2 += abs(distance2sp[node1][node2] - distance2[node1][node2]) err2 = err2/G.number_of_edges() print ' mean gap for pair: %.f'%(err2) assert err2 < 0.1 print 'passed.'
def test_grids(): l = [10, 20, 30] w = [10, 20, 30] for i in l: for j in w: G = nx.grid_graph([i, j]) G.graph['name'] = 'Grid Graph {},{}'.format(i, j) total_time, sizes = test_graph(G) with open('grids.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 my_grid_graph(shape): """ Create an nxn grid graph, with uniformly random edge weights, and a position dict G.pos """ G = nx.grid_graph(list(shape)) for u,v in G.edges(): G[u][v]['weight'] = random.random() G.pos = {} for v in G: G.pos[v] = [v[0], -v[1]] return G
def make_grid(): grid = nx.grid_graph([3,3]) grid = nx.relabel_nodes(grid, { (0,0): 9, (1,0): 6, (2,0): 3, (0,1): 8, (1,1): 5, (2,1): 2, (0,2): 7, (1,2): 4, (2,2): 1, }) return grid
def __init__(self, dim=[4, 4], field_disorder=1., fields=None): self.dim = copy(dim) self.nspins = np.prod(dim) self.G = nx.grid_graph(dim, periodic=True) self.fields = np.zeros([self.nspins, 3]) self.indices = dict() nodes = sorted(self.G.nodes()) for i, node in enumerate(nodes): self.indices[node] = i if fields is None: self.fields[i,:] = rotations.vec_random() * np.sqrt(field_disorder) else: self.fields[i,:] = fields[i,:]
def my_grid_graph(shape): """ Create an nxn grid graph, with uniformly random edge weights, and a position dict G.pos """ G = nx.grid_graph(list(shape)) G.shape = shape for u, v in G.edges_iter(): if len(G[u]) < 4 and len(G[v]) < 4: G[u][v]['straight_line'] = True G.pos = {} for v in G: G.pos[v] = [v[0], v[1]] return G
def test_astar_grid(): graph = nx.grid_graph(dim=[5,5]) assert nx.astar_path_length(graph,(0,0),(4,4)) == len(nx.astar_path(graph, (0,0),(4,4)))-1
return partition.flip({flip[0]: flip[1]}) def b_nodes(partition): return {(x[0], partition.assignment[x[1]]) for x in partition["cut_edges"] }.union({(x[1], partition.assignment[x[0]]) for x in partition["cut_edges"]}) # BUILD GRAPH gn = 2 k = 4 ns = 50 p = 0.5 q = .4 graph = nx.grid_graph([k * gn, k * gn]) for n in graph.nodes(): graph.node[n]["population"] = 1 if random.random() < p: graph.node[n]["pink"] = 1 graph.node[n]["purple"] = 0 else: graph.node[n]["pink"] = 0 graph.node[n]["purple"] = 1 if n[0] < k*gn*q: graph.node["green"] = 1 graph.node["yellow"] = 0
def nemoodar2(s, p, n): positions = np.arange(n) + 1 # indices = [] # for w in range(n): # indices.append(math.log(w+1)) random_g_distances = [] l1d_distances = [] first_value = 0 last_none = 0 for v in range(n): av_degree, av_distance = generate_random_g(s, p, v + 1) lattice_g1d = grid_graph(dim=[v + 1]) av_dis = math.log(av_distance) if av_distance > 0 else None if av_dis is None: last_none = v + 1 else: first_value = v + 1 if first_value == 0 else first_value random_g_distances.append(av_dis) av_l1d_dis = average_g_distance(lattice_g1d) l1d_distances.append(math.log(av_l1d_dis) if av_l1d_dis > 0 else None) print("First Connected Random Graph: " + str(first_value)) print("Last Unconnected Random Graph: " + str(last_none)) l2d_distances = [None] * n n2 = int(n**(1 / 2)) for v2 in range(n2): lattice_g2d = grid_graph(dim=[v2 + 1, v2 + 1]) n_g2d = (v2 + 1) * (v2 + 1) av_l2d_dis = average_g_distance(lattice_g2d) l2d_distances[n_g2d - 1] = math.log(av_l2d_dis) if av_l2d_dis > 0 else None l3d_distances = [None] * n n3 = int(n**(1 / 3)) for v3 in range(n3): lattice_g3d = grid_graph(dim=[v3 + 1, v3 + 1, v3 + 1]) n_g3d = (v3 + 1) * (v3 + 1) * (v3 + 1) av_l3d_dis = average_g_distance(lattice_g3d) l3d_distances[n_g3d - 1] = math.log(av_l3d_dis) if av_l3d_dis > 0 else None plt.plot( positions, random_g_distances, 'r-', l1d_distances, 'k-', l2d_distances, 'b+', l3d_distances, 'g+', ) # plt.xticks(positions, indices) plt.axis(xmin=1, ymin=0) # plt.yscale('log') plt.xscale('log') plt.xlabel('log N') plt.ylabel('log <d>') plt.savefig('nemoodar2.png') plt.show()
def gen_laplacian(data_num=DATA_NUM, opt=27, cache=False): label = None if cache: print('Loading cached graph') graph = pk.load(open('tmp/g.pk', 'rb')) else: print('Generating graph opt {}'.format(opt)) if 1 == opt: graph = gen_rand_graph(data_num=data_num) if 2 == opt: top_num = random.randint(1, data_num) bottom_num = data_num - top_num graph = nx.bipartite.random_graph(top_num, bottom_num, 0.9) label = [d['bipartite'] for n, d in graph.nodes(data=True)] elif 3 == opt: graph = nx.balanced_tree(4, 5) elif 4 == opt: graph = nx.complete_graph(data_num) elif 5 == opt: no1 = random.randint(1, data_num) no2 = random.randint(1, int(data_num / no1)) no3 = data_num / no1 / no2 graph = nx.complete_multipartite_graph(no1, no2, no3) elif 6 == opt: graph = nx.circular_ladder_graph(data_num) elif 7 == opt: graph = nx.cycle_graph(data_num) elif 8 == opt: graph = nx.dorogovtsev_goltsev_mendes_graph(5) elif 9 == opt: top_num = int(random.random() * data_num) bottom_num = data_num / top_num graph = nx.grid_2d_graph(top_num, bottom_num) elif 10 == opt: no1 = random.randint(1, data_num) no2 = random.randint(1, int(data_num / no1)) no3 = data_num / no1 / no2 graph = nx.grid_graph([no1, no2, no3]) elif 11 == opt: graph = nx.hypercube_graph(10) elif 12 == opt: graph = nx.ladder_graph(data_num) elif 13 == opt: top_num = int(random.random() * data_num) bottom_num = data_num - top_num graph = nx.lollipop_graph(top_num, bottom_num) elif 14 == opt: graph = nx.path_graph(data_num) elif 15 == opt: graph = nx.star_graph(data_num) elif 16 == opt: graph = nx.wheel_graph(data_num) elif 17 == opt: graph = nx.margulis_gabber_galil_graph(35) elif 18 == opt: graph = nx.chordal_cycle_graph(data_num) elif 19 == opt: graph = nx.fast_gnp_random_graph(data_num, random.random()) elif 20 == opt: # jump eigen value graph = nx.gnp_random_graph(data_num, random.random()) elif 21 == opt: # disconnected graph graph = nx.dense_gnm_random_graph(data_num, data_num / 2) elif 22 == opt: # disconnected graph graph = nx.gnm_random_graph(data_num, data_num / 2) elif 23 == opt: graph = nx.erdos_renyi_graph(data_num, data_num / 2) elif 24 == opt: graph = nx.binomial_graph(data_num, data_num / 2) elif 25 == opt: graph = nx.newman_watts_strogatz_graph(data_num, 5, random.random()) elif 26 == opt: graph = nx.watts_strogatz_graph(data_num, 5, random.random()) elif 26 == opt: # smooth eigen graph = nx.connected_watts_strogatz_graph(data_num, 5, random.random()) elif 27 == opt: # smooth eigen graph = nx.random_regular_graph(5, data_num) elif 28 == opt: # smooth eigen graph = nx.barabasi_albert_graph(data_num, 5) elif 29 == opt: # smooth eigen graph = nx.powerlaw_cluster_graph(data_num, 5, random.random()) elif 30 == opt: # smooth eigen graph = nx.duplication_divergence_graph(data_num, random.random()) elif 31 == opt: p = random.random() q = random.random() graph = nx.random_lobster(data_num, p, q) elif 32 == opt: p = random.random() q = random.random() k = random.random() graph = nx.random_shell_graph([(data_num / 3, 50, p), (data_num / 3, 40, q), (data_num / 3, 30, k)]) elif 33 == opt: # smooth eigen top_num = int(random.random() * data_num) bottom_num = data_num - top_num graph = nx.k_random_intersection_graph(top_num, bottom_num, 3) elif 34 == opt: graph = nx.random_geometric_graph(data_num, .1) elif 35 == opt: graph = nx.waxman_graph(data_num) elif 36 == opt: graph = nx.geographical_threshold_graph(data_num, .5) elif 37 == opt: top_num = int(random.random() * data_num) bottom_num = data_num - top_num graph = nx.uniform_random_intersection_graph( top_num, bottom_num, .5) elif 39 == opt: graph = nx.navigable_small_world_graph(data_num) elif 40 == opt: graph = nx.random_powerlaw_tree(data_num, tries=200) elif 41 == opt: graph = nx.karate_club_graph() elif 42 == opt: graph = nx.davis_southern_women_graph() elif 43 == opt: graph = nx.florentine_families_graph() elif 44 == opt: graph = nx.complete_multipartite_graph(data_num, data_num, data_num) # OPT 1 # norm_lap = nx.normalized_laplacian_matrix(graph).toarray() # OPT 2: renormalized # pk.dump(graph, open('tmp/g.pk', 'wb')) # plot_graph(graph, label) # note difference: normalized laplacian and normalzation by eigenvalue norm_lap, eigval, eigvec = normalize_lap(graph) return graph, norm_lap, eigval, eigvec
def test_node_input(self): G = nx.grid_graph([range(7, 9), range(3, 6)]) assert_equal(len(G), 2 * 3) assert_true(nx.is_isomorphic(G, nx.grid_graph([2, 3])))
def get_graph(args): if args.graph == "grid": dims = args.grid_dims nodes = round(args.nodes**(1 / dims)) shape = [nodes] * dims graph = nx.grid_graph(dim=shape) graph.name = f"grid{dims}d_{args.nodes}" elif args.graph == "tree": graph = nx.balanced_tree(args.tree_branching, args.tree_height) graph.name = f"tree_branch{args.tree_branching}_height{args.tree_height}" # expanders elif args.graph == "expander-margulis": graph = expanders.margulis_gabber_galil_graph(args.nodes) graph.name = f"expander-margulis-{args.nodes}" elif args.graph == "expander-chordal": if not utils.is_prime(args.nodes): raise ValueError( f"args.nodes must be prime for {args.graph} graph") graph = expanders.chordal_cycle_graph(args.nodes) graph.name = f"expander-chordal-{args.nodes}" elif args.graph == "expander-paley": if not utils.is_prime(args.nodes): raise ValueError( f"args.nodes must be prime for {args.graph} graph") graph = expanders.paley_graph(args.nodes) graph.name = f"expander-paley-{args.nodes}" # social networks elif args.graph == "social-karate": graph = social.karate_club_graph() graph.name = f"social-karate" elif args.graph == "social-davis": graph = social.davis_southern_women_graph() graph.name = f"social-davis" elif args.graph == "social-florentine": graph = social.florentine_families_graph() graph.name = f"social-florentine" elif args.graph == "social-miserables": graph = social.les_miserables_graph() graph.name = f"social-miserables" # graph products elif args.graph == "product-cartesian": dims = args.grid_dims nodes = round(args.nodes**(1 / dims)) shape = [nodes] * dims grid = nx.grid_graph(dim=shape) tree = nx.balanced_tree(args.tree_branching, args.tree_height) graph = nx.cartesian_product(tree, grid) graph.name = f"product-cartesian" elif args.graph == "product-rooted": dims = args.grid_dims nodes = round(args.nodes**(1 / dims)) shape = [nodes] * dims grid = nx.grid_graph(dim=shape) tree = nx.balanced_tree(args.tree_branching, args.tree_height) # if invoked rooted_product(tree, grid, list(grid.nodes())[0]), it gives a tree of grids # if invoked rooted_product(grid, tree, list(tree.nodes())[0]), it gives a grid with trees hanging graph = nx.algorithms.operators.rooted_product(tree, grid, list(grid.nodes())[0]) graph.name = f"product-rooted" else: graph = load_graph(args) return graph
# not a serious bench script, used for debugging mainly import matplotlib.pyplot as plt, cmasher as cmr, pandas as pd import numpy as np, os, sys, networkx as nx, warnings from plexsim import models from imi import infcy warnings.simplefilter("ignore") plt.style.use("fivethirtyeight spooky".split()) g = nx.grid_graph((6, 6)) g = nx.krackhardt_kite_graph() g = nx.karate_club_graph() g = nx.path_graph(100) print(g) m = models.Potts(g, t=2) # print(m.sampleNodes(1).base) N = 1000 M = 1000 import time # print(m.simulate(M).shape) sim = infcy.Simulator(m) s = time.time() m.spawn() print(time.time() - s) s = time.time() snaps = sim.snapshots(N) print(time.time() - s)
import matplotlib.pyplot as plt def add_cross_edge(gp, shape): """ 2DGridのグラフに斜め方向のエッジを追加する """ for node in gp.nodes(): nx_node = (node[0] + 1, node[1] + 1) if nx_node[0] < shape[0] and nx_node[1] < shape[1]: gp.add_edge(node, nx_node) nx_node = (node[0] + 1, node[1] - 1) if nx_node[0] < shape[0] and nx_node[1] >= 0: gp.add_edge(node, nx_node) ngrid = 20 gp = nx.grid_graph(dim=[ngrid, ngrid]) add_cross_edge(gp, [ngrid, ngrid]) idcs = np.random.choice(len(gp.nodes()), int(ngrid * ngrid * 0.2), replace=False) # スタート・ゴール・障害物を設定する st, gl, obs = list(gp.nodes())[idcs[0]], list(gp.nodes())[idcs[1]], [list(gp.nodes())[i] for i in idcs[2:]] gp.node[st]['color'] = 'green' gp.node[gl]['color'] = 'red' for o in obs: gp.node[o]['color'] = 'black' def dist(a, b): print a, b """ ヒューリスティック関数 """ x1 = np.array(a, dtype=np.float32)
def statistics(): trials = 100 #samples = trials*500 m = 20 graph = nx.grid_graph([m, m]) graph.name = "grid_size:" + str(m) print(graph.name) for x in graph.nodes(): graph.nodes[x]["pos"] = np.array([x[0], x[1]]) dual = Facefinder.planar_dual(graph) W_trees = [] branches = [] supernode = find_supernode(dual) boundary_faces = list(dual.neighbors(supernode)) face_1 = boundary_faces[0] face_2 = boundary_faces[int(len(boundary_faces) / 2) + 1] #if (face_1, supernode) or (supernode, face_1) in dual.edges(): # print("OK") #if (face_2, supernode) or (supernode, face_2) in dual.edges(): # print("OK2") cycles = [] cycles_containing_prescribed_faces = [] corresponding_walks = [] boundary_faces_frequencies = {} for face_a in boundary_faces: for face_b in boundary_faces: boundary_faces_frequencies[(face_a, face_b)] = 0 #print("testing", boundary_faces_frequencies[ ( face_1, face_2)]) done = False sample_counter = 0 while not done: tree = nx.to_undirected(random_spanning_tree_wilson(dual)) available_edges = set(dual.edges()) available_edges = available_edges - set(tree.edges()) e = random.choice(list(available_edges)) unicycle = copy.deepcopy(tree) unicycle = nx.Graph(unicycle) unicycle.add_edge(e[0], e[1]) #cycles.append(simple_cycle(unicycle)) cycle = simple_cycle(unicycle) #faces = [x[0] for x in cycle] + [x[1] for x in cycle] #faces = set(faces) #print(faces) for face_a in boundary_faces: for face_b in boundary_faces: if (face_a, supernode) in cycle or (supernode, face_a) in cycle: if (face_b, supernode) in cycle or (supernode, face_b) in cycle: boundary_faces_frequencies[(face_a, face_b)] += 1 face_a = face_1 face_b = face_2 if (face_a, supernode) in cycle or (supernode, face_a) in cycle: if (face_b, supernode) in cycle or (supernode, face_b) in cycle: #print('1') cycles_containing_prescribed_faces.append(cycle) walk = nx.Graph(nx.edge_subgraph(dual, cycle)) walk.remove_node(supernode) corresponding_walks.append(walk) sample_counter += 1 print(sample_counter) if sample_counter == trials: done = True #print("testing2", boundary_faces_frequencies[ (face_1, face_2)]) #print(corresponding_walks[0].edges()) #print(len(cycles_containing_prescribed_faces)) #print(boundary_faces_frequencies) print("finished with cycle portions") LERW = [] dual.remove_node(supernode) #Because we are testing whether the distributions looks like a LERW in the grid #portion of the dual graph for i in range(trials): trip = random_walk_until_hit(dual, face_1, set([face_2])) new_branch, branch_length = loop_erasure(trip) LERW.append(new_branch) return LERW, corresponding_walks, dual, boundary_faces_frequencies
splumatrix = scipy.sparse.linalg.splu(m) diag_L = np.diag(splumatrix.L.A) diag_U = np.diag(splumatrix.U.A) try: S_log_L = [np.log(np.abs(s)) for s in diag_L] S_log_U = [np.log(np.abs(s)) for s in diag_U] except Warning: print(diag_U) LU_prod = np.sum(S_log_U) + np.sum(S_log_L) return LU_prod m = 3 n = 3 d = 2 G = nx.grid_graph([m, n]) H = nx.grid_graph([m, n]) for x in G.edges(): a = x[0] b = x[1] G.edges[x]["weight"] = (np.abs(a[0] - b[0]) + np.abs(a[1] - b[1])) for x in H.edges(): a = x[0] b = x[1] H.edges[x]["weight"] = (d * np.abs(a[0] - b[0]) + (1 / d) * np.abs(a[1] - b[1])) W_G = log_weighted_number_trees(G) W_H = log_weighted_number_trees(H) print("WG", W_G) print("WH", W_H)
def hamiltonCycle(G, start=0): path = [-1] * G.number_of_nodes() # Start at node 0 path[0] = start if hamiltonCycleHeuristic(G, path, 1) == False: # There is no hamilton cycle print("No Hamilton Cycle") return False route.append(path[0]) R = createRoute(G) return R # Create matrix G = nx.grid_graph(dim=[6, 6]) R = hamiltonCycle(G) edge_colors = ["orange" if R.has_edge(u, v) else "gray" for u, v in G.edges] edge_widths = [5 if R.has_edge(u, v) else 0.5 for u, v in G.edges] #print graph graph, ax = plt.subplots(1, 1, figsize=(10, 10)) nx.draw(G, pos=nx.kamada_kawai_layout(G), ax=ax, with_labels=True, node_color='#444444', font_color="white", edge_color=edge_colors, width=edge_widths)
def __init__(self, n_clutter=50, size=15, agent_view_size=5, max_steps=250, goal_noise=0., random_z_dim=50, choose_goal_last=False): """Initializes environment in which adversary places goal, agent, obstacles. Args: n_clutter: The maximum number of obstacles the adversary can place. size: The number of tiles across one side of the grid; i.e. make a size x size grid. agent_view_size: The number of tiles in one side of the agent's partially observed view of the grid. max_steps: The maximum number of steps that can be taken before the episode terminates. goal_noise: The probability with which the goal will move to a different location than the one chosen by the adversary. random_z_dim: The environment generates a random vector z to condition the adversary. This gives the dimension of that vector. choose_goal_last: If True, will place the goal and agent as the last actions, rather than the first actions. """ self.agent_start_pos = None self.goal_pos = None self.n_clutter = n_clutter self.goal_noise = goal_noise self.random_z_dim = random_z_dim self.choose_goal_last = choose_goal_last # Add two actions for placing the agent and goal. self.adversary_max_steps = self.n_clutter + 2 super().__init__( n_agents=1, minigrid_mode=True, grid_size=size, max_steps=max_steps, agent_view_size=agent_view_size, see_through_walls=True, # Set this to True for maximum speed competitive=True, ) # Metrics self.reset_metrics() # Create spaces for adversary agent's specs. self.adversary_action_dim = (size - 2)**2 self.adversary_action_space = gym.spaces.Discrete( self.adversary_action_dim) self.adversary_ts_obs_space = gym.spaces.Box( low=0, high=self.adversary_max_steps, shape=(1, ), dtype='uint8') self.adversary_randomz_obs_space = gym.spaces.Box( low=0, high=1.0, shape=(random_z_dim, ), dtype=np.float32) self.adversary_image_obs_space = gym.spaces.Box(low=0, high=255, shape=(self.width, self.height, 3), dtype='uint8') # Adversary observations are dictionaries containing an encoding of the # grid, the current time step, and a randomly generated vector used to # condition generation (as in a GAN). self.adversary_observation_space = gym.spaces.Dict({ 'image': self.adversary_image_obs_space, 'time_step': self.adversary_ts_obs_space, 'random_z': self.adversary_randomz_obs_space }) # NetworkX graph used for computing shortest path self.graph = grid_graph(dim=[size - 2, size - 2]) self.wall_locs = []
def test_graph_state_circuit() -> None: graph = nx.grid_graph([3, 3]) _ = qf.graph_state_circuit(graph)
nx.draw(self.ambient_graph, pos=names, node_size = 0, node_color= 'black', edge_color = 'blue', width = 8) nx.draw(self.matching_graph, pos=names, node_size = 0, node_color= 'black', edge_color = 'r', width = 8) def display_sum(M1,M2): names = {} for g in M1.ambient_graph.nodes: names[g] = g nx.draw(M1.ambient_graph, pos=names, node_size = 0, node_color= 'black', edge_color = 'black', width = 1) nx.draw(M1.matching_graph, pos=names, node_size = 0, node_color= 'black', edge_color = 'red', width = 8) nx.draw(M2.matching_graph, pos=names, node_size = 0, node_color= 'black', edge_color = 'blue', width = 8) print("note that this doesn't handle overlapping edgs correctly...)") G = nx.grid_graph([100,100]) M = matching(G,[((2,2),(2,3))],.01) lengths = [] for i in range(50000): if i == 1000: N = copy.deepcopy(M) M.step() lengths.append(len(M.matching_graph.edges())) #M.display() print(max(lengths)) display_sum(N,M) def sym_dif(I,F):
def main(): grapht0 = time.process_time() G = nx.grid_graph(list(size)) obstacles = [ (4, 0, 0), (4, 1, 0), (4, 2, 0), (4, 3, 0), (4, 6, 0), (4, 7, 0), (4, 8, 0), (4, 9, 0), (4, 0, 1), (4, 1, 1), (4, 2, 1), (4, 3, 1), (4, 6, 1), (4, 7, 1), (4, 8, 1), (4, 9, 1), (4, 0, 2), (4, 1, 2), (4, 2, 2), (4, 3, 2), (4, 6, 2), (4, 7, 2), (4, 8, 2), (4, 9, 2), ] start = (0, 0, 0) end = (9, 0, 2) add_edges(G) remove_obstacles(obstacles, G) nx.freeze(G) grapht1 = time.process_time() print("Graph:", (grapht1 - grapht0)) patht0 = time.process_time() path = nx.astar_path(G, start, end, heuristic=heuristic) patht1 = time.process_time() print("AStar:", (patht1 - patht0)) fig = plt.figure() ax = fig.add_subplot(111, projection="3d") for o in obstacles: ax.scatter(o[0], o[1], o[2], marker="o", c="blue") for point in path: ax.scatter( point[0], point[1], point[2], marker="o", c="magenta", ) ax.scatter(start[0], start[1], start[2], marker="o", c="red") ax.scatter(end[0], end[1], end[2], marker="o", c="green") ax.set_xlabel("X Label") ax.set_ylabel("Y Label") ax.set_zlabel("Z Label") plt.show()
#t= get_spanning_tree_u_w(nx.grid_graph([4,5])) t= get_spanning_tree_u_w(nx.complete_graph(20)) tgraph=nx.Graph() tgraph.add_edges_from(t) diams.append(nx.diameter(tgraph)) radii.append(nx.radius(tgraph)) avgpath.append(nx.average_shortest_path_length(tgraph)) diams2 = [] radii2 = [] avgpath2 = [] accept = [] G= nx.grid_graph([4,5]) G = nx.complete_graph(20) t= get_spanning_tree_u_w(G) tgraph=nx.Graph() tgraph.add_edges_from(t) tgraphs = [tgraph] pos = nx.kamada_kawai_layout(tgraph)#spectral_layout(G)# for i in range(1000): #plt.figure() #nx.draw(tgraphs[-1],pos = pos) #plt.show() tempT = tree_cycle_walk_cut(tgraphs[-1],G) if nx.radius(tgraphs[-1]) > nx.radius(tempT):
def torrents_and_ferraro_graph(): # Graph from http://arxiv.org/pdf/1503.04476v1 p.26 G = nx.convert_node_labels_to_integers( nx.grid_graph([5, 5]), label_attribute='labels', ) rlabels = nx.get_node_attributes(G, 'labels') labels = {v: k for k, v in rlabels.items()} for nodes in [(labels[(0, 4)], labels[(1, 4)]), (labels[(3, 4)], labels[(4, 4)])]: new_node = G.order() + 1 # Petersen graph is triconnected P = nx.petersen_graph() G = nx.disjoint_union(G, P) # Add two edges between the grid and P G.add_edge(new_node + 1, nodes[0]) G.add_edge(new_node, nodes[1]) # K5 is 4-connected K = nx.complete_graph(5) G = nx.disjoint_union(G, K) # Add three edges between P and K5 G.add_edge(new_node + 2, new_node + 11) G.add_edge(new_node + 3, new_node + 12) G.add_edge(new_node + 4, new_node + 13) # Add another K5 sharing a node G = nx.disjoint_union(G, K) nbrs = G[new_node + 10] G.remove_node(new_node + 10) for nbr in nbrs: G.add_edge(new_node + 17, nbr) # This edge makes the graph biconnected; it's # needed because K5s share only one node. G.add_edge(new_node + 16, new_node + 8) for nodes in [(labels[(0, 0)], labels[(1, 0)]), (labels[(3, 0)], labels[(4, 0)])]: new_node = G.order() + 1 # Petersen graph is triconnected P = nx.petersen_graph() G = nx.disjoint_union(G, P) # Add two edges between the grid and P G.add_edge(new_node + 1, nodes[0]) G.add_edge(new_node, nodes[1]) # K5 is 4-connected K = nx.complete_graph(5) G = nx.disjoint_union(G, K) # Add three edges between P and K5 G.add_edge(new_node + 2, new_node + 11) G.add_edge(new_node + 3, new_node + 12) G.add_edge(new_node + 4, new_node + 13) # Add another K5 sharing two nodes G = nx.disjoint_union(G, K) nbrs = G[new_node + 10] G.remove_node(new_node + 10) for nbr in nbrs: G.add_edge(new_node + 17, nbr) nbrs2 = G[new_node + 9] G.remove_node(new_node + 9) for nbr in nbrs2: G.add_edge(new_node + 18, nbr) G.name = 'Example graph for connectivity' return G
+ "-" + str(current)[14:16] + "-" + str(current)[17:19] + "/" os.makedirs(os.path.dirname(newdir + "init.txt"), exist_ok=True) with open(newdir + "init.txt", "w") as f: f.write("Created Folder") # This builds a graph #graph = construct_graph(graph_path, id_col="id", area_col=area_col, # pop_col=pop_col, district_col=district_col, # data_cols=[county_col] + [cols # for pair in election_columns for cols in pair], # data_source_type="json") gn=10 ns=600 graph=nx.grid_graph([gn,gn]) #add_data_to_graph() #ctemp=0 for e in graph.edges(): graph[e[0]][e[1]]["shared_perim"]=1 #ctemp+=1 #print(ctemp) orange_list=[2,3,4,5,6,7,19,20,22,23,24,28,29,31,32,35,36,37,40,41,47,49,50,54,59,60,62,63,64,66,70,72,79,80,84,85,89,93,98,99]
best_solution = G_2 G = G_2 else: prob = rnd.uniform(low=0, high=1) if prob < thr_p: G = G_2 thr_p = 0.6 * thr_p return best_solution, iterations if __name__ == '__main__': tsd = generateTrafficMatrix(NODES, PROBABILITY) G = nx.grid_graph(dim=[SQRT, SQRT], periodic=True) tsd_2 = copy.copy(tsd) # we create a list with the total amount of traffic exchanged between each pair of nodes traffic_list = [] for s in range(NODES): for d in range(NODES): if tsd_2[s][d] > 0: traffic_list.append([[s, d], tsd_2[s][d] + tsd_2[d][s]]) tsd_2[s][d] = 0 tsd_2[d][s] = 0 # we order the elements of the list in traffic_list = sorted(traffic_list, key=lambda x: x[1], reverse=True) print traffic_list
import networkx as nx import matplotlib.pyplot as plt import spanning_trees.Broder_Wilson_algorithms as bwa from spanning_trees import explore_random """ Generating pretty pictures of trees, stealing from Lorenzo's visualization_tools package. """ # Specify the number of cuts to make and generate a toy grid graph. cuts = 4 graph = nx.grid_graph([10 * cuts, 10 * cuts]) # Fake the data on the graph. for vertex in graph: graph.nodes[vertex]["geopos"] = vertex graph.nodes[vertex]["POP10"] = 1 # Find a partition and find a tree for that partition. partition = explore_random(graph, 1, cuts, divide_and_conquer=True, equi=False, with_walk=False)[0] tree = bwa.random_spanning_tree_wilson(graph) geopos = nx.get_node_attributes(tree, "geopos") # Color the nodes. for i in range(len(partition)):
def nemoodar1(s, p, n): indices = np.arange(n) + 1 random_g_distances = [] random_g_eq_distances = [] l1d_distances = [] l1d_eq_distances = [] first_value = 0 last_none = 0 for v in range(n): av_degree, av_distance = generate_random_g(s, p, v + 1) lattice_g1d = grid_graph(dim=[v + 1]) av_dis = av_distance if av_distance > 0 else None if av_dis is None: last_none = v + 1 else: first_value = v + 1 if first_value == 0 else first_value random_g_distances.append(av_dis) random_g_eq_distances.append( math.log(v + 1) / math.log(av_degree) if av_degree > 0 and math.log(av_degree) != 0 else None) l1d_distances.append(average_g_distance(lattice_g1d)) l1d_eq_distances.append(v + 1) print("First Connected Random Graph: " + str(first_value)) print("Last Unconnected Random Graph: " + str(last_none)) l2d_distances = [None] * n l2d_eq_distances = [None] * n n2 = int(n**(1 / 2)) for v2 in range(n2): lattice_g2d = grid_graph(dim=[v2 + 1, v2 + 1]) n_g2d = (v2 + 1) * (v2 + 1) # print(n_g2d) l2d_distances[n_g2d - 1] = average_g_distance(lattice_g2d) l2d_eq_distances[n_g2d - 1] = n_g2d**(1 / 2) l3d_distances = [None] * n l3d_eq_distances = [None] * n n3 = int(n**(1 / 3)) for v3 in range(n3): lattice_g3d = grid_graph(dim=[v3 + 1, v3 + 1, v3 + 1]) n_g3d = (v3 + 1) * (v3 + 1) * (v3 + 1) # print(n_g3d) l3d_distances[n_g3d - 1] = average_g_distance(lattice_g3d) l3d_eq_distances[n_g3d - 1] = n_g3d**(1 / 3) plt.plot( indices, random_g_distances, 'r-', # random_g_eq_distances, 'y-', l1d_distances, 'k-', # l1d_eq_distances, 'y-', l2d_distances, 'b+', # l2d_eq_distances, 'y+', l3d_distances, 'g+', # l3d_eq_distances, 'y+' ) plt.axis(xmin=1, ymin=0) plt.xlabel('N') plt.ylabel('<d>') plt.savefig('nemoodar1.png') plt.show()
T13=[] T21=[] T22=[] T23=[] T31=[] T32=[] T33=[] T41=[] T42=[] T43=[] for x4 in range(repeticiones): t1i=time.time() G = nx.grid_graph(dim=[x1, x1]) t1f=time.time() K=[i for i in G.edges()] Pesos=[max(0.1,random.gauss(media,desviacion)) for i in range(len(K))] e=[] for i in range(len(G.edges())): a=(K[i][0],K[i][1],Pesos[i]) e.append(a) G.add_weighted_edges_from(e)
def test_rcm_grid_graph(n): g = Graph.from_networkx(nx.grid_graph((n, ), periodic=False)) p = rcm(g) for i, j in enumerate(p[-1::-1]): assert (i == j)
from gerrychain.updaters import Election, Tally, cut_edges from gerrychain.partition import Partition from gerrychain.proposals import recom from gerrychain.metrics import mean_median, efficiency_gap # BUILD GRAPH n = 10 # side length of grid k = 10 #Number of Districts m = n**2 / k #Number of nodes per district rho = 0.4 # Minority Fraction l = rho * n**2 # Number of minority voters: May run into problems if this isn't an integer ns = 50 # Node Size for drawing plans # Create n x n Grid Graph graph = nx.grid_graph([n, n]) # this part adds queen adjacency # for i in range(k*gn-1): # for j in range(k*gn): # if j<(k*gn-1): # graph.add_edge((i,j),(i+1,j+1)) # graph[(i,j)][(i+1,j+1)]["shared_perim"]=0 # if j >0: # graph.add_edge((i,j),(i+1,j-1)) # graph[(i,j)][(i+1,j-1)]["shared_perim"]=0 # Initialization steps for vertex in graph.nodes(): # Set each vertex in the graph to have population 1 graph.node[vertex]["population"] = 1
head_width=0.1, head_length=0.1, length_includes_head=True, head_starts_at_zero=True, fc=color, ec=color) plt.xlim(-0.5, 4.5) plt.ylim(-0.5, 4.5) plt.gca().set_aspect('equal') if __name__ == '__main__': import matplotlib.pyplot as plt G = nx.grid_graph(dim=[5, 5]) # pos = nx.spring_layout(G) # nx.draw(G, pos, node_size=25) # plt.show() fig = plt.figure(figsize=(4, 4)) path = bfs(G, (0, 0), (4, 4)) print(" bfs", *path) plt.subplot(2, 2, 1) plt.title('Breath-first') plot_trajectory_2d(path, label="bfs") path = heuristic_search(G, (0, 0), (4, 4)) print("heuristics", *path) plt.subplot(2, 2, 2) plt.title('Heuristic Search')
# coding: utf-8 # In[1]: import networkx as nx import matplotlib.pyplot as plt # In[82]: #Creo un grafo cuadrado G = nx.grid_graph(dim = [2,2],periodic = False) G.add_edge((1,1),(0,0)) #lista_nodos = G.nodes() # In[83]: #Asigno los pesos a las distintas aristas for edge in G.edges(): #print(edge) G.edges[edge]["Peso"] = 0 #G.edges[edge[0]][edge[1]]["Peso"] = 0 # In[84]:
logdet = np.sum([np.log(s) for s in S]) - np.log(n) return logdet def log_number_spanning_tree(G): n = G.number_of_nodes() spectrum = nx.laplacian_spectrum(G) non_zero_spect = np.delete(spectrum, 0) return np.prod(non_zero_spect) / n m = 3 n = 3 d = 2 G = nx.grid_graph([m, n]) H = nx.grid_graph([m, n]) for x in G.edges(): a = x[0] b = x[1] G.edges[x]["weight"] = (np.abs(a[0] - b[0]) + np.abs(a[1] - b[1])) for x in H.edges(): a = x[0] b = x[1] H.edges[x]["weight"] = (d * np.abs(a[0] - b[0]) + (1 / d) * np.abs(a[1] - b[1])) #W_G 98.44804291763761 #W_H 209.95528522499345 # #
def oneroom(w, h): g = nx.grid_graph(dim=(w, h)) return g
import networkx as nx import matplotlib.pyplot as plt import numpy as np from matplotlib import colors import matplotlib as mpl import math from matplotlib.colors import ListedColormap, LinearSegmentedColormap import json dim = 10 G = nx.grid_graph([dim, dim]) pos = dict(zip(G.nodes(), G.nodes())) for x in range(9, -1, -1): for y in range(9, 0, -1): if x > 0: G.add_edge((x, y), (x - 1, y - 1)) if x < 9: G.add_edge((x, y), (x + 1, y - 1)) services = 4 capacity = np.zeros(6) capacity[0] = 0.01 #print capacity.reshape((2,3)) #Defining capacity node (radial) #par = dim%2.0==0 #dist_capacity=[2,4,] mapCapacity = {0: (1, 2), 1: (2, 2), 2: (3, 3), 3: (4, 4), 4: (5, 5)}
def test_graph_circuit() -> None: graph = nx.grid_graph([2, 3]) layers = 8 params = qf.graph_circuit_params(graph, layers) _ = qf.graph_circuit(graph, layers, params)