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


Python networkx.read_adjlist函数代码示例

本文整理汇总了Python中networkx.read_adjlist函数的典型用法代码示例。如果您正苦于以下问题:Python read_adjlist函数的具体用法?Python read_adjlist怎么用?Python read_adjlist使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: adjlist2gexf

def adjlist2gexf(fAdjlist, bIntNode=1):
    '''
    Converts a graph in the adjacency list format to the GEXF format.

    input parameters:
          fAdjlist:   The file name of the adjacency list
          bIntNode:   Indicates if the node type is integer. The default is 1
                      (i.e., nodes are interger type).
    
    returns:
          None

    output:
          This function generates an GEXF format file with the same name the 
          input file, with .gexf extension.

    '''
    # first, loading the graph
    if bIntNode==1:
        G = nx.read_adjlist(fAdjlist, nodetype=int)
    else:
        G = nx.read_adjlist(fAdjlist)

    # the output file name
    (fOutRoot,tmpExt) = os.path.splitext(fAdjlist)
    fOut = fOutRoot + '.gexf'

    # writing out
    nx.write_gexf(G, fOut)
开发者ID:sathayas,项目名称:fMRIConnectome,代码行数:29,代码来源:NetUtil.py

示例2: test_adjlist_integers

 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)
开发者ID:yamaguchiyuto,项目名称:networkx,代码行数:10,代码来源:test_adjlist.py

示例3: test_adjlist_graph

 def test_adjlist_graph(self):
     G=self.G
     (fd,fname)=tempfile.mkstemp()
     nx.write_adjlist(G,fname)  
     H=nx.read_adjlist(fname)
     H2=nx.read_adjlist(fname)
     assert_not_equal(H,H2) # they should be different graphs
     assert_equal(sorted(H.nodes()),sorted(G.nodes()))
     assert_equal(sorted(H.edges()),sorted(G.edges()))
     os.close(fd)
     os.unlink(fname)
开发者ID:c0ns0le,项目名称:zenoss-4,代码行数:11,代码来源:test_adjlist.py

示例4: test_adjlist_digraph

 def test_adjlist_digraph(self):
     G = self.DG
     (fd, fname) = tempfile.mkstemp()
     nx.write_adjlist(G, fname)
     H = nx.read_adjlist(fname, create_using=nx.DiGraph())
     H2 = nx.read_adjlist(fname, create_using=nx.DiGraph())
     assert_not_equal(H, H2)  # they should be different graphs
     assert_nodes_equal(list(H), list(G))
     assert_edges_equal(list(H.edges()), list(G.edges()))
     os.close(fd)
     os.unlink(fname)
开发者ID:yamaguchiyuto,项目名称:networkx,代码行数:11,代码来源:test_adjlist.py

示例5: test_adjlist_multidigraph

 def test_adjlist_multidigraph(self):
     G=self.XDG
     (fd,fname)=tempfile.mkstemp()
     nx.write_adjlist(G,fname)  
     H=nx.read_adjlist(fname,nodetype=int,
                       create_using=nx.MultiDiGraph())
     H2=nx.read_adjlist(fname,nodetype=int,
                        create_using=nx.MultiDiGraph())
     assert_not_equal(H,H2) # they should be different graphs
     assert_equal(sorted(H.nodes()),sorted(G.nodes()))
     assert_equal(sorted(H.edges()),sorted(G.edges()))
     os.close(fd)
     os.unlink(fname)
开发者ID:c0ns0le,项目名称:zenoss-4,代码行数:13,代码来源:test_adjlist.py

示例6: main

def main(args):

	G = nx.read_adjlist(args["--graph"])

	leaveOneOut = args["--folds"] == "loo"
	numFolds = None
	if not leaveOneOut:
		numFolds = int(args["--folds"])
	else:
		numFolds = G.size()

	ofname = args["--out"]
	root = ET.Element("cvtest", name="{0}_{1}_test".format(args["--graph"], numFolds))
		
	edges = G.edges()
	random.shuffle(edges)

	kf = KFold(G.size(), numFolds, indices=True)
	for i, (trainIDs, testIDs) in enumerate(kf):
		tset = ET.SubElement(root, "testset", name="fold_{0}".format(i))
		trainEdges = [edges[i] for i in trainIDs]
		testEdges = [edges[j] for j in testIDs]
		for u,v in testEdges:
			ET.SubElement(tset, "edge", u=u, v=v)

	with open(ofname, 'wb') as ofile:
		ofile.write(ET.tostring(root, pretty_print=True))
开发者ID:kingsfordgroup,项目名称:parana2,代码行数:27,代码来源:GenerateCrossValidationFile.py

示例7: ex1

def ex1():
	G= nx.Graph();
	G=nx.read_adjlist("gr.txt", nodetype=int)
	nodos=[]
	for nodo in G.nodes():
		nodos.append((len(G.neighbors(nodo)),nodo,G.neighbors(nodo)))
	
	#nodos.sort()
	wifi=[]
	re=[]
	while(len(wifi)!=len(G.nodes())):
		n=max(nodos)
		print "while", len(wifi),"!=",len(G.nodes())
		print "nodo max: ", n[1]
		m=len(wifi)
		print "len(wifi)-->m:", m
		wifi.extend(n[2])
		print "wifi1: ", wifi
		wifi = list(set(wifi)) #quita duplicados
		print "wifi2: ", wifi
		
		nodos.remove(n)
		print "nodos: ", nodos
		print "if(", m,"<",len(wifi),")"
		
		if(m<len(wifi)):        #Si hemos anyadido algun nodo recubierto nuevo
			re.append(n[1])
		print "RESULTADO: ", re
		print " "
	print re
开发者ID:fitigf15,项目名称:PYTHON-VICTOR,代码行数:30,代码来源:greedy_otro.py

示例8: timeflow

def timeflow(opts, argv):
	"""
	Read cluster tracking results and aggregate into a single file
	"""
	g = nx.read_adjlist(argv[0])
	f = sorted(glob.glob(opts.aabbIn))
	N = map(lambda x: map(int,x.split(".")), nx.nodes(g))
	C = dict((t,set()) for t in map(lambda x:x[0], N))
	for (t,l) in N: C[t].add(l)
	newMesh = vtk.vtkPolyData()
	newLines = vtk.vtkCellArray()
	newPoints = vtk.vtkPoints()
	newTimeData = vtkIntArray()
	newTimeData.SetName("TimeStep")
	for t in C:
		p = readVTP(f[t])
		"Filter cluster labels"
		a = p.GetCellData().GetArray("VortexCluster", vtk.mutable(0))
		for (i,l) in enumerate(lineGenerator(p.GetLines())):
			c = a.GetValue(i)
			if c in C[t]:
				newLine = vtkIdList()
				for j in range(0, l.GetNumberOfIds()):
					newLine.InsertNextId(newPoints.GetNumberOfPoints())
					newPoints.InsertNextPoint(p.GetPoint(l.GetId(j)))
				newLines.InsertNextCell(newLine)
				newTimeData.InsertNextValue(t)
	newMesh.GetCellData().SetScalars(newTimeData)
	newMesh.SetPoints(newPoints)
	newMesh.SetLines(newLines)
	writeVTK(opts.output, newMesh)
开发者ID:fayhot,项目名称:gradworks,代码行数:31,代码来源:streamlines.py

示例9: finding_community

def finding_community():
	file_name = "data/amazon/com-amazon."

	print "...reading graph"
	with open(file_name + "ungraph.txt", "rb") as f:
		G = nx.read_adjlist(f, nodetype=int)
	
	print "...reading communities"
	communities = read_communities(file_name + "all.cmty.txt", G)

	alpha = 1.2
	beta = 0.8
	epsilon = 0.001
	
	c = communities[10]
	ns = c.subgraph.nodes()

	print ns
	
	seed = ns[np.random.randint(len(ns))]
	print seed

	founded = detect_community(G, seed, beta, epsilon, alpha)

	print "Founded: ", founded.subgraph.nodes()

	nrel,rel, irel = evaluate_f1(c, founded)
	print (nrel, rel, irel)
开发者ID:ShuaiYAN,项目名称:community-1,代码行数:28,代码来源:tests.py

示例10: netinfo

def netinfo(request):
    """Take uploaded network, find its values, output them"""
#    cleans out images, so that only the most recent upload displays: to be replaced with session handling
    format = ['png', 'svg']    
    for f in format:
        if os.path.isfile(MEDIA_ROOT + '/nets/H.' + f):
            os.remove(MEDIA_ROOT + '/nets/H.' + f)

    if os.path.isfile(MEDIA_ROOT+"/nets/degree_histogram.png"):
        os.remove(os.path.join(MEDIA_ROOT+"/nets/degree_histogram.png"))

   #Generate graph
#    G = nx.petersen_graph()
#    G=nx.path_graph(12)
#    G=nx.random_geometric_graph(50,0.125)

   # Store the generated graph.
#    path = os.path.join(MEDIA_ROOT, 'nets/test.adjlist') #settings.GRAPH_DIR, 'graph.gml.bz2')
#    nx.write_gml(G, path)
    G=nx.read_adjlist(MEDIA_ROOT+"/nets/test.adjlist")
#    nx.write_adjlist(G, path)

    nssresult = netstats_simple(G)
#    raise fromInfo
#    try:
#        true
#    except fromInfo:
    return render_to_response('netinfo.html', nssresult) 
开发者ID:freyley,项目名称:nets,代码行数:28,代码来源:views.py

示例11: network_analysis

def network_analysis(gene_list,network_file,outdir):
    outfn = "%s/output" % outdir
    f = open(outfn,'w')
    f.write("gene\tdegrees\tbtw_centrality\n")
    network = networkx.read_adjlist(network_file)
    print "Number of edges in input graph: %s" % network.number_of_edges()
    print "Number of nodes in input graph: %s" % network.number_of_nodes()
    subnetwork = network.subgraph(gene_list)
    print "Number of edges in subgraph: %s" % subnetwork.number_of_edges()
    print "Number of nodes in subgraph: %s" % subnetwork.number_of_nodes()
    bwt_central = networkx.betweenness_centrality(subnetwork)
    degrees = subnetwork.degree(gene_list)
    for gene in gene_list:
        # Number of degrees
        if gene in degrees:
            num_degrees = degrees[gene]
        else:
            num_degress = "NA"
        # Betweenness centrality
        if gene in bwt_central:
            btw_gene = bwt_central[gene]
        else:
            btw_gene = "NA"
        # File with neighbor nodes
        if subnetwork.has_node(gene):
            neighbors = list(networkx.all_neighbors(subnetwork,gene))
            edges = [(unicode(gene),neighbor) for neighbor in neighbors]
            neighbor_networks = networkx.from_edgelist(edges)
            write_networks(neighbor_networks,gene,outdir)
        f.write("%s\t%s\t%s\n" % (gene,num_degrees,btw_gene))
    f.close()
开发者ID:ffrancis,项目名称:Network_SNPs,代码行数:31,代码来源:network_snps.py

示例12: main

def main():
  gname = sys.argv[1]  
  species = sys.argv[2]
  ofname = sys.argv[3]
  ofile = open(ofname,'wb')

  G = nx.read_adjlist(gname)
  notFound = []
  fs = 'http://www.uniprot.org/uniprot/?query={0}+AND+organism%3A{1}&sort=score&format=fasta&limit=3' 
  for i,n in enumerate(G.nodes()):
    try:
      on = float(n)
      on = "ORF"+n  
    except Exception as e:
      on = n

    url = fs.format(on, species)
    print("fetching {0} using {1}".format(on,url)) 
    req = urllib2.urlopen( url ) 
    e = firstEnt( req.read() ) 
    if e == "":
      notFound.append(on)
      #raise NameError("Could not find {0} @ {1}".format(n, url))
    else:
      ofile.write( ">{0}\n".format(n)+"\n".join(e.split("\n")[1:]) )

  ofile.close()
  print("couldn't find {0}".format(notFound))
开发者ID:kingsfordgroup,项目名称:parana2,代码行数:28,代码来源:CrawlData.py

示例13: main

def main():
    crawl_data_dir = (
        "/media/rna/yahoo_crawl_data/Yahoo-20190406T235503Z-001/Yahoo/yahoo/"
    )
    csv_file = "/media/rna/yahoo_crawl_data/Yahoo-20190406T235503Z-001/Yahoo/URLtoHTML_yahoo_news.csv"
    mapping_file_df = (
        pd.read_csv(csv_file).sort_values(by=["filename", "URL"]).reset_index(drop=True)
    )
    list_of_html_files = glob.glob("{}/*.html".format(crawl_data_dir))
    with open("edgeList.txt", "w") as fh:
        for filepath in list_of_html_files:
            filename = path_leaf(filepath)
            links = get_outgoing_links(filepath)
            filenames_for_url = get_filenames_for_URLs(mapping_file_df, links)
            # connection_matrix.loc[filename, filenames_for_url]+=1
            # connection_matrix.loc[filename, filenames_for_url] =1
            # with open()
            fh.write("{} {}\n".format(filename, " ".join(filenames_for_url)))

    G = nx.read_adjlist("edgeList.txt", create_using=nx.DiGraph())
    pagerank = nx.pagerank(
        G,
        alpha=0.85,
        personalization=None,
        max_iter=100,
        tol=1e-06,
        nstart=None,
        weight="weight",
        dangling=None,
    )
    with open("external_PageRankFile.txt", "w") as fh:
        for key, value in pagerank.items():
            fh.write("{}/{}={}\n".format(crawl_data_dir, key, value))
开发者ID:saketkc,项目名称:hatex,代码行数:33,代码来源:create_edgerank.py

示例14: llegir_graf

def llegir_graf():						# O(V+E)

	#nom = input("Dona'm un nom pel graf: ")	# O(1)
	#nom = "ex1_biconnexe.dat"
	nom = "ex2_no_biconnexe.dat"
	P = nx.read_adjlist(nom,nodetype = int)	# O(V+E)				
	return P # O(1)
开发者ID:fitigf15,项目名称:PYTHON-VICTOR,代码行数:7,代码来源:P1_C_CamiloPalacios.py

示例15: repo_property

def repo_property(repo_file_names, in_pattern):
    """Calculates network property of repos.

    param
    ----
    repo_file_names: List of file names of repo (/ replaced to _).
    in_pattern: Location of adjacency list formatted graph.

    return
    ----
    List of tuples (richness, triangles, transitivity).

    Example of in_pattern:
    graph_dir = "../data/network/issues/python/{0}.txt"
    """

    property_list = []

    for repo in repo_file_names:
        print repo
        graph = nx.read_adjlist(in_pattern.format(repo))
        p = networkutil.get_network_property(graph)

        property_list.append(p)

    return property_list
开发者ID:saeed-abdullah,项目名称:github-social,代码行数:26,代码来源:social.py


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