当前位置: 首页>>代码示例>>Python>>正文


Python networkx.is_weakly_connected函数代码示例

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


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

示例1: exp_10

def exp_10():
  net = MinTTTLagrangianCTMProblem.load("/Users/jdr/Desktop/out.json")
  net.cache_props()
  print len(net.sources)
  print len(net.sinks)
  print len(net.all_routes())
  print len(net.get_links())
  # for route in net.all_routes():
  #   print net.max_flow(route), net.ff_travel_time(route)
  import networkx
  print networkx.is_weakly_connected(net)
  with open('/Users/jdr/Desktop/flowdata.csv','r') as fn:
    flows = {}
    for row in fn:
      splits = row[:-1].split(';')
      print splits
      name = splits[2]
      flow = float(splits[1])
      density = float(splits[0])
      flows[name] = {
        'flow': flow,
        'density': density
      }
  def get_flows(link):
    try:
      return flows[link.name]['flow']
    except:
      return 0.0
  for junction in net.junctions:
    lsum = sum(get_flows(link) for link in junction.in_links)
    rsum = sum(get_flows(link) for link in junction.out_links)
    print lsum, rsum
  for link in net.get_links():
    print bool(link.fd.q_max < get_flows(link)), link.fd.q_max, get_flows(link)
开发者ID:samitha,项目名称:commroute,代码行数:34,代码来源:experiments.py

示例2: subgraphs_product

def subgraphs_product(G1, G2, length):
    assert length <= len(G1.nodes())
    assert length <= len(G2.nodes())

    a = it.combinations(G1.nodes(), length)
    b = it.combinations(G2.nodes(), length)
    gen = it.product(a, b)

    for pair in gen:
        sub1 = G1.subgraph(pair[0])
        sub2 = G2.subgraph(pair[1])
        if nx.is_weakly_connected(sub1) and nx.is_weakly_connected(sub2):
            yield (sub1, sub2)
开发者ID:viennadd,项目名称:Compare-two-control-flow,代码行数:13,代码来源:network_similarity.py

示例3: evaluate

def evaluate(graph):
    """evaluate(Graph) -> None

    :class:`Graph` -> IO ()

    Starting from the root node, evaluate the branches.
    The graph nodes are updated in-place.

    Example:

    >>> @delayed()
    ... def foo(a):
    ...   return a
    >>> node = foo(42) & foo(24)
    >>> print evaluate(node.graph)
    None
    >>> for _, data in node.graph.nodes(data=True):
    ...   n = data['node']
    ...   print n.name, n.result.result()
    & None
    foo 42
    foo 24
    """

    assert nx.is_weakly_connected(graph)
    node = find_root_node(graph)
    node.eval()
开发者ID:ashwinir20,项目名称:workflow,代码行数:27,代码来源:workflow.py

示例4: connected

    def connected(self):
        """
        Test if the graph is connected.

        Return True if connected, False otherwise
        """
        return nx.is_weakly_connected(self.G)
开发者ID:LuisCarlosEiras,项目名称:qiskit-sdk-py,代码行数:7,代码来源:_coupling.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: 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

示例7: average_shortest_path_length

def average_shortest_path_length(G, weight=None):
    r"""Return the average shortest path length.

    The average shortest path length is

    .. math::

       a =\sum_{s,t \in V} \frac{d(s, t)}{n(n-1)}

    where `V` is the set of nodes in `G`,
    `d(s, t)` is the shortest path from `s` to `t`,
    and `n` is the number of nodes in `G`.

    Parameters
    ----------
    G : NetworkX graph

    weight : None or string, optional (default = None)
       If None, every edge has weight/distance/cost 1.
       If a string, use this edge attribute as the edge weight.
       Any edge attribute not present defaults to 1.

    Raises
    ------
    NetworkXError:
       if the graph is not connected.

    Examples
    --------
    >>> G=nx.path_graph(5)
    >>> print(nx.average_shortest_path_length(G))
    2.0

    For disconnected graphs you can compute the average shortest path
    length for each component:
    >>> G=nx.Graph([(1,2),(3,4)])
    >>> for g in nx.connected_component_subgraphs(G):
    ...     print(nx.average_shortest_path_length(g))
    1.0
    1.0

    """
    if G.is_directed():
        if not nx.is_weakly_connected(G):
            raise nx.NetworkXError("Graph is not connected.")
    else:
        if not nx.is_connected(G):
            raise nx.NetworkXError("Graph is not connected.")
    avg=0.0
    if weight is None:
        for node in G:
            path_length=nx.single_source_shortest_path_length(G, node)
            avg += sum(path_length.values())
    else:
        for node in G:
            path_length=nx.single_source_dijkstra_path_length(G, node, weight=weight)
            avg += sum(path_length.values())
    n=len(G)
    return avg/(n*(n-1))
开发者ID:ChrisOelmueller,项目名称:networkx,代码行数:59,代码来源:generic.py

示例8: is_connected

 def is_connected(self):
     """
     Return True if the Xmrs represents a connected graph.
     Subgraphs can be connected through things like arguments,
     QEQs, and label equalities.
     """
     try:
         return nx.is_weakly_connected(self._graph)
     except nx.exception.NetworkXPointlessConcept:
         raise XmrsError("Connectivity is undefined for an empty Xmrs.")
开发者ID:alvations,项目名称:pydelphin,代码行数:10,代码来源:xmrs.py

示例9: random_connected_graph

def random_connected_graph(numNodes, numEdges):
    '''Generates a weakly connected random graph with numNodes nodes
       and numEdges edges
    '''
    tries = 0
    while tries < 100:
        tries += 1
        random_graph = nx.gnm_random_graph(numNodes,numEdges,directed = True)
        if nx.is_weakly_connected(random_graph): 
            return random_graph
    return None
开发者ID:jinpan,项目名称:6.854-project,代码行数:11,代码来源:experiments_argv.py

示例10: _get_subgraphs

 def _get_subgraphs(self, graph, name, size=3):
     subgraphs = set()
     # print "\nSubgraphs START: " + name
     target = nx.complete_graph(size)
     for sub_nodes in itertools.combinations(graph.nodes(),len(target.nodes())):
         subg = graph.subgraph(sub_nodes)
         if nx.is_weakly_connected(subg):
             # print subg.edges()
             subgraphs.add(subg)
     # print "Subgraphs END \n"
     return subgraphs
开发者ID:Eszti,项目名称:4lang,代码行数:11,代码来源:sim_feats.py

示例11: 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

示例12: set_domain

    def set_domain(clz, dag):
        """ Sets the domain.  Should only be called once per class instantiation. """
        logging.info("Setting domain for poset %s" % clz.__name__)
        if nx.number_of_nodes(dag) == 0:
            raise CellConstructionFailure("Empty DAG structure.")
            
        if not nx.is_directed_acyclic_graph(dag):
            raise CellConstructionFailure("Must be directed and acyclic")

        if not nx.is_weakly_connected(dag):
            raise CellConstructionFailure("Must be connected")
        clz.domain_map[clz] = dag
开发者ID:EventTeam,项目名称:beliefs,代码行数:12,代码来源:posets.py

示例13: rooted_core_interface_pairs

    def rooted_core_interface_pairs(self, root, thickness=None,  for_base=False,
                                        hash_bitmask=None,
                                      radius_list=[],
                                      thickness_list=None,
                                      node_filter=lambda x, y: True):
        """

        Parameters
        ----------
        root:
        thickness:
        args:

        Returns
        -------

        """

        ciplist = super(self.__class__, self).rooted_core_interface_pairs(root, thickness, for_base=for_base,
                                        hash_bitmask=hash_bitmask,
                                      radius_list=radius_list,
                                      thickness_list=thickness_list,
                                      node_filter=node_filter)



        # numbering shards if cip graphs not connected
        for cip in ciplist:
            if not nx.is_weakly_connected(cip.graph):
                comps = [list(node_list) for node_list in nx.weakly_connected_components(cip.graph)]
                comps.sort()

                for i, nodes in enumerate(comps):

                    for node in nodes:
                        cip.graph.node[node]['shard'] = i

        '''
        solve problem of single-ede-nodes in the core
        this may replace the need for fix_structure thing
        this is a little hard.. may fix later

        it isnt hard if i write this code in merge_core in ubergraphlearn

        for cip in ciplist:
            for n,d in cip.graph.nodes(data=True):
                if 'edge' in d and 'interface' not in d:
                    if 'interface' in cip.graph.node[ cip.graph.successors(n)[0]]:
                        #problem found
        '''

        return ciplist
开发者ID:smautner,项目名称:GraphLearn,代码行数:52,代码来源:rnadecomposer.py

示例14: is_semiconnected

def is_semiconnected(G):
    """Return True if the graph is semiconnected, False otherwise.

    A graph is semiconnected if, and only if, for any pair of nodes, either one
    is reachable from the other, or they are mutually reachable.

    Parameters
    ----------
    G : NetworkX graph
        A directed graph.

    Returns
    -------
    semiconnected : bool
        True if the graph is semiconnected, False otherwise.

    Raises
    ------
    NetworkXNotImplemented :
        If the input graph is undirected.

    NetworkXPointlessConcept :
        If the graph is empty.

    Examples
    --------
    >>> G=nx.path_graph(4,create_using=nx.DiGraph())
    >>> print(nx.is_semiconnected(G))
    True
    >>> G=nx.DiGraph([(1, 2), (3, 2)])
    >>> print(nx.is_semiconnected(G))
    False

    See Also
    --------
    is_strongly_connected
    is_weakly_connected
    is_connected
    is_biconnected
    """
    if len(G) == 0:
        raise nx.NetworkXPointlessConcept(
            'Connectivity is undefined for the null graph.')

    if not nx.is_weakly_connected(G):
        return False

    G = nx.condensation(G)
    path = nx.topological_sort(G)
    return all(G.has_edge(u, v) for u, v in pairwise(path))
开发者ID:ProgVal,项目名称:networkx,代码行数:50,代码来源:semiconnected.py

示例15: generate_triads_1

def generate_triads_1(network):
	"""
	Generate triads by making all node combinations, filtering < 2 edges. 
	Not suitable for large graphs. 

	"""
	nodes = network.nodes()
	node_combos = list(itertools.combinations(nodes, 3))
	triads = []

	for combo in node_combos:
		sub_graph = network.subgraph(combo)
		if nx.is_weakly_connected(sub_graph):
			triads.append(sub_graph)
	return triads
开发者ID:piazzatron,项目名称:networks_final,代码行数:15,代码来源:Motif_Counter.py


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