Python networkx.to_numpy_array() Examples

The following are 30 code examples of networkx.to_numpy_array(). 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: salts_solution.py    From esoteric-python-challenges with GNU General Public License v3.0 8 votes vote down vote up
def deobfuscator(dict_of_dicts):
    #====Work backwards====
    #Build graph from dict_of_dicts:
    graph_from_dict = nx.DiGraph(dict_of_dicts)

    #Get adjacency matrix of graph
    graph_array = nx.to_numpy_array(graph_from_dict)

    #Change 1's to 255's to save as an image
    graph_array[graph_array == 1] = 255
    image_from_array = Image.fromarray(graph_array).convert("L")
    #We can send the array directly to OCR, but I like to see the image.
    image_from_array.save("obfuscated.png")

    #Run OCR on our image
    return pytesseract.image_to_string("obfuscated.png") 
Example #2
Source File: sample.py    From strawberryfields with Apache License 2.0 6 votes vote down vote up
def seed(value: Optional[int]) -> None:
    """Seed for random number generators.

    Wrapper function for `numpy.random.seed <https://docs.scipy.org/doc/numpy//reference/generated
    /numpy.random.seed.html>`_ to seed all NumPy-based random number generators. This allows for
    repeatable sampling.

    **Example usage:**

    >>> g = nx.erdos_renyi_graph(5, 0.7)
    >>> a = nx.to_numpy_array(g)
    >>> seed(1967)
    >>> sample(a, 3, 4)
    [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 0, 1, 0, 1], [0, 0, 0, 0, 0]]
    >>> seed(1967)
    >>> sample(a, 3, 4)
    [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 0, 1, 0, 1], [0, 0, 0, 0, 0]]

    Args:
        value (int): random seed
    """
    np.random.seed(value) 
Example #3
Source File: similarity.py    From strawberryfields with Apache License 2.0 6 votes vote down vote up
def _get_state(graph: nx.Graph, n_mean: float = 5, loss: float = 0.0) -> BaseGaussianState:
    r"""Embeds the input graph into a GBS device and returns the corresponding Gaussian state.
    """
    modes = graph.order()
    A = nx.to_numpy_array(graph)
    mean_photon_per_mode = n_mean / float(modes)

    p = sf.Program(modes)

    # pylint: disable=expression-not-assigned
    with p.context as q:
        sf.ops.GraphEmbed(A, mean_photon_per_mode=mean_photon_per_mode) | q

        if loss:
            for _q in q:
                sf.ops.LossChannel(1 - loss) | _q

    eng = sf.LocalEngine(backend="gaussian")
    return eng.run(p).state 
Example #4
Source File: test_convert_numpy.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_dtype_int_multigraph(self):
        """Test that setting dtype int actually gives an integer array.

        For more information, see GitHub pull request #1363.

        """
        G = nx.MultiGraph(nx.complete_graph(3))
        A = nx.to_numpy_array(G, dtype=int)
        assert_equal(A.dtype, int) 
Example #5
Source File: test_utils.py    From graspy with Apache License 2.0 5 votes vote down vote up
def test_lcc_numpy(self):
        expected_lcc_matrix = np.array(
            [
                [0, 1, 1, 0, 0],
                [0, 0, 0, 0, 0],
                [0, 0, 0, 1, 1],
                [0, 1, 0, 0, 0],
                [0, 0, 1, 0, 0],
            ]
        )
        expected_nodelist = np.array([0, 1, 2, 3, 5])
        g = nx.DiGraph()
        [g.add_node(i) for i in range(1, 7)]
        g.add_edge(1, 2)
        g.add_edge(1, 3)
        g.add_edge(3, 4)
        g.add_edge(3, 4)
        g.add_edge(3, 6)
        g.add_edge(6, 3)
        g.add_edge(4, 2)
        g = nx.to_numpy_array(g)
        lcc_matrix, nodelist = gus.get_lcc(g, return_inds=True)
        np.testing.assert_array_equal(lcc_matrix, expected_lcc_matrix)
        np.testing.assert_array_equal(nodelist, expected_nodelist)
        lcc_matrix = gus.get_lcc(g)
        np.testing.assert_array_equal(lcc_matrix, expected_lcc_matrix) 
Example #6
Source File: test_utils.py    From graspy with Apache License 2.0 5 votes vote down vote up
def test_multigraph_lcc_numpystack(self):
        expected_g_matrix = np.array(
            [[0, 1, 0, 0], [0, 0, 1, 1], [0, 0, 0, 0], [0, 1, 0, 0]]
        )
        expected_f_matrix = np.array(
            [[0, 1, 0, 0], [1, 0, 1, 1], [0, 0, 0, 0], [0, 1, 0, 0]]
        )
        expected_mats = [expected_f_matrix, expected_g_matrix]
        expected_nodelist = np.array([0, 2, 3, 5])
        g = nx.DiGraph()
        [g.add_node(i) for i in range(1, 7)]
        g.add_edge(1, 3)
        g.add_edge(3, 4)
        g.add_edge(3, 4)
        g.add_edge(3, 6)
        g.add_edge(6, 3)
        g.add_edge(4, 2)
        f = g.copy()
        f.add_edge(5, 4)
        f.remove_edge(4, 2)
        f.add_edge(3, 1)
        f = nx.to_numpy_array(f)
        g = nx.to_numpy_array(g)
        lccs, nodelist = gus.get_multigraph_intersect_lcc(
            np.stack([f, g]), return_inds=True
        )
        for i, graph in enumerate(lccs):
            np.testing.assert_array_equal(graph, expected_mats[i])
            np.testing.assert_array_equal(nodelist, expected_nodelist)
        for i, graph in enumerate(lccs):
            np.testing.assert_array_equal(graph, expected_mats[i]) 
Example #7
Source File: test_utils.py    From graspy with Apache License 2.0 5 votes vote down vote up
def test_multigraph_lcc_numpylist(self):
        expected_g_matrix = np.array(
            [[0, 1, 0, 0], [0, 0, 1, 1], [0, 0, 0, 0], [0, 1, 0, 0]]
        )
        expected_f_matrix = np.array(
            [[0, 1, 0, 0], [1, 0, 1, 1], [0, 0, 0, 0], [0, 1, 0, 0]]
        )
        expected_mats = [expected_f_matrix, expected_g_matrix]
        expected_nodelist = np.array([0, 2, 3, 5])
        g = nx.DiGraph()
        [g.add_node(i) for i in range(1, 7)]
        g.add_edge(1, 3)
        g.add_edge(3, 4)
        g.add_edge(3, 4)
        g.add_edge(3, 6)
        g.add_edge(6, 3)
        g.add_edge(4, 2)
        f = g.copy()
        f.add_edge(5, 4)
        f.remove_edge(4, 2)
        f.add_edge(3, 1)
        f = nx.to_numpy_array(f)
        g = nx.to_numpy_array(g)
        lccs, nodelist = gus.get_multigraph_intersect_lcc([f, g], return_inds=True)
        for i, graph in enumerate(lccs):
            np.testing.assert_array_equal(graph, expected_mats[i])
            np.testing.assert_array_equal(nodelist, expected_nodelist)
        lccs = gus.get_multigraph_intersect_lcc([f, g], return_inds=False)
        for i, graph in enumerate(lccs):
            np.testing.assert_array_equal(graph, expected_mats[i]) 
Example #8
Source File: test_utils.py    From graspy with Apache License 2.0 5 votes vote down vote up
def test_multigraph_lcc_networkx(self):
        expected_g_matrix = np.array(
            [[0, 1, 0, 0], [0, 0, 1, 1], [0, 0, 0, 0], [0, 1, 0, 0]]
        )
        expected_f_matrix = np.array(
            [[0, 1, 0, 0], [1, 0, 1, 1], [0, 0, 0, 0], [0, 1, 0, 0]]
        )
        expected_mats = [expected_f_matrix, expected_g_matrix]
        expected_nodelist = np.array([1, 3, 4, 6])
        g = nx.DiGraph()
        [g.add_node(i) for i in range(1, 7)]
        g.add_edge(1, 3)
        g.add_edge(3, 4)
        g.add_edge(3, 4)
        g.add_edge(3, 6)
        g.add_edge(6, 3)
        g.add_edge(4, 2)
        f = g.copy()
        f.add_edge(5, 4)
        f.remove_edge(4, 2)
        f.add_edge(3, 1)
        lccs, nodelist = gus.get_multigraph_intersect_lcc([f, g], return_inds=True)
        for i, graph in enumerate(lccs):
            np.testing.assert_array_equal(nx.to_numpy_array(graph), expected_mats[i])
            np.testing.assert_array_equal(nodelist, expected_nodelist)
        lccs = gus.get_multigraph_intersect_lcc([f, g], return_inds=False)
        for i, graph in enumerate(lccs):
            np.testing.assert_array_equal(nx.to_numpy_array(graph), expected_mats[i]) 
Example #9
Source File: lap.py    From BioNEV with MIT License 5 votes vote down vote up
def __init__(self, graph, rep_size=128):
        self.g = graph
        self.node_size = self.g.G.number_of_nodes()
        self.rep_size = rep_size
        self.adj_mat = nx.to_numpy_array(self.g.G)
        self.vectors = {}
        self.embeddings = self.get_train()
        look_back = self.g.look_back_list

        for i, embedding in enumerate(self.embeddings):
            self.vectors[look_back[i]] = embedding 
Example #10
Source File: test_convert_numpy.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_identity_graph_array(self):
        "Conversion from graph to array to graph."
        A = nx.to_numpy_array(self.G1)
        self.identity_conversion(self.G1, A, nx.Graph()) 
Example #11
Source File: test_convert_numpy.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_identity_digraph_array(self):
        """Conversion from digraph to array to digraph."""
        A = nx.to_numpy_array(self.G2)
        self.identity_conversion(self.G2, A, nx.DiGraph()) 
Example #12
Source File: test_convert_numpy.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_identity_weighted_graph_array(self):
        """Conversion from weighted graph to array to weighted graph."""
        A = nx.to_numpy_array(self.G3)
        self.identity_conversion(self.G3, A, nx.Graph()) 
Example #13
Source File: test_convert_numpy.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_identity_weighted_digraph_array(self):
        """Conversion from weighted digraph to array to weighted digraph."""
        A = nx.to_numpy_array(self.G4)
        self.identity_conversion(self.G4, A, nx.DiGraph()) 
Example #14
Source File: test_convert_numpy.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_nodelist(self):
        """Conversion from graph to array to graph with nodelist."""
        P4 = path_graph(4)
        P3 = path_graph(3)
        nodelist = list(P3)
        A = nx.to_numpy_array(P4, nodelist=nodelist)
        GA = nx.Graph(A)
        self.assert_equal(GA, P3)

        # Make nodelist ambiguous by containing duplicates.
        nodelist += [nodelist[0]]
        assert_raises(nx.NetworkXError, nx.to_numpy_array, P3, nodelist=nodelist) 
Example #15
Source File: test_convert_numpy.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_numpy_multigraph(self):
        G = nx.MultiGraph()
        G.add_edge(1, 2, weight=7)
        G.add_edge(1, 2, weight=70)
        A = nx.to_numpy_array(G)
        assert_equal(A[1, 0], 77)
        A = nx.to_numpy_array(G, multigraph_weight=min)
        assert_equal(A[1, 0], 7)
        A = nx.to_numpy_array(G, multigraph_weight=max)
        assert_equal(A[1, 0], 70) 
Example #16
Source File: test_convert_numpy.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_dtype_int_graph(self):
        """Test that setting dtype int actually gives an integer array.

        For more information, see GitHub pull request #1363.

        """
        G = nx.complete_graph(3)
        A = nx.to_numpy_array(G, dtype=int)
        assert_equal(A.dtype, int) 
Example #17
Source File: test_utils.py    From graspy with Apache License 2.0 5 votes vote down vote up
def test_graphin(self):
        G = nx.from_numpy_array(self.A)
        np.testing.assert_array_equal(nx.to_numpy_array(G), gus.import_graph(G)) 
Example #18
Source File: test_layout.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_adjacency_interface_numpy(self):
        A = nx.to_numpy_array(self.Gs)
        pos = nx.drawing.layout._fruchterman_reingold(A)
        assert_equal(pos.shape, (6, 2))
        pos = nx.drawing.layout._fruchterman_reingold(A, dim=3)
        assert_equal(pos.shape, (6, 3)) 
Example #19
Source File: test_convert_numpy.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_identity_graph_array(self):
        "Conversion from graph to array to graph."
        A = nx.to_numpy_array(self.G1)
        self.identity_conversion(self.G1, A, nx.Graph()) 
Example #20
Source File: test_convert_numpy.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_identity_digraph_array(self):
        """Conversion from digraph to array to digraph."""
        A = nx.to_numpy_array(self.G2)
        self.identity_conversion(self.G2, A, nx.DiGraph()) 
Example #21
Source File: test_convert_numpy.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_identity_weighted_graph_array(self):
        """Conversion from weighted graph to array to weighted graph."""
        A = nx.to_numpy_array(self.G3)
        self.identity_conversion(self.G3, A, nx.Graph()) 
Example #22
Source File: test_convert_numpy.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_identity_weighted_digraph_array(self):
        """Conversion from weighted digraph to array to weighted digraph."""
        A = nx.to_numpy_array(self.G4)
        self.identity_conversion(self.G4, A, nx.DiGraph()) 
Example #23
Source File: test_convert_numpy.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_nodelist(self):
        """Conversion from graph to array to graph with nodelist."""
        P4 = path_graph(4)
        P3 = path_graph(3)
        nodelist = list(P3)
        A = nx.to_numpy_array(P4, nodelist=nodelist)
        GA = nx.Graph(A)
        self.assert_equal(GA, P3)

        # Make nodelist ambiguous by containing duplicates.
        nodelist += [nodelist[0]]
        assert_raises(nx.NetworkXError, nx.to_numpy_array, P3, nodelist=nodelist) 
Example #24
Source File: test_convert_numpy.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_numpy_multigraph(self):
        G = nx.MultiGraph()
        G.add_edge(1, 2, weight=7)
        G.add_edge(1, 2, weight=70)
        A = nx.to_numpy_array(G)
        assert_equal(A[1, 0], 77)
        A = nx.to_numpy_array(G, multigraph_weight=min)
        assert_equal(A[1, 0], 7)
        A = nx.to_numpy_array(G, multigraph_weight=max)
        assert_equal(A[1, 0], 70) 
Example #25
Source File: test_convert_numpy.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_dtype_int_graph(self):
        """Test that setting dtype int actually gives an integer array.

        For more information, see GitHub pull request #1363.

        """
        G = nx.complete_graph(3)
        A = nx.to_numpy_array(G, dtype=int)
        assert_equal(A.dtype, int) 
Example #26
Source File: test_convert_numpy.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_dtype_int_multigraph(self):
        """Test that setting dtype int actually gives an integer array.

        For more information, see GitHub pull request #1363.

        """
        G = nx.MultiGraph(nx.complete_graph(3))
        A = nx.to_numpy_array(G, dtype=int)
        assert_equal(A.dtype, int) 
Example #27
Source File: lap.py    From OpenNE with MIT License 5 votes vote down vote up
def __init__(self, graph, rep_size=128):
        self.g = graph
        self.node_size = self.g.G.number_of_nodes()
        self.rep_size = rep_size
        self.adj_mat = nx.to_numpy_array(self.g.G)
        self.vectors = {}
        self.embeddings = self.get_train()
        look_back = self.g.look_back_list

        for i, embedding in enumerate(self.embeddings):
            self.vectors[look_back[i]] = embedding 
Example #28
Source File: batch_utils.py    From gnn-comparison with GNU General Public License v3.0 5 votes vote down vote up
def mock_batch(batch_size):
    """construct pyG batch"""
    graphs = []
    while len(graphs) < batch_size:
        G = nx.erdos_renyi_graph(np.random.choice([300, 500]), 0.5)
        if G.number_of_edges() > 1:
            graphs.append(G)

    adjs = [torch.from_numpy(nx.to_numpy_array(G)) for G in graphs]
    graph_data = [dense_to_sparse(A) for A in adjs]
    data_list = [Data(x=x, edge_index=e) for (e, x) in graph_data]
    return Batch.from_data_list(data_list) 
Example #29
Source File: graph.py    From gnn-comparison with GNU General Public License v3.0 5 votes vote down vote up
def get_edge_index(self):
        adj = torch.Tensor(nx.to_numpy_array(self))
        edge_index, _ = dense_to_sparse(adj)
        return edge_index 
Example #30
Source File: test_decompositions.py    From strawberryfields with Apache License 2.0 5 votes vote down vote up
def test_real_degenerate(self):
        """Verify that the Takagi decomposition returns a matrix that is unitary and results in a
        correct decomposition when input a real but highly degenerate matrix. This test uses the
        adjacency matrix of a balanced tree graph."""
        g = nx.balanced_tree(2, 4)
        a = nx.to_numpy_array(g)
        rl, U = dec.takagi(a)
        assert np.allclose(U @ U.conj().T, np.eye(len(a)))
        assert np.allclose(U @ np.diag(rl) @ U.T, a)