Python networkx.lollipop_graph() Examples

The following are 20 code examples of networkx.lollipop_graph(). 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_subgraph.py    From strawberryfields with Apache License 2.0 6 votes vote down vote up
def test_correct_resize(self):
        """Test if function correctly resizes on a fixed example where the ideal resizing is
        known. The example is a lollipop graph of 6 fully connected nodes and 2 nodes on the
        lollipop stick. An edge between node zero and node ``dim - 1`` (the lollipop node
        connecting to the stick) is removed and a starting subgraph of nodes ``[2, 3, 4, 5,
        6]`` is selected. The objective is to add-on 1 and 2 nodes and remove 1 node."""
        dim = 6
        g = nx.lollipop_graph(dim, 2)
        g.remove_edge(0, dim - 1)

        s = [2, 3, 4, 5, 6]
        min_size = 4
        max_size = 7

        ideal = {
            4: [2, 3, 4, 5],
            5: [2, 3, 4, 5, 6],
            6: [1, 2, 3, 4, 5, 6],
            7: [0, 1, 2, 3, 4, 5, 6],
        }
        resized = subgraph.resize(s, g, min_size, max_size)

        assert ideal == resized 
Example #2
Source File: test_clique.py    From strawberryfields with Apache License 2.0 6 votes vote down vote up
def test_swap_degree(self, dim):
        """Test if function performs correct swap operation when degree-based node selection is
        used. Input graph is a lollipop graph, consisting of a fully connected graph with a
        single additional node connected to just one of the nodes in the graph. Additionally,
        a connection between node ``0`` and ``dim - 1`` is removed as well as a connection
        between node ``0`` and ``dim - 2``. A clique of the first ``dim - 2`` nodes is then
        input. In this case, C1 consists of nodes ``dim - 1`` and ``dim - 2``. However,
        node ``dim - 1`` has greater degree due to the extra node in the lollipop graph. This
        test confirms that the resultant swap is performed correctly."""
        graph = nx.lollipop_graph(dim, 1)
        graph.remove_edge(0, dim - 1)
        graph.remove_edge(0, dim - 2)
        s = list(range(dim - 2))
        result = set(clique.swap(s, graph, node_select="degree"))
        expected = set(range(1, dim - 2)) | {dim - 1}
        assert result == expected 
Example #3
Source File: test_connected.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        G1 = cnlti(nx.grid_2d_graph(2, 2), first_label=0, ordering="sorted")
        G2 = cnlti(nx.lollipop_graph(3, 3), first_label=4, ordering="sorted")
        G3 = cnlti(nx.house_graph(), first_label=10, ordering="sorted")
        self.G = nx.union(G1, G2)
        self.G = nx.union(self.G, G3)
        self.DG = nx.DiGraph([(1, 2), (1, 3), (2, 3)])
        self.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1)

        self.gc = []
        G = nx.DiGraph()
        G.add_edges_from([(1, 2), (2, 3), (2, 8), (3, 4), (3, 7), (4, 5),
                          (5, 3), (5, 6), (7, 4), (7, 6), (8, 1), (8, 7)])
        C = [[3, 4, 5, 7], [1, 2, 8], [6]]
        self.gc.append((G, C))

        G = nx.DiGraph()
        G.add_edges_from([(1, 2), (1, 3), (1, 4), (4, 2), (3, 4), (2, 3)])
        C = [[2, 3, 4],[1]]
        self.gc.append((G, C))

        G = nx.DiGraph()
        G.add_edges_from([(1, 2), (2, 3), (3, 2), (2, 1)])
        C = [[1, 2, 3]]
        self.gc.append((G,C))

        # Eppstein's tests
        G = nx.DiGraph({0:[1], 1:[2, 3], 2:[4, 5], 3:[4, 5], 4:[6], 5:[], 6:[]})
        C = [[0], [1], [2],[ 3], [4], [5], [6]]
        self.gc.append((G,C))

        G = nx.DiGraph({0:[1], 1:[2, 3, 4], 2:[0, 3], 3:[4], 4:[3]})
        C = [[0, 1, 2], [3, 4]]
        self.gc.append((G, C)) 
Example #4
Source File: minigc.py    From dgl with Apache License 2.0 5 votes vote down vote up
def _gen_lollipop(self, n):
        for _ in range(n):
            num_v = np.random.randint(self.min_num_v, self.max_num_v)
            path_len = np.random.randint(2, num_v // 2)
            g = nx.lollipop_graph(m=num_v - path_len, n=path_len)
            self.graphs.append(g)
            self.labels.append(3) 
Example #5
Source File: test_clique.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_maximal_by_cardinality(self):
        """Tests that the maximal clique is computed according to maximum
        cardinality of the sets.

        For more information, see pull request #1531.

        """
        G = nx.complete_graph(5)
        G.add_edge(4, 5)
        clique = max_clique(G)
        assert_greater(len(clique), 1)

        G = nx.lollipop_graph(30, 2)
        clique = max_clique(G)
        assert_greater(len(clique), 2) 
Example #6
Source File: test_efficiency.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        # G1 is a disconnected graph
        self.G1 = nx.Graph()
        self.G1.add_nodes_from([1, 2, 3])
        # G2 is a cycle graph
        self.G2 = nx.cycle_graph(4)
        # G3 is the triangle graph with one additional edge
        self.G3 = nx.lollipop_graph(3, 1) 
Example #7
Source File: layout.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def random_layout(G, center=None, dim=2):
    """Position nodes uniformly at random in the unit square.

    For every node, a position is generated by choosing each of dim
    coordinates uniformly at random on the interval [0.0, 1.0).

    NumPy (http://scipy.org) is required for this function.

    Parameters
    ----------
    G : NetworkX graph or list of nodes
        A position will be assigned to every node in G.

    center : array-like or None
        Coordinate pair around which to center the layout.

    dim : int
        Dimension of layout.

    Returns
    -------
    pos : dict
        A dictionary of positions keyed by node

    Examples
    --------
    >>> G = nx.lollipop_graph(4, 3)
    >>> pos = nx.random_layout(G)

    """
    import numpy as np

    G, center = _process_params(G, center, dim)
    shape = (len(G), dim)
    pos = np.random.random(shape) + center
    pos = pos.astype(np.float32)
    pos = dict(zip(G, pos))

    return pos 
Example #8
Source File: test_connected.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        G1 = cnlti(nx.grid_2d_graph(2, 2), first_label=0, ordering="sorted")
        G2 = cnlti(nx.lollipop_graph(3, 3), first_label=4, ordering="sorted")
        G3 = cnlti(nx.house_graph(), first_label=10, ordering="sorted")
        self.G = nx.union(G1, G2)
        self.G = nx.union(self.G, G3)
        self.DG = nx.DiGraph([(1, 2), (1, 3), (2, 3)])
        self.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1)

        self.gc = []
        G = nx.DiGraph()
        G.add_edges_from([(1, 2), (2, 3), (2, 8), (3, 4), (3, 7), (4, 5),
                          (5, 3), (5, 6), (7, 4), (7, 6), (8, 1), (8, 7)])
        C = [[3, 4, 5, 7], [1, 2, 8], [6]]
        self.gc.append((G, C))

        G = nx.DiGraph()
        G.add_edges_from([(1, 2), (1, 3), (1, 4), (4, 2), (3, 4), (2, 3)])
        C = [[2, 3, 4], [1]]
        self.gc.append((G, C))

        G = nx.DiGraph()
        G.add_edges_from([(1, 2), (2, 3), (3, 2), (2, 1)])
        C = [[1, 2, 3]]
        self.gc.append((G, C))

        # Eppstein's tests
        G = nx.DiGraph({0: [1], 1: [2, 3], 2: [4, 5], 3: [4, 5], 4: [6], 5: [], 6: []})
        C = [[0], [1], [2], [3], [4], [5], [6]]
        self.gc.append((G, C))

        G = nx.DiGraph({0: [1], 1: [2, 3, 4], 2: [0, 3], 3: [4], 4: [3]})
        C = [[0, 1, 2], [3, 4]]
        self.gc.append((G, C))

        G = nx.DiGraph()
        C = []
        self.gc.append((G, C)) 
Example #9
Source File: test_clique.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_maximal_by_cardinality(self):
        """Tests that the maximal clique is computed according to maximum
        cardinality of the sets.

        For more information, see pull request #1531.

        """
        G = nx.complete_graph(5)
        G.add_edge(4, 5)
        clique = max_clique(G)
        assert_greater(len(clique), 1)

        G = nx.lollipop_graph(30, 2)
        clique = max_clique(G)
        assert_greater(len(clique), 2) 
Example #10
Source File: test_efficiency.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self):
        # G1 is a disconnected graph
        self.G1 = nx.Graph()
        self.G1.add_nodes_from([1, 2, 3])
        # G2 is a cycle graph
        self.G2 = nx.cycle_graph(4)
        # G3 is the triangle graph with one additional edge
        self.G3 = nx.lollipop_graph(3, 1) 
Example #11
Source File: test_connected.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        G1 = cnlti(nx.grid_2d_graph(2, 2), first_label=0, ordering="sorted")
        G2 = cnlti(nx.lollipop_graph(3, 3), first_label=4, ordering="sorted")
        G3 = cnlti(nx.house_graph(), first_label=10, ordering="sorted")
        self.G = nx.union(G1, G2)
        self.G = nx.union(self.G, G3)
        self.DG = nx.DiGraph([(1, 2), (1, 3), (2, 3)])
        self.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1)

        self.gc = []
        G = nx.DiGraph()
        G.add_edges_from([(1, 2), (2, 3), (2, 8), (3, 4), (3, 7), (4, 5),
                          (5, 3), (5, 6), (7, 4), (7, 6), (8, 1), (8, 7)])
        C = [[3, 4, 5, 7], [1, 2, 8], [6]]
        self.gc.append((G, C))

        G = nx.DiGraph()
        G.add_edges_from([(1, 2), (1, 3), (1, 4), (4, 2), (3, 4), (2, 3)])
        C = [[2, 3, 4],[1]]
        self.gc.append((G, C))

        G = nx.DiGraph()
        G.add_edges_from([(1, 2), (2, 3), (3, 2), (2, 1)])
        C = [[1, 2, 3]]
        self.gc.append((G,C))

        # Eppstein's tests
        G = nx.DiGraph({0:[1], 1:[2, 3], 2:[4, 5], 3:[4, 5], 4:[6], 5:[], 6:[]})
        C = [[0], [1], [2],[ 3], [4], [5], [6]]
        self.gc.append((G,C))

        G = nx.DiGraph({0:[1], 1:[2, 3, 4], 2:[0, 3], 3:[4], 4:[3]})
        C = [[0, 1, 2], [3, 4]]
        self.gc.append((G, C)) 
Example #12
Source File: layout.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def random_layout(G, dim=2, scale=1., center=None):
    """Position nodes uniformly at random.

    For every node, a position is generated by choosing each of dim
    coordinates uniformly at random on the default interval [0.0, 1.0),
    or on an interval of length `scale` centered at `center`.

    NumPy (http://scipy.org) is required for this function.

    Parameters
    ----------
    G : NetworkX graph or list of nodes
       A position will be assigned to every node in G.

    dim : int
       Dimension of layout.

    scale : float (default 1)
        Scale factor for positions

    center : array-like (default scale*0.5 in each dim)
       Coordinate around which to center the layout.

    Returns
    -------
    pos : dict
       A dictionary of positions keyed by node

    Examples
    --------
    >>> G = nx.lollipop_graph(4, 3)
    >>> pos = nx.random_layout(G)
    """
    import numpy as np

    shape = (len(G), dim)
    pos = np.random.random(shape) * scale
    if center is not None:
        pos += np.asarray(center) - 0.5 * scale
    return dict(zip(G, pos)) 
Example #13
Source File: test_clique.py    From strawberryfields with Apache License 2.0 5 votes vote down vote up
def test_correct_c_0(self, dim):
        """Tests that :math:`c_0` is generated correctly for the lollipop graph"""
        g = nx.lollipop_graph(dim, 1)
        s = set(range(int(dim / 2)))
        res = set(clique.c_0(s, g))

        assert res not in s
        assert {dim + 1} not in res
        assert res | s == set(range(dim)) 
Example #14
Source File: test_clique.py    From strawberryfields with Apache License 2.0 5 votes vote down vote up
def test_is_output_clique(self, dim):
        """Test that the output subgraph is a valid clique, in this case the maximum clique
        in a lollipop graph"""
        graph = nx.lollipop_graph(dim, dim)
        subgraph = list(range(2 * dim))  # subgraph is the entire graph
        resized = clique.shrink(subgraph, graph)
        assert clique.is_clique(graph.subgraph(resized))
        assert resized == list(range(dim)) 
Example #15
Source File: test_clique.py    From strawberryfields with Apache License 2.0 5 votes vote down vote up
def test_grow_maximal_degree(self, dim):
        """Test if function grows to expected maximal graph when degree-based node selection is
        used. The chosen graph is a fully connected graph with only the final node being
        connected to an additional node. Furthermore, the ``dim - 2`` node is disconnected from
        the ``dim - 1`` node. Starting from the first ``dim - 3`` nodes, one can either add in
        the ``dim - 2`` node or the ``dim - 1`` node. The ``dim - 1`` node has a higher degree
        due to the lollipop graph structure, and hence should be selected."""
        graph = nx.lollipop_graph(dim, 1)
        graph.remove_edge(dim - 2, dim - 1)
        s = set(range(dim - 2))
        target = s | {dim - 1}
        assert set(clique.grow(s, graph, node_select="degree")) == target 
Example #16
Source File: test_clique.py    From strawberryfields with Apache License 2.0 5 votes vote down vote up
def test_expected_growth(self):
        """Test if function performs a growth and swap phase, followed by another growth and
        attempted swap phase. This is carried out by starting with a 4+1 node lollipop graph,
        adding a connection from node 4 to node 2 and starting with the [3, 4] clique. The local
        search algorithm should first grow to [2, 3, 4] and then swap to either [0, 2, 3] or [1,
        2, 3], and then grow again to [0, 1, 2, 3] and being unable to swap, hence returning [0,
        1, 2, 3]"""

        graph = nx.lollipop_graph(4, 1)
        graph.add_edge(4, 2)

        c = [3, 4]
        result = clique.search(c, graph, iterations=100)
        assert result == [0, 1, 2, 3] 
Example #17
Source File: adjlist.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def generate_adjlist(G, delimiter=' '):
    """Generate a single line of the graph G in adjacency list format.

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

    delimiter : string, optional
       Separator for node labels

    Returns
    -------
    lines : string
        Lines of data in adjlist format.

    Examples
    --------
    >>> G = nx.lollipop_graph(4, 3)
    >>> for line in nx.generate_adjlist(G):
    ...     print(line)
    0 1 2 3
    1 2 3
    2 3
    3 4
    4 5
    5 6
    6

    See Also
    --------
    write_adjlist, read_adjlist

    """
    directed = G.is_directed()
    seen = set()
    for s, nbrs in G.adjacency():
        line = make_str(s) + delimiter
        for t, data in nbrs.items():
            if not directed and t in seen:
                continue
            if G.is_multigraph():
                for d in data.values():
                    line += make_str(t) + delimiter
            else:
                line += make_str(t) + delimiter
        if not directed:
            seen.add(s)
        yield line[:-len(delimiter)] 
Example #18
Source File: layout.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def random_layout(G, center=None, dim=2, seed=None):
    """Position nodes uniformly at random in the unit square.

    For every node, a position is generated by choosing each of dim
    coordinates uniformly at random on the interval [0.0, 1.0).

    NumPy (http://scipy.org) is required for this function.

    Parameters
    ----------
    G : NetworkX graph or list of nodes
        A position will be assigned to every node in G.

    center : array-like or None
        Coordinate pair around which to center the layout.

    dim : int
        Dimension of layout.

    seed : int, RandomState instance or None  optional (default=None)
        Set the random state for deterministic node layouts.
        If int, `seed` is the seed used by the random number generator,
        if numpy.random.RandomState instance, `seed` is the random
        number generator,
        if None, the random number generator is the RandomState instance used
        by numpy.random.

    Returns
    -------
    pos : dict
        A dictionary of positions keyed by node

    Examples
    --------
    >>> G = nx.lollipop_graph(4, 3)
    >>> pos = nx.random_layout(G)

    """
    import numpy as np

    G, center = _process_params(G, center, dim)
    pos = seed.rand(len(G), dim) + center
    pos = pos.astype(np.float32)
    pos = dict(zip(G, pos))

    return pos 
Example #19
Source File: adjlist.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 4 votes vote down vote up
def generate_adjlist(G, delimiter = ' '):
    """Generate a single line of the graph G in adjacency list format.

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

    delimiter : string, optional
       Separator for node labels

    Returns
    -------
    lines : string
        Lines of data in adjlist format.

    Examples
    --------
    >>> G = nx.lollipop_graph(4, 3)
    >>> for line in nx.generate_adjlist(G):
    ...     print(line)
    0 1 2 3
    1 2 3
    2 3
    3 4
    4 5
    5 6
    6

    See Also
    --------
    write_adjlist, read_adjlist

    """
    directed=G.is_directed()
    seen=set()
    for s,nbrs in G.adjacency_iter():
        line = make_str(s)+delimiter
        for t,data in nbrs.items():
            if not directed and t in seen:
                continue
            if G.is_multigraph():
                for d in data.values():
                    line += make_str(t) + delimiter
            else:
                line += make_str(t) + delimiter
        if not directed:
            seen.add(s)
        yield line[:-len(delimiter)] 
Example #20
Source File: adjlist.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
def generate_adjlist(G, delimiter=' '):
    """Generate a single line of the graph G in adjacency list format.

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

    delimiter : string, optional
       Separator for node labels

    Returns
    -------
    lines : string
        Lines of data in adjlist format.

    Examples
    --------
    >>> G = nx.lollipop_graph(4, 3)
    >>> for line in nx.generate_adjlist(G):
    ...     print(line)
    0 1 2 3
    1 2 3
    2 3
    3 4
    4 5
    5 6
    6

    See Also
    --------
    write_adjlist, read_adjlist

    """
    directed = G.is_directed()
    seen = set()
    for s, nbrs in G.adjacency():
        line = make_str(s) + delimiter
        for t, data in nbrs.items():
            if not directed and t in seen:
                continue
            if G.is_multigraph():
                for d in data.values():
                    line += make_str(t) + delimiter
            else:
                line += make_str(t) + delimiter
        if not directed:
            seen.add(s)
        yield line[:-len(delimiter)]