Python networkx.selfloop_edges() Examples

The following are 30 code examples of networkx.selfloop_edges(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module networkx , or try the search function .
Example #1
Source File: test_graph.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_deprecated():
    # for backwards compatibility with 1.x, will be removed for 3.x
    G = nx.complete_graph(3)
    assert_equal(G.node, {0: {}, 1: {}, 2: {}})

    G = nx.DiGraph()
    G.add_path([3, 4])
    assert_equal(G.adj, {3: {4: {}}, 4: {}})

    G = nx.DiGraph()
    G.add_cycle([3, 4, 5])
    assert_equal(G.adj, {3: {4: {}}, 4: {5: {}}, 5: {3: {}}})

    G = nx.DiGraph()
    G.add_star([3, 4, 5])
    assert_equal(G.adj, {3: {4: {}, 5: {}}, 4: {}, 5: {}})

    G = nx.DiGraph([(0, 0), (0, 1), (1, 2)])
    assert_equal(G.number_of_selfloops(), 1)
    assert_equal(list(G.nodes_with_selfloops()), [0])
    assert_equal(list(G.selfloop_edges()), [(0, 0)]) 
Example #2
Source File: graphwave.py    From karateclub with GNU General Public License v3.0 6 votes vote down vote up
def fit(self, graph):
        """
        Fitting a GraphWave model.

        Arg types:
            * **graph** *(NetworkX graph)* - The graph to be embedded.
        """
        self._set_seed()
        self._check_graph(graph)
        graph.remove_edges_from(nx.selfloop_edges(graph))
        self._create_evaluation_points()
        self._check_size(graph)
        self._G = pygsp.graphs.Graph(nx.adjacency_matrix(graph))

        if self.mechanism == "exact":
            self._exact_structural_wavelet_embedding()
        elif self.mechanism == "approximate":
            self._approximate_structural_wavelet_embedding()
        else:
            raise NameError("Unknown method.") 
Example #3
Source File: function.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def number_of_selfloops(G):
    """Returns the number of selfloop edges.

    A selfloop edge has the same node at both ends.

    Returns
    -------
    nloops : int
        The number of selfloops.

    See Also
    --------
    nodes_with_selfloops, selfloop_edges

    Examples
    --------
    >>> G = nx.Graph()   # or DiGraph, MultiGraph, MultiDiGraph, etc
    >>> G.add_edge(1, 1)
    >>> G.add_edge(1, 2)
    >>> nx.number_of_selfloops(G)
    1
    """
    return sum(1 for _ in nx.selfloop_edges(G)) 
Example #4
Source File: function.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def nodes_with_selfloops(G):
    """Returns an iterator over nodes with self loops.

    A node with a self loop has an edge with both ends adjacent
    to that node.

    Returns
    -------
    nodelist : iterator
        A iterator over nodes with self loops.

    See Also
    --------
    selfloop_edges, number_of_selfloops

    Examples
    --------
    >>> G = nx.Graph()   # or DiGraph, MultiGraph, MultiDiGraph, etc
    >>> G.add_edge(1, 1)
    >>> G.add_edge(1, 2)
    >>> list(nx.nodes_with_selfloops(G))
    [1]

    """
    return (n for n, nbrs in G.adj.items() if n in nbrs) 
Example #5
Source File: test_graph.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def test_deprecated():
    # for backwards compatibility with 1.x, will be removed for 3.x
    G = nx.complete_graph(3)
    assert_equal(G.node, {0: {}, 1: {}, 2: {}})

    G = nx.DiGraph()
    G.add_path([3, 4])
    assert_equal(G.adj, {3: {4: {}}, 4: {}})

    G = nx.DiGraph()
    G.add_cycle([3, 4, 5])
    assert_equal(G.adj, {3: {4: {}}, 4: {5: {}}, 5: {3: {}}})

    G = nx.DiGraph()
    G.add_star([3, 4, 5])
    assert_equal(G.adj, {3: {4: {}, 5: {}}, 4: {}, 5: {}})

    G = nx.DiGraph([(0, 0), (0, 1), (1, 2)])
    assert_equal(G.number_of_selfloops(), 1)
    assert_equal(list(G.nodes_with_selfloops()), [0])
    assert_equal(list(G.selfloop_edges()), [(0, 0)]) 
Example #6
Source File: function.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def number_of_selfloops(G):
    """Return the number of selfloop edges.

    A selfloop edge has the same node at both ends.

    Returns
    -------
    nloops : int
        The number of selfloops.

    See Also
    --------
    nodes_with_selfloops, selfloop_edges

    Examples
    --------
    >>> G = nx.Graph()   # or DiGraph, MultiGraph, MultiDiGraph, etc
    >>> G.add_edge(1, 1)
    >>> G.add_edge(1, 2)
    >>> nx.number_of_selfloops(G)
    1
    """
    return sum(1 for _ in nx.selfloop_edges(G)) 
Example #7
Source File: function.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def nodes_with_selfloops(G):
    """Returns an iterator over nodes with self loops.

    A node with a self loop has an edge with both ends adjacent
    to that node.

    Returns
    -------
    nodelist : iterator
        A iterator over nodes with self loops.

    See Also
    --------
    selfloop_edges, number_of_selfloops

    Examples
    --------
    >>> G = nx.Graph()   # or DiGraph, MultiGraph, MultiDiGraph, etc
    >>> G.add_edge(1, 1)
    >>> G.add_edge(1, 2)
    >>> list(nx.nodes_with_selfloops(G))
    [1]

    """
    return (n for n, nbrs in G.adj.items() if n in nbrs) 
Example #8
Source File: test_function.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_selfloops():
    graphs = [nx.Graph(), nx.DiGraph(), nx.MultiGraph(), nx.MultiDiGraph()]
    for graph in graphs:
        G = nx.complete_graph(3, create_using=graph)
        G.add_edge(0, 0)
        assert_nodes_equal(nx.nodes_with_selfloops(G), [0])
        assert_edges_equal(nx.selfloop_edges(G), [(0, 0)])
        assert_edges_equal(nx.selfloop_edges(G, data=True), [(0, 0, {})])
        assert_equal(nx.number_of_selfloops(G), 1)
        # test selfloop attr
        G.add_edge(1, 1, weight=2)
        assert_edges_equal(nx.selfloop_edges(G, data=True),
                           [(0, 0, {}), (1, 1, {'weight': 2})])
        assert_edges_equal(nx.selfloop_edges(G, data='weight'),
                           [(0, 0, None), (1, 1, 2)]) 
Example #9
Source File: test_kcutsets.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_configuration():
    deg_seq = nx.random_powerlaw_tree_sequence(100, tries=5, seed=72)
    G = nx.Graph(nx.configuration_model(deg_seq))
    G.remove_edges_from(nx.selfloop_edges(G))
    _check_separating_sets(G) 
Example #10
Source File: test_edge_kcomponents.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_configuration():
    # seeds = [2718183590, 2470619828, 1694705158, 3001036531, 2401251497]
    seeds = [14, 15]
    for seed in seeds:
        deg_seq = nx.random_powerlaw_tree_sequence(20, seed=seed, tries=5000)
        G = nx.Graph(nx.configuration_model(deg_seq, seed=seed))
        G.remove_edges_from(nx.selfloop_edges(G))
        _check_edge_connectivity(G) 
Example #11
Source File: test_edge_kcomponents.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_configuration_directed():
    # seeds = [671221681, 2403749451, 124433910, 672335939, 1193127215]
    seeds = [67]
    for seed in seeds:
        deg_seq = nx.random_powerlaw_tree_sequence(20, seed=seed, tries=5000)
        G = nx.DiGraph(nx.configuration_model(deg_seq, seed=seed))
        G.remove_edges_from(nx.selfloop_edges(G))
        _check_edge_connectivity(G) 
Example #12
Source File: test_edge_augmentation.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_configuration():
    # seeds = [2718183590, 2470619828, 1694705158, 3001036531, 2401251497]
    seeds = [1001, 1002, 1003, 1004]
    for seed in seeds:
        deg_seq = nx.random_powerlaw_tree_sequence(20, seed=seed, tries=5000)
        G = nx.Graph(nx.configuration_model(deg_seq, seed=seed))
        G.remove_edges_from(nx.selfloop_edges(G))
        _check_augmentations(G) 
Example #13
Source File: graph.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def selfloop_edges(self, data=False, keys=False, default=None):
        msg = "selfloop_edges is deprecated. Use nx.selfloop_edges instead."
        warnings.warn(msg, DeprecationWarning)
        return nx.selfloop_edges(self, data=False, keys=False, default=None)
    # Done with backward compatibility methods for 1.x 
Example #14
Source File: utils.py    From EgoSplitting with GNU General Public License v3.0 5 votes vote down vote up
def graph_reader(path):
    """
    Function to read the graph from the path.
    :param path: Path to the edge list.
    :return graph: NetworkX object returned.
    """
    graph = nx.from_edgelist(pd.read_csv(path).values.tolist())
    graph.remove_edges_from(nx.selfloop_edges(graph))
    return graph 
Example #15
Source File: test_graph.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_selfloops_attr(self):
        G = self.K3.copy()
        G.add_edge(0, 0)
        G.add_edge(1, 1, weight=2)
        assert_edges_equal(nx.selfloop_edges(G, data=True),
                           [(0, 0, {}), (1, 1, {'weight': 2})])
        assert_edges_equal(nx.selfloop_edges(G, data='weight'),
                           [(0, 0, None), (1, 1, 2)]) 
Example #16
Source File: test_kcutsets.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_configuration():
    deg_seq = nx.random_powerlaw_tree_sequence(100, tries=5000)
    G = nx.Graph(nx.configuration_model(deg_seq))
    G.remove_edges_from(nx.selfloop_edges(G))
    _check_separating_sets(G) 
Example #17
Source File: test_edge_kcomponents.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_configuration():
    seeds = [2718183590, 2470619828, 1694705158, 3001036531, 2401251497]
    for seed in seeds:
        deg_seq = nx.random_powerlaw_tree_sequence(20, seed=seed, tries=5000)
        G = nx.Graph(nx.configuration_model(deg_seq, seed=seed))
        G.remove_edges_from(nx.selfloop_edges(G))
        _check_edge_connectivity(G) 
Example #18
Source File: test_edge_kcomponents.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_configuration_directed():
    # seeds = [671221681, 2403749451, 124433910, 672335939, 1193127215]
    seeds = [672335939]
    for seed in seeds:
        deg_seq = nx.random_powerlaw_tree_sequence(20, seed=seed, tries=5000)
        G = nx.DiGraph(nx.configuration_model(deg_seq, seed=seed))
        G.remove_edges_from(nx.selfloop_edges(G))
        _check_edge_connectivity(G) 
Example #19
Source File: build_gcn.py    From incubator-tvm with Apache License 2.0 5 votes vote down vote up
def load_dataset(dataset="cora"):
    args = namedtuple("args", ["dataset"])
    data = load_data(args(dataset))

    # Remove self-loops to avoid duplicate passing of a node's feature to itself
    g = data.graph
    g.remove_edges_from(nx.selfloop_edges(g))
    g.add_edges_from(zip(g.nodes, g.nodes))

    return g, data 
Example #20
Source File: utils.py    From role2vec with GNU General Public License v3.0 5 votes vote down vote up
def load_graph(graph_path):
    """
    Reading an edge list csv to an NX graph object.
    :param graph_path: Path to the edhe list csv.
    :return graph: NetworkX object.
    """
    graph = nx.from_edgelist(pd.read_csv(graph_path).values.tolist())
    graph.remove_edges_from(nx.selfloop_edges(graph))
    return graph 
Example #21
Source File: utils.py    From EdMot with GNU General Public License v3.0 5 votes vote down vote up
def graph_reader(path):
    """
    Function to read the graph from the path.
    :param path: Path to the edge list.
    :return graph: NetworkX object returned.
    """
    graph = nx.from_edgelist(pd.read_csv(path).values.tolist())
    graph.remove_edges_from(nx.selfloop_edges(graph))
    return graph 
Example #22
Source File: utils.py    From MixHop-and-N-GCN with GNU General Public License v3.0 5 votes vote down vote up
def graph_reader(path):
    """
    Function to read the graph from the path.
    :param path: Path to the edge list.
    :return graph: NetworkX object returned.
    """
    graph = nx.from_edgelist(pd.read_csv(path).values.tolist())
    graph.remove_edges_from(list(nx.selfloop_edges(graph)))
    return graph 
Example #23
Source File: utils.py    From BANE with GNU General Public License v3.0 5 votes vote down vote up
def read_graph(args):
    """
    Method to read graph and create a target matrix with adjacency matrix powers.
    :param args: Arguments object.
    :return powered_P: Target matrix.
    """
    print("\nTarget matrix creation started.\n")
    graph = nx.from_edgelist(pd.read_csv(args.edge_path).values.tolist())
    graph.remove_edges_from(nx.selfloop_edges(graph))
    P = normalize_adjacency(graph, args)
    powered_P = P
    if args.order > 1:
        for _ in tqdm(range(args.order-1), desc="Adjacency matrix powers"):
            powered_P = powered_P.dot(P)
    return powered_P 
Example #24
Source File: symmnmf.py    From karateclub with GNU General Public License v3.0 5 votes vote down vote up
def fit(self, graph):
        """
        Fitting a Symm-NMF clustering model.

        Arg types:
            * **graph** *(NetworkX graph)* - The graph to be clustered.
        """
        self._set_seed()
        self._check_graph(graph)
        graph.remove_edges_from(nx.selfloop_edges(graph))
        A_hat = self._create_base_matrix(graph)
        self._setup_embeddings(A_hat)
        for step in range(self.iterations):
            self._do_admm_update(A_hat) 
Example #25
Source File: netlsd.py    From karateclub with GNU General Public License v3.0 5 votes vote down vote up
def _calculate_netlsd(self, graph):
        """
        Calculating the features of a graph.

        Arg types:
            * **graph** *(NetworkX graph)* - A graph to be embedded.

        Return types:
            * **hist** *(Numpy array)* - The embedding of a single graph.
        """
        graph.remove_edges_from(nx.selfloop_edges(graph))
        laplacian = sps.coo_matrix(nx.normalized_laplacian_matrix(graph, nodelist = range(graph.number_of_nodes())), dtype=np.float32)
        eigen_values = self._calculate_eigenvalues(laplacian)
        heat_kernel_trace = self._calculate_heat_kernel_trace(eigen_values)
        return heat_kernel_trace 
Example #26
Source File: utils.py    From AttentionWalk with GNU General Public License v3.0 5 votes vote down vote up
def read_graph(graph_path):
    """
    Method to read graph and create a target matrix with pooled adjacency matrix powers.
    :param args: Arguments object.
    :return graph: graph.
    """
    print("\nTarget matrix creation started.\n")
    graph = nx.from_edgelist(pd.read_csv(graph_path).values.tolist())
    graph.remove_edges_from(nx.selfloop_edges(graph))
    return graph 
Example #27
Source File: utils.py    From Splitter with GNU General Public License v3.0 5 votes vote down vote up
def graph_reader(path):
    """
    Function to read the graph from the path.
    :param path: Path to the edge list.
    :return graph: NetworkX object returned.
    """
    graph = nx.from_edgelist(pd.read_csv(path).values.tolist())
    graph.remove_edges_from(nx.selfloop_edges(graph))
    return graph 
Example #28
Source File: utils.py    From MUSAE with GNU General Public License v3.0 5 votes vote down vote up
def load_graph(graph_path):
    """
    Reading a NetworkX graph.
    :param graph_path: Path to the edge list.
    :return graph: NetworkX object.
    """
    data = pd.read_csv(graph_path)
    edges = data.values.tolist()
    edges = [[int(edge[0]), int(edge[1])] for edge in edges]
    graph = nx.from_edgelist(edges)
    graph.remove_edges_from(nx.selfloop_edges(graph))
    return graph 
Example #29
Source File: utils.py    From GraphWaveletNeuralNetwork with GNU General Public License v3.0 5 votes vote down vote up
def graph_reader(path):
    """
    Function to create an NX graph object.
    :param path: Path to the edge list csv.
    :return graph: NetworkX graph.
    """
    graph = nx.from_edgelist(pd.read_csv(path).values.tolist())
    graph.remove_edges_from(nx.selfloop_edges(graph))
    return graph 
Example #30
Source File: utils.py    From APPNP with GNU General Public License v3.0 5 votes vote down vote up
def graph_reader(path):
    """
    Function to read the graph from the path.
    :param path: Path to the edge list.
    :return graph: NetworkX object returned.
    """
    graph = nx.from_edgelist(pd.read_csv(path).values.tolist())
    graph.remove_edges_from(nx.selfloop_edges(graph))
    return graph