Python networkx.convert_node_labels_to_integers() Examples

The following are 30 code examples of networkx.convert_node_labels_to_integers(). 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: dataset_utils.py    From rl_graph_generation with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __getitem__(self, item):
    """
    Returns an rdkit mol object
    :param item:
    :return:
    """
    smiles = self.df['smiles'][item]
    mol = Chem.MolFromSmiles(smiles)
    return mol

# # TESTS
# path = 'gdb13.rand1M.smi.gz'
# dataset = gdb_dataset(path)
#
# print(len(dataset))
# mol,_ = dataset[0]
# graph = mol_to_nx(mol)
# graph_sub = graph.subgraph([0,3,5,7,9])
# graph_sub_new = nx.convert_node_labels_to_integers(graph_sub,label_attribute='old')
# graph_sub_node = graph_sub.nodes()
# graph_sub_new_node = graph_sub_new.nodes()
# matrix = nx.adjacency_matrix(graph_sub)
# np_matrix = matrix.toarray()
# print(np_matrix)
# print('end') 
Example #2
Source File: utils.py    From clusternet with MIT License 6 votes vote down vote up
def load_nofeatures(dataset, version, n = None):
    '''
    Loads a dataset that is just an edgelist, creating sparse one-hot features. 

    n: total number of nodes in the graph. This is the number of nodes present
    in the edgelist unless otherwise specified    
    '''
#    g = nx.read_edgelist('data/{}/{}{}.txt'.format(dataset, dataset, version))
#    g = nx.convert_node_labels_to_integers(g)
#    edges = np.array([(x[0], x[1]) for x in nx.to_edgelist(g)])
    edges = np.loadtxt('data/{}/{}{}.cites'.format(dataset, dataset, version), dtype=np.int)
    if n == None:
        n = int(edges.max()) + 1
    adj = make_normalized_adj(torch.tensor(edges).long(), n)
    features = torch.eye(n).to_sparse()
    return adj, features, None 
Example #3
Source File: _quantum_computer.py    From pyquil with Apache License 2.0 6 votes vote down vote up
def _get_9q_square_qvm(
    name: str, noisy: bool, connection: Optional[ForestConnection] = None, qvm_type: str = "qvm"
) -> QuantumComputer:
    """
    A nine-qubit 3x3 square lattice.

    This uses a "generic" lattice not tied to any specific device. 9 qubits is large enough
    to do vaguely interesting algorithms and small enough to simulate quickly.

    :param name: The name of this QVM
    :param connection: The connection to use to talk to external services
    :param noisy: Whether to construct a noisy quantum computer
    :param qvm_type: The type of QVM. Either 'qvm' or 'pyqvm'.
    :return: A pre-configured QuantumComputer
    """
    topology = nx.convert_node_labels_to_integers(nx.grid_2d_graph(3, 3))
    return _get_qvm_with_topology(
        name=name,
        connection=connection,
        topology=topology,
        noisy=noisy,
        requires_executable=True,
        qvm_type=qvm_type,
    ) 
Example #4
Source File: test_edgelist.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_edgelist_integers(self):
        G = nx.convert_node_labels_to_integers(self.G)
        (fd, fname) = tempfile.mkstemp()
        bipartite.write_edgelist(G, fname)
        H = bipartite.read_edgelist(fname, nodetype=int)
        # isolated nodes are not written in edgelist
        G.remove_nodes_from(list(nx.isolates(G)))
        assert_nodes_equal(list(H), list(G))
        assert_edges_equal(list(H.edges()), list(G.edges()))
        os.close(fd)
        os.unlink(fname) 
Example #5
Source File: test_edgelist.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_edgelist_integers(self):
        G=nx.convert_node_labels_to_integers(self.G)
        (fd,fname)=tempfile.mkstemp()
        bipartite.write_edgelist(G,fname)
        H=bipartite.read_edgelist(fname,nodetype=int)
        # isolated nodes are not written in edgelist
        G.remove_nodes_from(list(nx.isolates(G)))
        assert_nodes_equal(list(H), list(G))
        assert_edges_equal(list(H.edges()), list(G.edges()))
        os.close(fd)
        os.unlink(fname) 
Example #6
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 #7
Source File: test_generic.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        from networkx import convert_node_labels_to_integers as cnlti
        self.grid=cnlti(nx.grid_2d_graph(4,4),first_label=1,ordering="sorted")
        self.cycle=nx.cycle_graph(7)
        self.directed_cycle=nx.cycle_graph(7,create_using=nx.DiGraph()) 
Example #8
Source File: test_weighted.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def setup(self):
        """Creates some graphs for use in the unit tests."""
        cnlti = nx.convert_node_labels_to_integers
        self.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1,
                          ordering="sorted")
        self.cycle = nx.cycle_graph(7)
        self.directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph())
        self.XG = nx.DiGraph()
        self.XG.add_weighted_edges_from([('s', 'u', 10), ('s', 'x', 5),
                                         ('u', 'v', 1), ('u', 'x', 2),
                                         ('v', 'y', 1), ('x', 'u', 3),
                                         ('x', 'v', 5), ('x', 'y', 2),
                                         ('y', 's', 7), ('y', 'v', 6)])
        self.MXG = nx.MultiDiGraph(self.XG)
        self.MXG.add_edge('s', 'u', weight=15)
        self.XG2 = nx.DiGraph()
        self.XG2.add_weighted_edges_from([[1, 4, 1], [4, 5, 1],
                                          [5, 6, 1], [6, 3, 1],
                                          [1, 3, 50], [1, 2, 100],
                                          [2, 3, 100]])

        self.XG3 = nx.Graph()
        self.XG3.add_weighted_edges_from([[0, 1, 2], [1, 2, 12],
                                          [2, 3, 1], [3, 4, 5],
                                          [4, 5, 1], [5, 0, 10]])

        self.XG4 = nx.Graph()
        self.XG4.add_weighted_edges_from([[0, 1, 2], [1, 2, 2],
                                          [2, 3, 1], [3, 4, 1],
                                          [4, 5, 1], [5, 6, 1],
                                          [6, 7, 1], [7, 0, 1]])
        self.MXG4 = nx.MultiGraph(self.XG4)
        self.MXG4.add_edge(0, 1, weight=3)
        self.G = nx.DiGraph()  # no weights
        self.G.add_edges_from([('s', 'u'), ('s', 'x'),
                               ('u', 'v'), ('u', 'x'),
                               ('v', 'y'), ('x', 'u'),
                               ('x', 'v'), ('x', 'y'),
                               ('y', 's'), ('y', 'v')]) 
Example #9
Source File: test_edgelist.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_edgelist_integers(self):
        G=nx.convert_node_labels_to_integers(self.G)
        (fd,fname)=tempfile.mkstemp()
        nx.write_edgelist(G,fname)  
        H=nx.read_edgelist(fname,nodetype=int)
        # isolated nodes are not written in edgelist
        G.remove_nodes_from(list(nx.isolates(G)))
        assert_nodes_equal(list(H), list(G))
        assert_edges_equal(list(H.edges()), list(G.edges()))
        os.close(fd)
        os.unlink(fname) 
Example #10
Source File: test_adjlist.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_multiline_adjlist_integers(self):
        (fd,fname)=tempfile.mkstemp()
        G=nx.convert_node_labels_to_integers(self.G)
        nx.write_multiline_adjlist(G,fname)
        H=nx.read_multiline_adjlist(fname,nodetype=int)
        H2=nx.read_multiline_adjlist(fname,nodetype=int)
        assert_nodes_equal(list(H), list(G))
        assert_edges_equal(list(H.edges()), list(G.edges()))
        os.close(fd)
        os.unlink(fname) 
Example #11
Source File: test_adjlist.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_adjlist_integers(self):
        (fd,fname)=tempfile.mkstemp()
        G=nx.convert_node_labels_to_integers(self.G)
        nx.write_adjlist(G,fname)
        H=nx.read_adjlist(fname,nodetype=int)
        H2=nx.read_adjlist(fname,nodetype=int)
        assert_nodes_equal(list(H), list(G))
        assert_edges_equal(list(H.edges()), list(G.edges()))
        os.close(fd)
        os.unlink(fname) 
Example #12
Source File: small.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def hoffman_singleton_graph():
    '''Return the Hoffman-Singleton Graph.'''
    G = nx.Graph()
    for i in range(5):
        for j in range(5):
            G.add_edge(('pentagon', i, j), ('pentagon', i, (j - 1) % 5))
            G.add_edge(('pentagon', i, j), ('pentagon', i, (j + 1) % 5))
            G.add_edge(('pentagram', i, j), ('pentagram', i, (j - 2) % 5))
            G.add_edge(('pentagram', i, j), ('pentagram', i, (j + 2) % 5))
            for k in range(5):
                G.add_edge(('pentagon', i, j),
                           ('pentagram', k, (i * k + j) % 5))
    G = nx.convert_node_labels_to_integers(G)
    G.name = 'Hoffman-Singleton Graph'
    return G 
Example #13
Source File: historical_tests.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.null = nx.null_graph()
        self.P1 = cnlti(nx.path_graph(1), first_label=1)
        self.P3 = cnlti(nx.path_graph(3), first_label=1)
        self.P10 = cnlti(nx.path_graph(10), first_label=1)
        self.K1 = cnlti(nx.complete_graph(1), first_label=1)
        self.K3 = cnlti(nx.complete_graph(3), first_label=1)
        self.K4 = cnlti(nx.complete_graph(4), first_label=1)
        self.K5 = cnlti(nx.complete_graph(5), first_label=1)
        self.K10 = cnlti(nx.complete_graph(10), first_label=1)
        self.G = nx.Graph 
Example #14
Source File: test_unweighted.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        from networkx import convert_node_labels_to_integers as cnlti
        self.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1, ordering="sorted")
        self.cycle = nx.cycle_graph(7)
        self.directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph()) 
Example #15
Source File: test_generic.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        from networkx import convert_node_labels_to_integers as cnlti
        self.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1,
                          ordering="sorted")
        self.cycle = nx.cycle_graph(7)
        self.directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph())
        self.neg_weights = nx.DiGraph()
        self.neg_weights.add_edge(0, 1, weight=1)
        self.neg_weights.add_edge(0, 2, weight=3)
        self.neg_weights.add_edge(1, 3, weight=1)
        self.neg_weights.add_edge(2, 3, weight=-2) 
Example #16
Source File: test_weighted.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setup(self):
        """Creates some graphs for use in the unit tests."""
        cnlti = nx.convert_node_labels_to_integers
        self.grid = cnlti(nx.grid_2d_graph(4, 4), first_label=1,
                          ordering="sorted")
        self.cycle = nx.cycle_graph(7)
        self.directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph())
        self.XG = nx.DiGraph()
        self.XG.add_weighted_edges_from([('s', 'u', 10), ('s', 'x', 5),
                                         ('u', 'v', 1), ('u', 'x', 2),
                                         ('v', 'y', 1), ('x', 'u', 3),
                                         ('x', 'v', 5), ('x', 'y', 2),
                                         ('y', 's', 7), ('y', 'v', 6)])
        self.MXG = nx.MultiDiGraph(self.XG)
        self.MXG.add_edge('s', 'u', weight=15)
        self.XG2 = nx.DiGraph()
        self.XG2.add_weighted_edges_from([[1, 4, 1], [4, 5, 1],
                                          [5, 6, 1], [6, 3, 1],
                                          [1, 3, 50], [1, 2, 100],
                                          [2, 3, 100]])

        self.XG3 = nx.Graph()
        self.XG3.add_weighted_edges_from([[0, 1, 2], [1, 2, 12],
                                          [2, 3, 1], [3, 4, 5],
                                          [4, 5, 1], [5, 0, 10]])

        self.XG4 = nx.Graph()
        self.XG4.add_weighted_edges_from([[0, 1, 2], [1, 2, 2],
                                          [2, 3, 1], [3, 4, 1],
                                          [4, 5, 1], [5, 6, 1],
                                          [6, 7, 1], [7, 0, 1]])
        self.MXG4 = nx.MultiGraph(self.XG4)
        self.MXG4.add_edge(0, 1, weight=3)
        self.G = nx.DiGraph()  # no weights
        self.G.add_edges_from([('s', 'u'), ('s', 'x'),
                               ('u', 'v'), ('u', 'x'),
                               ('v', 'y'), ('x', 'u'),
                               ('x', 'v'), ('x', 'y'),
                               ('y', 's'), ('y', 'v')]) 
Example #17
Source File: test_clique.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        z = [3, 4, 3, 4, 2, 4, 2, 1, 1, 1, 1]
        self.G = cnlti(nx.generators.havel_hakimi_graph(z), first_label=1)
        self.cl = list(nx.find_cliques(self.G))
        H = nx.complete_graph(6)
        H = nx.relabel_nodes(H, dict([(i, i + 1) for i in range(6)]))
        H.remove_edges_from([(2, 6), (2, 5), (2, 4), (1, 3), (5, 3)])
        self.H = H 
Example #18
Source File: historical_tests.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        self.null = nx.null_graph()
        self.P1 = cnlti(nx.path_graph(1), first_label=1)
        self.P3 = cnlti(nx.path_graph(3), first_label=1)
        self.P10 = cnlti(nx.path_graph(10), first_label=1)
        self.K1 = cnlti(nx.complete_graph(1), first_label=1)
        self.K3 = cnlti(nx.complete_graph(3), first_label=1)
        self.K4 = cnlti(nx.complete_graph(4), first_label=1)
        self.K5 = cnlti(nx.complete_graph(5), first_label=1)
        self.K10 = cnlti(nx.complete_graph(10), first_label=1)
        self.G = nx.Graph 
Example #19
Source File: test_edgelist.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_edgelist_integers(self):
        G = nx.convert_node_labels_to_integers(self.G)
        (fd, fname) = tempfile.mkstemp()
        nx.write_edgelist(G, fname)
        H = nx.read_edgelist(fname, nodetype=int)
        # isolated nodes are not written in edgelist
        G.remove_nodes_from(list(nx.isolates(G)))
        assert_nodes_equal(list(H), list(G))
        assert_edges_equal(list(H.edges()), list(G.edges()))
        os.close(fd)
        os.unlink(fname) 
Example #20
Source File: test_adjlist.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_multiline_adjlist_integers(self):
        (fd, fname) = tempfile.mkstemp()
        G = nx.convert_node_labels_to_integers(self.G)
        nx.write_multiline_adjlist(G, fname)
        H = nx.read_multiline_adjlist(fname, nodetype=int)
        H2 = nx.read_multiline_adjlist(fname, nodetype=int)
        assert_nodes_equal(list(H), list(G))
        assert_edges_equal(list(H.edges()), list(G.edges()))
        os.close(fd)
        os.unlink(fname) 
Example #21
Source File: test_adjlist.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_adjlist_integers(self):
        (fd, fname) = tempfile.mkstemp()
        G = nx.convert_node_labels_to_integers(self.G)
        nx.write_adjlist(G, fname)
        H = nx.read_adjlist(fname, nodetype=int)
        H2 = nx.read_adjlist(fname, nodetype=int)
        assert_nodes_equal(list(H), list(G))
        assert_edges_equal(list(H.edges()), list(G.edges()))
        os.close(fd)
        os.unlink(fname) 
Example #22
Source File: SRW_RWF_ISRW.py    From Graph_Sampling with MIT License 5 votes vote down vote up
def random_walk_sampling_with_fly_back(self,complete_graph, nodes_to_sample, fly_back_prob):
        complete_graph = nx.convert_node_labels_to_integers(complete_graph, 0, 'default', True)
        # giving unique id to every node same as built-in function id
        for n, data in complete_graph.nodes(data=True):
            complete_graph.node[n]['id'] = n

        nr_nodes = len(complete_graph.nodes())
        upper_bound_nr_nodes_to_sample = nodes_to_sample

        index_of_first_random_node = random.randint(0, nr_nodes-1)
        sampled_graph = nx.Graph()

        sampled_graph.add_node(complete_graph.node[index_of_first_random_node]['id'])

        iteration = 1
        edges_before_t_iter = 0
        curr_node = index_of_first_random_node
        while sampled_graph.number_of_nodes() != upper_bound_nr_nodes_to_sample:
            edges = [n for n in complete_graph.neighbors(curr_node)]
            index_of_edge = random.randint(0, len(edges) - 1)
            chosen_node = edges[index_of_edge]
            sampled_graph.add_node(chosen_node)
            sampled_graph.add_edge(curr_node, chosen_node)
            choice = np.random.choice(['prev','neigh'], 1, p=[fly_back_prob,1-fly_back_prob])
            if choice == 'neigh':
                curr_node = chosen_node
            iteration=iteration+1

            if iteration % self.T == 0:
                if ((sampled_graph.number_of_edges() - edges_before_t_iter) < self.growth_size):
                    curr_node = random.randint(0, nr_nodes-1)
                    print ("Choosing another random node to continue random walk ")
                edges_before_t_iter = sampled_graph.number_of_edges()

        return sampled_graph 
Example #23
Source File: SRW_RWF_ISRW.py    From Graph_Sampling with MIT License 5 votes vote down vote up
def random_walk_sampling_simple(self,complete_graph, nodes_to_sample):
        complete_graph = nx.convert_node_labels_to_integers(complete_graph, 0, 'default', True)
        # giving unique id to every node same as built-in function id
        for n, data in complete_graph.nodes(data=True):
            complete_graph.node[n]['id'] = n

        nr_nodes = len(complete_graph.nodes())
        upper_bound_nr_nodes_to_sample = nodes_to_sample
        index_of_first_random_node = random.randint(0, nr_nodes-1)
        sampled_graph = nx.Graph()

        sampled_graph.add_node(complete_graph.node[index_of_first_random_node]['id'])

        iteration = 1
        edges_before_t_iter = 0
        curr_node = index_of_first_random_node
        while sampled_graph.number_of_nodes() != upper_bound_nr_nodes_to_sample:
            edges = [n for n in complete_graph.neighbors(curr_node)]
            index_of_edge = random.randint(0, len(edges) - 1)
            chosen_node = edges[index_of_edge]
            sampled_graph.add_node(chosen_node)
            sampled_graph.add_edge(curr_node, chosen_node)
            curr_node = chosen_node
            iteration = iteration+1

            if iteration % self.T == 0:
                if ((sampled_graph.number_of_edges() - edges_before_t_iter) < self.growth_size):
                    curr_node = random.randint(0, nr_nodes-1)
                edges_before_t_iter = sampled_graph.number_of_edges()
        return sampled_graph 
Example #24
Source File: SRW_RWF_ISRW.py    From Graph_Sampling with MIT License 5 votes vote down vote up
def random_walk_induced_graph_sampling(self, complete_graph, nodes_to_sample):
        complete_graph = nx.convert_node_labels_to_integers(complete_graph, 0, 'default', True)
        # giving unique id to every node same as built-in function id
        for n, data in complete_graph.nodes(data=True):
            complete_graph.node[n]['id'] = n
            
        nr_nodes = len(complete_graph.nodes())
        upper_bound_nr_nodes_to_sample = nodes_to_sample
        index_of_first_random_node = random.randint(0, nr_nodes - 1)

        Sampled_nodes = set([complete_graph.node[index_of_first_random_node]['id']])

        iteration = 1
        nodes_before_t_iter = 0
        curr_node = index_of_first_random_node
        while len(Sampled_nodes) != upper_bound_nr_nodes_to_sample:
            edges = [n for n in complete_graph.neighbors(curr_node)]
            index_of_edge = random.randint(0, len(edges) - 1)
            chosen_node = edges[index_of_edge]
            Sampled_nodes.add(complete_graph.node[chosen_node]['id'])
            curr_node = chosen_node
            iteration=iteration+1

            if iteration % self.T == 0:
                if ((len(Sampled_nodes) - nodes_before_t_iter) < self.growth_size):
                    curr_node = random.randint(0, nr_nodes - 1)
                nodes_before_t_iter = len(Sampled_nodes)

        sampled_graph = complete_graph.subgraph(Sampled_nodes)

        return sampled_graph 
Example #25
Source File: SRW_RWF_ISRW.py    From Graph_Sampling with MIT License 5 votes vote down vote up
def random_walk_sampling_with_fly_back(self,complete_graph, nodes_to_sample, fly_back_prob):
        complete_graph = nx.convert_node_labels_to_integers(complete_graph, 0, 'default', True)
        # giving unique id to every node same as built-in function id
        for n, data in complete_graph.nodes(data=True):
            complete_graph.node[n]['id'] = n

        nr_nodes = len(complete_graph.nodes())
        upper_bound_nr_nodes_to_sample = nodes_to_sample

        index_of_first_random_node = random.randint(0, nr_nodes-1)
        sampled_graph = nx.Graph()

        sampled_graph.add_node(complete_graph.node[index_of_first_random_node]['id'])

        iteration = 1
        edges_before_t_iter = 0
        curr_node = index_of_first_random_node
        while sampled_graph.number_of_nodes() != upper_bound_nr_nodes_to_sample:
            edges = [n for n in complete_graph.neighbors(curr_node)]
            index_of_edge = random.randint(0, len(edges) - 1)
            chosen_node = edges[index_of_edge]
            sampled_graph.add_node(chosen_node)
            sampled_graph.add_edge(curr_node, chosen_node)
            choice = np.random.choice(['prev','neigh'], 1, p=[fly_back_prob,1-fly_back_prob])
            if choice == 'neigh':
                curr_node = chosen_node
            iteration=iteration+1

            if iteration % self.T == 0:
                if ((sampled_graph.number_of_edges() - edges_before_t_iter) < self.growth_size):
                    curr_node = random.randint(0, nr_nodes-1)
                    print ("Choosing another random node to continue random walk ")
                edges_before_t_iter = sampled_graph.number_of_edges()

        return sampled_graph 
Example #26
Source File: SRW_RWF_ISRW.py    From Graph_Sampling with MIT License 5 votes vote down vote up
def random_walk_sampling_simple(self,complete_graph, nodes_to_sample):
        complete_graph = nx.convert_node_labels_to_integers(complete_graph, 0, 'default', True)
        # giving unique id to every node same as built-in function id
        for n, data in complete_graph.nodes(data=True):
            complete_graph.node[n]['id'] = n

        nr_nodes = len(complete_graph.nodes())
        upper_bound_nr_nodes_to_sample = nodes_to_sample
        index_of_first_random_node = random.randint(0, nr_nodes-1)
        sampled_graph = nx.Graph()

        sampled_graph.add_node(complete_graph.node[index_of_first_random_node]['id'])

        iteration = 1
        edges_before_t_iter = 0
        curr_node = index_of_first_random_node
        while sampled_graph.number_of_nodes() != upper_bound_nr_nodes_to_sample:
            edges = [n for n in complete_graph.neighbors(curr_node)]
            index_of_edge = random.randint(0, len(edges) - 1)
            chosen_node = edges[index_of_edge]
            sampled_graph.add_node(chosen_node)
            sampled_graph.add_edge(curr_node, chosen_node)
            curr_node = chosen_node
            iteration = iteration+1

            if iteration % self.T == 0:
                if ((sampled_graph.number_of_edges() - edges_before_t_iter) < self.growth_size):
                    curr_node = random.randint(0, nr_nodes-1)
                edges_before_t_iter = sampled_graph.number_of_edges()
        return sampled_graph 
Example #27
Source File: test_kcomponents.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def graph_example_1():
    G = nx.convert_node_labels_to_integers(nx.grid_graph([5,5]),
                                            label_attribute='labels')
    rlabels = nx.get_node_attributes(G, 'labels')
    labels = dict((v, k) for k, v in rlabels.items())

    for nodes in [(labels[(0,0)], labels[(1,0)]),
                    (labels[(0,4)], labels[(1,4)]),
                    (labels[(3,0)], labels[(4,0)]),
                    (labels[(3,4)], labels[(4,4)]) ]:
        new_node = G.order()+1
        # Petersen graph is triconnected
        P = nx.petersen_graph()
        G = nx.disjoint_union(G,P)
        # Add two edges between the grid and P
        G.add_edge(new_node+1, nodes[0])
        G.add_edge(new_node, nodes[1])
        # K5 is 4-connected
        K = nx.complete_graph(5)
        G = nx.disjoint_union(G,K)
        # Add three edges between P and K5
        G.add_edge(new_node+2,new_node+11)
        G.add_edge(new_node+3,new_node+12)
        G.add_edge(new_node+4,new_node+13)
        # Add another K5 sharing a node
        G = nx.disjoint_union(G,K)
        nbrs = G[new_node+10]
        G.remove_node(new_node+10)
        for nbr in nbrs:
            G.add_edge(new_node+17, nbr)
        G.add_edge(new_node+16, new_node+5)

    G.name = 'Example graph for connectivity'
    return G 
Example #28
Source File: mol_graph.py    From hgraph2graph with MIT License 5 votes vote down vote up
def tensorize_graph(graph_batch, vocab):
        fnode,fmess = [None],[(0,0,0,0)] 
        agraph,bgraph = [[]], [[]] 
        scope = []
        edge_dict = {}
        all_G = []

        for bid,G in enumerate(graph_batch):
            offset = len(fnode)
            scope.append( (offset, len(G)) )
            G = nx.convert_node_labels_to_integers(G, first_label=offset)
            all_G.append(G)
            fnode.extend( [None for v in G.nodes] )

            for v, attr in G.nodes(data='label'):
                G.nodes[v]['batch_id'] = bid
                fnode[v] = vocab[attr]
                agraph.append([])

            for u, v, attr in G.edges(data='label'):
                if type(attr) is tuple:
                    fmess.append( (u, v, attr[0], attr[1]) )
                else:
                    fmess.append( (u, v, attr, 0) )
                edge_dict[(u, v)] = eid = len(edge_dict) + 1
                G[u][v]['mess_idx'] = eid
                agraph[v].append(eid)
                bgraph.append([])

            for u, v in G.edges:
                eid = edge_dict[(u, v)]
                for w in G.predecessors(u):
                    if w == v: continue
                    bgraph[eid].append( edge_dict[(w, u)] )

        fnode[0] = fnode[1]
        fnode = torch.IntTensor(fnode)
        fmess = torch.IntTensor(fmess)
        agraph = create_pad_tensor(agraph)
        bgraph = create_pad_tensor(bgraph)
        return (fnode, fmess, agraph, bgraph, scope), nx.union_all(all_G) 
Example #29
Source File: test_simple_paths.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_shortest_simple_paths():
    G = cnlti(nx.grid_2d_graph(4, 4), first_label=1, ordering="sorted")
    paths = nx.shortest_simple_paths(G, 1, 12)
    assert_equal(next(paths), [1, 2, 3, 4, 8, 12])
    assert_equal(next(paths), [1, 5, 6, 7, 8, 12])
    assert_equal([len(path) for path in nx.shortest_simple_paths(G, 1, 12)],
                 sorted([len(path) for path in nx.all_simple_paths(G, 1, 12)])) 
Example #30
Source File: test_simple_paths.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_bidirectional_shortest_path_restricted():
    grid = cnlti(nx.grid_2d_graph(4,4), first_label=1, ordering="sorted")
    cycle = nx.cycle_graph(7)
    directed_cycle = nx.cycle_graph(7, create_using=nx.DiGraph())
    length, path = _bidirectional_shortest_path(cycle, 0, 3)
    assert_equal(path, [0, 1, 2, 3])
    length, path = _bidirectional_shortest_path(cycle, 0, 3, ignore_nodes=[1])
    assert_equal(path, [0, 6, 5, 4, 3])
    length, path = _bidirectional_shortest_path(grid, 1, 12)
    assert_equal(path, [1, 2, 3, 4, 8, 12])
    length, path = _bidirectional_shortest_path(grid, 1, 12, ignore_nodes=[2])
    assert_equal(path, [1, 5, 6, 10, 11, 12])
    length, path = _bidirectional_shortest_path(grid, 1, 12, ignore_nodes=[2, 6])
    assert_equal(path, [1, 5, 9, 10, 11, 12])
    length, path = _bidirectional_shortest_path(grid, 1, 12,
                                                ignore_nodes=[2, 6],
                                                ignore_edges=[(10, 11)])
    assert_equal(path, [1, 5, 9, 10, 14, 15, 16, 12])
    length, path = _bidirectional_shortest_path(directed_cycle, 0, 3)
    assert_equal(path, [0, 1, 2, 3])
    assert_raises(
        nx.NetworkXNoPath,
        _bidirectional_shortest_path,
        directed_cycle,
        0, 3,
        ignore_nodes=[1],
    )
    length, path = _bidirectional_shortest_path(directed_cycle, 0, 3,
                                                ignore_edges=[(2, 1)])
    assert_equal(path, [0, 1, 2, 3])
    assert_raises(
        nx.NetworkXNoPath,
        _bidirectional_shortest_path,
        directed_cycle,
        0, 3, 
        ignore_edges=[(1, 2)],
    )