当前位置: 首页>>代码示例>>Python>>正文


Python networkx.read_edgelist方法代码示例

本文整理汇总了Python中networkx.read_edgelist方法的典型用法代码示例。如果您正苦于以下问题:Python networkx.read_edgelist方法的具体用法?Python networkx.read_edgelist怎么用?Python networkx.read_edgelist使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在networkx的用法示例。


在下文中一共展示了networkx.read_edgelist方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: read_graph

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import read_edgelist [as 别名]
def read_graph(edgeList,weighted=False, directed=False):
    '''
    Reads the input network in networkx.
    '''
    if weighted:
        G = nx.read_edgelist(edgeList, nodetype=str, data=(('type',int),('weight',float),('id',int)), create_using=nx.DiGraph())
    else:
        G = nx.read_edgelist(edgeList, nodetype=str,data=(('type',int),('id',int)), create_using=nx.DiGraph())
        for edge in G.edges():
            G[edge[0]][edge[1]]['weight'] = 1.0

    if not directed:
        G = G.to_undirected()

    # print (G.edges(data = True))
    return G 
开发者ID:RoyZhengGao,项目名称:edge2vec,代码行数:18,代码来源:transition.py

示例2: load_nofeatures

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import read_edgelist [as 别名]
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 
开发者ID:bwilder0,项目名称:clusternet,代码行数:18,代码来源:utils.py

示例3: __network_loading

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import read_edgelist [as 别名]
def __network_loading(self, desc):

        compartments = ['LOAD_NETWORK', 'FROM']

        if len(desc) > 1:
            raise ValueError("Unsupported description")
        stm = desc[0].split(" ")
        if len(stm) != 4 or stm[0] not in compartments or stm[2] not in compartments:
            raise ValueError("Experiment description malformed (wrong network loading statement): check your syntax")

        self.__net_name = stm[1]
        filename = stm[3]

        if os.path.isfile(filename):
            return "%s = nx.read_edgelist('%s')\n" % (self.__net_name, filename)
        else:
            raise ValueError("Experiment description malformed (file not existing): check your syntax") 
开发者ID:GiulioRossetti,项目名称:ndlib,代码行数:19,代码来源:ExperimentParser.py

示例4: remove_cycle_edges_by_mfas

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import read_edgelist [as 别名]
def remove_cycle_edges_by_mfas(graph_file):
	g = nx.read_edgelist(graph_file,create_using = nx.DiGraph(),nodetype = int)
	from remove_self_loops import remove_self_loops_from_graph
	self_loops = remove_self_loops_from_graph(g)

	scc_nodes,_,_,_ = scc_nodes_edges(g)
	degree_dict = get_nodes_degree_dict(g,scc_nodes)
	sccs = get_big_sccs(g)
	if len(sccs) == 0:
		print("After removal of self loop edgs: %s" % nx.is_directed_acyclic_graph(g))
		return self_loops
	edges_to_be_removed = []
	import timeit
	t1 = timeit.default_timer()
	greedy_local_heuristic(sccs,degree_dict,edges_to_be_removed)
	t2 = timeit.default_timer()
	print("mfas time usage: %0.4f s" % (t2 - t1))
	edges_to_be_removed = list(set(edges_to_be_removed))
	g.remove_edges_from(edges_to_be_removed)
	edges_to_be_removed += self_loops
	edges_to_be_removed_file = graph_file[:len(graph_file)-6] + "_removed_by_mfas.edges"
	write_pairs_to_file(edges_to_be_removed,edges_to_be_removed_file)
	return edges_to_be_removed 
开发者ID:zhenv5,项目名称:breaking_cycles_in_noisy_hierarchies,代码行数:25,代码来源:remove_cycle_edges_by_minimum_feedback_arc_set_greedy.py

示例5: introduce_cycles_2_DAG

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import read_edgelist [as 别名]
def introduce_cycles_2_DAG(graph_file,num_extra_edges,path_length):

	if path_length <= 0:
		print("no constraints on path length")
	else:
		print("path length: %d" % path_length)

	g = nx.read_edgelist(graph_file,create_using = nx.DiGraph(),nodetype = int)
	extra_edges = introduce_cycles(g,num_extra_edges,path_length = path_length)

	extra_edges_file = graph_file[:len(graph_file)-6] + "_extra_" + str(num_extra_edges) + "_path_len_" + str(path_length) + ".edges"
	graph_with_extra_edges_file = graph_file[:len(graph_file)-6] + "_graph_w_extra_" + str(num_extra_edges) + "_path_len_" + str(path_length) + ".edges"

	print("extra edges saved in: %s" % extra_edges_file)
	print("graph with extra edges saved in: %s" % graph_with_extra_edges_file)
	from file_io import write_pairs_to_file

	write_pairs_to_file(extra_edges,extra_edges_file)
	write_pairs_to_file(extra_edges + g.edges(),graph_with_extra_edges_file)	

	return (extra_edges_file,graph_with_extra_edges_file) 
开发者ID:zhenv5,项目名称:breaking_cycles_in_noisy_hierarchies,代码行数:23,代码来源:introduce_cycles_to_DAG.py

示例6: __init__

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import read_edgelist [as 别名]
def __init__(self, graph_file, emb_file1, emb_file2, dimension):
		self.graph = graph_file
		self.emb1 = emb_file1
		self.emb2 = emb_file2
		self.dimension = dimension

		self.G = nx.read_edgelist(self.graph, nodetype=int, create_using=nx.DiGraph())
		self.G = self.G.to_undirected()
		self.node_number = self.G.number_of_nodes()
		matrix0 = scipy.sparse.lil_matrix((self.node_number, self.node_number))

		for e in self.G.edges():
			if e[0] != e[1]:
				matrix0[e[0], e[1]] = 1
				matrix0[e[1], e[0]] = 1
		self.matrix0 = scipy.sparse.csr_matrix(matrix0)
		print(matrix0.shape) 
开发者ID:THUDM,项目名称:ProNE,代码行数:19,代码来源:proNE.py

示例7: test_latin1

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import read_edgelist [as 别名]
def test_latin1(self):
        G = nx.Graph()
        try: # Python 3.x
            blurb = chr(1245) # just to trigger the exception
            name1 = 'Bj' + chr(246) + 'rk'
            name2 = chr(220) + 'ber'
        except ValueError: # Python 2.6+
            name1 = 'Bj' + unichr(246) + 'rk'
            name2 = unichr(220) + 'ber'
        G.add_edge(name1, 'Radiohead', attr_dict={name2: 3})
        fd, fname = tempfile.mkstemp()
        nx.write_edgelist(G, fname, encoding = 'latin-1')
        H = nx.read_edgelist(fname, encoding = 'latin-1')
        assert_graphs_equal(G, H)
        os.close(fd)
        os.unlink(fname) 
开发者ID:SpaceGroupUCL,项目名称:qgisSpaceSyntaxToolkit,代码行数:18,代码来源:test_edgelist.py

示例8: test_latin1

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import read_edgelist [as 别名]
def test_latin1(self):
        G = nx.Graph()
        try:  # Python 3.x
            blurb = chr(1245)  # just to trigger the exception
            name1 = 'Bj' + chr(246) + 'rk'
            name2 = chr(220) + 'ber'
        except ValueError:  # Python 2.6+
            name1 = 'Bj' + unichr(246) + 'rk'
            name2 = unichr(220) + 'ber'
        G.add_edge(name1, 'Radiohead', **{name2: 3})
        fd, fname = tempfile.mkstemp()
        nx.write_edgelist(G, fname, encoding='latin-1')
        H = nx.read_edgelist(fname, encoding='latin-1')
        assert_graphs_equal(G, H)
        os.close(fd)
        os.unlink(fname) 
开发者ID:holzschu,项目名称:Carnets,代码行数:18,代码来源:test_edgelist.py

示例9: test_latin1

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import read_edgelist [as 别名]
def test_latin1(self):
        G = nx.Graph()
        try: # Python 3.x
            blurb = chr(1245) # just to trigger the exception
            name1 = 'Bj' + chr(246) + 'rk'
            name2 = chr(220) + 'ber'
        except ValueError: # Python 2.6+
            name1 = 'Bj' + unichr(246) + 'rk'
            name2 = unichr(220) + 'ber'
        G.add_edge(name1, 'Radiohead', **{name2: 3})
        fd, fname = tempfile.mkstemp()
        nx.write_edgelist(G, fname, encoding = 'latin-1')
        H = nx.read_edgelist(fname, encoding = 'latin-1')
        assert_graphs_equal(G, H)
        os.close(fd)
        os.unlink(fname) 
开发者ID:aws-samples,项目名称:aws-kube-codesuite,代码行数:18,代码来源:test_edgelist.py

示例10: read_net

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import read_edgelist [as 别名]
def read_net(fname, weighted, directed, log):
    if weighted:
        G = nx.read_edgelist(inodetype=int, data=(('weight', float),),
                             create_using=nx.DiGraph())
    else:
        G = nx.read_edgelist(fname, nodetype=int, create_using=nx.DiGraph())
        for edge in G.edges():
            G[edge[0]][edge[1]]['weight'] = 1

    if not directed:
        G = G.to_undirected()

    log.info('N: %d E: %d' % (G.number_of_nodes(), G.number_of_edges()))
    log.info('CC: %d' % nx.number_connected_components(G))
    giant = max(nx.connected_component_subgraphs(G), key=len)
    log.info('N: %d E: %d' % (giant.number_of_nodes(), giant.number_of_edges()))
    return giant 
开发者ID:mims-harvard,项目名称:ohmnet,代码行数:19,代码来源:utility.py

示例11: read_graph

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import read_edgelist [as 别名]
def read_graph():
	'''
	Reads the input network in networkx.
	'''
	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 
开发者ID:cambridgeltl,项目名称:link-prediction_with_deep-learning,代码行数:17,代码来源:main.py

示例12: load_edgelist

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import read_edgelist [as 别名]
def load_edgelist(self, members, csv_name):
        """Load edgelist and add edges with existing account vertices
        :param members: Account vertex list
        :param csv_name: Edgelist file name
        :return:
        """
        topology = nx.MultiDiGraph()
        topology = nx.read_edgelist(csv_name, delimiter=",", create_using=topology)
        self.add_subgraph(members, topology) 
开发者ID:IBM,项目名称:AMLSim,代码行数:11,代码来源:transaction_graph_generator.py

示例13: load_edgelist

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import read_edgelist [as 别名]
def load_edgelist(self, members, csv_name):
    """Load edgelist and add edges with existing account vertices
    
    :param members: Account vertex list
    :param csv_name: Edgelist file name
    :return:
    """
    topology = nx.MultiDiGraph()
    topology = nx.read_edgelist(csv_name, delimiter=",", create_using=topology)
    self.add_subgraph(members, topology)


  
  #### Add transaction set of fraud groups based on AML rule 
开发者ID:IBM,项目名称:AMLSim,代码行数:16,代码来源:transaction_generator.py

示例14: preprocess

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import read_edgelist [as 别名]
def preprocess(setup, nw_outpath, i):
    """
    Graph preprocessing routine.
    """
    print('Preprocessing graph...')

    # Load a graph
    if setup.directed:
        G = nx.read_edgelist(setup.inpaths[i], delimiter=setup.separators[i], comments=setup.comments[i],
                             create_using=nx.DiGraph, nodetype=int)
    else:
        G = nx.read_edgelist(setup.inpaths[i], delimiter=setup.separators[i], comments=setup.comments[i], nodetype=int)

    # Preprocess the graph
    if setup.task == 'lp' and setup.split_alg == 'random':
        G, ids = pp.prep_graph(G, relabel=setup.relabel, del_self_loops=setup.del_selfloops, maincc=False)
    else:
        G, ids = pp.prep_graph(G, relabel=setup.relabel, del_self_loops=setup.del_selfloops)

    # Save preprocessed graph to a file
    if setup.save_prep_nw:
        pp.save_graph(G, output_path=os.path.join(nw_outpath, 'prep_nw.edgelist'), delimiter=setup.delimiter,
                      write_stats=setup.write_stats, write_weights=False, write_dir=True)

    # Return the preprocessed graph
    return G, ids 
开发者ID:Dru-Mara,项目名称:EvalNE,代码行数:28,代码来源:__main__.py

示例15: learn_representations

# 需要导入模块: import networkx [as 别名]
# 或者: from networkx import read_edgelist [as 别名]
def learn_representations(args):
	nx_graph = nx.read_edgelist(args.input, nodetype = int, comments="%")
	print "read in graph"
	adj = nx.adjacency_matrix(nx_graph)#.todense()
	print "got adj matrix"
	
	graph = Graph(adj, node_attributes = args.attributes)
	max_layer = args.untillayer
	if args.untillayer == 0:
		max_layer = None
	alpha = args.alpha
	num_buckets = args.buckets #BASE OF LOG FOR LOG SCALE
	if num_buckets == 1:
		num_buckets = None
	rep_method = RepMethod(max_layer = max_layer, 
							alpha = alpha, 
							k = args.k, 
							num_buckets = num_buckets, 
							normalize = True, 
							gammastruc = args.gammastruc, 
							gammaattr = args.gammaattr)
	if max_layer is None:
		max_layer = 1000
	print("Learning representations with max layer %d and alpha = %f" % (max_layer, alpha))
	representations = xnetmf.get_representations(graph, rep_method)
	pickle.dump(representations, open(args.output, "w")) 
开发者ID:GemsLab,项目名称:REGAL,代码行数:28,代码来源:regal.py


注:本文中的networkx.read_edgelist方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。