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

Python networkx.create_empty_copy函数代码示例

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

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



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

示例1: test_create_empty_copy

 def test_create_empty_copy(self):
     G=networkx.create_empty_copy(self.G, with_nodes=False)
     assert_equal(G.nodes(),[])
     assert_equal(G.graph,{})
     assert_equal(G.node,{})
     assert_equal(G.edge,{})
     G=networkx.create_empty_copy(self.G)
     assert_equal(G.nodes(),self.G.nodes())
     assert_equal(G.graph,{})
     assert_equal(G.node,{}.fromkeys(self.G.nodes(),{}))
     assert_equal(G.edge,{}.fromkeys(self.G.nodes(),{}))
开发者ID:Bludge0n,项目名称:AREsoft,代码行数:11,代码来源:test_function.py


示例2: test_create_empty_copy

 def test_create_empty_copy(self):
     G = nx.create_empty_copy(self.G, with_data=False)
     assert_nodes_equal(G, list(self.G))
     assert_equal(G.graph, {})
     assert_equal(G._node, {}.fromkeys(self.G.nodes(), {}))
     assert_equal(G._adj, {}.fromkeys(self.G.nodes(), {}))
     G = nx.create_empty_copy(self.G)
     assert_nodes_equal(G, list(self.G))
     assert_equal(G.graph, self.G.graph)
     assert_equal(G._node, self.G._node)
     assert_equal(G._adj, {}.fromkeys(self.G.nodes(), {}))
开发者ID:iaciac,项目名称:networkx,代码行数:11,代码来源:test_function.py


示例3: Prim

def Prim(G = nx.Graph(), R = None):
    # Q é a lista de vértices que não estão na árvore
    Q    = {}
    # pred armazenará o predecessor de cada vértice
    pred = {}

    # Inicializamos Q com todos os vértices com valor infinito, pois neste
    # ponto ainda não há ligação entre nenhum vértice. Igualmente, nenhum
    # vértice tem predecessor, portanto utilizamos o valor 'null'.
    for v,data in G.nodes(data=True):
        Q[v]    = n.inf
        pred[v] = 'null'

    # Caso não haja pesos definidos para os vértices, atribuímos o valor 1.0.
    # Esta é uma abordagem alternativa à que usamos em Kruskal, de utilizar uma
    # variável para verificar se estamos levando em conta o peso ou não.
    for e,x in G.edges():
        if ('weight' not in G[e][x]):
            G[e][x]['weight'] = 1.0

    # Inicializamos a raiz da árvore com valor 0, e criamos uma árvore chamada
    # MST apenas com os vértices de G.
    Q[R] = 0.0
    MST  = nx.create_empty_copy(G)

    while Q:
        # u := índice do menor elemento de Q
        # pois queremos o vértice de menor peso
        u = min(Q,key=Q.get)

        # removemos de Q, pois ele será adicionado na árvore
        del Q[u]

        # guardamos os pesos mínimos de cada vizinho de u em Q, se forem
        # menores do que os já armazenados
        for vizinho in G[u]:
            if vizinho in Q:
                if G[u][vizinho]['weight'] < Q[vizinho]:
                    pred[vizinho] = u
                    Q[vizinho]    = G[u][vizinho]['weight']

        # Se existirem predecessores para u, então adicionaremos as arestas
        # conectando o vértice u a seus predecessores
        if pred[u] is not 'null':
            for v1,v2,data in G.edges(data=True):
                # para preservar os dados da aresta, foi necessário esse loop
                # que verifica todas as arestas do grafo e procura a aresta
                # (pred(u),u), porém, como um grafo não direcionado da
                # biblioteca não duplica a existência de suas arestas no
                # conjunto de arestas, isto é, se tem (u,v) não tem (v,u), há a
                # necessidade de verificar, no caso de grafos não direcionados,
                # se há a existência da aresta (u,pred(u)) ao invés de
                # (pred(u),u)
                if ( v1 is pred[u] and v2 is u ):
                    MST.add_edge(pred[u],u,data)
                elif (  ( v1 is u and v2 is pred[u] ) and
                        ( not nx.is_directed(G) )  ):
                    MST.add_edge(pred[u],u,data)

    return MST
开发者ID:andrewalker,项目名称:grafos,代码行数:60,代码来源:Prim.py


示例4: allocate_role

    def allocate_role(self):
        # Make a copy of the graph
        graph = nx.create_empty_copy(self._graph, with_nodes=True)
        graph.add_edges_from(self._graph.edges())

        while len(graph.nodes()) > 0:
            # Try to get a node with degree 1
            nodes = self._get_nodes_with_degree_one(graph)
            if len(nodes) > 0:
                for node in nodes:
                    #if not self._has_p_neighbors(node):
                    # Mark as PE
                    self._graph.node[node]['vrf_role'] = 'PE'
                    # Mark neighbor as P
                    neighbors = graph.neighbors(node)
                    for neighbor in neighbors:
                        self._graph.node[neighbor]['vrf_role'] = 'P'
                graph.remove_node(node)
                graph.remove_nodes_from(neighbors)
                    #else:
                        # Mark as P and remove
                    #    self._graph.node[node]['vrf_role'] = 'P'
                    #    print ' - Mark %s as P' % node
                    #    graph.remove_node(node)
            else:
                node_with_max_degree = self._get_max_degree_node(graph)
                if node_with_max_degree is not None:
                    self._graph.node[node_with_max_degree]['vrf_role'] = 'P'
                    graph.remove_node(node_with_max_degree)
开发者ID:glospoto,项目名称:service-comparison,代码行数:29,代码来源:processing.py


示例5: max_flow

def max_flow(graph, source, sink, attribute='capacity'):
    """Return the maximum flow through a flow network.

    Uses the Edmonds-Karp algorithm.
    Parameters:
    graph -- an nx.Digraph object representing the flow network. Antiparallel
        edges are supported, but other contraints on flow networks must hold.
    source -- The source node on the graph.
    sink -- The sink node on the graph.
    attribute -- the edge attribute containing the capacities.

    Returns: An nx.Digraph representing the flow.
    """
    # Eliminate any antiparallel edges.
    simplified_graph = graph.copy()
    fake_nodes = remove_antiparallel(simplified_graph)

    # Create the empty flow.
    curr_flow = nx.create_empty_copy(simplified_graph)

    # Keep augmenting the flow with paths from the residual network until
    # no more augmenting paths exist.
    can_augment = True
    while can_augment:
        can_augment = augment(simplified_graph, curr_flow,
                              source, sink, attribute)

    # Restore antiparallel edges.
    restore_antiparallel(curr_flow, fake_nodes)

    return curr_flow
开发者ID:Patrick-Payne,项目名称:snippets,代码行数:31,代码来源:max_flow.py


示例6: residual_flow

def residual_flow(network, flow, attribute='capacity'):
    """Return the residual flow through a flow network.

    Parameters:
    network -- The flow network, represented using an nx.DiGraph object.
    flow -- The flow through the network, also represented by an nx.DiGraph.
    attribute -- The name of the edge attribute containing the capacity.

    Returns: An nx.Digraph representing the residual flow.
    """
    residual = nx.create_empty_copy(network)
    for u, v in network.edges_iter():
        # Get the edge attributes from each graph
        capacity = network[u][v][attribute]
        used = flow[u][v][attribute] if (u, v) in flow.edges() else 0
        excess = capacity - used
        assert excess >= 0, "Flow had edges greater than capacity."

        # Add in any leftover forward capacity.
        if excess > 0:
            residual.add_edge(u, v, {attribute: excess})
        # Add in the decreasing flow residual
        if used > 0:
            residual.add_edge(v, u, {attribute: used})

    return residual
开发者ID:Patrick-Payne,项目名称:snippets,代码行数:26,代码来源:max_flow.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python networkx.cubical_graph函数代码示例发布时间:2022-05-27
下一篇:
Python networkx.cost_of_flow函数代码示例发布时间: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