def main(): LOG = True #if (len(sys.argv) != 3): # print "ERROR: genRandomGeorml <nodes> <raio>" # sys.exit(1) NMAX = int(sys.argv[1]) RAIO = float(sys.argv[2]) #NMAX=40 #RAIO=0.1 ALCANCE=250 G=nx.random_geometric_graph(NMAX,RAIO,2) while not nx.is_connected(G): RAIO=RAIO+.005 G=nx.random_geometric_graph(NMAX,RAIO,2) if LOG: print "Graph is not full connected" pos=nx.get_node_attributes(G,'pos') network(G,pos,1) #Remove vizinhos que estejam demasiado perto while nodeNear(G)<1000 : G.remove_node(nodeNear(G)) if nx.is_connected(G): pos=nx.get_node_attributes(G,'pos') network(G,pos,2) #Remove no que tem mais vizinhos T=G if not nodeSolo(T,nodeMaxDegree(T)): T.remove_node(nodeMaxDegree(T)) if nx.is_connected(T): G=T pos=nx.get_node_attributes(G,'pos') network(G,pos,3) for n in G.neighbors(nodeMaxDegree(G)): if nx.degree(G,n)== 2 : degree=nx.degree(G,n) node=n print "node=",n if not nodeSolo(G,n): G.remove_node(n) break pos=nx.get_node_attributes(G,'pos') network(G,pos,4) else: if LOG: print "SubGraph is not full connected"
def main(): LOG = True if (len(sys.argv) != 5): print "ERROR: genMina3.py <nodes> <radius> <delta> <maxdegree>" sys.exit(1) NMAX = int(sys.argv[1]) RAIO = float(sys.argv[2]) delta = float(sys.argv[3]) degree = float(sys.argv[4]) #NMAX=40 #RAIO=0.1 ALCANCE=250 c=0 run=True first=True while run: c+=1 G=nx.random_geometric_graph(NMAX,RAIO,2) while not nx.is_connected(G): if first: RAIO=RAIO+.005 G=nx.random_geometric_graph(NMAX,RAIO,2) if LOG: print c,"- Radius: Graph is not full connected R=",RAIO first=False #Remove vizinhos que estejam demasiado pertoc candidate=nodeNear(G,delta) while not candidate==10000 : G.remove_node(candidate) candidate=nodeNear(G,delta) if nx.is_connected(G): #Remove no que tem mais vizinhos candidate=nodeMaxDegree(G) while nx.degree(G,candidate)> degree : G.remove_node(candidate) candidate=nodeMaxDegree(G) if nx.is_connected(G): run=False else: if LOG: print c,"- MaxDegree: Split Graph" else: if LOG: print c,"- nodeNear: Split Graph" pos=nx.get_node_attributes(G,'pos') network(G,pos,5) if LOG: print "Raio =",RAIO if LOG: print "NMAX =",NMAX if LOG: print "Nodes =",nx.number_of_nodes(G)
def test_QueueNetwork_blocking(self): g = nx.random_geometric_graph(100, 0.2).to_directed() g = qt.set_types_random(g, proportions={k: 1.0 / 6 for k in range(1, 7)}) q_cls = { 1: qt.LossQueue, 2: qt.QueueServer, 3: qt.InfoQueue, 4: qt.ResourceQueue, 5: qt.ResourceQueue, 6: qt.QueueServer } q_arg = { 3: {'net_size': g.number_of_edges()}, 4: {'num_servers': 500}, 6: {'AgentFactory': qt.GreedyAgent} } qn = qt.QueueNetwork(g, q_classes=q_cls, q_args=q_arg, seed=17) qn.blocking = 'RS' self.assertEqual(qn.blocking, 'RS') self.assertEqual(qn._blocking, False) qn.clear() self.assertEqual(qn._initialized, False)
def init_graph(): clusters = 10 cluster_size = 10 p = [] for i in range(clusters): x = random.uniform(-10,10) y = random.uniform(-10,10) p.extend(create_cluster(cluster_size, (x,y), 2)) p = dict(zip(range(len(p)), p)) graph = nx.random_geometric_graph(len(p), 5, pos=p) graph = graph.to_directed() for u,d in graph.nodes(data=True): d['alive'] = True d['anger'] = 0 d['total_friend'] = 0 d['num_deaths'] = 0 d['death_priority'] = 0 for u,v,d in graph.edges(data=True): d['friend'] = random.gauss(5,3) graph.node[u]['total_friend'] += d['friend'] cluster_edges = graph.edges(data=True) for u in graph.node: for v in graph.node: if u != v: if v not in graph.edge[u]: graph.add_edge(u,v, friend=np.random.rayleigh(0.15)) #print graph.edge[u][v]['friend'] graph.node[u]['total_friend'] += graph.edge[u][v]['friend'] return graph, cluster_edges
def test_from_nx(): """ Creating from a networkx graph """ g = nx.random_geometric_graph(100, 2) psi = GraphState(g) assert len(psi.node) == 100 psi = GraphState(nx.Graph(((0, 1),)))
def generate_random_level(nodes=180, radius=0.1, repel=0.05, players=2): """ Generates random graph. Occupies one planet per player. pre: nodes > 0 pre: players > nodes pre: players > 0 """ #generate level G = None while G is None or not nx.is_connected(G): G = nx.random_geometric_graph( n=nodes, radius=radius, repel=repel, ) #setup map map = models.Map(G) for n in xrange(nodes): p = n + 1 if n < players else 0 map.set_owner(n, settings.PLAYER[p]) if p is not 0: map.set_factory(n, True) map.set_garrison(n, 10) return map
def generate_random_graph(n,m,width,height): """ Recibe como parametro la cantidad de vertices y la cantidad de aristas que se desean y deveulve un grafo generado aleatoriamente y la posicion en la cual se encuentran sus nodos """ from random import randint m1=randint(0,m) m2=m-m1 random_g1=nx.random_graphs.gnm_random_graph(n, m1) random_g2=nx.random_graphs.gnm_random_graph(n, m2) G=nx.random_geometric_graph(n,0.125) r_pos=G.pos # aqui obtengo las posiciones de los nodos #escalar estas posiciones y convertirlas en QPointF real_pos={} #crear n nodos y annadirlos a un grafo y luego coger las aristas de graph=SimulationGraph() for i in range(n): graph.add_node(SimulationNode(i)) real_pos[i]=QPointF(r_pos[i][0]*width,r_pos[i][1]*height) for i,j in random_g1.edges_iter():graph.add_edge(SimulationEdge(i,j)) for i,j in random_g2.edges_iter():graph.add_edge(SimulationEdge(j,i)) return graph,real_pos
def __init__(self,n): self.graph = nx.random_geometric_graph(n,0.7) if not nx.is_connected(self.graph): self.graph = nx.connected_component_subgraphs(self.graph)[0] list_nodes = self.graph.nodes() for i in range(0,len(list_nodes)): self.initializeNode(i)
def savegraph(G, i): G = nx.random_geometric_graph(200, 0.125) # position is stored as node attribute data for random_geometric_graph # pos=nx.get_node_attributes(G,'pos') # find node near center (0.5,0.5) # dmin=1 # ncenter=0 # for n in pos: # x,y=pos[n] # d=(x-0.5)**2+(y-0.5)**2 # if d<dmin: # ncenter=n # dmin=d ncenter = 0.5 dmin = 0.5 # color by path length from node near center p = nx.single_source_shortest_path_length(G, ncenter) plt.figure(figsize=(8, 8)) nx.draw_networkx_edges(G, pos, nodelist=[ncenter], alpha=0.4) nx.draw_networkx_nodes(G, pos, nodelist=p.keys(), node_size=80, node_color=p.values(), cmap=plt.cm.Reds_r) plt.xlim(-0.05, 1.05) plt.ylim(-0.05, 1.05) plt.axis("off") name = "graph " + str(i) + ".png" plt.savefig(name)
def random_graph(): G=nx.random_geometric_graph(200,0.125) # position is stored as node attribute data for random_geometric_graph pos=nx.get_node_attributes(G,'pos') # find node near center (0.5,0.5) dmin=1 ncenter=0 for n in pos: x,y=pos[n] d=(x-0.5)**2+(y-0.5)**2 if d<dmin: ncenter=n dmin=d # color by path length from node near center p=nx.single_source_shortest_path_length(G,ncenter) plt.figure(figsize=(8,8)) nx.draw_networkx_edges(G,pos,nodelist=[ncenter],alpha=0.4) nx.draw_networkx_nodes(G,pos,nodelist=p.keys(), node_size=80, node_color=p.values(), cmap=plt.cm.Reds_r) plt.xlim(-0.05,1.05) plt.ylim(-0.05,1.05) plt.axis('off') #plt.savefig('random_geometric_graph.png') plt.show()
def test_QueueNetwork_copy(self): g = nx.random_geometric_graph(100, 0.2).to_directed() g = qt.set_types_random(g, proportions={k: 0.2 for k in range(1, 6)}) q_cls = { 1: qt.LossQueue, 2: qt.QueueServer, 3: qt.InfoQueue, 4: qt.ResourceQueue, 5: qt.ResourceQueue } q_arg = {3: {'net_size': g.number_of_edges()}, 4: {'num_servers': 500}} qn = qt.QueueNetwork(g, q_classes=q_cls, q_args=q_arg, seed=17) qn.max_agents = np.infty qn.initialize(queues=range(g.number_of_edges())) qn.simulate(n=50000) qn2 = qn.copy() stamp = [(q.num_arrivals, q.time) for q in qn2.edge2queue] qn2.simulate(n=25000) self.assertFalse(qn.current_time == qn2.current_time) self.assertFalse(qn.time == qn2.time) ans = [] for k, q in enumerate(qn2.edge2queue): if stamp[k][1] != q.time: ans.append(q.time != qn.edge2queue[k].time) self.assertTrue(np.array(ans).all())
def test_set_types_random(self): nV = 1200 nT = np.random.randint(5, 10) g = nx.random_geometric_graph(nV, 0.1).to_directed() eType = np.random.choice(np.arange(5, 100), size=nT, replace=False) prob = np.random.uniform(size=nT) prob = prob / sum(prob) pType = {eType[k]: prob[k] for k in range(nT)} g = qt.set_types_random(g, proportions=pType) non_loops = [e for e in g.edges() if e[0] != e[1]] mat = [[g.ep(e, 'edge_type') == k for e in non_loops] for k in eType] props = (np.array(mat).sum(1) + 0.0) / len(non_loops) ps = np.array([pType[k] for k in eType]) self.assertTrue(np.allclose(props, ps, atol=0.01)) prob[-1] = 2 pType = {eType[k]: prob[k] for k in range(nT)} with self.assertRaises(ValueError): g = qt.set_types_random(g, proportions=pType, seed=10) with self.assertRaises(ValueError): g = qt.set_types_random(g, loop_proportions=pType, seed=10)
def __init__(self,n): self.average = 0.0 self.graph = nx.random_geometric_graph(n,0.15) if not nx.is_connected(self.graph): self.graph = nx.is_connected_component_subgraphs(self.graph)[0] for i in range(0,len(self.graph.nodes())): self.initializeNode(i) self.average = self.average/len(self.graph.nodes())
def _generate_gemetric_graph( self, nb_node, radius, pos, ): import networkx as nx return nx.random_geometric_graph(nb_node, radius, pos=pos)
def test_from_nx(): """ Test that making graphs from networkx objects goes smoothly """ g = nx.random_geometric_graph(100, 2) psi = NXGraphState(g) assert psi.node[0]["vop"] == 0 assert len(psi.edges()) > 0 psi.measure(0, "px", detail=True) psi = NXGraphState(nx.Graph(((0, 1),)))
def gen_geo(self): for i in range(1, self.seed + 1): g = nx.random_geometric_graph(self.nodes, 0.042) for j in range(10, self.rewire + 1, 10): num_rewire = int(j * self.edges / 100) g_tmp = nx.double_edge_swap(g, num_rewire, self.edges) self.graphs_rewire.append(g_tmp) self.labels_rewire.append(3) self.graphs.append(g) self.labels.append(3)
def randomCityGraph(n): G = nx.random_geometric_graph(n,1) pos=nx.get_node_attributes(G,'pos') weight = {}; for u,v,d in G.edges(data=True): G.add_edge(u, v, weight=sqrt((pos[u][0] - pos[v][0])**2 + (pos[u][1] - pos[v][1])**2)) return G
def test_p_dist_default(self): """Tests default p_dict = 0.5 returns graph with edge count <= RGG with same n, radius, dim and positions """ nodes = 50 dim = 2 pos = {v: [random.random() for i in range(dim)] for v in range(nodes)} RGG = nx.random_geometric_graph(50, 0.25, pos=pos) SRGG = nx.soft_random_geometric_graph(50, 0.25, pos=pos) assert_true(len(SRGG.edges()) <= len(RGG.edges()))
def random_geometric_graph(n,r): g = nx.random_geometric_graph(n,r) for node in g.nodes(): g.node[node]["x"] = g.node[node]["pos"][0] g.node[node]["y"] = g.node[node]["pos"][1] g.node[node].pop("pos") for v in g.nodes(): for w in g.edge[v]: g.edge[v][w]['cost'] = distance(g, v, w) return g
def test_geom_graph(self): g = nx.random_geometric_graph(30, 0.3) nx.draw(g) plt.show() candidate = select_removal_candidate(g) while candidate is not None: g.remove_edge(*candidate) candidate = select_removal_candidate(g) nx.draw(g) plt.show() print(g.nodes(data=True))
def random_graph(N): def distance(p0, p1): x = p0[0] - p1[0] y = p0[1] - p1[1] return math.sqrt(x*x + y*y) random.seed(100) g = nx.random_geometric_graph(N, 0.125) pos = nx.get_node_attributes(g, 'pos') H = Graph().from_nx(g) for e in H.E.keys(): H.E[e] = {"weight": distance(pos[e[0]], pos[e[1]])} return (H, pos)
def test_InfoQueue_network(self): g = nx.random_geometric_graph(100, 0.2).to_directed() q_cls = {1: qt.InfoQueue} q_arg = {1: {'net_size': g.number_of_edges()}} qn = qt.QueueNetwork(g, q_classes=q_cls, q_args=q_arg, seed=17) qn.max_agents = 40000 qn.initialize(queues=range(qn.g.number_of_edges())) qn.simulate(n=2000) # Finish this self.assertTrue(True)
def draw_random(self): graph = nx.random_geometric_graph(200,0.125) self.add_nodes_and_edges(graph) pos = nx.get_node_attributes(graph, 'pos') nx.draw(graph, pos) plt.xlim(-0.05,1.05) plt.ylim(-0.05,1.05) plt.axis('off') plt.show()
def main(): import networkx as nx from complex_systems.pgg_diffusion import PGG_diffusion from complex_systems.quasi_unit_disk_graph import gen_quasi_unit_disk_weight from complex_systems.quasi_unit_disk_graph import remove_edges_from_graph import pylab as plt import numpy as np nb_node = 400 xmax = 1000 ymax = 1000 coop_ratio = 0.5 synergy = 2 nb_round = 100 nb_game_per_round = 1 nb_def = [] nb_coop = [] inner_radius = 45 outer_radius = 75 alpha = 0.3 nb_seeder = 40 # Generate a Random Graph p = dict((i,(np.random.uniform(low=0.0, high=xmax),np.random.uniform(low=0.0, high=ymax))) for i in range(nb_node)) G = nx.random_geometric_graph(nb_node,outer_radius,pos=p) G = gen_quasi_unit_disk_weight(G=G, outer_radius=outer_radius, inner_radius=inner_radius, alpha=alpha) G = remove_edges_from_graph(G) # initialize the game PGG = PGG_diffusion(G=G, synergy=synergy,nb_simulation_step=nb_game_per_round, nb_seeder=nb_seeder, buffer_size = 100, cooperator_ratio=coop_ratio, noise_var=0.0) for i in range(nb_round): PGG.run_game() nb_def.append(PGG.defector_counter()) nb_coop.append(PGG.cooperator_counter()) plt.figure() plt.plot(nb_def,'b-*') plt.plot(nb_coop,'r-*') plt.figure() nx.draw_networkx(G, node_size=20, pos=p, with_labels = False) time_stamps_dist = PGG.get_distribution_time_stamps() x = [] y = [] for key,val in time_stamps_dist.iteritems(): x.append(key) y.append(val) plt.figure() plt.bar(x,y) plt.show()
def test_ResourceQueue_network(self): g = nx.random_geometric_graph(100, 0.2).to_directed() q_cls = {1: qt.ResourceQueue, 2: qt.ResourceQueue} q_arg = {1: {'num_servers': 50}, 2: {'num_servers': 500}} qn = qt.QueueNetwork(g, q_classes=q_cls, q_args=q_arg) qn.max_agents = 400000 qn.initialize(queues=range(qn.g.number_of_edges())) qn.simulate(n=50000) nServ = {1: 50, 2: 500} ans = np.array([q.num_servers != nServ[q.edge[3]] for q in qn.edge2queue]) self.assertTrue(ans.any())
def __init__(self, n): r = 0.0 self.graph = nx.random_geometric_graph(n, 0.7) if not nx.is_connected(self.graph): self.graph = nx.connected_component_subgraphs(self.graph)[0] list_nodes = self.graph.nodes() # initialize nodes with a random value for i in range(0, len(list_nodes)): x = random.uniform(1.0, 1000.0) r += x list_m = [] list_m.append(msg.Message(x, 1.0, 0)) self.graph.node[list_nodes[i]]["msg"] = list_m self.realVal = r / len(self.graph.nodes())
def __init__(self,n): self.graph = nx.random_geometric_graph(n,0.8) if not nx.is_connected(self.graph): self.graph = nx.connected_component_subgraphs(self.graph)[0] self.alpha = 1/len(self.graph.nodes()) #initialize nodes with a random value nr_Nodes = len(self.graph.nodes()) for i in range(0,len(self.graph.nodes())): list_m = [] list_m.append(msg.Message(0,l=nr_Nodes,indice=i)) self.graph.node[self.graph.nodes()[i]]['vector'] = list_m self.graph.node[self.graph.nodes()[i]]['initVal'] = random.uniform(1.0, 1000.0) self.average += self.graph.node[self.graph.nodes()[i]]['initVal'] self.average = self.average/len(self.graph.nodes())
def netconf(): n_hosts = 1 # connect n_hosts to every switch global G G=nx.random_geometric_graph(n_switches,0.5) # configure link between hosts linkopts = dict(bw=10, delay='5ms', loss=10, max_queue_size=1000, use_htb=True) hostlimit = 0.5/n_switches for e in G.edges(): G[e[0]][e[1]]['linkopt'] = linkopts init_switch_ip = ipaddress.ip_address(u'2001:5c0:9168::0') init_host_ip = ipaddress.ip_address(u'2001:5c0:9168::0') + G.number_of_nodes() switchno = {} hostswitchno = {} switchip = {} for n in G.nodes(): s = hex(n+1)[2:] s = s.zfill(15)+'%s' init_switch_ip += 1 ip = init_switch_ip ip = ip.__str__().encode('ascii','ignore') G.node[n]['name'] ='s%s' % (n+1) G.node[n]['dpid'] = s % 0 G.node[n]['ip'] = ip G.node[n]['hosts'] = {} G.node[n]['isroot'] = False switchno[G.node[n]['name']] = n switchip[int('0x'+G.node[n]['dpid'],0)] = ip for count in xrange(1,n_hosts+1): host = 'h_%s_%s' % (G.node[n]['name'], count) hostswitchno[host] = n init_host_ip += 1 ip = init_host_ip +1 ip = ip.__str__().encode('ascii','ignore') ipv4 = '10.0.%s.%s' % (n+1, count) mac = s % count # CPU fraction G.node[n]['hosts'][host]={'mac':mac,'ipv4':ipv4,'ip': ip ,'cpu': hostlimit} G.graph['switchno'] = switchno G.graph['hostswitchno'] = hostswitchno G.graph['switchip'] = switchip return G
def test_p(self): """Tests for providing an alternate distance metric to the generator. """ # Use the L1 metric. dist = l1dist G = nx.random_geometric_graph(50, 0.25, p=1) for u, v in combinations(G, 2): # Adjacent vertices must be within the given distance. if v in G[u]: assert_true(dist(G.nodes[u]['pos'], G.nodes[v]['pos']) <= 0.25) # Nonadjacent vertices must be at greater distance. else: assert_false(dist(G.nodes[u]['pos'], G.nodes[v]['pos']) <= 0.25)
def __init__(self,sample): sample = "/Users/rafaelremondes/UM/MEI/Thesis/DistributedAggregationAlgortihmsSM/code/NetworkSamples/"+sample self.graph = nx.random_geometric_graph(200,0.7)#self.loadSample(sample) if not nx.is_connected(self.graph): self.graph = nx.connected_component_subgraphs(self.graph)[0] list_nodes = self.graph.nodes() for i in range(0,len(list_nodes)): x = random.uniform(1.0, 10.0) self.graph.node[list_nodes[i]]['inbox'] = [] self.graph.node[list_nodes[i]]['initVal'] = x self.graph.node[list_nodes[i]]['size'] = 0.0 self.realVal += x self.realSum = self.realVal self.realVal = self.realVal/len(self.graph.nodes()) self.isOn = False
def generate_udg_graph(parameters): radius = parameters[0] num = parameters[1] seed = parameters[2] return nx.random_geometric_graph(num, radius, seed=seed)
def generateHouseholdsAggregateGraph(numHouseholds, radius): # generate a random geometric graph for households in range: randomGeometric = nx.random_geometric_graph(numHouseholds, radius) return randomGeometric
def test_random_geometric_graph(self): G = nx.random_geometric_graph(50, 0.25) assert_equal(len(G), 50)
}, 'zoom': 6 }) # bus_data_14_map = bus_data_14_map.query("Status in ['Normal','Alarm','Alert']") #fig = px.line_mapbox(bus_vol, lat="Latitude", lon="Longitude", color="Status", hover_data=["ID", "Vmin", "Vmax"], # zoom=5.5, color_discrete_sequence=['green', 'red ', 'orange'], height=550) # fig = px.scatter_mapbox(bus_data_14_map, lat="Latitude", lon="Longitude", hover_data=["ID", "Vmin", "Vmax"], # color_discrete_sequence=["#19a0ff"], zoom=5, height=550)) #fig.update_layout(mapbox_style="") #fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) #### G = nx.random_geometric_graph(50, 0.102) edge_x = [] edge_y = [] for edge in G.edges(): x0, y0 = G.nodes[edge[0]]['pos'] x1, y1 = G.nodes[edge[1]]['pos'] edge_x.append(x0) edge_x.append(x1) edge_x.append(None) edge_y.append(y0) edge_y.append(y1) edge_y.append(None) edge_trace = go.Scatter(x=edge_x, y=edge_y,
import networkx as nx from dynsimf.models.Model import Model from dynsimf.models.components.PropertyFunction import PropertyFunction if __name__ == '__main__': g = nx.random_geometric_graph(50, 0.3) model = Model(g) def node_amount(G): return len(G.nodes()) prop1 = PropertyFunction('1', nx.average_clustering, 2, {'G': model.graph}) prop2 = PropertyFunction('2', node_amount, 2, {'G': model.graph}) model.add_property_function(prop1) model.add_property_function(prop2) model.simulate(7) out = model.get_properties() print(out)
import matplotlib.pyplot as plt import networkx as nx G = nx.random_geometric_graph(900, 0.05) # position is stored as node attribute data for random_geometric_graph pos = nx.get_node_attributes(G, 'pos') print pos # find node near center (0.5,0.5) dmin = 1 ncenter = 0 for n in pos: x, y = pos[n] d = (x - 0.5)**2 + (y - 0.5)**2 if d < dmin: ncenter = n dmin = d # color by path length from node near center p = dict(nx.single_source_shortest_path_length(G, ncenter)) plt.figure(figsize=(8, 8)) nx.draw_networkx_edges(G, pos, nodelist=[ncenter], alpha=0.4) nx.draw_networkx_nodes(G, pos, nodelist=list(p.keys()), node_size=80, node_color=list(p.values()), cmap=plt.cm.Reds_r)
def G(): G = nx.random_geometric_graph(50, 0.125) nx.set_node_attributes(G, 3, "prop") nx.set_edge_attributes(G, 12, "edge_prop") return G
# 17. turan_graph(n, r), the Turan Graph # 18. wheel_graph(n[, create_using]), the wheel graph # # # ## Try to choose your own network! # # These networks are deterministic (are generated with deterministic prescribed rules). # ## Random networks generation # In[6]: G_rg = nx.random_geometric_graph(500, 0.1) G_er = nx.erdos_renyi_graph(20, 0.3) nx.draw(G_rg) plt.show() nx.draw(G_er) plt.show() # ## Generating your own network # # You can also create your own network by giving to networkx a matrix or edgelist, or adding nodes and links. # #
def random_graph(no_nodes=200, edge_percent=0.125): return nx.random_geometric_graph(no_nodes, edge_percent)
async def generate_graph_file(self, request): # WARNING: don't do that if you plan to receive large files! data = await request.post() nodesNumber = int(data['nodesNumber']) if data['graphGenerator'] == 'complete': nxOutputGraph = nx.complete_graph(nodesNumber) elif data['graphGenerator'] == "cycle": nxOutputGraph = nx.cycle_graph(nodesNumber) elif data['graphGenerator'] == "wheel": nxOutputGraph = nx.wheel_graph(nodesNumber) elif data['graphGenerator'] == "star": nxOutputGraph = nx.star_graph(nodesNumber) elif data['graphGenerator'] == "random": prob = float(data['probability']) nxOutputGraph = nx.erdos_renyi_graph(nodesNumber, prob) elif data['graphGenerator'] == "watts": prob = float(data['probability']) k = int(data['neighDist']) # neighbours distance nxOutputGraph = nx.watts_strogatz_graph(nodesNumber, k, prob) elif data['graphGenerator'] == "barabasi": m = int(data['edgesNew']) # number of edges to attach a new node nxOutputGraph = nx.barabasi_albert_graph(nodesNumber, m) elif data['graphGenerator'] == "geometric": radius = float(data['radius']) # distance threshold value nxOutputGraph = nx.random_geometric_graph(nodesNumber, radius) # writing gml file with open('{}.gml'.format(data['graphOutputFile']), 'w') as f: # Header of graphml file f.write('<?xml version="1.0" encoding="UTF-8"?>\n') f.write( '<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ' ) f.write( 'xsi:schemaLocation=\"http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.1/graphml.xsd\">\n' ) f.write( '<key id = "name" for ="node" attr.name="name" attr.type="string" />\n' ) f.write( '<key id = "lim_inf" for ="node" attr.name="lim_inf" attr.type="float" />\n' ) f.write( '<key id = "lim_sup" for ="node" attr.name="lim_sup" attr.type="float" />\n' ) f.write( '<key id = "x0" for ="node" attr.name="x0" attr.type="float" />\n' ) f.write( '<key id = "w" for ="node" attr.name="w" attr.type="float" />\n' ) f.write('<graph id = "G" edgedefault = "undirected">\n') i = 0 # Writing nodes if data['nodeWeight'] == "same": weight = np.random.random() for node in nxOutputGraph.nodes(): f.write('<node id="{}">\n'.format(i)) f.write('<data key="name">{}</data>\n'.format("".join( names.get_full_name().split()))) new_node_value = np.random.random() rangeSize = float(data['rangeSize']) if data['initialCentered'] == 'yes': porc_range = 0.5 else: porc_range = np.random.random() f.write( '<data key="lim_inf">{}</data>\n'.format(new_node_value - porc_range * rangeSize)) f.write( '<data key="lim_sup">{}</data>\n'.format(new_node_value + porc_range * rangeSize)) f.write('<data key="x0">{}</data>\n'.format(new_node_value)) if data['nodeWeight'] == "different": weight = np.random.random() f.write('<data key="w">{}</data>\n'.format(weight)) f.write('</node>\n') i = i + 1 # Writing edges for (u, v) in nxOutputGraph.edges(): f.write( '<edge id="{}" source="{}" target="{}" label="knows"></edge>\n' .format(i, u, v)) i = i + 1 f.write('</graph>\n') f.write('</graphml>') raise web.HTTPFound('/launcher')
import plotly.graph_objects as go import networkx as nx import random import os n = 10 print('Creating ' + str(n) + ' random geometric node graph ') G = nx.random_geometric_graph(n, 0.5) ip_list = [] print('Creating ' + str(n) + ' random IP address for the node') while len(ip_list) < n: x1 = 99 x2 = random.randint(0, 255) x3 = random.randint(0, 255) x4 = random.randint(0, 255) result = ".".join(map(str, ([x1, x2, x3, x4]))) if result not in ip_list: ip_list.append(result) # preparing for node configuration node_att = [] for i, node in enumerate(G.nodes()): host_name = 'host' + str(node + 1) host_ip = ip_list[i] as_name = 'AS' + str(node + 1) router_name = 'router' + str(node + 1) node_att.append(host_name + ';' + host_ip + ';' + router_name + ';' + as_name) #write node configuration to file
import networkx as nx import math import matplotlib.pyplot as plt import random import numpy as np ave_k = 6 #Wanted average degree num_nodes = 1000 #Number of nodes length = 1. #Size of network domain density = num_nodes / length #Density of nodes radius = math.sqrt( ave_k / (density * np.pi)) #Radius required to get wanted average degree given other values pos = {i: (random.random(), random.random()) for i in range(num_nodes)} #Generate positions for nodes G = nx.random_geometric_graph(num_nodes, radius, pos=pos) #Generate graph
def m_graph(n_clicks, interval_n, nodes_num, nodes_infected, radius, rate): dict['rate']=rate if n_clicks is None or n_clicks > dict['clicks']: print("Creating graph") dict['clicks']+=1 dict['X']=[] dict['Y']=[] dict['global_interval']=interval_n dict['infected_nodes_info']={} infected_nodes_info = dict['infected_nodes_info'] infected = 0 cont = 0 # Randomly infecting nodes while infected < nodes_infected and cont<nodes_num: print("Infecting...") randy = random.randint(0, nodes_num-1) if randy not in infected_nodes_info: infected_nodes_info[randy] = True infected += 1 cont += 1 print("Creating graph with %d nodes and %d as radius. Infecting %d nodes." % (nodes_num, radius, nodes_infected)) G = nx.random_geometric_graph(nodes_num, radius) dict['G'] = G print("Trying to draw created") figure = draw_a_graph() figure_2 = draw_scatter() wait_ies['drawing']=False return figure, figure_2, [html.P("Creating graph")] infected_nodes_info=dict['infected_nodes_info'] print("Updating graph") G = dict['G'] rate = dict['rate'] # Update infected nodes in graph update_infected() global_interval = dict['global_interval'] # Print information results['s_results']=[html.P('Interval:'), html.P(str(interval_n-global_interval)), html.P('Total nodes:'), html.P(str(len(G.nodes()))), html.P('Number of infected nodes'), html.P(str(len(dict['infected_nodes_info']))) ] print("Interval: ") print(interval_n) print("Vector de estado de infección:") print(infected_nodes_info) print("Número de nodos infectados:") print(len(dict['infected_nodes_info'])) print("Número de nodos totales:") print(len(G.nodes())) dict['G'] = G print("Trying to draw") figure = draw_a_graph() figure_2 = draw_scatter() print(figure_2) print("Updated graph") return [figure, figure_2, results['s_results']]
def random_geometric_graph(*args, **kwargs): return nx.random_geometric_graph(*args, **kwargs)
import plotly.graph_objs as go import plotly import random from dash.dependencies import Input, Output, State import time import datetime import pandas as pd external_stylesheets = [ 'https://codepen.io/chriddyp/pen/bWLwgP.css', 'https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.css' ] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) dict = { 'G': nx.random_geometric_graph(1, 1), 'rate': 0.2, 'recovery': '0.2', 'infected_nodes_info': {}, 'clicks': 0, 'X': [], 'Y': [] } wait_ies = {'drawing': True} results = {'s_results': []} def get_my_graph(): return dict['G']
import networkx name = "graph.txt" radius = .15 n_nodes = 100 g = networkx.random_geometric_graph(n_nodes, radius) while not networkx.is_connected(g): g = networkx.random_geometric_graph(n_nodes, radius) f = open(name, 'w') for e in g.edges(): e2 = (e[0]+1,e[1]+1) f.write(str(e2[0])+' '+str(e2[1])+'\n') f.close()
# We read our datasets (mode 1) if (mode == 1): positions = np.loadtxt(pjoin(folder, positions_file)) categories = np.loadtxt(pjoin(folder, categories_file), dtype=str) edges = np.loadtxt(pjoin(folder, edges_file), dtype=int) vertices_count = len(positions) ############################################################################### # Generate a geographic random network, requires networkx package (mode 0) if (mode == 0): import networkx as nx vertices_count = 100 view_size = 100 network = nx.random_geometric_graph(vertices_count, 0.2) positions = view_size * \ np.random.random((vertices_count, 3)) - view_size / 2.0 categories = np.arange(0, vertices_count) edges = np.array(network.edges()) positions = view_size * \ np.random.random((vertices_count, 3)) - view_size / 2.0 ############################################################################### # We attribute a color to each category of our dataset which correspond to our # nodes colors. category2index = { category: i for i, category in enumerate(np.unique(categories)) }
def test_number_of_nodes(self): G = nx.random_geometric_graph(50, 0.25, seed=42) assert len(G) == 50 G = nx.random_geometric_graph(range(50), 0.25, seed=42) assert len(G) == 50
for n in g.nodes(): g.node[n]['fv'] = nodefeat[n, 0].astype(float) for u, v in g.edges(): # sublevel filtration g[u][v]['fv'] = max(g.node[u]['fv'], g.node[v]['fv']) elif method == 'combined': # need to turn on zigzag flag try: p_zhang = graphonlib.smoothing.zhang.smoother(a, h=kwargs['h']) # h : neighborhood size parameter. Example: 0.3 means to include except ValueError: # for nci1, some adj matrix is rather small print('Exception: set p_zhang as 0') p_zhang = np.zeros((len(g), len(g))) # edge probability for edge value. Nodefeat for node value. for u, v in g.edges(): g[u][v]['fv'] = p_zhang[u][v] for n in g.nodes(): g.node[n]['fv'] = nodefeat[n, 0].astype(float) else: raise Exception('No such filtration strategy') return g if __name__ == '__main__': g = nx.random_geometric_graph(1000, 0.1) # create a random graph nodefeat = np.random.random((1000,1)) edge_kwargs = {} g = fil_strategy(g, nodefeat, method='node', viz_flag=False, **edge_kwargs)
def export_node_edge_list_gephi(encode_data, name_data, matrix_form=False, thresh=3, inflation=1.5, header=True, delim=',', label=None, filename_edge='edge_list.csv', filename_node='node_list.csv'): print('building graph') if matrix_form: numnodes = encode_data.shape[0] matrix = encode_data else: numnodes = len(encode_data) positions = {i: encode_data[i] for i in range(numnodes)} # use networkx to generate the graph network = nx.random_geometric_graph(numnodes, thresh, pos=positions) # then get the adjacency matrix (in sparse form) matrix = nx.to_scipy_sparse_matrix(network) # print('runing mcl') result = mc.run_mcl(matrix, inflation=inflation) clusters = mc.get_clusters(result) if label == None: label = [str(i) for i in range(numnodes)] f = open(filename_node, 'w') if header: f.write("Id,Label,Cluster-ID,image\n") i = 1 record_of_single = () for j in clusters: if len(j) == 1: record_of_single += j continue for node in j: pos = label[node].find('!') pos2 = name_data[node].find('RTW') sent = "\"" + label[node] + "\"" + delim + "\"" + label[ node][:pos] + "\"" + delim + str(i) + delim + "\"" + name_data[ node][pos2 + 4:-4] + ".png" + "\"" + "\n" f.write(sent) i = i + 1 f.close() f = open(filename_edge, 'w') if header: f.write("Source,Target,Weight\n") if matrix_form: numnodes = encode_data.shape[0] else: numnodes = len(encode_data) if label == None: label = [str(i) for i in range(numnodes)] for i in range(numnodes): for j in range(numnodes): if (i in record_of_single) or (j in record_of_single): continue if not i == j: if matrix_form: dist = encode_data[i][j] else: dist = LA.norm(encode_data[i] - encode_data[j]) if dist > thresh: continue sent = "\"" + label[i] + "\"" + delim + "\"" + label[ j] + "\"" + delim + str(dist) + "\n" f.write(sent) f.close()
import plotly.plotly as py import plotly.graph_objs as go import networkx as nx G=nx.random_geometric_graph(30,0.125) pos=nx.get_node_attributes(G,'pos') dmin=1 ncenter=0 for n in pos: x,y=pos[n] d=(x-0.5)**2+(y-0.5)**2 if d<dmin: ncenter=n dmin=d p=nx.single_source_shortest_path_length(G,ncenter) edge_trace = go.Scatter( x=[], y=[], line=dict(width=0.5,color='#888'), hoverinfo='none', mode='lines') for edge in G.edges(): x0, y0 = G.node[edge[0]]['pos'] x1, y1 = G.node[edge[1]]['pos'] edge_trace['x'] += tuple([x0, x1, None]) edge_trace['y'] += tuple([y0, y1, None])
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_number_of_nodes(self): G = nx.random_geometric_graph(50, 0.25) assert_equal(len(G), 50) G = nx.random_geometric_graph(range(50), 0.25) assert_equal(len(G), 50)
random.seed(a=631996) #%% data = {} for loop in range(1, 6): for N in Nodes: connected = False while connected is False: G = nx.random_geometric_graph(N, 1.5 / sqrt(N), dim=2, p=2) connected = nx.is_connected(G) G = G.to_directed() for (i, j) in G.edges: p = random.random() q = random.uniform(0.25 * p, 0.75 * p) G[i][j]['length'] = -np.log(p) G[i][j]['interdicted_length'] = -np.log(q) + np.log(p)
n = 406793 # TODO: update number of nodes pos = { i: (random.uniform(0, 1000), random.uniform(0, 1000), random.uniform(0, 1000)) for i in range(n) } for linking_len in np.arange(0, 16, 0.25): # TODO: update range linking_len = round(linking_len, 2) # round off floating point excess print("At ", linking_len) ll.append(linking_len) ## build a random geometric graph w that linking length G = nx.random_geometric_graph(n, linking_len, pos=pos) ## calculate & store alpha A = 2 * G.number_of_edges() / G.number_of_nodes() alpha.append(A) ## find connected components of graph & calculate s_alpha graph_cc = sorted(nx.connected_components(G), key=len, reverse=True) G0 = len(G.subgraph(graph_cc[0])) # len of largest connected component SA = G0 / G.number_of_nodes() s1.append(SA) ## calculate s2 if len(graph_cc) > 1: G1 = len(G.subgraph(graph_cc[1])) else:
""" ====================== Random Geometric Graph ====================== Example """ import networkx as nx import matplotlib.pyplot as plt import numpy as np G = nx.random_geometric_graph(1000, 0.038) # position is stored as node attribute data for random_geometric_graph pos = nx.get_node_attributes(G, 'pos') # find node near center (0.5,0.5) dmin = 1 ncenter = 0 for n in pos: x, y = pos[n] d = (x - 0.5)**2 + (y - 0.5)**2 if d < dmin: ncenter = n dmin = d # color by path length from node near center p = dict(nx.single_source_shortest_path_length(G, ncenter)) plt.figure(figsize=(8, 8)) nx.draw_networkx_edges(G, pos, nodelist=[ncenter], alpha=0.5)
import networkx as nx import matplotlib.pyplot as plt import numpy as np np.random.seed(1234) # Generate random graph p = dict((i, (np.random.uniform(0, 1), np.random.uniform(0, 1))) for i in range(200)) G = nx.random_geometric_graph(200, 0.12, pos=p) pos = nx.get_node_attributes(G, 'pos') # find node nearest the center point (0.5,0.5) dists = [(x - 0.5)**2 + (y - 0.5)**2 for x, y in list(pos.values())] ncenter = np.argmin(dists) # Plot graph, coloring by path length from central node p = nx.single_source_shortest_path_length(G, ncenter) plt.figure() nx.draw_networkx_edges(G, pos, alpha=0.4) nx.draw_networkx_nodes(G, pos, nodelist=list(p.keys()), node_size=120, alpha=0.5, node_color=list(p.values()), cmap=plt.cm.jet_r) plt.show()
import dash_core_components as dcc import dash_html_components as html import networkx as nx import plotly.graph_objs as go import plotly import random from dash.dependencies import Input, Output, State import time import datetime import pandas as pd external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css','https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) dict = {'G':nx.random_geometric_graph(1, 1), 'rate': 0.2, 'infected_nodes_info': {}, 'clicks':0, 'global_interval':0, 'X':[], 'Y':[]} wait_ies = {'drawing': True} results = {'s_results': []} def get_my_graph(): return dict['G'] def set_my_graph(temp_graph): dict['G'] = temp_graph app.layout = html.Div(className='row', children=[ html.Div([ html.Div([ html.Div([ html.H1('SI simulation', style={'color': '#CC6060', 'fontSize': 26}), html.Div([
rdata.append((stepaxis[istep], r, r)) gdata.append((stepaxis[istep], g, g)) bdata.append((stepaxis[istep], b, b)) mpl_data = {'red': rdata, 'green': gdata, 'blue': bdata} return mpl_data if __name__ == '__main__': N = 1000 p = 0.15 # G = nx.erdos_renyi_graph(N,p) G = nx.random_geometric_graph(N, p) # bb = nx.betweenness_centrality(G) # nx.set_node_attributes(G, bb, 'betweenness') # nx.set_node_attributes(G, [bb,bb], 'pos') pos = nx.get_node_attributes(G, 'pos') print(pos) dmin = 1 ncenter = 0 for n in pos: x, y = pos[n] print(x, y) d = (x - 0.5)**2 + (y - 0.5)**2
import networkx as nx import numpy as np import matplotlib.pyplot as plt from dynsimf.models.Model import Model from dynsimf.models.Model import ModelConfiguration if __name__ == "__main__": # Network definition g = nx.random_geometric_graph(250, 0.125) cfg = { 'utility': False, } model = Model(g, ModelConfiguration(cfg)) constants = { 'q': 0.8, 'b': 0.5, 'd': 0.2, 'h': 0.2, 'k': 0.25, 'S+': 0.5, } constants['p'] = 2*constants['d'] def initial_v(constants): return np.minimum(1, np.maximum(0, model.get_state('C') - model.get_state('S') - model.get_state('E'))) def initial_a(constants):