• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python networkx.random_geometric_graph函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中networkx.random_geometric_graph函数的典型用法代码示例。如果您正苦于以下问题:Python random_geometric_graph函数的具体用法?Python random_geometric_graph怎么用?Python random_geometric_graph使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了random_geometric_graph函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: main

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"
开发者ID:rmlima,项目名称:minas,代码行数:54,代码来源:genMina1.py


示例2: main

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)
开发者ID:rmlima,项目名称:minas,代码行数:52,代码来源:genMina3.py


示例3: test_set_types_random

    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)
开发者ID:djordon,项目名称:queueing-tool,代码行数:27,代码来源:test_graph_generation.py


示例4: test_QueueNetwork_copy

    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())
开发者ID:djordon,项目名称:queueing-tool,代码行数:34,代码来源:test_network.py


示例5: generate_random_level

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
开发者ID:meshy,项目名称:linkrease,代码行数:27,代码来源:levels.py


示例6: init_graph

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
开发者ID:DarkerAnt,项目名称:power,代码行数:33,代码来源:dwarf_model.py


示例7: savegraph

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)
开发者ID:rodolpheg,项目名称:Github-python,代码行数:31,代码来源:savegraph.py


示例8: generate_random_graph

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
    
    
    
    
开发者ID:KmiQ,项目名称:ERSN,代码行数:29,代码来源:randon_graph_generator.py


示例9: random_graph

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()
开发者ID:447327642,项目名称:wkk,代码行数:30,代码来源:showgraph.py


示例10: __init__

 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)
开发者ID:RafaelRemondes,项目名称:DistributedAggregationAlgorithmsSM,代码行数:7,代码来源:Network.py


示例11: test_QueueNetwork_blocking

    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)
开发者ID:djordon,项目名称:queueing-tool,代码行数:26,代码来源:test_network.py


示例12: test_from_nx

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),)))
开发者ID:peteshadbolt,项目名称:abp,代码行数:7,代码来源:test_graphstate.py


示例13: __init__

 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())
开发者ID:RafaelRemondes,项目名称:DistributedAggregationAlgorithmsSM,代码行数:8,代码来源:Network.py


示例14: test_from_nx

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),)))
开发者ID:peteshadbolt,项目名称:abp,代码行数:9,代码来源:test_nx.py


示例15: _generate_gemetric_graph

    def _generate_gemetric_graph(
        self,
        nb_node,
        radius,
        pos,
        ):

        import networkx as nx
        return nx.random_geometric_graph(nb_node, radius, pos=pos)
开发者ID:ComplexNetTSP,项目名称:CooperativeNetworking,代码行数:9,代码来源:dygraph.py


示例16: randomCityGraph

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
开发者ID:theofilis,项目名称:approximate-metric-tsp,代码行数:10,代码来源:myUtility.py


示例17: gen_geo

 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)
开发者ID:jieaozhu,项目名称:alignment_free_network_comparison,代码行数:10,代码来源:generate_feature.py


示例18: test_p_dist_default

    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()))
开发者ID:ProgVal,项目名称:networkx,代码行数:11,代码来源:test_geometric.py


示例19: test_geom_graph

    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))
开发者ID:salmatoolkit,项目名称:salma,代码行数:12,代码来源:networx_test.py


示例20: random_geometric_graph

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
开发者ID:kelwinfc,项目名称:Ambush,代码行数:12,代码来源:generate_graph.py



注:本文中的networkx.random_geometric_graph函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python networkx.random_layout函数代码示例发布时间:2022-05-27
下一篇:
Python networkx.radius函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap