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

Python networkx.is_strongly_connected函数代码示例

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

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



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

示例1: test_is_strongly_connected

 def test_is_strongly_connected(self):            
     ncc=nx.number_strongly_connected_components
     for G,C in self.gc:
         if len(C)==1:
             assert_true(nx.is_strongly_connected(G))
         else:
             assert_false(nx.is_strongly_connected(G))
开发者ID:123jefferson,项目名称:MiniBloq-Sparki,代码行数:7,代码来源:test_strongly_connected.py


示例2: test_scipy_sparse_eigs

def test_scipy_sparse_eigs(G, CN_name, self_link=False, seed_creation=False):
    eps = gm.epsilon
    print 'percentage of non-zero elements: '+str(float(np.count_nonzero(Transition_Matrix))/G.number_of_nodes()**2)
    print 'is strongly connected? '+str(nx.is_strongly_connected(G))+'\nis aperiodic? '+str(nx.is_aperiodic(G))
    M = salsa.get_matrix(G, mat_type='hub', sparse=True)  
    
    CN_index = G.nodes().index(CN_name)
    M = gm.convert_SL_and_CN_weights_to_val(M, val=eps, CN_idx=CN_index, stochastic_out=True)
    new_G = nx.DiGraph(M)  
    
    print 'AFTER get matrix:\npercentage of non-zero elements: ' + str(float(M.getnnz())/G.number_of_nodes()**2)
    print 'is strongly connected? '+str(nx.is_strongly_connected(new_G))+'\nis aperiodic? '+str(nx.is_aperiodic(new_G))
    print 'is stochastic? '+str(gm.check_if_stochastic_matrix(M.todense()))
    print M
    print M.shape[0]
    #M_pow = np.linalg.matrix_power(M.todense(), 111)
    #print M_pow
    e,ev=sp.sparse.linalg.eigen.arpack.eigs(M.copy().T, k=1,sigma=1, which='LM')#, maxiter=100000)
    h = ev/ev.sum()
    print e; print h;
    if (h.imag.sum() != 0.):
        print '##### COMPLEX VECTOR!!!! #####'
    print map(float,h.real)
    '''e1,ev1=sp.linalg.eig(M.todense(),left=True,right=False)
    m=e1.argsort()[-1]
    evMax1=np.array(ev1[:,m]).flatten()
    print '\n\tnp.linalg.eig(left)\n' + str(e1[m]) + '\n' +  str(evMax1)
    '''
    return
开发者ID:michaly,项目名称:Risk_Ranking_System,代码行数:29,代码来源:test.py


示例3: directed_stats

 def directed_stats(self):
     #   UG = nx.to_undirected(g) #claims to not have this function     
     if nx.is_strongly_connected(g): 
         sconl = nx.strongly_connected_components(g)
     else: sconl = 'NA - graph is not strongly connected'
     result = {#"""returns boolean"""
         'scon': nx.is_strongly_connected(g), 
         'sconn': nx.number_connected_components(g),
         # """returns boolean"""        
         'dag': nx.is_directed_acyclic_graph(g),
         # """returns lists"""
         'sconl': nx.strongly_connected_components(g),
         #Conl = connected_component_subgraphs(Ug)
         }
     return result
开发者ID:mayera,项目名称:netx,代码行数:15,代码来源:nets.py


示例4: test_hsdf_analysis

def test_hsdf_analysis(n = 15, p = 0.2, runs = 10000, debug = None):
    for run in range(runs) if debug is None else [debug]:
        sdfg = random_sdf_graph(n, p, seed = run)
        vectors = core.check_consistency(sdfg)
        assert nx.is_strongly_connected( sdfg )

        # Analysis of single-rate equivalent
        hsdfg = transform.single_rate_equivalent( sdfg, vectors['q'] )
        mg = make_marked_graph(hsdfg)

        # HSDF graph may not be strongly connected, compute its strongly connected components
        condensed = nx.DiGraph()
        idx = 0
        scc_idx = {}
        graph_mcr = None
        for scc in nx.strongly_connected_components(mg):
            idx += 1
            for v in scc:
                scc_idx[v] = idx

            cycletime, _, _ = mcr.compute_mcr(nx.subgraph(mg, scc), next(iter(scc)))
            condensed.add_node(idx, mcr = cycletime, size = len(scc))
            graph_mcr = cycletime if graph_mcr is None else max(cycletime, graph_mcr)

        for v, w in mg.edges_iter():
            if scc_idx[v] != scc_idx[w]:
                condensed.add_edge( scc_idx[v], scc_idx[w] )

        critical_size = mg.number_of_nodes()
        for v, data in condensed.nodes(data = True):
            d_in = condensed.in_degree(v)
            d_out = condensed.out_degree(v)
            if d_in == 0:
                critical_size = data['size']
            if d_in == 0 and data['mcr'] < graph_mcr:
                raise AssertionError("Run {}: SCC {} has MCR {} < {}".format(run, v, data['mcr'], graph_mcr))

            if d_in > 1 or d_out > 1:
                pass
                # raise AssertionError("Run {}: SCC {}: in-degree = {}, out-degree = {}".format(run, v, d_in, d_out))

        if debug:
            import pdb; pdb.set_trace()

        unfolded, _, _ = transform.unfold_depth_first( sdfg, vectors['q'], vectors['s'], vectors['q'] )
        assert nx.is_strongly_connected( unfolded )

        print("Run {:05}: MCR = {}, condensed: {} nodes. HSDF size: {}. Compression: {:.3f}".format(run, graph_mcr, condensed.number_of_nodes(), hsdfg.number_of_nodes(), hsdfg.number_of_nodes() / critical_size))
开发者ID:polca-project,项目名称:polca-toolbox,代码行数:48,代码来源:analysis.py


示例5: gen_network

def gen_network(graph,machines,basedata):
    """ Generates an LLD network from a graph
        distributing participants in a list of machines
    """
    network = ET.Element('network')
    #network.set('type',graphtype)
    network.set('participants',str(graph.number_of_nodes()))
    network.set('edges',str(graph.size()))
    network.set('density',str(NX.density(graph)))

    network.set('connected',str(NX.is_weakly_connected(graph)))
    network.set('stronglyconnected',str(NX.is_strongly_connected(graph)))

    for node in graph.nodes_iter():
        nodelement = ET.SubElement(network,'participant')
        nodelement.set('id','participant'+str(node))
        hostelem = ET.SubElement(nodelement,'host')
        #hostelem.text = 'node'+str(int(node) % len(machines))
        hostelem.text = machines[int(node) % len(machines)]
        portelem = ET.SubElement(nodelement,'port')
        portelem.text = str(20500+int(node))
        baseelem = ET.SubElement(nodelement,'basedata')
        baseelem.text = basedata
        nodelement.append(gen_dynamic())
        for source in gen_sources(graph,node):
            nodelement.append(source)
    return network
开发者ID:ldibanyez,项目名称:livelinkeddata,代码行数:27,代码来源:lldgen.py


示例6: netstats_listsdi

def netstats_listsdi(graph):
    G = graph
 #   UG = nx.to_undirected(G) #claims to not have this function     
    if nx.is_strongly_connected(G): 
        sconl = nx.strongly_connected_components(G)
    else: sconl = 'NA - graph is not strongly connected'
    result = {#"""returns boolean"""
              'scon': nx.is_strongly_connected(G), 
              'sconn': nx.number_connected_components(G),
             # """returns boolean"""        
              'dag': nx.is_directed_acyclic_graph(G),
             # """returns lists"""
              'sconl': nx.strongly_connected_components(G),
#              Conl = connected_component_subgraphs(UG)
              }
    return result    
开发者ID:freyley,项目名称:nets,代码行数:16,代码来源:views.py


示例7: create_shortest_path_matrix

def create_shortest_path_matrix(weighted=False, discount_highways=False):
    G = nx.DiGraph()

    logging.info("Loading graph to NetworkX from database...")
    c = connection.cursor()
    if discount_highways:
        c.execute("SELECT l.beg_node_id, l.end_node_id, (CASE WHEN l.link_type='1' THEN 0.5 WHEN l.link_type='2' THEN 0.5 ELSE 1.0 END) FROM microsim_link l")
    else:
        c.execute("SELECT l.beg_node_id, l.end_node_id, l.length/l.lane_count AS resistance FROM microsim_link l")
    G.add_weighted_edges_from(c.fetchall())

    logging.debug("Road network is strongly connected: %s" % repr(nx.is_strongly_connected(G)))

    logging.info("Computing shortest paths...")
    if weighted:
        sp = nx.all_pairs_dijkstra_path_length(G)
    else:
        sp = nx.all_pairs_shortest_path_length(G)

    logging.info("Converting shortest paths into matrix...")
    c.execute("SELECT ROW_NUMBER() OVER (ORDER BY id), beg_node_id, end_node_id FROM microsim_link")
    links = c.fetchall()
    N_LINKS = len(links)
    shortest_paths = np.zeros((N_LINKS, N_LINKS))
    for col_idx, _, col_end_node in links:
        for row_idx, _, row_end_node in links:
            if col_idx == row_idx:
                continue
            nodes = sp[col_end_node]
            if row_end_node not in nodes:
                shortest_paths[row_idx - 1, col_idx - 1] = float(N_LINKS)
            else:
                shortest_paths[row_idx - 1, col_idx - 1] = nodes[row_end_node]
    logging.info("Shortest path matrix complete.")
    return shortest_paths
开发者ID:syadlowsky,项目名称:density-estimation,代码行数:35,代码来源:shortest_paths.py


示例8: draw_graph

def draw_graph(nodes, edges, graphs_dir, default_lang='all'):
    lang_graph = nx.MultiDiGraph()
    lang_graph.add_nodes_from(nodes)
    for edge in edges:
        if edges[edge] == 0:
            lang_graph.add_edge(edge[0], edge[1])
        else:
            lang_graph.add_edge(edge[0], edge[1], weight=float(edges[edge]), label=str(edges[edge]))

    # print graph info in stdout
    # degree centrality
    print('-----------------\n\n')
    print(default_lang)
    print(nx.info(lang_graph))
    try:
        # When ties are associated to some positive aspects such as friendship or collaboration,
        #  indegree is often interpreted as a form of popularity, and outdegree as gregariousness.
        DC = nx.degree_centrality(lang_graph)
        max_dc = max(DC.values())
        max_dc_list = [item for item in DC.items() if item[1] == max_dc]
    except ZeroDivisionError:
        max_dc_list = []
    # https://ru.wikipedia.org/wiki/%D0%9A%D0%BE%D0%BC%D0%BF%D0%BB%D0%B5%D0%BA%D1%81%D0%BD%D1%8B%D0%B5_%D1%81%D0%B5%D1%82%D0%B8
    print('maxdc', str(max_dc_list), sep=': ')
    # assortativity coef
    AC = nx.degree_assortativity_coefficient(lang_graph)
    print('AC', str(AC), sep=': ')
    # connectivity
    print("Слабо-связный граф: ", nx.is_weakly_connected(lang_graph))
    print("количество слабосвязанных компонент: ", nx.number_weakly_connected_components(lang_graph))
    print("Сильно-связный граф: ", nx.is_strongly_connected(lang_graph))
    print("количество сильносвязанных компонент: ", nx.number_strongly_connected_components(lang_graph))
    print("рекурсивные? компоненты: ", nx.number_attracting_components(lang_graph))
    print("число вершинной связности: ", nx.node_connectivity(lang_graph))
    print("число рёберной связности: ", nx.edge_connectivity(lang_graph))
    # other info
    print("average degree connectivity: ", nx.average_degree_connectivity(lang_graph))
    print("average neighbor degree: ", sorted(nx.average_neighbor_degree(lang_graph).items(),
                                              key=itemgetter(1), reverse=True))
    # best for small graphs, and our graphs are pretty small
    print("pagerank: ", sorted(nx.pagerank_numpy(lang_graph).items(), key=itemgetter(1), reverse=True))

    plt.figure(figsize=(16.0, 9.0), dpi=80)
    plt.axis('off')
    pos = graphviz_layout(lang_graph)
    nx.draw_networkx_edges(lang_graph, pos, alpha=0.5, arrows=True)
    nx.draw_networkx(lang_graph, pos, node_size=1000, font_size=12, with_labels=True, node_color='green')
    nx.draw_networkx_edge_labels(lang_graph, pos, edges)

    # saving file to draw it with dot-graphviz
    # changing overall graph view, default is top-bottom
    lang_graph.graph['graph'] = {'rankdir': 'LR'}
    # marking with blue nodes with maximum degree centrality
    for max_dc_node in max_dc_list:
        lang_graph.node[max_dc_node[0]]['fontcolor'] = 'blue'
    write_dot(lang_graph, os.path.join(graphs_dir, default_lang + '_links.dot'))

    # plt.show()
    plt.savefig(os.path.join(graphs_dir, 'python_' + default_lang + '_graph.png'), dpi=100)
    plt.close()
开发者ID:irinfox,项目名称:minor_langs_internet_analysis,代码行数:60,代码来源:get_links_info.py


示例9: is_eulerian

def is_eulerian(G):
    """Returns ``True`` if and only if ``G`` is Eulerian.

    An graph is *Eulerian* if it has an Eulerian circuit. An *Eulerian
    circuit* is a closed walk that includes each edge of a graph exactly
    once.

    Parameters
    ----------
    G : NetworkX graph
       A graph, either directed or undirected.

    Examples
    --------
    >>> nx.is_eulerian(nx.DiGraph({0: [3], 1: [2], 2: [3], 3: [0, 1]}))
    True
    >>> nx.is_eulerian(nx.complete_graph(5))
    True
    >>> nx.is_eulerian(nx.petersen_graph())
    False

    Notes
    -----
    If the graph is not connected (or not strongly connected, for
    directed graphs), this function returns ``False``.

    """
    if G.is_directed():
        # Every node must have equal in degree and out degree and the
        # graph must be strongly connected
        return (all(G.in_degree(n) == G.out_degree(n) for n in G)
                and nx.is_strongly_connected(G))
    # An undirected Eulerian graph has no vertices of odd degree and
    # must be connected.
    return all(d % 2 == 0 for v, d in G.degree()) and nx.is_connected(G)
开发者ID:4c656554,项目名称:networkx,代码行数:35,代码来源:euler.py


示例10: test_load_call_graph_return_edges_file_granularity

    def test_load_call_graph_return_edges_file_granularity(self):
        # Act
        graph = self.target.load_call_graph(granularity=Gran.FILE)

        # Assert
        self.assertTrue(nx.is_strongly_connected(graph))
        for (u, v) in nx.get_edge_attributes(graph, 'call'):
            self.assertTrue('return' in graph[v][u])
开发者ID:andymeneely,项目名称:attack-surface-metrics,代码行数:8,代码来源:test_gprof_loader.py


示例11: prog_27

def prog_27(fname):
    graph = nx.DiGraph()
    f = open(fname)

    ns,es = map(int, f.readline().strip().split())

    graph.add_nodes_from(range(1,ns+1))

    for line in f:
        e1,e2 = map(int, line.strip().split())
        graph.add_edge(e1,e2)

    f.close()

    print nx.is_strongly_connected(graph)
        # print 'xxxxxxxx'

    print nx.number_strongly_connected_components(graph)
开发者ID:crf1111,项目名称:Bio-Informatics-Learning,代码行数:18,代码来源:LearnAlgorithm.py


示例12: test_networkx_methods

def test_networkx_methods():
    reducible_G = nx.DiGraph(np.matrix([[1,0],[0,1]]))
    print 'reducible- is strongly connected? ' + str(nx.is_strongly_connected(reducible_G)) #False
    print 'reducible- strongly connected components: ' + str(nx.strongly_connected_components(reducible_G)) #[[0], [1]]
    print 'reducible- is aperiodic? ' + str(nx.is_aperiodic(reducible_G)) #True
    
    irreducible_periodic_G = nx.DiGraph(np.matrix([[0,1],[1,0]]))
    print '\nirreducible_periodic- is strongly connected? ' + str(nx.is_strongly_connected(irreducible_periodic_G)) #True
    print 'irreducible_periodic- strongly connected components: ' + str(nx.strongly_connected_components(irreducible_periodic_G)) #[[0, 1]]
    print 'irreducible_periodic- is aperiodic? ' + str(nx.is_aperiodic(irreducible_periodic_G)) #False (2)
    
    ergodic_G = nx.DiGraph(np.matrix([[0,1,1,0],[1,0,0,1],[0,1,0,0],[0,1,0,0]]))
    modified_G = nx.DiGraph(salsa.get_matrix(ergodic_G, mat_type='hub', sparse=False))
    print 'modified- is strongly connected? ' + str(nx.is_strongly_connected(modified_G)) #False
    print 'modified- strongly connected components: ' + str(nx.strongly_connected_components(modified_G)) #[[0, 2, 3], [1]]
    print 'modified- is aperiodic? ' + str(nx.is_aperiodic(modified_G)) #True

    return
开发者ID:michaly,项目名称:Risk_Ranking_System,代码行数:18,代码来源:test.py


示例13: test_load_call_graph_return_edges_file_granularity

    def test_load_call_graph_return_edges_file_granularity(self):
        # Act
        test_graph = self.test_loader.load_call_graph(granularity=Gran.FILE)

        # Assert
        call_edges = nx.get_edge_attributes(test_graph, 'call')

        self.assertTrue(nx.is_strongly_connected(test_graph))
        for (u, v) in call_edges:
            self.assertTrue('return' in test_graph[v][u])
开发者ID:andymeneely,项目名称:attack-surface-metrics,代码行数:10,代码来源:test_cflow_loader.py


示例14: output_conectivity_info

def output_conectivity_info (graph, path):
    """Output connectivity information about the graph.
       graph : (networkx.Graph)
       path: (String) contains the path to the output file
    """
    with open(path, 'w') as out:
        out.write('***Conectivity***\n')
        out.write('Is weakly connected: %s\n' % nx.is_weakly_connected(graph))
        out.write('Number of weakly connected components: %d\n' % nx.number_weakly_connected_components(graph))
        out.write('Is strongly connected: %s\n' % nx.is_strongly_connected(graph))
        out.write('Number of strongly connected components: %d' % nx.number_strongly_connected_components(graph))
开发者ID:jillzz,项目名称:transport-network-analysis,代码行数:11,代码来源:graph_info.py


示例15: get_relation_node_free_graph

    def get_relation_node_free_graph(self):
        if nx.is_strongly_connected(self):
            raise ArgGraphException(('Cannot produce relation node free graph.'
                                     'Arggraph contains cycles.'))
        if False in [self.out_degree(node) <= 1 for node in self.nodes()]:
            raise ArgGraphException(('Cannot produce relation node free graph.'
                                    'Nodes with multiple outgoing edges.'))

        a = ArgGraph(self)

        if ('relation-node-free' in a.graph and
                a.graph['relation-node-free'] == True):
            return a

        # reduce multi-source relations to adu.addsource->adu
        for rel_node in [node for node, d in a.nodes(data=True)
                         if a.out_degree(node) >= 1 and d['type'] == 'rel']:
            sources = sorted_nicely(
                [source for source in a.predecessors(rel_node)
                 if a.node[source]['type'] == 'adu']
            )
            for source in sources[1:]:
                a.remove_edge(source, rel_node)
                a.add_edge(source, sources[0], type="add")

        # first reduce rel->rel
        remove_nodes = []
        remove_edges = []
        for (src, trg, d) in a.edges(data=True):
            if a.node[src]['type'] == 'rel' and a.node[trg]['type'] == 'rel':
                src_pre = a.predecessor_by_edge_type(src, 'src')[0]
                trg_pre = a.predecessor_by_edge_type(trg, 'src')[0]
                a.remove_edge(src, trg)
                a.add_edge(src_pre, trg_pre, type=d['type'])
                remove_edges.append((src_pre, src, ))
                remove_nodes.append(src)

        for src, trg in remove_edges:
            a.remove_edge(src, trg)
        for node in remove_nodes:
            a.remove_node(node)

        # then reduce rel->adu (remaining relnodes)
        for (src, trg, d) in a.edges(data=True):
            if a.node[src]['type'] == 'rel' and a.node[trg]['type'] == 'adu':
                src_pre = a.predecessors(src)[0]
                a.add_edge(src_pre, trg, type=d['type'])
                a.remove_edge(src_pre, src)
                a.remove_edge(src, trg)
                a.remove_node(src)

        a.graph['relation-node-free'] = True

        return a
开发者ID:peldszus,项目名称:emnlp2015,代码行数:54,代码来源:arggraph.py


示例16: test_eig_error

def test_eig_error():
    #graph_file = '/home/michal/SALSA_files/tmp/real_run/graph_11'
    #G = gm.read_graph_from_file(graph_file)
    graph_list = [(354, 354, {'weight': 0.5}),\
                  (354, 13291, {'weight': 0.25}),\
                  (354, 11354, {'weight': 0.25}),\
                  (15204, 15204, {'weight': 0.5}),\
                  (15204, 14639, {'weight': 0.5}),\
                  (11210, 6898, {'weight': 0.25}),\
                  (11210, 11210, {'weight': 0.5}),\
                  (11210, 11354, {'weight': 0.25}),\
                  (13291, 354, {'weight': 0.5}),\
                  (13291, 13291, {'weight': 0.5}),\
                  (14639, 13236, {'weight': 0.16666666666666666}),\
                  (14639, 6898, {'weight': 0.16666666666666666}),\
                  (14639, 15204, {'weight': 0.25}),\
                  (14639, 14639, {'weight': 0.41666666666666663}),\
                  (6898, 6898, {'weight': 0.6111111111111112}),\
                  (6898, 13236, {'weight': 0.1111111111111111}),\
                  (6898, 11210, {'weight': 0.16666666666666666}),\
                  (6898, 14639, {'weight': 0.1111111111111111}),\
                  (13236, 6898, {'weight': 0.3333333333333333}),\
                  (13236, 13236, {'weight': 0.3333333333333333}),\
                  (13236, 14639, {'weight': 0.3333333333333333}),\
                  (11354, 11210, {'weight': 0.25}),\
                  (11354, 354, {'weight': 0.25}),\
                  (11354, 11354, {'weight': 0.5})]
    #(11354, 11354, {'weight': 0.5})]

    G = nx.DiGraph(graph_list)
    #print G.edges(data=True)
    print '--- eig_calc: is sub graph stochastic? ' + str(gm.check_if_stochastic_matrix(nx.to_numpy_matrix(G)))#; sys.stdout.flush()
    print '--- eig_calc: is sub graph strongly connected? ' + str(nx.is_strongly_connected(G))#; sys.stdout.flush()
    print '--- eig_calc: is sub graph aperiodic? ' + str(nx.is_aperiodic(G));# sys.stdout.flush()
    #np_mat = nx.to_numpy_matrix(G)
    #print 'det= '+ str(np.linalg.det(np_mat))
    print salsa.eig_calc(G)
    '''try:
        print salsa.eig_calc(G)
    except RuntimeError: 
        max_weight = max(e[2]['weight'] for e in G.edges_iter(data=True))
        noise = 1e-13
        for e in G.edges_iter(data=True):
            if e[2]['weight'] == max_weight:
                e[2]['weight'] += noise
        if not gm.check_if_stochastic_matrix(nx.to_numpy_matrix(G)):
            nx.stochastic_graph(G, copy=False)
        print salsa.eig_calc(G)'''
    
    

    
    return
开发者ID:michaly,项目名称:Risk_Ranking_System,代码行数:53,代码来源:test.py


示例17: test_enterprise_graph_properties

    def test_enterprise_graph_properties(self):
        """ EnterpriseTopology graph must be directed, containt 1577 nodes, be
        strongly connected and the paths need to be symmetric"""

        topo = self.topo

        self.assertTrue(topo.graph.is_directed())
        self.assertEqual(len(topo.graph.nodes()) + len(topo.leaves), 1577)
        self.assertTrue(nx.is_strongly_connected(topo.graph))
        for src in topo.graph.nodes():
            for dst in topo.graph.nodes():
                self.assertEqual(topo.paths[src][dst],
                                 list(reversed(topo.paths[dst][src])))
开发者ID:fg-inet,项目名称:panoptisim,代码行数:13,代码来源:test_topology.py


示例18: mcr_apx

def mcr_apx(g, upper= True, estimate_mcr = None):
    assert g.is_consistent()
    assert nx.is_strongly_connected(g)
    # mrsdfg = transform.multi_rate_equivalent(g)
    pess = transform.single_rate_apx(g, upper)
    mg = make_marked_graph( pess )
    #print("size of HSDFG: {}".format(mg.number_of_nodes()))
    try:
        ratio, cycle, _ = mcr.compute_mcr( mg, estimate = Fraction( estimate_mcr, g.tpi ) if estimate_mcr is not None else None)
    except mcr.InfeasibleException as ex:
        ratio, cycle = None, ex.cycle

    if ratio is None:
        return None, cycle
    else:
        return ratio * g.tpi, cycle
开发者ID:polca-project,项目名称:polca-toolbox,代码行数:16,代码来源:analysis.py


示例19: all_eulerian_cycles

def all_eulerian_cycles(g,start=None) :
    if not isinstance(g,nx.MultiDiGraph) :
        raise Exception("expect nx.MultiDiGraph")
    if not nx.euler.is_eulerian(g) :
        raise Exception("g is not eulerian")

    all_graphs = set([g])
    while True:
        tosimplify_g = next(ifilter(lambda gr : not is_simple(gr), all_graphs),None)
        if not tosimplify_g :
            break
        multivertex = next(ifilter(lambda v : in_degree(tosimplify_g,v) > 1,tosimplify_g.nodes()),None)
        assert multivertex

        for incoming in tosimplify_g.in_edges(multivertex) :
            for outgoing in tosimplify_g.out_edges(multivertex) :
                #modify simplify_g to add the bypass edge

                newvertex = Node(multivertex.kmer)
                tosimplify_g.add_edge(incoming[0],newvertex)
                tosimplify_g.add_edge(newvertex,outgoing[1])
                tosimplify_g.remove_edge(*incoming)
                tosimplify_g.remove_edge(*outgoing)

                simplified = tosimplify_g.copy()
                if nx.is_strongly_connected(simplified) :
                    all_graphs.add(simplified)
                #else :
                    #print "not sc : ", simplified.edges()

                #revert all modifications
                tosimplify_g.add_edge(*outgoing)
                tosimplify_g.add_edge(*incoming)
                tosimplify_g.remove_edge(newvertex,outgoing[1])
                tosimplify_g.remove_edge(incoming[0],newvertex)
                assert len(tosimplify_g.in_edges(newvertex)) == 0
                assert len(tosimplify_g.out_edges(newvertex)) == 0
                tosimplify_g.remove_node(newvertex)

        all_graphs.remove(tosimplify_g)

    for g in all_graphs :
        assert nx.euler.is_eulerian(g)

        start = next(ifilter(lambda n : n.start==True,g.nodes()),None)
        assert start != None
        yield nx.euler.eulerian_circuit(g,start)
开发者ID:mdk2029,项目名称:rl,代码行数:47,代码来源:all_eulerian_cycles.py


示例20: get_largest_component

def get_largest_component(G, strongly=False):
    """
    Return a subgraph of the largest weakly or strongly connected component
    from a directed graph.

    Parameters
    ----------
    G : networkx multidigraph
    strongly : bool
        if True, return the largest strongly instead of weakly connected
        component

    Returns
    -------
    G : networkx multidigraph
        the largest connected component subgraph from the original graph
    """

    start_time = time.time()
    original_len = len(list(G.nodes()))

    if strongly:
        # if the graph is not connected retain only the largest strongly connected component
        if not nx.is_strongly_connected(G):
            
            # get all the strongly connected components in graph then identify the largest
            sccs = nx.strongly_connected_components(G)
            largest_scc = max(sccs, key=len)
            G = induce_subgraph(G, largest_scc)
            
            msg = ('Graph was not connected, retained only the largest strongly '
                   'connected component ({:,} of {:,} total nodes) in {:.2f} seconds')
            log(msg.format(len(list(G.nodes())), original_len, time.time()-start_time))
    else:
        # if the graph is not connected retain only the largest weakly connected component
        if not nx.is_weakly_connected(G):
            
            # get all the weakly connected components in graph then identify the largest
            wccs = nx.weakly_connected_components(G)
            largest_wcc = max(wccs, key=len)
            G = induce_subgraph(G, largest_wcc)
            
            msg = ('Graph was not connected, retained only the largest weakly '
                   'connected component ({:,} of {:,} total nodes) in {:.2f} seconds')
            log(msg.format(len(list(G.nodes())), original_len, time.time()-start_time))

    return G
开发者ID:gboeing,项目名称:osmnx,代码行数:47,代码来源:utils.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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