How to use the networkx.read_edgelist function in networkx

To help you get started, we’ve selected a few networkx examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github THUDM / cogdl / cogdl / datasets / edgelist_label.py View on Github external
def read_edgelist_label_data(folder, prefix):
    graph_path = osp.join(folder, "{}.ungraph".format(prefix))
    cmty_path = osp.join(folder, "{}.cmty".format(prefix))

    G = nx.read_edgelist(graph_path, nodetype=int, create_using=nx.Graph())
    num_node = G.number_of_nodes()
    print("edge number: ", num_node)
    with open(graph_path) as f:
        context = f.readlines()
        print("edge number: ", len(context))
        edge_index = np.zeros((2, len(context)))
        for i, line in enumerate(context):
            edge_index[:, i] = list(map(int, line.strip().split("\t")))
    edge_index = torch.from_numpy(edge_index).to(torch.int)

    with open(cmty_path) as f:
        context = f.readlines()
        print("class number: ", len(context))
        label = np.zeros((num_node, len(context)))

        for i, line in enumerate(context):
github Lab41 / Circulo / metricSuite.py View on Github external
def main(argv):
    
    #File IO Handling/Reading in Graph
    f_edge = open(argv[0], 'rb')
    f_comm = open(argv[1])
    #with open error checking
    #pass in path, check for error cases for G
    G = nx.read_edgelist(f_edge,comments='#',nodetype=int,edgetype=int)
    f_edge.close()
    
    
    #Initializing Important Var
    num_nodes = len(G)
    num_edges = nx.number_of_edges(G)
    degree_dict = G.degree(G.nodes_iter())
    #better name for d_m
    d_m = np.median(list(degree_dict.values()))
    
    
    #Iterating through community file
    for line in f_comm:
        
        comm_line = map(int, line.split())
        comm_line.sort()
github KatolaZ / mammult / structure / metrics / cartography_from_layers.py View on Github external
import sys
import networkx as net
import collections
from compiler.ast import flatten



if len(sys.argv) < 3:
    print "Usage: %s   [...]" % sys.argv[0]
    sys.exit(1)


layers = []

for f in sys.argv[1:]:
    G = net.Graph(net.read_edgelist(f, nodetype=int))
    layers.append(G)

nodes = flatten([x for j in layers for x in j.nodes()])
#nodes.sort()
nodes = set(nodes)

M = len(layers)

#print nodes

for n in nodes:
    deg_alpha_square = 0
    deg = 0
    col = 0
    print n, 
    for l in layers:
github yebiro / Link-Prediction-on-Social-Networks / network-visualizations-statistics.py View on Github external
print('Reading {} edgelist'.format(network))
        network_edges_dir = './data/{}/{}.txt'.format(network, network)


        if network in ['hamster']:
            with open(network_edges_dir, 'rb')as edges_f:
                network_g = nx.read_edgelist(edges_f, nodetype=int, create_using=nx.Graph(), encoding='latin1',
                                             data=(('weight', float),))

            # print('Generating network visualization')
            visualization_file_name = './visualizations/{0}-visualization.png'.format(network)
            save_visualization(network_g, visualization_file_name, '{} Network'.format(network))

        else:
            with open(network_edges_dir, 'rb')as edges_f:
                network_g = nx.read_edgelist(edges_f, nodetype=int, create_using=nx.DiGraph(), encoding='latin1',
                                             data=(('weight', float),))
            print('Num. weakly connected components: ', nx.number_weakly_connected_components(network_g))

            # print('Generating network visualization and statistics')
            visualization_file_name = './visualizations/{0}-visualization.png'.format(network)
            statistics_file_name_pkl = './network-statistics/{0}-statistics.pkl'.format(network)
            statistics_file_name_json = './network-statistics/{0}-statistics.json'.format(network)
            #save_visualization(network_g, visualization_file_name, '{} Network'.format(network))
            save_network_statistics(network_g, statistics_file_name_pkl)
            save_network_statistics_json(network_g, statistics_file_name_json)
github Lab41 / Circulo / src / evaluation / metrics.py View on Github external
def main(argv):

    with open(argv[0], 'rb') as edgelist_file:

        #Creating graph in networkX
        graph = nx.read_edgelist(edgelist_file, comments='#', nodetype=int, edgetype=int)

    #Collecting statistics on entire graph
    num_nodes = len(graph)
    num_edges = nx.number_of_edges(graph)
    graph_degree = graph.degree(graph.nodes_iter())
    median_degree = np.median(list(graph_degree.values()))

    #Demo sample metrics collected for visualization
    cond_list = []
    cut_list = []
    flake_list = []
    fomd_list = []
    tpr_list = []
    sep_list = []
    num_comm = 0
github habedi / MyPythonCodes / codes / personalized_pagerank.py View on Github external
def loadGraph(gfile):
    return nx.read_edgelist(path=gfile, comments='#',
                            delimiter="\t", nodetype=int)
github SotirisKot / Content-Aware-Node2Vec / experiments.py View on Github external
def read_graph(file, get_connected_graph=True, remove_selfloops=True, get_directed=False):
    if args.weighted:
        G = nx.read_edgelist(file, nodetype=int, data=(('weight', float),), create_using=nx.DiGraph())
    else:
        G = nx.read_edgelist(file, nodetype=int, create_using=nx.DiGraph())
        for edge in G.edges():
            G[edge[0]][edge[1]]['weight'] = 1
    print('Graph created!!!')

    if remove_selfloops:
        # remove the edges with selfloops
        for node in G.nodes_with_selfloops():
            G.remove_edge(node, node)

    if not get_directed:
        G = G.to_undirected()
        if get_connected_graph and not nx.is_connected(G):
            connected_sub_graph = max(nx.connected_component_subgraphs(G), key=len)
            print('Initial graph not connected...returning the largest connected subgraph..')
            return connected_sub_graph
        else:
github D2KLab / entity2vec / src / main.py View on Github external
def read_graph():
	'''
	Reads the input network in networkx.
	'''
	print 'asd'
	if args.weighted:
		G = nx.read_edgelist(args.input,  nodetype = int,data=(('weight',float),), create_using=nx.DiGraph())
	else:
		G = nx.read_edgelist(args.input, nodetype = int, create_using=nx.DiGraph())
		for edge in G.edges():
			G[edge[0]][edge[1]]['weight'] = 1

	if not args.directed:
		G = G.to_undirected()

	return G
github ComparativeGenomicsToolkit / cactus / progressive / schedule.py View on Github external
def readFromFile(self, path):
        self.depTree = NX.read_edgelist(path)
        self.checkDepTree()