How to use the networkx.is_connected function in networkx

To help you get started, we’ve selected a few networkx examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Networks-Learning / nevae / nevae_rl / nevae_3d / modelrl.py View on Github external
if (4 - degree[v]) <= 1:
                    indicator[v][1] = 0
                if (4 - degree[v]) <= 2:
                    indicator[v][2] = 0
            #'''
            trial = 0
            candidate_edges = []
            G = nx.Graph()

            while trial < 50:
                candidate_edges = get_masked_candidate_new(p_theta, w_theta, n_fill_edges, atom_list, indicator, edge_mask, degree)
                candidate_edges.extend(known_edges)
                G = nx.Graph()
                G.add_nodes_from(range(self.n))
                G.add_weighted_edges_from(candidate_edges)
                if nx.is_connected(G):
                    print("Debug trial", trial)
                    break
                trial += 1
                print("Trial", trial)
            return candidate_edges, G
github c30ra / uv-align-distribute / uv_align_distribute / networkx / networkx / algorithms / connectivity / kcutsets.py View on Github external
def _is_separating_set(G, cut):
    """Assumes that the input graph is connected"""
    if len(cut) == len(G) - 1:
        return True

    H = G.copy()
    H.remove_nodes_from(cut)
    if nx.is_connected(H):
        return False
    return True
github cogeorg / BlackRhino / networkx / algorithms / swap.py View on Github external
nodes.

    Notes
    -----

    The initial graph `G` must be connected, and the resulting graph is
    connected. The graph `G` is modified in place.

    References
    ----------
    .. [1] C. Gkantsidis and M. Mihail and E. Zegura,
           The Markov chain simulation method for generating connected
           power law random graphs, 2003.
           http://citeseer.ist.psu.edu/gkantsidis03markov.html
    """
    if not nx.is_connected(G):
        raise nx.NetworkXError("Graph not connected")
    if len(G) < 4:
        raise nx.NetworkXError("Graph has less than four nodes.")
    n = 0
    swapcount = 0
    deg = G.degree()
    # Label key for nodes
    dk = list(n for n, d in G.degree())
    cdf = nx.utils.cumulative_distribution(list(d for n, d in G.degree()))
    window = 1
    while n < nswap:
        wcount = 0
        swapped = []
        # If the window is small, we just check each time whether the graph is
        # connected by checking if the nodes that were just separated are still
        # connected.
github dwavesystems / dwave_networkx / dwave_networkx / algorithms / coloring.py View on Github external
def _chromatic_number_upper_bound(G):
    # tries to determine an upper bound on the chromatic number of G
    # Assumes G is not complete

    if not nx.is_connected(G):
        return max((_chromatic_number_upper_bound(G.subgraph(c))
                    for c in nx.connected_components(G)))

    n_nodes = len(G.nodes)
    n_edges = len(G.edges)

    # chi * (chi - 1) <= 2 * |E|
    quad_bound = ceil((1 + math.sqrt(1 + 8 * n_edges)) / 2)

    if n_nodes % 2 == 1 and is_cycle(G):
        # odd cycle graphs need three colors
        bound = 3
    elif n_nodes > 2:
        if not eigenvalues:
            # chi <= max degree, unless it is complete or a cycle graph of odd length,
            # in which case chi <= max degree + 1 (Brook's Theorem)
github SotirisKot / Content-Aware-Node2Vec / average_node2vec / average_link_prediction.py View on Github external
if args.weighted:
        G = nx.read_edgelist(file, nodetype=int, data=(('weight', float),), create_using=nx.DiGraph())
    else:
        G = nx.read_edgelist(file, nodetype=int, create_using=nx.DiGraph())
        for edge in G.edges():
            G[edge[0]][edge[1]]['weight'] = 1
    print('Graph created!!!')

    if remove_selfloops:
        # remove the edges with selfloops
        for node in G.nodes_with_selfloops():
            G.remove_edge(node, node)

    if not args.directed:
        G = G.to_undirected()
        if get_connected_graph and not nx.is_connected(G):
            connected_sub_graph = max(nx.connected_component_subgraphs(G), key=len)
            print('Initial graph not connected...returning the largest connected subgraph..')
            return connected_sub_graph
        else:
            print('Returning undirected graph!')
            return G
    else:
        print('Returning directed graph!')
        return G
github Orange-OpenSource / pyDcop / pydcop / commands / generate.py View on Github external
"%s colors, target density %s and %s agents",
        node_count,
        color_count,
        args.density,
        agents_count,
    )

    # First a random graph
    is_connected = False
    if not args.allow_subgraph:
        while not is_connected:
            graph = nx.gnp_random_graph(args.node_count, density)
            is_connected = nx.is_connected(graph)
    else:
        graph = nx.gnp_random_graph(args.node_count, density)
        is_connected = nx.is_connected(graph)

    real_density = nx.density(graph)
    logger.info(nx.info(graph))
    logger.info("Connected : %s", nx.is_connected(graph))
    logger.info("Density %s", nx.density(graph))

    # Now create a DCOP from the graph
    d = VariableDomain("colors", "color", range(color_count))
    variables = {}
    agents = {}
    for i, node in enumerate(graph.nodes_iter()):
        logger.debug("node %s - %s", node, i)
        name = "v" + str(i)
        variables[name] = Variable(name, d)
        if auto_agents:
            a_name = "a" + str(i)
github networkl / networkl / networkl / dynamic_shortes_path_length.py View on Github external
The updated dictionary of shortest path lengths.

	Examples
    --------
    >>> G=nx.barabasi_albert_graph(100,2)
    >>> D=nx.all_pairs_shortest_path_length(G)
    >>> i=1; j=2;
    >>> D=nx.update_distance_matrix(G,D,i,j,mode='add')

    Notes
    -----
    The initial graph G must be connected.
    The graph G is modified in place.
    """
	
	if not nx.is_connected(G):
		raise nl.NetworkLError("path_length_update() not defined for disconnected graphs.")
	if G.is_directed():
		raise nl.NetworkLError("path_length_update() not defined for directed graphs.")
	if not (i in G.nodes()):
		raise nl.NetworkLError("node %s does not exist in graph G" % i)
	if not (j in G.nodes()):
		raise nl.NetworkLError("node %s does not exist in graph G" % j)
	if i==j:
		print "Warning: node i and j are the same"
		#raise nl.NetworkLError("node i and j are the same")
		return 1
	if mode=='add' and G.has_edge(i,j):
		print "Warning: edge (%s,%s) already exists in graph G" % (i,j)
		#raise nl.NetworkLError("edge (%s,%s) already exist in graph G" % (i,j))
		return 1
	if mode=='remove' and not G.has_edge(i,j):
github networkx / networkx / networkx / algorithms / tree / recognition.py View on Github external
-----
    In another convention, a directed tree is known as a *polytree* and then
    *tree* corresponds to an *arborescence*.

    See Also
    --------
    is_arborescence

    """
    if len(G) == 0:
        raise nx.exception.NetworkXPointlessConcept('G has no nodes.')

    if G.is_directed():
        is_connected = nx.is_weakly_connected
    else:
        is_connected = nx.is_connected

    # A connected graph with no cycles has n-1 edges.
    return len(G) - 1 == G.number_of_edges() and is_connected(G)
github SUNCAT-Center / CatKit / catkit / gen / molecules.py View on Github external
backbones, molecules = [], []
    combos = itertools.combinations(np.arange(ln), n - 1)
    for c in combos:
        # Construct the connectivity matrix
        ltm = np.zeros(ln)
        ltm[np.atleast_2d(c)] = 1

        connectivity = np.zeros((n, n))
        connectivity[il] = ltm
        connectivity = np.maximum(connectivity, connectivity.T)

        degree = connectivity.sum(axis=0)

        # Not fully connected (subgraph)
        if np.any(degree == 0) or not \
           nx.is_connected(nx.from_numpy_matrix(connectivity)):
            continue

        # Overbonded atoms.
        remaining_bonds = (max_degree - degree).astype(int)
        if np.any(remaining_bonds < 0):
            continue

        atoms = catkit.Gratoms(
            numbers=elements,
            edges=connectivity,
            cell=[1, 1, 1])

        isomorph = False
        for G0 in backbones:
            if atoms.is_isomorph(G0):
                isomorph = True
github frenetic-lang / pyretic / pyretic / evaluations / gen-waxman.py View on Github external
import fnss
import networkx as nx
import time
import sys

n=int(sys.argv[1])
alpha=float(sys.argv[2])
beta=float(sys.argv[3])
standard_bw = 100 # dummy bandwidth value to go on topo files

disconnected = True
tries = 0
while disconnected:
    topo = fnss.waxman_1_topology(n, alpha=alpha, beta=beta)
    disconnected = not nx.is_connected(topo)
    tries += 1
    if tries == 300:
        sys.stderr.write("%d FAIL\n" % n)
        break

if not disconnected:
    print "edges"
    nodes = list(topo.nodes())
    num_nodes = len(nodes)
    for n in nodes[:int(0.7*num_nodes)]:
        print n, 'p%d' % n
    print "links"
    for (src,dst) in topo.edges():
        print src, dst, standard_bw