def GgenerationReseau(_nbr_noeuds, _pos, _max_distance): """ Génère le réseau à partir d'une liste de positions des noeuds :param _nbr_noeuds : le nombre de noeuds du réseau :param _pos : dictionnaire des positions des noeuds. exe : {1:(2.5, 3.0), 2:(5.6, 3.1)} :param _max_distance : la distance pour que deux capteurs soient connectés :return Un graphe networkX """ _log.Linfo("Début ## Generateur.GgenerationReseau") # Fonction utilisée lors de la génération du graphe, permet de définir si un arc doit être créer entre deux # noeuds en fonction de la distance entre eux passée en paramètre def p_dist(_r): if _max_distance >= _r: return 1 else: return -1 # Génération du réseau. Un arc est créé entre deux noeuds a et b si : # (weight(a) + weight(b)) * p_dist(r) >= teta # On prend teta = 1 et weight(x) = 0.5 pour influencer le choix seulement en fonction de la distance _teta = 1 _weights = [0.5] * _nbr_noeuds return nx.geographical_threshold_graph(_nbr_noeuds, _teta, pos=_pos, dim=1, weight=_weights, p_dist=p_dist)
def test_p_dist_zero(self): """Tests if p_dict = 0 returns disconencted graph with 0 edges""" def p_dist(dist): return 0 G = nx.geographical_threshold_graph(50, 1, p_dist=p_dist) assert len(G.edges) == 0
def testGraph(self): return import networkx as nx graph = nx.geographical_threshold_graph(100,1.2) self.g = GraphSpace(graph) for idx, node in self.g.cells(): self.g[idx] = sim.BugCell() self.bugs = sim.init_grid(self.g, numbugs=20)
def GenerateGraph( rand: np.random.RandomState, num_nodes_min_max, dimensions: int = 2, theta: float = 1000.0, rate: float = 1.0, weight_name: str = "distance", ) -> nx.Graph: """Creates a connected graph. The graphs are geographic threshold graphs, but with added edges via a minimum spanning tree algorithm, to ensure all nodes are connected. Args: rand: A random seed for the graph generator. num_nodes_min_max: A sequence [lower, upper) number of nodes per graph. dimensions: (optional) An `int` number of dimensions for the positions. Default= 2. theta: (optional) A `float` threshold parameters for the geographic threshold graph's threshold. Large values (1000+) make mostly trees. Try 20-60 for good non-trees. Default=1000.0. rate: (optional) A rate parameter for the node weight exponential sampling distribution. Default= 1.0. weight_name: The name for the weight edge attribute. Returns: The graph. """ # Sample num_nodes. num_nodes = rand.randint(*num_nodes_min_max) # Create geographic threshold graph. pos_array = rand.uniform(size=(num_nodes, dimensions)) pos = dict(enumerate(pos_array)) weight = dict(enumerate(rand.exponential(rate, size=num_nodes))) geo_graph = nx.geographical_threshold_graph(num_nodes, theta, pos=pos, weight=weight) # Create minimum spanning tree across geo_graph's nodes. distances = spatial.distance.squareform(spatial.distance.pdist(pos_array)) i_, j_ = np.meshgrid(range(num_nodes), range(num_nodes), indexing="ij") weighted_edges = list(zip(i_.ravel(), j_.ravel(), distances.ravel())) mst_graph = nx.Graph() mst_graph.add_weighted_edges_from(weighted_edges, weight=weight_name) mst_graph = nx.minimum_spanning_tree(mst_graph, weight=weight_name) # Put geo_graph's node attributes into the mst_graph. for i in mst_graph.nodes(): mst_graph.node[i].update(geo_graph.node[i]) # Compose the graphs. combined_graph = nx.compose_all((mst_graph, geo_graph.copy())) # Put all distance weights into edge attributes. for i, j in combined_graph.edges(): combined_graph.get_edge_data(i, j).setdefault(weight_name, distances[i, j]) return combined_graph
def test_p_dist_zero(self): """Tests if p_dict = 0 returns disconencted graph with 0 edges """ def p_dist(dist): return 0 G = nx.geographical_threshold_graph(50, 1, p_dist=p_dist) assert_true(len(G.edges) == 0)
def test_metric(self): """Tests for providing an alternate distance metric to the generator. """ # Use the L1 metric. G = nx.geographical_threshold_graph(50, 10, metric=l1dist) for u, v in combinations(G, 2): # Adjacent vertices must exceed the threshold. if v in G[u]: assert join(G, u, v, 10, -2, l1dist) # Nonadjacent vertices must not exceed the threshold. else: assert not join(G, u, v, 10, -2, l1dist)
def test_metric(self): """Tests for providing an alternate distance metric to the generator. """ # Use the L1 metric. dist = l1dist G = nx.geographical_threshold_graph(50, 10, metric=dist) for u, v in combinations(G, 2): # Adjacent vertices must exceed the threshold. if v in G[u]: assert_true(join(G, u, v, 10, -2, dist)) # Nonadjacent vertices must not exceed the threshold. else: assert_false(join(G, u, v, 10, -2, dist))
def test_metric(self): """Tests for providing an alternate distance metric to the generator. """ # Use the L1 metric. dist = lambda x, y: sum(abs(a - b) for a, b in zip(x, y)) G = nx.geographical_threshold_graph(50, 100, metric=dist) for u, v in combinations(G, 2): # Adjacent vertices must not exceed the threshold. if v in G[u]: assert_true(join(G, u, v, 100, 2, dist)) # Nonadjacent vertices must exceed the threshold. else: assert_false(join(G, u, v, 100, 2, dist))
def test_distances(self): """Tests that pairs of vertices adjacent if and only if their distances meet the given threshold. """ # Use the Euclidean metric and alpha = -2 # the default according to the documentation. G = nx.geographical_threshold_graph(50, 10) for u, v in combinations(G, 2): # Adjacent vertices must exceed the threshold. if v in G[u]: assert join(G, u, v, 10, -2, math.dist) # Nonadjacent vertices must not exceed the threshold. else: assert not join(G, u, v, 10, -2, math.dist)
def test_distances(self): """Tests that pairs of vertices adjacent if and only if their distances meet the given threshold. """ # Use the Euclidean metric, the default according to the # documentation. dist = lambda x, y: sqrt(sum((a - b)**2 for a, b in zip(x, y))) G = nx.geographical_threshold_graph(50, 100) for u, v in combinations(G, 2): # Adjacent vertices must not exceed the threshold. if v in G[u]: assert_true(join(G, u, v, 100, 2, dist)) # Nonadjacent vertices must exceed the threshold. else: assert_false(join(G, u, v, 100, 2, dist))
def test_distances(self): """Tests that pairs of vertices adjacent if and only if their distances meet the given threshold. """ # Use the Euclidean metric and alpha = -2 # the default according to the documentation. dist = euclidean G = nx.geographical_threshold_graph(50, 10) for u, v in combinations(G, 2): # Adjacent vertices must exceed the threshold. if v in G[u]: assert_true(join(G, u, v, 10, -2, dist)) # Nonadjacent vertices must not exceed the threshold. else: assert_false(join(G, u, v, 10, -2, dist))
def test_distances(self): """Tests that pairs of vertices adjacent if and only if their distances meet the given threshold. """ # Use the Euclidean metric, the default according to the # documentation. dist = lambda x, y: sqrt(sum((a - b) ** 2 for a, b in zip(x, y))) G = nx.geographical_threshold_graph(50, 100) for u, v in combinations(G, 2): # Adjacent vertices must not exceed the threshold. if v in G[u]: assert_true(join(G, u, v, 100, 2, dist)) # Nonadjacent vertices must exceed the threshold. else: assert_false(join(G, u, v, 100, 2, dist))
def GenerateGraph(self) -> nx.Graph: """Creates a connected graph. The graphs are geographic threshold graphs, but with added edges via a minimum spanning tree algorithm, to ensure all nodes are connected. Returns: The graph. """ # Sample num_nodes. num_nodes = self.rand.randint(*self.options.num_nodes_min_max) # Create geographic threshold graph. pos_array = self.rand.uniform(size=(num_nodes, self.options.dimensions)) pos = dict(enumerate(pos_array)) weight = dict( enumerate(self.rand.exponential(self.options.rate, size=num_nodes))) geo_graph = nx.geographical_threshold_graph(num_nodes, self.options.theta, pos=pos, weight=weight) # Create minimum spanning tree across geo_graph's nodes. distances = spatial.distance.squareform( spatial.distance.pdist(pos_array)) i_, j_ = np.meshgrid(range(num_nodes), range(num_nodes), indexing="ij") weighted_edges = list(zip(i_.ravel(), j_.ravel(), distances.ravel())) mst_graph = nx.Graph() mst_graph.add_weighted_edges_from(weighted_edges, weight=self.options.weight_name) mst_graph = nx.minimum_spanning_tree(mst_graph, weight=self.options.weight_name) # Put geo_graph's node attributes into the mst_graph. for i in mst_graph.nodes(): mst_graph.node[i].update(geo_graph.node[i]) # Compose the graphs. combined_graph = nx.compose_all([mst_graph, geo_graph.copy()]) # Put all distance weights into edge attributes. for i, j in combined_graph.edges(): combined_graph.get_edge_data(i, j).setdefault( self.options.weight_name, distances[i, j]) return combined_graph
def geometric_graphs(): print("Random geometric graphs") G = nx.random_geometric_graph(20, 0.1) draw_graph(G) n = 20 p = {i: (random.gauss(0, 2), random.gauss(0, 2)) for i in range(n)} G = nx.random_geometric_graph(n, 0.2, pos=p) draw_graph(G) print("Geographical threshold graph") n = 10 w = {i: random.expovariate(1.0) for i in range(n)} G = nx.geographical_threshold_graph(n, 30, weight=w) draw_graph(G) print("Waxman graph") G = nx.waxman_graph(27) draw_graph(G) print("Navigable small world graph") G = nx.navigable_small_world_graph(7) draw_graph(G)
def generate_connected_graph(generator, num_nodes, theta, rate): """Generates graph ensures all nodes are connected Args: generator: A numpy random generator num_nodes: An integer number of nodes in the graph theta: A `float` threshold parameters for the geographic threshold graph's threshold. rate: A rate parameter for the node weight exponential sampling distribution. Returns: combined_graph: A generated graph """ pos_array = generator.uniform(size=(num_nodes, 2)) pos = dict(enumerate(pos_array)) weight = dict(enumerate(generator.exponential(rate, size=num_nodes))) geo_graph = nx.geographical_threshold_graph(num_nodes, theta, pos=pos, weight=weight) distances = spatial.distance.squareform(spatial.distance.pdist(pos_array)) i_, j_ = np.meshgrid(range(num_nodes), range(num_nodes), indexing="ij") weighted_edges = list(zip(i_.ravel(), j_.ravel(), distances.ravel())) mst_graph = nx.Graph() mst_graph.add_weighted_edges_from(weighted_edges, weight=DISTANCE_WEIGHT_NAME) mst_graph = nx.minimum_spanning_tree(mst_graph, weight=DISTANCE_WEIGHT_NAME) # Put geo_graph's node attributes into the mst_graph. for i in mst_graph.nodes(): mst_graph.nodes[i].update(geo_graph.nodes[i]) # Compose the graphs. combined_graph = nx.compose_all([mst_graph, geo_graph.copy()]) # Put all distance weights into edge attributes. for i, j in combined_graph.edges(): combined_graph.get_edge_data(i, j).setdefault(DISTANCE_WEIGHT_NAME, distances[i, j]) return combined_graph
def test_number_of_nodes(self): G = nx.geographical_threshold_graph(50, 100, seed=42) assert len(G) == 50 G = nx.geographical_threshold_graph(range(50), 100, seed=42) assert len(G) == 50
def create_real_life_population_network(n, home_size_dist, home_pos_dist, theta, max_edges_per_node=5): home_sizes, probs = zip(*home_size_distributions[home_size_dist].items()) epsilon = 0.000001 positions = {} node_to_home_id = {} home_id_to_nodes = {} fixed_nodes = [] while n > 0: home_size = random.choices(home_sizes, probs, k=1)[0] if home_pos_dist == 'gaussian': pos = (random.gauss(0, 1), random.gauss(0, 1)) else: pos = (random.random(), random.random()) home_id = n home_id_to_nodes[home_id] = [] for i in range(home_size): node = len(positions) positions[node] = (pos[0] + random.uniform(-0.01, 0.01), pos[1] + random.uniform(-0.01, 0.01)) node_to_home_id[node] = home_id home_id_to_nodes[home_id].append(node) if i == 0: fixed_nodes.append(node) n -= home_size n = len(positions) # graph = nx.soft_random_geometric_graph(n, 1, pos=positions) graph = nx.geographical_threshold_graph( n, theta, pos=positions, p_dist=lambda r: max(r, epsilon)**-2) for node in graph.nodes(): neighbors = graph.adj[node].keys() if len(neighbors) > max_edges_per_node: neighbors_to_remove = random.sample( neighbors, len(neighbors) - max_edges_per_node) graph.remove_edges_from([(node, neighbor) for neighbor in neighbors_to_remove if graph.degree(neighbor) > 1]) for home_id, node_list in home_id_to_nodes.items(): graph.add_edges_from([(a, b) for a in node_list for b in node_list if a != b], weight=24) # to separate a bit the nodes in the same family # positions = nx.spring_layout(graph, pos=positions, fixed=fixed_nodes, k=0.1, weight='weight') nx.set_node_attributes(graph, positions, 'pos') nx.set_node_attributes(graph, node_to_home_id, 'home_id') return graph
def test_geographical_threshold_graph(self): G = nx.geographical_threshold_graph(50, 100) assert_equal(len(G), 50)
def genGraph(graphKind, numNodes): """ Parameters -------------- graphKind: string numNodes: integer """ G=nx.Graph() print "Loading Graph" if graphKind == linearGraph: G.add_nodes_from(range(0,numNodes)) for i in range(0,numNodes-1): G.add_edge(i,i+1) elif graphKind == ringGraph: G.add_nodes_from(range(0,numNodes)) for i in range(0,numNodes): G.add_edge(i,(i+1)%numNodes) elif graphKind == unitDisk: r = 20 # 90 nodes with 400*400 is ok, try to keep the same density #density = 90.0/(400*400) #area = numNodes/density #xSize = np.sqrt(area) xSize = 150 # use this to keep area fixed w = dict((i,r/2) for i in range(numNodes)) for i in range(1000): random.jumpahead(i) p = dict((i,(random.uniform(0,xSize),random.uniform(0,xSize))) for i in range(numNodes)) G = nx.geographical_threshold_graph(numNodes,theta=1,alpha=1, pos=p, weight=w) if nx.is_connected(G): break if not nx.is_connected(G): print >> sys.stderr, "Could not find a connected graph \ with the given features in 1000 attempts!" sys.exit(1) elif graphKind == regularGraph: degree = 6 G= nx.random_regular_graph(degree,numNodes) elif graphKind == gridGraph or graphKind == meshGraph: if graphKind == meshGraph: radius = 90.0 # with diagonals else: radius = 70.0 # without diagonals side = int(np.sqrt(numNodes)) if side*side != numNodes: print >> sys.stderr, "Error, you want a squared \ grid with",numNodes,"nodes, it's not a square" sys.exit(1) distance = 60 positions = {} w = {} for i in range(numNodes): positions[i] = (distance*(i%side), distance*(i/side)) w[i] = radius/2 G = nx.geographical_threshold_graph(numNodes, theta=1, alpha=1, pos=positions, weight=w) if not nx.is_connected(G): print >> sys.stderr, "Error, something is \ wrong with the graph definition" sys.exit(1) elif graphKind == plainGrid: side = int(np.sqrt(float(numNodes))) G = nx.grid_2d_graph(side, side) numNodes = side*side elif graphKind == powerLaw: gamma=2 powerlaw_gamma = lambda x: nx.utils.powerlaw_sequence(x, exponent=gamma) loop = True for i in range(1000): z = nx.utils.create_degree_sequence(numNodes, powerlaw_gamma, max_tries=5000) G = nx.configuration_model(z) G = nx.Graph(G) G.remove_edges_from(G.selfloop_edges()) mainC = nx.connected_component_subgraphs(G)[0] if len(mainC.nodes()) >= numNodes*0.9: loop = False break if loop: print "ERROR: generating powerLow graph with \ impossible parameters" sys.exit() else: errMsg = "Unknown graph type " + graphKind print >> sys.stderr, errMsg sys.exit(1) print >> sys.stderr, "ok" return G
def test_geographical_threshold_graph(self): G=nx.geographical_threshold_graph(50,100) assert_equal(len(G),50)
def test_number_of_nodes(self): G = nx.geographical_threshold_graph(50, 100) assert_equal(len(G), 50) G = nx.geographical_threshold_graph(range(50), 100) assert_equal(len(G), 50)
DEBUG = 0 SHOW = 0 HEIGHT=6 WIDTH=5 DELTAS=75 ALTEZZAZ=500 ORDINE=1/ALTEZZAZ WEIGHTED = 1 lisofrelevantsizes = [i*i*30 for i in range(1,30) if i*i < 10000] FRACTION=0.2796296296296296 for N in lisofrelevantsizes: print "I am processing size "+str(N)+"\n" M=grd.mapInfo("files/Grid.xyz") w = {i: random.expovariate(0.5) for i in range(N)} G = nx.geographical_threshold_graph(N, 500) nx.draw(G, pos={i:G.node[i]['pos'] for i in G.nodes()}) plt.show() listOfNodes = G.nodes() listOfPositions, posconvert = getAll3dPos(G, M) Xs, Ys, Zs = zip(*listOfPositions) plt.scatter(Xs,Ys) plt.show() lookup={} for item in listOfPositions: if item[0] in lookup.keys(): lookup[str(item[0])][str[item[1]]]=item[2] else: lookup[str(item[0])]={str(item[1]): item[2]} for node in G.nodes(): x, y, z=posconvert[tuple(G.node[node]['pos'])]
def __init__(self, agent, id=COMPLETE, choice=1, Beta = 0.1, sparse = 0): self.tipo = id if id != COMPLETE: N = len(agent) if id == ERDOS: self.G = nx.erdos_renyi_graph(N, ERDOS_p) elif id == BARABASI: self.G = nx.barabasi_albert_graph(N, BARABASI_M) elif id == THRESHOLD: w = {i: random.expovariate(0.5) for i in range(N)} self.G = nx.geographical_threshold_graph(N, 500) removinglist=nx.isolates(self.G) self.G.remove_nodes_from(removinglist) fig2=plt.plot(nx.degree_histogram(self.G)) plt.show() print nx.average_clustering(self.G) print nx.diameter(self.G) fig2=plt.figure() positions=[self.G.node[n]['pos'] for n in self.G] nx.draw(self.G, pos=positions) plt.show() # display elif id == GRID2D: L = sqrt(N) if (int(L) != L): raise Exception("Number of Agents is not a square number") self.G = nx.grid_2d_graph(int(L),int(L),True) elif id == GRID2DBAND: L = sqrt(N) if (int(L) != L): raise Exception("Number of Agents is not a square number") self.G = nx.grid_2d_graph(int(L),int(L),False) Edge_list = self.G.edges() middle = int(L/2) for a in Edge_list: if (a[0][0]==middle and a[1][0]==middle+1) or (a[1][0]==middle and a[0][0]==middle+1): self.G[a[0]][a[1]]['weight'] = GRID2DBAND_p else: self.G[a[0]][a[1]]['weight'] = 1.0 elif id == GRIDONMAP: nodeColor=[] lisofrelevantsizes = [i*i*30 for i in range(1,30) if i*i < 10000] if N not in lisofrelevantsizes: print "the number of agents doesn't fit the grid, changing to closest possibility\n" N=min(lisofrelevantsizes, key=lambda x:abs(x-N)) print "the closest number is: " + str(N) + "\n" #self.G = gi.topologyInit(N, choice, Beta) filename= "files/topolgy"+str(N)+".pk" with open(filename, 'rb') as input: self.G = pk.load(input) if sparse==True: values = [] removinglist = [] with open('Comuni_altitudine','r') as file: for n, line in enumerate(file): if n != 0: values.append(int(line.split('\t')[1])) altitudini=np.array(values) lookup={} hist, bins = np.histogram(altitudini, bins=50, normed=1) norm=hist.max() for tupla in zip(*np.histogram(altitudini, bins=50, normed=1)): lookup[tupla[1]]=tupla[0]/norm for node in self.G.nodes(): x=np.random.uniform() y=self.G.node[node]['height'] freq=lookup[min(list(lookup.keys()), key=lambda x:abs(x-y))] if x>freq: removinglist.append(node) self.G.remove_nodes_from(removinglist) if choice == WEIGHTED: for edge in self.G.edges(): self.G[edge[0]][edge[1]]['weight'] = 2.7**(-Beta*abs(self.G.node[edge[0]]['height'] - self.G.node[edge[1]]['height'])) if DEBUG: print self.G[edge[0]][edge[1]]['weight'] #print str(edge) + "\t" + str(G[edge[0]][edge[1]]['weight']) + str(G.node[edge[0]]['height']) + "\t" + str(G.node[edge[1]]['height']) else: for edge in self.G.edges(): self.G[edge[0]][edge[1]]['weight']=1 print "the number of edges in this simulation will be " + str(len(self.G.edges())) + " And the number of agents will be " + str(len(self.G.nodes())) for x in self.G.nodes(): nodeColor.append(int(self.G.node[x]['height'])) #target = open("node_height", "w") #for x in range(len(nodeColor)): #target.write(str(x)+"\t"+str(nodeColor[x])+"\n") if SHOW == 1: colors = cm.rainbow(np.linspace(0, 1, len(nodeColor))) fig=plt.figure() elarge=[(u,v) for (u,v,d) in self.G.edges(data=True) if d['weight'] >=0.05] esmall=[(u,v) for (u,v,d) in self.G.edges(data=True) if d['weight'] <0.05] nx.draw_networkx_edges(self.G, pos={i:i for i in self.G.nodes()}, edgelist=elarge, width=2) nx.draw_networkx_edges(self.G, pos={i:i for i in self.G.nodes()}, edgelist=esmall, width=2, alpha=0.5,edge_color='b',style='dashed') nx.draw_networkx_nodes(self.G, pos={i:i for i in self.G.nodes()}, node_color=nodeColor, node_cmap=plt.cm.summer, node_size=20) plt.xlabel('X_grid identifier') plt.ylabel('Y_grid identifier') plt.title('The grid\nGenerated on the basis of given DEM') plt.show() # display self.len=len(self.G.nodes()) i = 0 if id != COMPLETE: for n in self.G: self.G.node[n]['agent'] = agent[i] i += 1 if id == GRIDONMAP: if SHOW==1: edgeWeights=[d['weight'] for (u,v,d) in self.G.edges(data=True)] bins=np.arange(0.1,1,0.05) plt.hist(edgeWeights, bins, histtype='bar', rwidth=0.8, label='Edge Weights') plt.xlabel('Edge Weights') plt.ylabel('Frequency') plt.title('Edge Weights\nThe frequency with witch a given weight is assigned given this DEM distribution') plt.show() if DEBUG==1: orderedWeights=sorted(edgeWeights) xs=range(len(edgeWeights)) fig2=plt.figure() plt.scatter(xs, orderedWeights) plt.show()
p = float(args[4]) g = nx.watts_strogatz_graph(n,k,p) name = 'Watts y Strogatz (n='+str(n)+', k='+str(k)+', p='+str(p)+')' elif option == "rgg": r = float(args[3]) name = "" if len(args) > 4: d = int(args[4]) g = nx.random_geometric_graph(n,r,d) name = 'Random Geometric Graph (n='+str(n)+', r='+str(r)+', d='+str(d)+')' else: g = random_geometric_graph(n,r) name = 'Random Geometric Graph (n='+str(n)+', r='+str(r)+')' elif option == "gtg": t = float(args[3]) g = nx.geographical_threshold_graph(n,t) name = 'Geographical Threshold Graph (n='+str(n)+', t='+str(t)+')' elif option == "wg": g = nx.waxman_graph(n) name = 'Waxman Graph (n='+str(n)+')' elif option == "nswg": g = navigable_small_world_graph(n) name = 'Navigable Small World Graph (n='+str(n)+')' elif option == "l": p1 = 0.5 p2 = 0.5 if len(args) > 4: p1 = float(args[4]) if len(args) > 5: p2 = float(args[5])
def __init__(self, n): self.map = nx.geographical_threshold_graph(n, 0) self.set_travel_time() self.set_travel_cost() self.set_customers()
def generate_raw_graph(rand, min_max_nodes, dimensions=2, geo_density=None, node_rate=1.0, min_length=1, seed=0): """Creates a connected graph. The graphs are geographic threshold graphs, but with added edges via a minimum spanning tree algorithm, to ensure all nodes are connected. Args: rand: A random seed for the graph generator. Default= None. min_max_nodes: A sequence [lower, upper) number of nodes per graph. dimensions: (optional) An `int` number of dimensions for the positions. Default= 2. geo_density: (optional) A `float` threshold parameters for the geographic threshold graph's threshold. Large values (1000+) make mostly trees. Try 20-60 for good non-trees. Default=1000.0. node_rate: (optional) A node_rate parameter for the node weight exponential sampling distribution. Default= 1.0. Returns: The graph. """ min_nodes, max_nodes = min_max_nodes if not geo_density: geo_density = (min_nodes + max_nodes) / 2.0 # Sample num_nodes. num_nodes = rand.randint(min_nodes, max_nodes) pos_array = np.arange(num_nodes) pos_array = (2 * np.pi * pos_array) / num_nodes pos_array = np.array([np.cos(pos_array), np.sin(pos_array)]) pos_array = pos_array.transpose() #pos_array = rand.uniform(size=(num_nodes, dimensions)) weight_array = rand.exponential(node_rate, size=num_nodes) # Create geographic threshold graph. geo_graph = nx.geographical_threshold_graph(num_nodes, 10.0 / geo_density, pos=dict(enumerate(pos_array)), weight=dict( enumerate(weight_array))) #geo_graph = nx.complement(geo_graph) cycle_graph = nx.DiGraph() nodes = np.array(geo_graph.nodes()) rand.shuffle(nodes) nodes = list(nodes) cycle_graph.add_cycle(nodes) # Compose the graphs. graph = nx.compose_all((cycle_graph, geo_graph.copy().to_directed())) # Put geo_graph's node attributes into the cycle_graph. for v in cycle_graph.nodes(): graph.node[v].update(geo_graph.node[v]) # Put all distance weights into edge attributes. graph.add_nodes_from(set_diff(graph.nodes(), cycle_graph.nodes()), solution=False) graph.add_nodes_from(cycle_graph.nodes(), solution=True) graph.add_edges_from(set_diff(graph.edges(), cycle_graph.edges()), solution=False) graph.add_edges_from(cycle_graph.edges(), solution=True) for u, v in graph.edges(): graph[u][v][DISTANCE_WEIGHT_NAME] = rand.random_sample() if seed != 0: graph = nx.relabel_nodes( graph, mapping={ i: p for i, p in enumerate(np.random.permutation(len(graph))) }) return graph
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