Python networkx.read_weighted_edgelist() Examples

The following are 9 code examples of networkx.read_weighted_edgelist(). 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: DNGR.py    From DNGR-Keras with MIT License 5 votes vote down vote up
def read_graph(filename,g_type):
	with open('data/'+filename,'rb') as f:
		if g_type == "undirected":
			G = nx.read_weighted_edgelist(f)
  		else:
			G = nx.read_weighted_edgelist(f,create_using=nx.DiGraph())
		node_idx = G.nodes()
	adj_matrix = np.asarray(nx.adjacency_matrix(G, nodelist=None,weight='weight').todense())	
	return adj_matrix, node_idx 
Example #2
Source File: test_edgelist.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_read_edgelist_2(self):
        s = b"""\
# comment line
1 2 2.0
# comment line
2 3 3.0
"""
        bytesIO = io.BytesIO(s)
        G = nx.read_edgelist(bytesIO,nodetype=int,data=False)
        assert_edges_equal(G.edges(),[(1,2),(2,3)])

        bytesIO = io.BytesIO(s)
        G = nx.read_weighted_edgelist(bytesIO,nodetype=int)
        assert_edges_equal(G.edges(data=True),
                            [(1,2,{'weight':2.0}),(2,3,{'weight':3.0})]) 
Example #3
Source File: utils.py    From BioNEV with MIT License 5 votes vote down vote up
def read_for_SVD(filename, weighted=False):
    if weighted:
        G = nx.read_weighted_edgelist(filename)
    else:
        G = nx.read_edgelist(filename)
    return G 
Example #4
Source File: utils.py    From BioNEV with MIT License 5 votes vote down vote up
def split_train_test_graph(input_edgelist, seed, testing_ratio=0.2, weighted=False):
    
    if (weighted):
        G = nx.read_weighted_edgelist(input_edgelist)
    else:
        G = nx.read_edgelist(input_edgelist)
    node_num1, edge_num1 = len(G.nodes), len(G.edges)
    print('Original Graph: nodes:', node_num1, 'edges:', edge_num1)
    testing_edges_num = int(len(G.edges) * testing_ratio)
    random.seed(seed)
    testing_pos_edges = random.sample(G.edges, testing_edges_num)
    G_train = copy.deepcopy(G)
    for edge in testing_pos_edges:
        node_u, node_v = edge
        if (G_train.degree(node_u) > 1 and G_train.degree(node_v) > 1):
            G_train.remove_edge(node_u, node_v)

    G_train.remove_nodes_from(nx.isolates(G_train))
    node_num2, edge_num2 = len(G_train.nodes), len(G_train.edges)
    assert node_num1 == node_num2
    train_graph_filename = 'graph_train.edgelist'
    if weighted:
        nx.write_edgelist(G_train, train_graph_filename, data=['weight'])
    else:
        nx.write_edgelist(G_train, train_graph_filename, data=False)

    node_num1, edge_num1 = len(G_train.nodes), len(G_train.edges)
    print('Training Graph: nodes:', node_num1, 'edges:', edge_num1)
    return G, G_train, testing_pos_edges, train_graph_filename 
Example #5
Source File: test_edgelist.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_read_edgelist_2(self):
        s = b"""\
# comment line
1 2 2.0
# comment line
2 3 3.0
"""
        bytesIO = io.BytesIO(s)
        G = nx.read_edgelist(bytesIO, nodetype=int, data=False)
        assert_edges_equal(G.edges(), [(1, 2), (2, 3)])

        bytesIO = io.BytesIO(s)
        G = nx.read_weighted_edgelist(bytesIO, nodetype=int)
        assert_edges_equal(G.edges(data=True),
                           [(1, 2, {'weight': 2.0}), (2, 3, {'weight': 3.0})]) 
Example #6
Source File: test_edgelist.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_read_edgelist_2(self):
        s = b"""\
# comment line
1 2 2.0
# comment line
2 3 3.0
"""
        bytesIO = io.BytesIO(s)
        G = nx.read_edgelist(bytesIO,nodetype=int,data=False)
        assert_edges_equal(G.edges(),[(1,2),(2,3)])

        bytesIO = io.BytesIO(s)
        G = nx.read_weighted_edgelist(bytesIO,nodetype=int)
        assert_edges_equal(G.edges(data=True),
                            [(1,2,{'weight':2.0}),(2,3,{'weight':3.0})]) 
Example #7
Source File: edgelist.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 4 votes vote down vote up
def read_weighted_edgelist(path, comments="#", delimiter=None,
                           create_using=None, nodetype=None, encoding='utf-8'):

    """Read a graph as list of edges with numeric weights.

    Parameters
    ----------
    path : file or string
       File or filename to read. If a file is provided, it must be
       opened in 'rb' mode.
       Filenames ending in .gz or .bz2 will be uncompressed.
    comments : string, optional
       The character used to indicate the start of a comment.
    delimiter : string, optional
       The string used to separate values.  The default is whitespace.
    create_using : Graph container, optional,
       Use specified container to build graph.  The default is networkx.Graph,
       an undirected graph.
    nodetype : int, float, str, Python type, optional
       Convert node data from strings to specified type
    encoding: string, optional
       Specify which encoding to use when reading file.

    Returns
    -------
    G : graph
       A networkx Graph or other type specified with create_using

    Notes
    -----
    Since nodes must be hashable, the function nodetype must return hashable
    types (e.g. int, float, str, frozenset - or tuples of those, etc.)

    Example edgelist file format.

    With numeric edge data::

     # read with
     # >>> G=nx.read_weighted_edgelist(fh)
     # source target data
     a b 1
     a c 3.14159
     d e 42
    """
    return read_edgelist(path,
                         comments=comments,
                         delimiter=delimiter,
                         create_using=create_using,
                         nodetype=nodetype,
                         data=(('weight',float),),
                         encoding = encoding
                         )


# fixture for nose tests 
Example #8
Source File: edgelist.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def read_weighted_edgelist(path, comments="#", delimiter=None,
                           create_using=None, nodetype=None, encoding='utf-8'):
    """Read a graph as list of edges with numeric weights.

    Parameters
    ----------
    path : file or string
       File or filename to read. If a file is provided, it must be
       opened in 'rb' mode.
       Filenames ending in .gz or .bz2 will be uncompressed.
    comments : string, optional
       The character used to indicate the start of a comment.
    delimiter : string, optional
       The string used to separate values.  The default is whitespace.
    create_using : NetworkX graph constructor, optional (default=nx.Graph)
       Graph type to create. If graph instance, then cleared before populated.
    nodetype : int, float, str, Python type, optional
       Convert node data from strings to specified type
    encoding: string, optional
       Specify which encoding to use when reading file.

    Returns
    -------
    G : graph
       A networkx Graph or other type specified with create_using

    Notes
    -----
    Since nodes must be hashable, the function nodetype must return hashable
    types (e.g. int, float, str, frozenset - or tuples of those, etc.)

    Example edgelist file format.

    With numeric edge data::

     # read with
     # >>> G=nx.read_weighted_edgelist(fh)
     # source target data
     a b 1
     a c 3.14159
     d e 42
    """
    return read_edgelist(path,
                         comments=comments,
                         delimiter=delimiter,
                         create_using=create_using,
                         nodetype=nodetype,
                         data=(('weight', float),),
                         encoding=encoding
                         )


# fixture for nose tests 
Example #9
Source File: edgelist.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
def read_weighted_edgelist(path, comments="#", delimiter=None,
                           create_using=None, nodetype=None, encoding='utf-8'):

    """Read a graph as list of edges with numeric weights.

    Parameters
    ----------
    path : file or string
       File or filename to read. If a file is provided, it must be
       opened in 'rb' mode.
       Filenames ending in .gz or .bz2 will be uncompressed.
    comments : string, optional
       The character used to indicate the start of a comment.
    delimiter : string, optional
       The string used to separate values.  The default is whitespace.
    create_using : Graph container, optional,
       Use specified container to build graph.  The default is networkx.Graph,
       an undirected graph.
    nodetype : int, float, str, Python type, optional
       Convert node data from strings to specified type
    encoding: string, optional
       Specify which encoding to use when reading file.

    Returns
    -------
    G : graph
       A networkx Graph or other type specified with create_using

    Notes
    -----
    Since nodes must be hashable, the function nodetype must return hashable
    types (e.g. int, float, str, frozenset - or tuples of those, etc.)

    Example edgelist file format.

    With numeric edge data::

     # read with
     # >>> G=nx.read_weighted_edgelist(fh)
     # source target data
     a b 1
     a c 3.14159
     d e 42
    """
    return read_edgelist(path,
                         comments=comments,
                         delimiter=delimiter,
                         create_using=create_using,
                         nodetype=nodetype,
                         data=(('weight',float),),
                         encoding = encoding
                         )


# fixture for nose tests