def RBR(Na, Nb, za, zb, p): ''' Return a NetworkX graph composed of two random za-, zb-regular graphs of sizes Na, Nb, with Bernoulli(p) distributed coupling. ''' network_build_time = time.time() a_internal_graph = nx.random_regular_graph(za, Na) b_internal_graph = nx.random_regular_graph(zb, Nb) a_inter_stubs = [bern(p) for i in xrange(Na)] b_inter_stubs = [bern(p*float(Na)/float(Nb)) for i in xrange(Nb)] while sum(a_inter_stubs) != sum(b_inter_stubs) or abs(sum(a_inter_stubs)-(p*Na)) > 0: a_inter_stubs = [bern(p) for i in xrange(Na)] b_inter_stubs = [bern(p*float(Na)/float(Nb)) for i in xrange(Nb)] G = nx.bipartite_configuration_model(a_inter_stubs, b_inter_stubs) for u, v in a_internal_graph.edges(): G.add_edge(u, v) for u, v in b_internal_graph.edges(): G.add_edge(Na+u, Na+v) network_build_time = time.time() - network_build_time print('Generating the network took {0:.3f} seconds, {1:.3f} minutes, {2:.3f} hours.'.format(network_build_time, network_build_time/60.0, network_build_time/3600.0)) return G
def generate_random_regular(): d = randint(2,number_of_vertices-1) G = NX.random_regular_graph(d, number_of_vertices) while not (G and NX.is_connected(G)): d = randint(2, number_of_vertices-1) G = NX.random_regular_graph(d, number_of_vertices) return G
def regular(size, degree, seed=None): assert size > 0 assert degree >= 0 if seed: g = nx.random_regular_graph(d=degree, n=size, seed=seed) else: g = nx.random_regular_graph(d=degree, n=size) g.name = 'Random Regular Graph: {n} nodes, {d} degree'.format(n=size, d=degree) return g
def main(): msg = "usage: ./p2p2012.py type r|g|g2 ttl par tries churn_rate" if len(sys.argv) < 7: print msg sys.exit(1) global out_file, churn_rate out_file = sys.stdout gtype = sys.argv[1] walk = sys.argv[2] ttl = int(sys.argv[3]) par = int(sys.argv[4]) tries = int(sys.argv[5]) churn_rate = float(sys.argv[6]) if gtype == "a": g = nx.barabasi_albert_graph(97134, 3) elif gtype == "b": g = nx.barabasi_albert_graph(905668, 12) elif gtype == "c": g = sm.randomWalk_mod(97134, 0.90, 0.23) elif gtype == "d": g = sm.randomWalk_mod(905668, 0.93, 0.98) elif gtype == "e": g = sm.nearestNeighbor_mod(97134, 0.53, 1) elif gtype == "f": g = sm.nearestNeighbor_mod(905668, 0.90, 5) elif gtype == "g": g = nx.random_regular_graph(6, 97134) elif gtype == "h": g = nx.random_regular_graph(20, 905668) elif gtype == "i": g = nx.read_edgelist(sys.argv[7]) if walk == "r": lookup(g, ttl, tries, par, get_random_node) elif walk == "g": lookup(g, ttl, tries, par, get_greedy_node) elif walk == "g2": lookup(g, ttl, tries, par, get_greedy2_node) elif walk == "sum": sum_edges(g, int(sys.argv[3])) nodes = g.number_of_nodes() edges = g.size() avg_cc = nx.average_clustering(g) print >> sys.stderr, nodes, edges, avg_cc
def setup_network(self): # make an adjacency matrix n = self.params.number_agents # make a random graph of links, all nodes have # a fixed number of neighbors. will want to add more controls # here later. self.neighbors = nx.random_regular_graph(NUM_NEIGHBORS, n + (n % 2))
def add_edges_to_groups(output_graph, groups_list, edges_to_add, prob, level): global template_created total_groups = len(groups_list) edges_per_node = max((3 - level), 1) triangle_prob = 0.1*level if False: random_graph = nx.random_regular_graph(int(total_groups/3), total_groups) else: random_graph = nx.powerlaw_cluster_graph(total_groups, edges_per_node, triangle_prob, random.random()*10) if template_created: template_created = False plt.axis('off') position = nx.graphviz_layout(random_graph, prog='sfdp') nx.draw_networkx_nodes(random_graph, position, node_size=30, node_color='r') #output_graph.degree().values()) nx.draw_networkx_edges(random_graph, position, alpha=0.3) plt.savefig(dataset_name2 +"/"+ "template_" + image_name, bbox_inches='tight', dpi=500) print "plot saved as ", image_name random_edges = random_graph.edges() for edge in random_edges: e0 = edge[0] e1 = edge[1] if random.random() > 0.3: e0, e1 = e1, e0 print("adding level{} edges between group{} and group{}".format(level, e0, e1)) add_edges_to_two_groups(output_graph, groups_list[e0], groups_list[e1], edges_to_add, prob)
def regular_D(n,d,D): while True: G=nx.random_regular_graph(d,n) if nx.is_connected(G): diameter = nx.diameter(G) if diameter == D: return G
def create_graph(N_nodes,p_edge,n_infected,regular = False): if regular: k = int(round(p_edge*(N_nodes-1))) G = nx.random_regular_graph(k,N_nodes) else: G = nx.gnp_random_graph(N_nodes,p_edge,directed=False) return set_graph_strategies(G, n_infected)
def connect_fixed_degree(self,N,p): """ All nodes have identical degree; they are each randomly connected to p*N other nodes. If p > 1 - 1/N, this will return the regular, fully connected graph.' """ self.connect_empty(N) d = int(p*N) self.add_edges_from(nx.random_regular_graph(d,N).edges())
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 generate_network(mem_pars, net_pars): if net_pars['type']==graph_type[1]: G = nx.watts_strogatz_graph(net_pars['N'],net_pars['k'],net_pars['p']) elif net_pars['type']==graph_type[2]: G = nx.random_regular_graph(net_pars['degree'], net_pars['N']) cir = Circuit('Memristor network test') # assign dictionary with terminals and memristors memdict = {} w = mem_pars['w'] D = mem_pars['D'] Roff = mem_pars['Roff'] Ron = mem_pars['Ron'] mu = mem_pars['mu'] Tao = mem_pars['Tao'] for e in G.edges_iter(): rval = round(Roff + 0.01 * Roff * (random.random() - 0.5), 2) key = 'R' + str(e[0]) + str(e[1]) [v1, v2] = [e[0], e[1]] memdict[key] = [v1, v2, memristor.memristor(w, D, Roff, Ron, mu, Tao, 0.0)] # we set v=0.0 value in the beginning cir.add_resistor(key, 'n' + str(v1), 'n' + str(v2), rval) G[e[0]][e[1]]['weight'] = rval # edge_labels[e]=rval; for n in G.nodes_iter(): G.node[n]['number'] = n # Add random ground and voltage terminal nodes [v1, gnd] = random.sample(xrange(0, len(G.nodes())), 2) lastnode = len(G.nodes()) G.add_edge(v1, lastnode) G.node[lastnode]['number'] = 'V1' lastnode += 1 G.add_edge(gnd, lastnode) G.node[lastnode]['number'] = 'gnd' plot_graph(G) export_graph(G,'/Users/nfrik/CloudStation/Research/LaBean/ESN/FalstadSPICE/test.txt') cir.add_resistor("RG", 'n' + str(gnd), cir.gnd, 0.001) cir.add_vsource("V1", 'n' + str(v1), cir.gnd, 1000) opa = new_op() # netdict contains setup graph and circuit networkdict = {} networkdict['Graph'] = G networkdict['Circuit'] = cir networkdict['Memristors'] = memdict networkdict['Opa']=opa return networkdict
def main(): graphs = { 'star_graph': nx.star_graph(1000), 'ba_graph': nx.barabasi_albert_graph(1000, 2), 'watts_strogatz': nx.watts_strogatz_graph(1000, 4, p=0.3), 'random_regular': nx.random_regular_graph(4, 1000), } folder = 'resources/' for name, graph in graphs.iteritems(): create_graph_file(graph, folder + name)
def run(self): # Run simulation for several type of networks, in this case Erdos-Renyi and Random Network self.networks = [ { 'network': nx.scale_free_graph(n = self.nodes), 'name': 'ScaleFree' }, { 'network': nx.erdos_renyi_graph(n = self.nodes, p = 0.1), # 0.2, 0.5 'name': 'ErdosRenyi' }, { 'network': nx.random_regular_graph(n = self.nodes, d = 10), 'name': 'RandomNetwork' } ] for network in self.networks: nxgraph = network['network'] graph = helper.convert_nxgraph_to_dict(nxgraph) # write network in pajek filename = 'pajek/'+ network['name'] + '_' + str(self.nodes) + '.net' nx.write_pajek(nxgraph, filename) for mu in self.mu_values: print 'Starting...' start_time = time.time() # B beta (at least 51 values, B=0.02) beta = 0.0 betas = [] averages = [] for i in range(0, 51): start_time_beta = time.time() sis_initial_model = sis.SIS(graph, mu, beta, self.p0) simulation = mc.MonteCarlo(sis_initial_model, self.rep, self.t_max, self.t_trans) total_average = simulation.run() total_time_beta = time.time() - start_time_beta betas.append(beta) averages.append(total_average) print 'B: {}, average: {}, time: {}s'.format(beta, total_average, total_time_beta) beta += 0.02 total_time = time.time() - start_time print 'total time: {}'.format(total_time) # plot results and save in file helper.plot_results(network['name'], self.nodes, mu, betas, averages) helper.write_results(network['name'], self.nodes, mu, betas, averages) break
def generate_noisy_eulerian_circuit_data(options): """ This is a noisy version of the eularian circuit problem. """ while True: num_nodes = options["num_entities"] g = nx.random_regular_graph(2, num_nodes) try: path = list(nxalg.eulerian_circuit(g)) except: continue break edges = g.edges() # generate another misleading cycle num_confusing = options["num_confusing"] if num_confusing > 0: g_confusing = nx.random_regular_graph(2, num_confusing) for e in g_confusing.edges(): edges.append((e[0] + num_nodes, e[1] + num_nodes)) random.shuffle(edges) # randomize index idx = _generate_random_node_index(num_nodes + num_confusing) new_edges = _relabel_nodes_in_edges(edges, idx) new_path = _relabel_nodes_in_edges(path, idx) for edge in new_edges: print "%s connected-to %s" % (edge[0], edge[1]) print "%s connected-to %s" % (edge[1], edge[0]) first_edge = new_path[0] node_list = [str(edge[0]) for edge in new_path] print "eval eulerian-circuit %s %s\t%s" % (first_edge[0], first_edge[1], ",".join(node_list))
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 RandomRegular(d, n, seed=None): """ Returns a random d-regular graph on n vertices, or returns False on failure. Since every edge is incident to two vertices, n\*d must be even. INPUT: - ``n`` - number of vertices - ``d`` - degree - ``seed`` - for the random number generator EXAMPLE: We show the edge list of a random graph with 8 nodes each of degree 3. :: sage: graphs.RandomRegular(3, 8).edges(labels=False) [(0, 1), (0, 4), (0, 7), (1, 5), (1, 7), (2, 3), (2, 5), (2, 6), (3, 4), (3, 6), (4, 5), (6, 7)] :: sage: G = graphs.RandomRegular(3, 20) sage: if G: ... G.show() # random output, long time REFERENCES: - [1] Kim, Jeong Han and Vu, Van H. Generating random regular graphs. Proc. 35th ACM Symp. on Thy. of Comp. 2003, pp 213-222. ACM Press, San Diego, CA, USA. http://doi.acm.org/10.1145/780542.780576 - [2] Steger, A. and Wormald, N. Generating random regular graphs quickly. Prob. and Comp. 8 (1999), pp 377-396. """ if seed is None: seed = current_randstate().long_seed() import networkx try: N = networkx.random_regular_graph(d, n, seed=seed) if N is False: return False return graph.Graph(N, sparse=True) except StandardError: return False
def build_topology_regular(config): """Build a N-regular graph""" size = config['RegularTopology']['size'] degree = config['RegularTopology']['degree'] seed = config['Simulation']['seed'] assert size > 0 assert degree >= 0 top = nx.random_regular_graph(d=degree, n=size, seed=seed) top.name = 'Random Regular Graph: {n} nodes, {d} degree, {s} seed'.format(n=size, d=degree, s=seed) return top
def __init__(self, vertices, degree, seed = int(time.time())): """ Construct a Random Regular Network. The vertices argument contains objects of type Vertex representing the vertices of the network. The degree argument specifies the degree of each vertex. The seed argument is the seed for the random number generator used to build the network. Note that an random regular network has no self loops or parallel edges. """ self.vertices = vertices self.degree = degree self.seed = seed self.g = networkx.random_regular_graph(degree, len(vertices), seed = seed) self.__adj_list_map__ = {}
def random_graph_from_parameters(vertices_per_block, block_neighbors, seed=None): """Returns a random graph that satisfies the given parameters. `vertices_per_block` and `block_neighbors` are the matrices returned by :func:`~fraciso.partitions.partition_parameters`. If `seed` is specified, it must be an integer provided as the seed to the pseudorandom number generator used to generate the graph. """ # TODO there is an alternate way to implement this function: create a # random regular networkx.Graph object for each block of the partition, # create a random biregular Graph object between blocks of the partition, # then compute the union of the two graphs. # # Rename some variables for the sake of brevity. n, D = np.asarray(vertices_per_block), np.asarray(block_neighbors) # p is the number of blocks p = len(n) mat = to_numpy_matrix rr = lambda d, s: random_regular_graph(d, s, seed=seed) rb = lambda L, R, d, e: _random_biregular_graph(L, R, d, e, True, seed) # Create a block diagonal matrix that has the regular graphs corresponding # to the blocks of the partition along its diagonal. regular_graphs = block_diag(*(mat(rr(d, s)) for s, d in zip(n, D.diagonal()))) # Create a block strict upper triangular matrix containing the upper-right # blocks of the bipartite adjacency matrices. # # First, we create a list containing only the blocks necessary. blocks = [[rb(n[i], n[j], D[i, j], D[j, i]) for j in range(i + 1, p)] for i in range(p - 1)] # Next, we pad the lower triangular entries with blocks of zeros. (We also # need to add an extra block row of all zeros.) At this point, `padded` is # a square list of lists. padded = [[np.zeros((n[i], n[j])) for j in range(p - len(row))] + row for i, row in enumerate(blocks)] padded.append([np.zeros((n[-1], n[i])) for i in range(p)]) # To get the block strict upper triangular matrix, we concatenate the block # matrices in each row. biregular_graphs = np.vstack(np.hstack(row) for row in padded) # Finally, we add the regular graphs on the diagonaly, the upper biregular # graphs, and the transpose of the upper biregular graphs in order to get a # graph that has the specified parameters. adjacency_matrix = regular_graphs + biregular_graphs + biregular_graphs.T return from_numpy_matrix(adjacency_matrix)
def run_regular(degree=3, nodes=1000, iterations=1000, epsilon_control=0.1, epsilon_damage=0.001): """ Run on a k-regular graph. Returns (uncontrolled, controlled, df, costs). """ # Generate graph and set up parameters degree = int(degree) nodes = int(nodes) iterations = int(iterations) G = nx.random_regular_graph(degree, nodes) # p = {0: 0.11351, 1: 0.35651} # Flipped p and passed C, so that run_regular matches how things are done in run_scalefree p = {0: 0.52998, 1: 0.35651, 2: 0.11351} # Max capacity is linked to the graph's degree C = (degree - 1) * np.ones(nodes) G, L0 = sandpile.initialize_loads(G, p=p, C=C) return do_run(G, L0, C, iterations, epsilon_control, epsilon_damage)
def init_graph(self,g='reg',k=2): """Creates a graph of type g""" self.diseasenetwork.add_nodes_from(self.agents) #Rewiring of graphs could count as random_mixing #Types of random graphs gtype = { 'er':nx.fast_gnp_random_graph(self.population,0.05), 'nws':nx.newman_watts_strogatz_graph(self.population,k,0.5), 'ws':nx.watts_strogatz_graph(self.population,k,0.5), 'cws':nx.connected_watts_strogatz_graph(self.population,k,0.5,10), 'ba':nx.barabasi_albert_graph(self.population,k), 'reg':nx.random_regular_graph(k,self.population), 'grid':nx.grid_2d_graph(self.population/2,self.population/2) } #This is causing the trouble need to map each edge to nodes :) if g == 'grid': self.diseasenetwork.add_edges_from([ (self.agents[x[0]],self.agents[y[0]]) for x,y in gtype[g].edges() ]) else: self.diseasenetwork.add_edges_from([ (self.agents[x],self.agents[y]) for x,y in gtype[g].edges() ])
def add_edges_to_groups(output_graph, groups_list, edges_to_add, prob, level): total_groups = len(groups_list) edges_per_node = max((3 - level), 1) triangle_prob = 0.1*level if False: random_graph = nx.random_regular_graph(int(total_groups/3), total_groups) else: random_graph = nx.powerlaw_cluster_graph(total_groups, edges_per_node, triangle_prob, random.random()*10) random_edges = random_graph.edges() for edge in random_edges: e0 = edge[0] e1 = edge[1] if random.random() > 0.3: e0, e1 = e1, e0 print("adding level{} edges between group{} and group{}".format(level, e0, e1)) add_edges_to_two_groups(output_graph, groups_list[e0], groups_list[e1], edges_to_add, prob)
def kronecker_regular(seed_degree=3, seed_nodes=8, exponent=2, a_nodes_left=0.8, a_edges_left=0.8, b_nodes_left=0.8, b_edges_left=0.8, anchors=5, candidates=8, random_seed=0): other_seed = random_seed + 1 seed_graph = nx.random_regular_graph(seed_degree, seed_nodes, random_seed) g = netgen.kronecker_graph(seed_graph, exponent) g_a = netgen.decimated_graph(g, a_nodes_left, a_edges_left, random_seed) g_b = netgen.decimated_graph(g, b_nodes_left, b_edges_left, other_seed) g_a, g_b, true_match = netgen.permute_graphs(g_a, g_b, random_seed) anchors, cands = netgen.get_anchors_candidates(g_a, g_b, true_match, anchors, candidates, random_seed) anchors = tuple(anchors) name = "kronecker_regular(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)" % ( seed_degree, seed_nodes, exponent, a_nodes_left, a_edges_left, b_nodes_left, b_edges_left, anchors, candidates, random_seed) return TestCase(g_a, g_b, anchors, cands, true_match, name)
def main(args): nnodes = args.nnodes degree = args.degree assert degree < nnodes low_diam, low_aspl = lower_bound_of_diam_aspl(nnodes, degree) g = nx.random_regular_graph(degree, nnodes, 0) if nx.is_connected(g): hops = nx.shortest_path_length(g, weight=None) diam, aspl = max_avg_for_matrix(hops) else: diam, aspl = float("inf"), float("inf") print("{}\t{}\t{}\t{}\t{}\t{}\t{}%".format(nnodes, degree, diam, aspl, diam - low_diam, aspl - low_aspl, 100 * (aspl - low_aspl) / low_aspl)) basename = "n{}d{}.random".format(nnodes, degree) save_edges(g, basename + ".edges") # save_image(g, basename + ".png") # save_json(author, email, text1, basename + ".edges", basename + ".json") return
def generate_random_graphs(numberOfNodes, outputFile, graphType, degree=None): sparseResult = open(outputFile, "w") # first writing the number of nodes if graphType == "degreeBased": G = nx.random_regular_graph(degree, numberOfNodes, numberOfNodes * int(math.sqrt(numberOfNodes))) if graphType == "completeChaos": G = nx.gnm_random_graph(numberOfNodes, numberOfNodes * int(math.sqrt(numberOfNodes))) if graphType == "dense": G = nx.dense_gnm_random_graph(numberOfNodes, numberOfNodes * int(math.sqrt(numberOfNodes))) sparseResult.write(str(numberOfNodes) + " " + str(nx.number_of_edges(G)) + "\n") semiSparseRep = nx.to_dict_of_lists(G) # print semiSparseRep for element in semiSparseRep: if len(semiSparseRep[element]) == 0: return 0 for j in semiSparseRep[element]: sparseResult.write(str(j + 1) + " ") sparseResult.write("\n") return 1
def make_neighborhoods(self, list_of_agents): """ Allocates the agents on a grip. A von Neumann neighborhood is assumed so every agent has four neighbors. """ assert isinstance(list_of_agents, list), "list of agents not list but {}".format(type(list_of_agents)) assert isinstance(list_of_agents[0], farmer.Farmer), \ "Entries of list not farmer but {}".format(type(list_of_agents[0])) self.logger_pop_gen.warning('Initiated a grid neighborhood.') graph = nx.random_regular_graph(4, self.__params['number_of_farmers']) neighborhood_lists = [[] for i in range(self.__params['number_of_farmers'])] for tup in graph.edges(): neighborhood_lists[tup[0]].append(tup[1]) neighborhood_lists[tup[1]].append(tup[0]) for i in range(len(self.__agents)): self.__agents[i].neighborhood = [self.__agents[j] for j in neighborhood_lists[i]] assert isinstance(self.__agents[i], farmer.Farmer), "An error in the list of agents." assert isinstance(self.__agents[i].neighborhood, list), "Neighborhood not given of list." assert isinstance(self.__agents[i].neighborhood[0], farmer.Farmer), \ "Elements in neighborhood not agents."
def main(): d = int(raw_input()) n = int(raw_input()) g = networkx.random_regular_graph(d, n) node_properties = {} for _n in g: angle = random.choice(block.ANGLES) group = random.choice(block.GROUPS) node_properties[_n] = block.Block(group, angle) cm = compound.Compound() for a, b in g.edges_iter(): bond = compound.Bond(node_properties[a], node_properties[b], 1, 1) cm.add_bond(bond) print cm.get_mass() print cm.get_max_energy() print cm.get_energy_absorption() print cm.get_friction()
def generate_eulerian_circuit_data(options): while True: num_nodes = options["num_entities"] g = nx.random_regular_graph(2, num_nodes) try: path = list(nxalg.eulerian_circuit(g)) except: continue # print path break for edge in g.edges(): print "%s connected-to %s" % (edge[0], edge[1]) print "%s connected-to %s" % (edge[1], edge[0]) first_edge = path[0] node_list = [str(edge[0]) for edge in path] print "eval eulerian-circuit %s %s\t%s" % (first_edge[0], first_edge[1], ",".join(node_list))
def create(self): self.last = datetime.now() self.frame = 0 self.unpinnedframe = 0 if self.graph: for n in self.graph.node: for m in self.graph[n]: if m > n: continue if 'actor' in self.graph[n][m]: self.stage.remove_child(self.stage.find_child(self.graph[n][m]['actor'])) del self.graph[n][m]['actor'] if 'actor' in self.graph.node[n]: self.stage.remove_child(self.stage.find_child(self.graph.node[n]['actor'])) del self.graph.node[n]['actor'] self.graph = networkx.random_regular_graph(3, 26) # nice test graph self.centre() self.mindist = 10. self.naturallength = 20. self.damping = 0.05 self.spring = 0.05 self.stepsize = 1. for n in self.graph.node: for m in self.graph[n]: if m > n: continue self.graph[n][m]['strength'] = 1. # including tooltips causes a memory leak when actors are destroyed (bgo 669688) self.graph[n][m]['actor'] = GooCanvas.CanvasPath(parent = self.stage, stroke_color_rgba = 0x11111180, line_width = 0.75, title='link') # create visualisation actor self.graph.node[n]['actor'] = GooCanvas.CanvasEllipse(parent = self.stage, fill_color_rgba = 0x33333380, line_width = 0, title = "node", height = self.blobsize, width = self.blobsize) self.graph.node[n]['actor'].connect("button-press-event", self.button) self.graph.node[n]['actor'].connect("motion-notify-event", self.drag) self.graph.node[n]['actor'].connect("button-release-event", self.unpin) self.graph.node[n]['actor'].connect("grab-broken-event", self.unpin) # set item physical attributes self.graph.node[n]['mass'] = 0.25 self.graph.node[n]['charge'] = 10.
pnm_params = { 'exp_data_path': args.exp_data, 'pore_data_path': args.pore_data, 'inlets': inlets, 'R_inlet': R_inlet, 'job_count': job_count, 'verbose': verbose } if args.stats_data is None: print('No network statistics were given, using random waiting times.') if args.generate_network: print('Generating an artificial network'); n = args.node_count pnm_params['graph'] = nx.random_regular_graph(4, n) elif pnm_params['exp_data_path'] is None: raise ValueError('Please use either -G or -E to choose a graph model') pnm = PNM(args.stats_data, **pnm_params) if verbose: print('\nre', pnm.radi, '\n') print('\nh0e', pnm.heights, '\n') print('\nwaiting times', pnm.waiting_times, '\n') print('\ninlets', pnm.inlets, '\n') if args.material: mp = [] for param in args.material.split(','): mp.append(np.float64(param))
def get_test_problem(n=14, p=2, d=3): G = nx.random_regular_graph(d, n) gamma, beta = [np.pi / 3] * p, [np.pi / 2] * p return G, gamma, beta
for thresh_dens in np.arange(.1, .51, .1): print 'Thresh: %s' % thresh_dens print time.ctime() subjid = d graph_dir = os.path.join(dat_dir, 'graphs') if not os.path.exists(graph_dir): os.makedirs(graph_dir) graph_outname = '%s.dens_%s.edgelist.gz' % (subjid, thresh_dens) gr = ge.GRAPHS(subjid, pc_dat[d], thresh_dens, graph_dir, os.path.join(graph_dir, graph_outname)) g = gr.make_networkx_graph(n_nodes) for n in xrange(niter): deg = int(np.mean(g.degree().values())) g_rand = nx.random_regular_graph(deg, n_nodes) outg_pref = 'iter%d_rand_%s.dens_%s.edgelist.gz' % \ (n, subjid, thresh_dens) outg = os.path.join(random_graph_dir, outg_pref) nx.write_edgelist(g_rand, outg, data=False) # get modularity and trees print 'Doing modularity evaluation... ' print time.ctime() Qs = np.zeros(niter) trees = np.zeros(n_nodes * niter).reshape(n_nodes, niter) for i in xrange(niter): trees[:, i], Qs[i] = gr.get_modularity(g_rand) Qs_outname = 'iter%d_rand_%s.dens_%s.Qval' % \ (n, subjid, thresh_dens) np.savetxt(os.path.join(mod_dir, Qs_outname), Qs, fmt='%.4f')
from GW import goemans_williamson as gw import numpy as np import time p_max = 8 # maxdepth N = 20 # number of graphs per node number n d = 3 # degree of regular graphs n_gw = 10 # number of tries GW algorithm per graph # creating dataframe filename = 'data_3-regular_unweighted_pyquil_random_1.csv' output = pd.DataFrame() for n in [8, 10, 12, 14, 16]: for s in range(N): G = nx.random_regular_graph(d, n, seed=s) graph_type = str(d) + '-regular_' + str(n) + '-nodal' # GW samples gw_samples = [gw(G) for _ in range(n_gw)] gw_mean = np.mean(gw_samples) gw_std = np.std(gw_samples) gw_max = np.max(gw_samples) gw_min = np.min(gw_samples) print("GW mean =", gw_mean) # Cmax (optimal) start_brute = time.time() Cmax = brute_force(G) gw_bound = 0.878 * Cmax end_brute = time.time()
def simulate_series(simulation_data): disease_params = simulation_data #disease_params['order'] = 1 simulation_data['G'] = simulation_data['network_n'] # genes simulation_data['S'] = simulation_data['P'] simulation_data['patients_number'] = simulation_data['S'] # make network if (simulation_data['network_type'] == 'BA'): g = nx.barabasi_albert_graph(simulation_data['network_n'], simulation_data['network_m']) elif (simulation_data['network_type'] == 'ER'): g = nx.erdos_renyi_graph(simulation_data['network_n'], simulation_data['network_p']) elif (simulation_data['model'] == '2D'): g = nx.grid_2d_graph(simulation_data['network_x'], simulation_data['network_y'], periodic=True) elif (simulation_data['model'] == 'CYC'): g = nx.cycle_graph(simulation_data['network_n']) elif (simulation_data['model'] == 'REG'): g = nx.random_regular_graph(simulation_data['network_d'], simulation_data['network_n']) #neighbors_dict = all_neighbors_order(g, simulation_params['order']) colored_graph = color_nodes_order(g, disease_params['D'], disease_params['p'], disease_params['order']) #colored_graph = color_nodes_order(g, disease_params['D'], disease_params['p'], disease_params['order']) g_strip = g.copy() #solitary = [ n for n,d in g_strip.degree_iter() if d == 0 ] solitary = [n for n, d in g_strip.degree() if d == 0] g_strip.remove_nodes_from(solitary) layout = nx.spring_layout(g_strip) result = {} #result['layout'] = layout #result['g'] = g #result['g_strip'] = g_strip for disease_params['rho_0'] in disease_params['rho_0_list']: result[str(disease_params['rho_0'])] = {} result_disease = simulate_artificial_disease(disease_params, simulation_data, colored_graph, colored_graph) collective_genes = get_collective_gene_expression( simulation_data, result_disease['expressed_genes_under'], result_disease['expressed_genes_over'], result_disease['phenotype_table'], mode='normal') filtered = collective_genes['flt'] for flt in simulation_data['f_list']: #result[str(disease_params['rho_0'])][str(flt)] = {} tmp_result = {} tmp_result['expressed_genes_sick'] = result_disease[ 'expressed_genes_sick'] tmp_result['expressed_genes_healthy'] = result_disease[ 'expressed_genes_healthy'] tmp_result['extracted_genes'] = list( set(filtered['dis_over_flt_' + str(flt)])) tmp_result['disease_genes'] = list( set(filtered['dis_under_flt_' + str(flt)])) tmp_result['true_poositive_genes'] = list( set(filtered['dis_under_flt_' + str(flt)]) & set(filtered['dis_over_flt_' + str(flt)])) tmp_result['disease_params'] = disease_params tmp_result['layout'] = layout tmp_result['g'] = g tmp_result['g_strip'] = g_strip tmp_result['rho_0'] = disease_params['rho_0'] tmp_result['flt'] = flt result[str(disease_params['rho_0'])][str(flt)] = tmp_result return result
######################################################################################################################## # initialization ######################################################################################################################## background_list1 = [Background([0, 1]) for j in range(int(group_size / 2.))] background_list2 = [Background([2, 3]) for j in range(int(group_size / 2.))] background_list = background_list1 + background_list2 participation_tendency = [1.] * group_size ### creat agent class agent: pass # create a small world network net = nx.random_regular_graph(d=4, n=20) # initialization agent_list = [] for i in range(group_size): ag = agent() ag.index = i ag.participation_tendency = participation_tendency[i] ag.background = background_list[i] ag.idea_pool = [] # add agent into agent list agent_list.append(ag) ######################################################################################################################## # generate three groups: cluster, random, and dispersed ########################################################################################################################
ephPopHistory = (epop[1].lower() == "true") elif "--ephTime" in arg: ephtime = arg.split("=") ephTime = int(ephtime[1]) elif "--graphFile" in arg: gfile = arg.split("=") graphFile = gfile[1] if operation == "newGraph": #Generate graph according to type if graphtype == "ba": newGraph = nx.barabasi_albert_graph(numNodes, numEdges) elif graphtype == "complete": newGraph = nx.complete_graph(numNodes) elif graphtype == "simple": newGraph = nx.random_regular_graph(numEdges, numNodes) else: newGraph = nx.barabasi_albert_graph(numNodes, numEdges) #print(newGraph.number_of_nodes()) #Write base graph to file nx.write_adjlist(newGraph, graphFile) file = open("opts_" + graphFile, "w") file.write(str(numNodes)) file.close() elif operation == "simulation": #Load previously generated graph G = nx.read_adjlist(graphFile) numNodes = G.number_of_nodes()
def main(): # Set problem parameters n = 6 p = 2 # Generate a random 3-regular graph on n nodes graph = networkx.random_regular_graph(3, n) # Make qubits qubits = cirq.LineQubit.range(n) # Print an example circuit betas = np.random.uniform(-np.pi, np.pi, size=p) gammas = np.random.uniform(-np.pi, np.pi, size=p) circuit = qaoa_max_cut_circuit(qubits, betas, gammas, graph) print('Example QAOA circuit:') print(circuit.to_text_diagram(transpose=True)) # Create variables to store the largest cut and cut value found largest_cut_found = None largest_cut_value_found = 0 # Initialize simulator simulator = cirq.Simulator() # Define objective function (we'll use the negative expected cut value) num_samples = 1000 def f(x): # Create circuit betas = x[:p] gammas = x[p:] circuit = qaoa_max_cut_circuit(qubits, betas, gammas, graph) # Sample bitstrings from circuit result = simulator.run(circuit, repetitions=num_samples) bitstrings = result.measurements['m'] # Process bitstrings sum_of_cut_values = 0 nonlocal largest_cut_found nonlocal largest_cut_value_found for bitstring in bitstrings: value = cut_value(bitstring, graph) sum_of_cut_values += value if value > largest_cut_value_found: largest_cut_value_found = value largest_cut_found = bitstring mean = sum_of_cut_values / num_samples return -mean # Pick an initial guess x0 = np.random.uniform(-np.pi, np.pi, size=2 * p) # Optimize f print('Optimizing objective function ...') scipy.optimize.minimize(f, x0, method='Nelder-Mead', options={'maxiter': 50}) # Compute best possible cut value via brute force search max_cut_value = max( cut_value(bitstring, graph) for bitstring in itertools.product(range(2), repeat=n)) # Print the results print( 'The largest cut value found was {}.'.format(largest_cut_value_found)) print('The largest possible cut has size {}.'.format(max_cut_value)) print('The approximation ratio achieved is {}.'.format( largest_cut_value_found / max_cut_value))
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 as e: print("ERROR ON '{}'. {}".format( getattr(args, 'input'+suffix).name, e), file=sys.stderr) exit(-1) else: raise RuntimeError("Command line does not specify a graph") # Graph modifications if getattr(args, 'plantclique'+suffix) is not None \ and getattr(args, 'plantclique'+suffix) > 1: cliquesize = getattr(args, 'plantclique'+suffix) if cliquesize > G.order(): raise ValueError("Clique cannot be larger than graph") clique = random.sample(G.nodes(), cliquesize) for v, w in combinations(clique, 2): G.add_edge(v, w) if getattr(args, 'addedges'+suffix) is not None \ and getattr(args, 'addedges'+suffix) > 0: k = getattr(args, 'addedges'+suffix) G.add_edges_from(sample_missing_edges(G, k)) if hasattr(G, 'name'): G.name = "{} with {} new random edges".format(G.name, k) if getattr(args, 'splitedge'+suffix): (u, v) = next(G.edges_iter()) G.remove_edge(u, v) for i in range(G.order()+1): if i not in G: new_node = i break G.add_edge(u, new_node) G.add_edge(v, new_node) if hasattr(G, 'name'): G.name = "{} with a split edge".format(G.name) # Output the graph is requested if getattr(args, 'savegraph'+suffix) is not None: writeGraph(G, getattr(args, 'savegraph'+suffix), 'simple', getattr(args, 'graphformat'+suffix)) return G
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render import networkx as nx from networkx.readwrite import json_graph import json import threading import thread import time from django.http import JsonResponse # Create your views here. #卫星网络,两个 SatG11 = nx.random_regular_graph(3, 12) SatG12 = nx.random_regular_graph(3, 12) SatG21 = nx.random_regular_graph(3, 12) SatG22 = nx.random_regular_graph(3, 12) SatG31 = nx.random_regular_graph(3, 12) SatG32 = nx.random_regular_graph(3, 12) #接入卫星,2个子网,每个子网有三个 InSatG11 = nx.random_regular_graph(3, 30) InSatG12 = nx.random_regular_graph(3, 40) InSatG21 = nx.random_regular_graph(3, 30) InSatG22 = nx.random_regular_graph(3, 40) InSatG31 = nx.random_regular_graph(3, 30)
def main(file=None, p=5, shots=1, g=[], b=[], lang='ibm', opt_iters=50, ER=[]): shots = int(shots) p = int(p) opt_iters = int(opt_iters) if len(g) != 0: g = [float(x) for x in g] if len(b) != 0: b = [float(x) for x in b] print('') print('QAOA with p=' + str(p) + ', shots=' + str(shots)) print('') if len(g) == 0: # and len(b) > 0: for it in range(p): g.append(np.random.normal(.5, .01)) if len(b) == 0: # and len(g) > 0: for it in range(p): b.append(np.random.normal(.5, .01)) x0 = np.array(g + b) def simulator_call(a, b): return 0 #adj_mat,p,lang,shots def run_func_scaled(x0): #pass this function through classical optimization g = x0[:len(x0) // 2] b = x0[len(x0) // 2:] #feed graph into simulator ##run = INSERT HERE## meta_circ_str, nqbits = circuit_gen(meta_adj_mat, g, b, p, 'ibm') run = IBM_run(meta_circ_str, nqbits, shots) #need to check that run output structure will match the average_cut function# avg_cut = average_cut(run, shots, meta_adj_mat) return -avg_cut if avg_cut != 0 else 0 def run_func_final(x): assert len(x) == 2 * p g_meta = x[:len(x) // 2] b_meta = x[len(x) // 2:] meta_circ_str, nqbits = circuit_gen(meta_adj_mat, g_meta, b_meta, p, 'ibm') meta_run = IBM_run(meta_circ_str, nqbits, shots) meta_avg_cut = average_cut(meta_run, shots, meta_adj_mat) fin_cut, bs = final_cut(meta_run, meta_adj_mat) return meta_avg_cut, fin_cut, meta_run, bs, meta_circ_str def scale_down_prob(e_l, N_l, N_s): return (e_l / N_l) * N_s try: os.mkdir('large_graphs') except: pass try: os.mkdir('scaled_down_graphs') except: pass try: os.mkdir('results') except: pass num_large_graphs = 1 num_scaled_graphs = 3 def cost_function_C(x, G): E = G.edges() if (len(x) != len(G.nodes())): return np.nan C = 0 for index in E: e1 = index[0] e2 = index[1] w = 1 C = C + w * x[e1] * (1 - x[e2]) + w * x[e2] * (1 - x[e1]) return C from qtensor import QAOA_energy, QtreeQAOAComposer, QtreeSimulator from qtensor import QAOA_energy from qtensor import CirqQAOAComposer, CirqSimulator from qtensor.ProcessingFrameworks import PerfNumpyBackend ##TESTING STARTS HERE## def simulate_one_amp(G, gamma, beta): composer = QtreeQAOAComposer(graph=G, gamma=gamma, beta=beta) composer.ansatz_state() print(composer.circuit) sim = QtreeSimulator() result = sim.simulate(composer.circuit) print('QTensor 1 amp', result.data) print('QTensor 1 prob', np.abs(result.data)**2) def profile_graph(G, gamma, beta): #print(G) meta_adj_mat = networkx.to_numpy_array(G) print(meta_adj_mat) gamma, beta = np.array(gamma), np.array(beta) #print(meta_adj_mat) start = time.time() def simulate_qiskit(meta_adj_mat, gamma, beta): meta_circ_str, nqbits = circuit_gen(meta_adj_mat, gamma, beta, p, 'ibm') #print('qiskit cirq\n', meta_circ_str) meta_run = IBM_run(meta_circ_str, nqbits, shots) print('qiskit sim time', time.time() - start) #print(meta_run) avr_C = 0 max_C = [0, 0] hist = {} for k in range(len(G.edges()) + 1): hist[str(k)] = hist.get(str(k), 0) for sample in list(meta_run.keys()): # use sampled bit string x to compute C(x) x = [int(num) for num in reversed(list(sample))] #x = [int(num) for num in (list(sample))] tmp_eng = cost_function_C(x, G) #print("cost", x, tmp_eng) # compute the expectation value and energy distribution avr_C = avr_C + meta_run[sample] * tmp_eng hist[str(round(tmp_eng))] = hist.get(str(round(tmp_eng)), 0) + meta_run[sample] # save best bit string if (max_C[1] < tmp_eng): max_C[0] = sample max_C[1] = tmp_eng print(hist) qiskit_time = time.time() - start label = '0' * G.number_of_nodes() try: print('Qiskit first prob: ', meta_run[label] / shots) except KeyError: print('Qiskit does not have samples for state 0') return qiskit_time, avr_C / shots try: qiskit_time, qiskit_e = 0, 0 qiskit_time, qiskit_e = simulate_qiskit(meta_adj_mat, gamma, beta) except Exception as e: print('Qiskit error', e) #gamma, beta = [-gamma/2/np.pi, gamma, gamma], [beta/1/np.pi, beta, beta] qiskit_result = simulate_qiskit_amps(G, gamma, beta) gamma, beta = -gamma / 2 / np.pi, beta / 1 / np.pi start = time.time() print(gamma, beta) E = QAOA_energy(G, gamma, beta) #assert E-E_no_lightcones<1e-6 qtensor_time = time.time() - start print('\n QTensor:', E) print('####== Qiskit:', qiskit_e) print('Delta with qtensor:', E - qiskit_e) print('####== Qiskit amps result', qiskit_result) print('Delta with qtensor:', E - qiskit_result) print('qiskit energy time', qiskit_time) print('QTensor full time', qtensor_time) assert abs(E - qiskit_result ) < 1e-6, 'Results of qtensor do not match with qiskit' return qiskit_time, qtensor_time gamma, beta = [np.pi / 8], [np.pi / 6] qiskit_profs = [] qtensor_profs = [] graphs = [networkx.random_regular_graph(3, n) for n in range(4, 16, 2)] for n in range(4, 8, 1): G = networkx.complete_graph(n) #graphs.append(G) continue G = networkx.Graph() G.add_nodes_from(range(n)) G.add_edges_from(zip(range(n), range(1, n))) G.add_edges_from([[0, n - 1]]) graphs.append(G) if False: n = 4 G = networkx.Graph() G.add_nodes_from(range(n)) G.add_edges_from(zip(range(n), range(1, n))) G.add_edges_from([[0, n - 1]]) graphs.append(G) #graphs = [] elist = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 0], [0, 5], [1, 6], [2, 7], [3, 8], [4, 9], [5, 7], [5, 8], [6, 8], [6, 9], [7, 9]] G = networkx.OrderedGraph() G.add_edges_from(elist) graphs.append(G) for G in graphs: #G.add_edges_from([[1,n-1]]) qiskit_time, qtensor_time = profile_graph(G, gamma, beta) qiskit_profs.append(qiskit_time) qtensor_profs.append(qtensor_time) #print((G.number_of_edges()-E)/2) tostr = lambda x: [str(a) for a in x] print(', '.join(tostr(qiskit_profs))) print(', '.join(tostr(qtensor_profs)))
def random_graph(n, M): #graph = networkx.erdos_renyi_graph(n,.03) graph = networkx.random_regular_graph(3, n) return graph
from networkx import random_regular_graph import networkx as nx import random n = 10 # 10 nodes m = 12 # 20 edges G = random_regular_graph(n, m, seed=12) G.remove_nodes_from(random.sample(G.nodes(), 2)) fh = open("new_test.edgelist", 'w') for edge in G.edges(): fh.write("{0} {1}\n".format(edge[0], edge[1]))
def refresh3(request): global tempSatG1, tempSatG2, tempInSatG1, tempInSatG2, tempLandG1, tempLandG2 global SatG11, SatG12, SatG21, SatG22, SatG31, SatG32 global InSatG11, InSatG12, InSatG21, InSatG22, InSatG31, InSatG32 global LandG11, LandG12, LandG21, LandG22, LandG31, LandG32 for item in range(0, tempSatG1.number_of_nodes()): tempSatG1.node[item]['category'] = 1 for item in range(0, tempSatG2.number_of_nodes()): tempSatG2.node[item]['category'] = 1 for item in range(0, tempInSatG1.number_of_nodes()): tempInSatG1.node[item]['category'] = 1 for item in range(0, tempInSatG2.number_of_nodes()): tempInSatG2.node[item]['category'] = 1 for item in range(0, tempLandG1.number_of_nodes()): tempLandG1.node[item]['category'] = 1 for item in range(0, tempLandG2.number_of_nodes()): tempLandG2.node[item]['category'] = 1 SatG11 = nx.random_regular_graph(3, 12) SatG12 = nx.random_regular_graph(3, 12) SatG21 = nx.random_regular_graph(3, 12) SatG22 = nx.random_regular_graph(3, 12) SatG31 = nx.random_regular_graph(3, 12) SatG32 = nx.random_regular_graph(3, 12) # 接入卫星,2个子网,每个子网有三个 InSatG11 = nx.random_regular_graph(3, 30) InSatG12 = nx.random_regular_graph(3, 40) InSatG21 = nx.random_regular_graph(3, 30) InSatG22 = nx.random_regular_graph(3, 40) InSatG31 = nx.random_regular_graph(3, 30) InSatG32 = nx.random_regular_graph(3, 40) # 地面子网,两个网络,第一个网络有70个结点,第二个网络有90个结点 LandG11 = nx.random_regular_graph(3, 100) LandG12 = nx.random_regular_graph(3, 100) LandG21 = nx.random_regular_graph(3, 100) LandG22 = nx.random_regular_graph(3, 100) LandG31 = nx.random_regular_graph(3, 100) #图初始化 for item in range(0, SatG11.number_of_nodes()): SatG11.node[item]['category'] = 1 SatG21.node[item]['category'] = 1 SatG31.node[item]['category'] = 1 for item in range(0, SatG12.number_of_nodes()): SatG12.node[item]['category'] = 1 SatG22.node[item]['category'] = 1 SatG32.node[item]['category'] = 1 for item in range(0, InSatG11.number_of_nodes()): InSatG11.node[item]['category'] = 1 InSatG21.node[item]['category'] = 1 InSatG31.node[item]['category'] = 1 for item in range(0, InSatG12.number_of_nodes()): InSatG12.node[item]['category'] = 1 InSatG22.node[item]['category'] = 1 InSatG32.node[item]['category'] = 1 for item in range(0, LandG11.number_of_nodes()): LandG11.node[item]['category'] = 1 LandG21.node[item]['category'] = 1 LandG31.node[item]['category'] = 1 for item in range(0, LandG12.number_of_nodes()): LandG12.node[item]['category'] = 1 LandG22.node[item]['category'] = 1 LandG32.node[item]['category'] = 1 return render(request, "index3.html")
import networkx as nx if __name__ == '__main__': n = int(input()) G = nx.random_regular_graph(4, n) f = open('10-regular_graph/10-regular_graph' + str(n) + '.txt', 'w') f.write(str(n) + ' ' + str(G.number_of_edges()) + '\n') for i, j in G.edges(): f.write(str(i) + ' ' + str(j) + '\n') print(nx.is_connected(G))
# Imports - useful additional packages import networkx as nx from docplex.mp.model import Model # Imports - Qiskit from qiskit import Aer from qiskit.aqua import QuantumInstance from qiskit.aqua.algorithms import QAOA from qiskit.aqua.components.optimizers import SPSA, NELDER_MEAD # Optimizers available: ['Optimizer', 'ADAM', 'AQGD', 'CG', 'COBYLA', 'GSLS', 'L_BFGS_B', 'NELDER_MEAD', 'NFT', 'P_BFGS', 'POWELL', 'SLSQP', 'SPSA', 'TNC', 'CRS', 'DIRECT_L', 'DIRECT_L_RAND', 'ESCH', 'ISRES'] from qiskit.optimization.applications.ising import docplex, max_cut from qiskit.optimization.applications.ising.common import sample_most_likely # Generate a graph and its corresponding adjacency matrix G = nx.random_regular_graph(2, 6) n = len(G) pos = nx.spring_layout(G) w = my_graphs.adjacency_matrix(G) print("\nAdjacency matrix\n", w, "\n") # setting p p = 1 # ... QAOA ... # Create an Ising Hamiltonian with docplex. mdl = Model(name='max_cut') mdl.node_vars = mdl.binary_var_list(list(range(n)), name='node') maxcut_func = mdl.sum(w[i, j] * mdl.node_vars[i] * (1 - mdl.node_vars[j]) for i in range(n) for j in range(n))
taken = 1 topo.add_edge(r.source, r.target, capacity=1, allocated_capacity=1, static=False) action_budget -= 1 + taken fitted_request_idx.append(r.mask) else: continue fitted_request_idx.extend(routed_requests) return fitted_request_idx if __name__ == "__main__": g = nx.random_regular_graph(d=3, n=6, seed=1) reqs = [rqs.Request(u, v, i) for i, (u, v) in enumerate(g.edges())] for u, v, d in g.edges(data=True): d["capacity"] = 1 d["allocated_capacity"] = 0 d["static"] = False f = fit_requests(g.copy(), reqs, 3, g.number_of_edges(), {i: 0 for i in range(6)}, 3) print f g.remove_edge(0, 3) g.remove_edge(0, 4) g.remove_edge(0, 5) f = fit_requests(g.copy(), reqs, 3, g.number_of_edges() + 3, {i: 0
#!./env/bin/python import networkx as nx import sys regularity = int(sys.argv[1]) vertices = int(sys.argv[2]) seed = int(sys.argv[3]) number = int(sys.argv[4]) output_dir = sys.argv[5] for n in range(number): G = nx.random_regular_graph(regularity, vertices, seed + n) filename = '{}regRand{}Node{}.dgf'.format(regularity, vertices, seed + n) f = open(output_dir + filename, 'w+') f.write( 'c {}-regular random {}-node graph generated by NetworkX with seed {}\n' .format(regularity, vertices, seed + n)) for edge in nx.generate_edgelist(G, data=False): f.write('e {}\n'.format(edge)) f.close()
def randomRegularGraph(n, d, sname=None): g = nx.random_regular_graph(d, n) if sname is not None: nx.write_edgelist(g, sname)
def networkRandom(): numNodes = random.randint(1, 100) Degree = random.randint(1, numNodes) while ((numNodes * Degree) % 2 != 0): Degree = random.randint(1, numNodes) H = nx.random_regular_graph(Degree, numNodes, seed=None) G = H.to_directed() print(nx.info(G)) triads = nx.triadic_census(G) print("Triad: Occurences") for i in triads: if (triads[i] != 0) and (i != '003') and (i != '012') and (i != '102'): print(i, " : ", triads[i]) print("-------------") TRICODES = (1, 2, 2, 3, 2, 4, 6, 8, 2, 6, 5, 7, 3, 8, 7, 11, 2, 6, 4, 8, 5, 9, 9, 13, 6, 10, 9, 14, 7, 14, 12, 15, 2, 5, 6, 7, 6, 9, 10, 14, 4, 9, 9, 12, 8, 13, 14, 15, 3, 7, 8, 11, 7, 12, 14, 15, 8, 14, 13, 15, 11, 15, 15, 16) #: important: it corresponds to the tricodes given in :data:`TRICODES`. TRIAD_NAMES = ('003', '012', '102', '021D', '021U', '021C', '111D', '111U', '030T', '030C', '201', '120D', '120U', '120C', '210', '300') #: A dictionary mapping triad code to triad name. TRICODE_TO_NAME = { i: TRIAD_NAMES[code - 1] for i, code in enumerate(TRICODES) } # ---------------------------------------------------------------------- # trianglesList = [] jsonList = [] if os.path.exists('randomTriads.json'): os.remove('randomTriads.json') for triangle in getting_Triangles(G): trianglesList.append(triangle) for triangle in trianglesList: triangle_code = TRICODE_TO_NAME[tricode(G, triangle[0], triangle[1], triangle[2])] jsonList.append({ 'x': int(triangle[0]), 'y': int(triangle[1]), 'z': int(triangle[2]), 'id': triangle_code, 'connections': [int(triangle[0]), int(triangle[1]), int(triangle[2])] }) with open('randomTriads.json', 'w') as json_file: json.dump(jsonList, json_file) return G
def generate_graph(parameters, type='random'): #n, type='random', d=0, m=0, k=5, p=.5, periodic=False, with_positions=True, create_using=None ''' INPUTS: type Type of graph parameters List of parameters specific to the type of graph OUTPUTS: Graph satisfying the specified parameters and of the specified type ''' try: if type == 'triangular_lattice': n_dim = parameters[0] m_dim = parameters[1] graph = nx.triangular_lattice_graph(n_dim, m_dim) return graph if type == 'hypercube': num_nodes = parameters[0] graph = nx.hypercube_graph(num_nodes) return graph elif type == 'random': num_nodes = parameters[0] av_deg = parameters[1] graph = nx.random_regular_graph(av_deg, num_nodes) return graph elif type == 'erdos_renyi': num_nodes = parameters[0] edges = parameters[1] graph = nx.erdos_renyi_graph(num_nodes, edges) elif type == 'complete': num_nodes = parameters[0] graph = nx.complete_graph(num_nodes) elif type == 'dumbell': n = parameters[0] graph = nx.barbell_graph(n // 2 - 1, n - 2 * (n // 2 - 1)) elif type == 'complete_bipartite': m = parameters[0] n = parameters[1] graph = nx.complete_bipartite_graph(m, n) elif type == 'dumbell_multiple': size_dumbell = parameters[0] num_dumbell = parameters[1] size_path = parameters[2] graph = generate_dumbell_multiple_cliques(size_dumbell, num_dumbell, size_path) elif type == 'rich_club': size_club = parameters[0] size_periphery = parameters[1] #prob_rp = parameters[2] #prob_rr = parameters[3] #prob_pp = parameters[4] num_peripheries = parameters[2] a = parameters[3] b = parameters[4] c = parameters[5] graph = generate_rich_club_adapted_version(size_club, size_periphery, num_peripheries, a, b, c) elif type == 'dumbell_multiple_sized': size_list = parameters[0] path_length = parameters[1] graph = generate_dumbell_multiple_sizes(size_list, path_length) elif type == 'dumbell_string': sizes = parameters[0] lengths = parameters[1] graph = generate_dumbell_string(sizes, lengths) elif type == 'with_indicator': indicator = parameters[0] graph = generate_dumbell_indicator_connectionstrength(indicator) return graph except ValueError: print("The specified graph type was invalid.")
def evolve(self, turns, **kwargs): self.rewire = None self.prefer = np.zeros((turns, self.adapter.category), dtype=np.int) super(self.__class__, self).evolve(turns, **kwargs) def show(self, fmt, label, wait=False, *args, **kwargs): super(self.__class__, self).show(True) f = plt.figure(2) color = 'brgcmykw' # symb = '.ox+*sdph' label = ['random', 'popularity', 'knn', 'pop*sim', 'similarity'] for i in xrange(self.adapter.category): plt.plot(self.prefer[:, i], color[i], label=label[i]) plt.title('CoEvolutionary Game') plt.xlabel('Step') plt.ylabel('Strategies') plt.legend() # plt.show() f.show() if __name__ == '__main__': G = nx.random_regular_graph(5, 10) pp = Population(G) gg = game.PDG() rr = rule.BirthDeath() e = Evolution() e.set_population(pp).set_game(gg).set_rule(rr) e.evolve(10000) e.show()
def generate_odd_graph(self): graph = nx.random_regular_graph(self.min_degree, self.essay_count-1) graph.add_node(self.isolated_node) for node in self.choose_random_nodes(): graph.add_edge(self.isolated_node, node) return graph
def setUp(self) -> None: self.qpu = Grid2dQPU(4, 6) problem_graph = nx.random_regular_graph(3, 24) self.problem = max_cut(problem_graph) self.mapping = Mapping(self.qpu, self.problem)
def make_cluster_representative( n_dim=10, degree=2, n_clusters=3, T=15, n_samples=100, repetitions=False, cluster_series=None, shuffle=False, ): """Based on the cluster representative, generate similar graphs.""" import networkx as nx cluster_reps = [] adjacencies = [] if cluster_series is not None: n_clusters = np.unique(cluster_series).size for i in range(n_clusters): representative = nx.random_regular_graph(d=degree, n=n_dim) A = nx.adjacency_matrix(representative).todense().astype(float) A[np.where(A != 0)] = np.random.rand(np.where(A != 0)[0].size) * 0.45 np.fill_diagonal(A, 1) adjacencies.append(A) cluster_reps.append(representative) pos = np.arange(0, T, T // (n_clusters + 1)) pos = list(pos) + [T - 1] if cluster_series is None: cluster_series = np.tile(range(n_clusters), (len(pos) // n_clusters) + 1)[:len(pos)] if shuffle: np.random.shuffle(cluster_series) # print(pos) # print(cluster_series) # pos = np.arange(0, T, T // (clusters + 1)) # pos = list(pos) + [T - 1] else: assert len(cluster_series) == len(pos) # a = np.where(cluster_series[:-1] != cluster_series[1:])[0] + 1 # T = len(cluster_series) # overwrites T # pos = np.concatenate(([0], a, [T-1])) thetas = [] for i in range(len(pos) - 1): # last one is always a representative how_many = int(pos[i + 1]) - int(pos[i]) - 1 new_list = [adjacencies[cluster_series[i]]] target = adjacencies[cluster_series[i + 1]] for i in range(how_many): new = new_list[-1].copy() diffs = (new != 0).astype(int) - (target != 0).astype(int) diff = np.where(diffs != 0) if diff == (): break if i == 0: edges_per_change = int( (np.nonzero(diffs)[0].shape[0] / 2) // (how_many + 1)) if edges_per_change == 0: edges_per_change += 1 ixs = np.arange(diff[0].shape[0]) np.random.shuffle(ixs) xs = diff[0][ixs[:edges_per_change]] ys = diff[1][ixs[:edges_per_change]] for j in range(xs.shape[0]): if diffs[xs[j], ys[j]] == -1: new[xs[j], ys[j]] = np.random.rand(1) * 0.2 new[ys[j], xs[j]] = new[xs[j], ys[j]] else: new[xs[j], ys[j]] = 0 new[ys[j], xs[j]] = 0 new_list.append(new) thetas += new_list thetas.append(target) covs = [linalg.pinvh(t) for t in thetas] X = np.vstack([ np.random.multivariate_normal(np.zeros(n_dim), c, size=n_samples) for c in covs ]) y = np.repeat(np.arange(len(covs)), n_samples) distances = squareform( [l1_od_norm(t1 - t2) for t1, t2 in combinations(thetas, 2)]) distances /= np.max(distances) labels_pred = AgglomerativeClustering( n_clusters=n_clusters, affinity="precomputed", linkage="complete").fit_predict(distances) id_cluster = np.repeat(labels_pred, n_samples) data = Bunch( X=X, y=y, id_cluster=id_cluster, precs=np.array(thetas), thetas=np.array(thetas), sparse_precs=np.array(thetas), cluster_reps=cluster_reps, cluster_series=cluster_series, ) return data
def __init__(self, gtype, n, k, numbers, seed=42, load=False, lr=0.1, damping=0.2, eps=1e-5, th=10.0, max_iters=200, lr_decay=0.1, device=torch.device("cpu")): # Model parameters torch.manual_seed(seed) self.gtype = gtype self.n = n self.k = k self.numbers = len(numbers) self.lr_decay = lr_decay self.best_bethe = -float('inf') self.device = device # Load model data if load: self.load_params() else: if gtype == GType.ER: # Use igraph for erdos-renyi G = igraph.Graph.Erdos_Renyi(n=n, p=2 * math.log(n) / n) print(" Graph connected? %r" % (G.is_connected())) adj_list= G.get_adjlist() col_list = [item for sublist in adj_list for item in sublist] row_list = list(chain.from_iterable(map(lambda x: x[0] * [x[1]], zip(list(map(lambda x: len(x), adj_list)), range(n))))) cr = dict(map(lambda x: ((row_list[x], col_list[x]), x), range(len(col_list)))) r2c = torch.LongTensor([cr[x] for x in list(zip(col_list, row_list))]) r2c = torch.LongTensor(list(map(lambda x: cr[x], list(zip(col_list, row_list))))) row = torch.LongTensor(row_list) col = torch.LongTensor(col_list) else: # Use nx for tree (exact inference test) or K-regular if gtype == GType.KR: G = nx.random_regular_graph(k, n) else: G = nx.star_graph(n=n-1) print("Graph connected? %r" % (nx.is_connected(G))) sparse_adj = nx.adjacency_matrix(G) row, col = sparse_adj.nonzero() cr = dict(map(lambda x: ((row[x], col[x]), x), range(col.shape[0]))) r2c = torch.LongTensor(list(map(lambda x: cr[x], list(zip(col, row))))) row = torch.from_numpy(row).type(torch.LongTensor) col = torch.from_numpy(col).type(torch.LongTensor) if torch.cuda.is_available(): row = row.cuda() col = col.cuda() r2c = r2c.cuda() # Normally distributed weights (look at RBM literature) adj = (torch.rand(row.shape[0], device=device) - 0.5) * 0.01 local = (torch.rand(n, device=device) - 0.5) * 0.01 # local = (torch.zeros(n, device=device)) self.adj = adj self.local = local self.row = row self.col = col self.r2c = r2c # Model Hyperparameters self.max_iters = max_iters self.lr = lr self.damping = damping self.eps = eps self.th = th
#!/usr/bin/env python # coding: utf-8 # In[8]: import matplotlib.pyplot as plt import networkx as nx G=nx.random_regular_graph(4, 30, seed=None) pos=nx.spring_layout(G) nx.draw(G, node_color='black',font_color='white',font_weight='bold',width=1,pos=pos,with_labels=True) # In[2]: from pyomo.environ import * import numpy as np import random import pandas as pd # In[3]: model = AbstractModel() model.N=Param(mutable=True,initialize=len(G.nodes)) model.E=Param(mutable=True,initialize=len(G.edges)) model.i = RangeSet(0,model.N-1) model.j = Set(initialize=model.i) model.L = Param(model.i,model.j, default=0,mutable=True)
#!/usr/bin/env python # coding: utf-8 # In[10]: import matplotlib.pyplot as plt import networkx as nx G = nx.random_regular_graph(3, 20, seed=None) pos = nx.spring_layout(G) l1 = nx.draw(G, pos=pos, with_labels=True) #labels = nx.draw_networkx_labels(G, pos=pos,font_color='white',font_weight='bold' ) plt.show() # In[11]: from pyomo.environ import * import numpy as np import random import pandas as pd # In[12]: model = AbstractModel() model.N = Param(mutable=True, initialize=len(G.nodes)) model.i = RangeSet(0, model.N - 1) model.j = Set(initialize=model.i) model.L = Param(model.i, model.j, default=0, mutable=True) model.X = Var(model.i, domain=Binary) model.y = Var(within=NonNegativeReals, initialize=0)
# -*- coding: utf-8 -*- """ Created on Fri Jun 26 16:21:01 2020 @author: joost """ import matplotlib.pyplot as plt import networkx as nx from INTERP import INTERP from QAOA import QAOA import numpy as np G = nx.random_regular_graph(3, 14, seed=1) inti = INTERP(G, optimizer='Nelder-Mead', optimizer_options={'disp': True}) p_min, p_max = 2, 10 g, b = inti.get_angles_INTERP(p_max, initial_gamma=[0.35], initial_beta=[0.8]) for i in range(p_min, p_max + 1): gamma = inti.gammas_list[i - 1] beta = inti.betas_list[i - 1] print(gamma, beta) counts = inti.sample(gamma, beta, n_samples=1024) v_counts = inti.counts_to_valueCounts(counts, plot_histogram=True) mean = QAOA.mean_valueCounts(v_counts) plt.title('Distribution objective values, p = ' + str(i) + ", mean = %.2f" % (mean))
"--save", help= "saves summarized results as a csv, with name as parameter. If csv exists, it appends to the end", type=str) args = parser.parse_args() num_qubits = args.q if args.var_form == 'RYRZ': var_form = RYRZ(args.q, depth=args.d, entanglement='linear', entanglement_gate='cx') num_parameters = var_form._num_parameters elif args.var_form == 'QAOA': A = nx.adjacency_matrix(nx.random_regular_graph(4, args.q)).todense() qubitOp, shift = get_maxcut_qubitops(A) var_form = QAOAVarForm(qubitOp, args.d) num_parameters = var_form.num_parameters parameters = np.random.uniform(0, np.pi, num_parameters) qc = var_form.construct_circuit(parameters) if not qc.cregs: c = ClassicalRegister(num_qubits, name='c') qc.add_register(c) qc.measure(qc.qregs[0], qc.cregs[0]) # Select the QasmSimulator from the Aer provider simulator = Aer.get_backend('qasm_simulator') # Define the simulation method
orig_dd = pd.read_csv( "AOA_1539000552401_1_ISP-Data-For-Anomaly-Detection/all_data.csv", encoding="UTF-8") orig_dd = orig_dd.iloc[:, 2:] orig_dd = orig_dd.astype(np.float32) orig_data_tensor = torch.FloatTensor(orig_dd.values) orig_data_tensor = orig_data_tensor.reshape( [orig_data_tensor.shape[0], orig_data_tensor.shape[1], 1, 1]) orig_data_tensor.shape train_data = orig_data_tensor[:orig_data_tensor.shape[0] // 7 * 5, :, :, :] val_data = orig_data_tensor[orig_data_tensor.shape[0] // 7 * 5:orig_data_tensor.shape[0] // 7 * 6, :, :, :] test_data = orig_data_tensor[orig_data_tensor.shape[0] // 7 * 6:, :, :, :] G = nx.random_regular_graph(4, 40, seed=2050) A = nx.to_scipy_sparse_matrix(G, format='csr') n, m = A.shape diags = A.sum(axis=1) D = scipy.sparse.spdiags(diags.flatten(), [0], m, n, format='csr') A = A.astype(dtype='float32') obj_matrix = torch.FloatTensor(A.toarray()) results = [obj_matrix, train_data, val_data, test_data] with open("isp_data.pickle", 'wb') as f: pickle.dump(results, f)