• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python networkx.read_pajek函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: main

def main():
    # Load Zachary data, randomly delete nodes, and report
    zachary=nx.Graph(nx.read_pajek("karate.net")) # Do not want graph in default MultiGraph format
    zachary.name="Original Zachary Data"
    print(nx.info(zachary))
    zachary_subset=rand_delete(zachary, 15) # Remove half of the structure
    zachary_subset.name="Randomly Deleted Zachary Data"
    print(nx.info(zachary_subset))
    
    # Create model, and simulate
    zachary_model=gmm.gmm(zachary_subset,R=karate_rule,T=node_ceiling_34)
    gmm.algorithms.simulate(zachary_model,4,poisson=False,new_name="Simulation from sample")  # Use tau=4 because data is so small (it's fun!)
    
    # Report and visualize
    print(nx.info(zachary_model.get_base()))
    fig=plt.figure(figsize=(30,10))
    fig.add_subplot(131)
    nx.draw_spring(zachary,with_labels=False,node_size=45,iterations=5000)
    plt.text(0.01,-0.1,"Original Karate Club",color="darkblue",size=20)
    fig.add_subplot(132)
    nx.draw_spring(zachary_subset,with_labels=False,node_size=45,iterations=5000)
    plt.text(0.01,-0.1,"Random sample of Karate Club",color="darkblue",size=20)
    fig.add_subplot(133)
    nx.draw_spring(zachary_model.get_base(),with_labels=False,node_size=45,iterations=5000)
    plt.text(0.01,-0.1,"Simulation from random sample",color="darkblue",size=20)
    plt.savefig("zachary_simulation.png")
开发者ID:drewconway,项目名称:GMM,代码行数:26,代码来源:zachary_regen.py


示例2: main

def main():
    g=net.Graph()
    #snowball_sampling(g,'navalny')
    #print 'done'
    print 'loading'
    g=net.read_pajek('lj_trim_graph.net')
    print len(g)
    #g=trim_degrees(g)
    #net.write_pajek(g,'lj_trim_graph.net')
    #print len(g)
    print 'done'
    #find the celebrities
    print 'calculating degrees'
    degrees=net.degree(g)
    s_degrees=sorted_map(degrees)
    res_degrees=s_degrees[0:9]
    print res_degrees
    print 'done'
    #find the gossipmongers
    print 'calculating closeness'
    closeness=net.closeness_centrality(g)
    s_closeness=sorted_map(closeness)
    res_closeness=s_closeness[0:9]
    print res_closeness
    print 'done'
    #find bottlenecks
    print 'calculating betweenness'
    betweenness=net.betweenness_centrality(g)
    s_betweenness=sorted_map(betweenness)
    res_betweenness=s_betweenness[0:9]
    print res_betweenness
    print 'done'
开发者ID:AaBelov,项目名称:SNA-Twitter,代码行数:32,代码来源:hy.py


示例3: correlation_betweenness_degree_on_ErdosNetwork

def correlation_betweenness_degree_on_ErdosNetwork():
    G = nx.read_pajek("dataset/Erdos971.net")
    isolated_nodes = nx.isolates(G)
    G.remove_nodes_from(isolated_nodes)

    print nx.info(G)
    ND, ND_lambda = ECT.get_number_of_driver_nodes(G)
    print "ND = ", ND
    print "ND lambda:", ND_lambda
    ND, driverNodes = ECT.get_driver_nodes(G)
    print "ND =", ND

    degrees = []
    betweenness = []
    tot_degree = nx.degree_centrality(G)
    tot_betweenness = nx.betweenness_centrality(G,weight=None)

    for node in driverNodes:
        degrees.append(tot_degree[node])
        betweenness.append(tot_betweenness[node])

    with open("results/driver_degree_Erdos.txt", "w") as f:
        for x in degrees:
            print >> f, x
    with open("results/driver_betweenness_Erdos.txt", "w") as f:
        for x in betweenness:
            print >> f, x
    with open("results/tot_degree_Erdos.txt", "w") as f:
        for key, value in tot_degree.iteritems():
            print >> f, value

    with open("results/tot_betweenness_Erdos.txt", "w") as f:
        for key, value in tot_betweenness.iteritems():
            print >> f, value
开发者ID:python27,项目名称:NetworkControllability,代码行数:34,代码来源:Degree_Betweenness_correlation.py


示例4: read_pajek

def read_pajek(fname, constructor=networkx.DiGraph):
    g = networkx.read_pajek(fname)
    print g.__class__
    # Test for multi-plicitiy
    for node in g.nodes_iter():
        neighbors = g.neighbors(node)
        assert len(neighbors) == len(set(neighbors)), "Not a simple graph..."
    return constructor(g)
开发者ID:rkdarst,项目名称:pcd,代码行数:8,代码来源:bulk.py


示例5: read_graph

def read_graph(G, gfile):
    print "Reading in artist graph..."
    try:
        G = nx.read_pajek(gfile)
        print "Read successfully!"
        print "The artist graph currently contains " + str(len(G)) + " artists."
        print "The artist graph currently contains " + str(nx.number_strongly_connected_components(G)) + " strongly connected components."
    except IOError:
        print "Could not find artistGraph"
开发者ID:brokoro,项目名称:cloudchaser,代码行数:9,代码来源:cloudreader.py


示例6: _read_pajek

def _read_pajek(*args, **kwargs):
    """Read Pajek file and make sure that we get an nx.Graph or nx.DiGraph"""
    G = nx.read_pajek(*args, **kwargs)
    edges = G.edges()
    if len(set(edges)) < len(edges):  # multiple edges
        log.warning("Network contains multiple edges. These will be ignored.")
    if G.is_directed():
        return nx.DiGraph(G)
    else:
        return nx.Graph(G)
开发者ID:TythonLee,项目名称:linkpred,代码行数:10,代码来源:linkpred.py


示例7: test_author_interaction

def test_author_interaction():

    clean_data = './test/integration_test/data/clean_data.json'
    graph_nodes = './test/integration_test/data/graph_nodes.csv'
    graph_edges = './test/integration_test/data/graph_edges.csv'
    pajek_file = './.tmp/integration_test/lib/analysis/author/graph/generate/author_graph.net'
    req_output1 = './test/integration_test/data/req_data/test_generate1.net'
    req_output2 = './test/integration_test/data/req_data/test_generate2.net'

    author_interaction(clean_data, graph_nodes, graph_edges, pajek_file, ignore_lat=True)

    output_graph = nx.read_pajek(pajek_file)
    req_grpah = nx.read_pajek(req_output1)
    assert nx.is_isomorphic(output_graph, req_grpah)

    author_interaction(clean_data, graph_nodes, graph_edges, pajek_file, ignore_lat=False)

    output_graph = nx.read_pajek(pajek_file)
    req_grpah = nx.read_pajek(req_output2)
    assert nx.is_isomorphic(output_graph, req_grpah)
开发者ID:prasadtalasila,项目名称:MailingListParser,代码行数:20,代码来源:test_generate.py


示例8: get_graph

def get_graph(graph_file, map_file, trim=False):
    """
    graph_file --> is the file to convert to a networkx graph
    trim --> either takes an integer or 'False'.  If integer, returned graph
        will call return graph with nodes having degree greater than integer
    """
    the_graph = net.DiGraph(net.read_pajek(graph_file))
    id_map = make_id_map(map_file)
    net.relabel_nodes(the_graph, id_map, copy=False)
    if trim:
        the_graph = trim_degrees(the_graph, degree=trim)
    return the_graph
开发者ID:goodwordalchemy,项目名称:echo_nest_love_like,代码行数:12,代码来源:social_util.py


示例9: main

def main():
    #print 'main running!'
    #g=nx.read_adjlist("te.adj",nodetype=int)
 
    #ad=list()
    #mi=list()
    #su=list()    
    ##print sel3(g,3,ad,mi,su)
    g=nx.Graph()
    g=nx.read_pajek("a.net")
 
    sh(g)
    nx.clustering(g)
开发者ID:liupenggl,项目名称:hybrid,代码行数:13,代码来源:rsel.py


示例10: read_file_net

def read_file_net(g,path=None):
    #read .net file. Ues the function of nx.read_pajek()
    g.clear()
 
    try:
        mg=nx.read_pajek(path,encoding='ascii')
        #g=g.to_undirected()
        g=nx.Graph(mg)#Tanslate mg(MultiGraph) to g(Graph)

    except:
        print "readFileTxt error" 

    return g
开发者ID:liupenggl,项目名称:hybrid,代码行数:13,代码来源:gfile.py


示例11: generate_demo_network_raga_recognition

def generate_demo_network_raga_recognition(network_file, community_file, output_network, colors = cons_net.colors, colorify = True, mydatabase = ''):
    """
    This function generates a network used as a demo for demonstrating relations between phrases.
    The configuration used to generate this network should ideally be the one that is used for the
    raga recognition task reported in the paper.
    """
    
    #loading the network
    full_net = nx.read_pajek(network_file)
    
    #loading community data
    comm_data = json.load(open(community_file,'r'))
    
    #loading all the phrase data
    comm_char.fetch_phrase_attributes(comm_data, database = mydatabase, user= 'sankalp')
    
    #getting all the communities from which we dont want any node in the graph in the demo
    #obtaining gamaka communities
    gamaka_comms = comm_char.find_gamaka_communities(comm_data)[0]
    
    #obtaining communities with only phrases from one mbid
    one_mbid_comms = comm_char.get_comm_1MBID(comm_data)
    
    #collect phrases which should be removed from the graph
    phrases = []
    for c in gamaka_comms:
        for n in comm_data[c]:
            phrases.append(int(n['nId']))
    for c in one_mbid_comms:
        for n in comm_data[c]:
            phrases.append(int(n['nId']))
    
    print len(phrases)
    
    #removing the unwanted phrases
    full_net = raga_recog.remove_nodes_graph(full_net, phrases)
    
    # colorify the nodes according to raga labels
    if colorify:
        cmd1 = "select raagaId from file where id = (select file_id from pattern where id =%d)"
        con = psy.connect(database='ICASSP2016_10RAGA_2S', user='sankalp') 
        cur = con.cursor()
        for n in full_net.nodes():
            cur.execute(cmd1%(int(n)))
            ragaId = cur.fetchone()[0]
            full_net.node[n]['color'] = ragaId

    #saving the network
    nx.write_gexf(full_net, output_network)
开发者ID:sankalpg,项目名称:WebInterfaces_MelodicPatterns,代码行数:49,代码来源:graph_generate.py


示例12: exportD3

def exportD3(readName, dumpName):
    
    #G = nx.path_graph(4)
    #G = nx.barbell_graph(6,3)
    G = nx.read_pajek(readName)

    for n in G:
        print 'node', n
        G.node[n]['name'] = G.node[n]['label']
        G.node[n]['size'] = G.node[n]['color']

    d = json_graph.node_link_data(G)

    json.dump(d, open(dumpName, 'w'))
    print('wrote node-link json data to {}'.format(dumpName))
开发者ID:sherryhuanggit,项目名称:socialCircle,代码行数:15,代码来源:generateD3.py


示例13: main

def main():

    """The main function"""

    try:
        file_name = sys.argv[1]
    except IndexError:
        print "Input file not given!"
        raise
    base_name = file_name.split('.')[0]

    net = nx.read_pajek(file_name)
    nx.draw_graphviz(net, with_labels=True, font_size=4,
                     node_size=100)
    plt.draw()
    plt.savefig(base_name + '.eps')
开发者ID:tschijnmo,项目名称:TopologyFromTraceroute,代码行数:16,代码来源:plotpajek.py


示例14: load_and_process_graph

def load_and_process_graph(filename):
    """Load the graph, normalize edge weights, compute pagerank, and store all
    this back in node data."""
    # Load the graph
    graph = nx.DiGraph(nx.read_pajek(filename))
    print "Loaded a graph (%d nodes, %d edges)" % (len(graph),
            len(graph.edges()))
    # Compute the normalized edge weights
    for node in graph:
        edges = graph.edges(node, data=True)
        total_weight = sum([data['weight'] for (_, _, data) in edges])
        for (_, _, data) in edges:
            data['weight'] = data['weight'] / total_weight
    # Get its PageRank, alpha is 1-tau where [RAB2009 says \tau=0.15]
    page_ranks = nx.pagerank(graph, alpha=1-TAU)
    for (node, page_rank) in page_ranks.items():
        graph.node[node][PAGE_RANK] = page_rank
    return graph
开发者ID:uwescience,项目名称:pyinfomap,代码行数:18,代码来源:pyinfomap.py


示例15: read_graph

 def read_graph(self, subgraph_file=None):
     if subgraph_file is None:
         subraph_file = self.context_graph_file
     logging.info("Writing graph.")
     # write the graph out
     file_format = subgraph_file.split(".")[-1]
     if file_format == "graphml":
         return nx.read_graphml(subgraph_file)
     elif file_format == "gml":
         return nx.read_gml(subgraph_file)
     elif file_format == "gexf":
         return nx.read_gexf(subgraph_file)
     elif file_format == "net":
         return nx.read_pajek(subgraph_file)
     elif file_format == "yaml":
         return nx.read_yaml(subgraph_file)
     elif file_format == "gpickle":
         return nx.read_gpickle(subgraph_file)
     else:
         logging.warning("File format not found, returning empty graph.")
     return nx.MultiDiGraph()
开发者ID:theseusyang,项目名称:Verum,代码行数:21,代码来源:networkx.py


示例16: read_graph

def read_graph(filename):
    """Read graph from file, raise IOError if cannot do it."""
    graph = None

    if filename.endswith('.yaml'):
        try:
            graph = nx.read_yaml(filename)
        except ImportError:
            print('E: cannot read graph from file in YAML format.')
            print('Please install PyYAML or other similar package '
                  'to use this functionality.')
            raise IOError
        else:
            print('Read graph from {0} in YAML format.'.format(filename))
    elif filename.endswith('.gml'):
        try:
            graph = nx.read_gml(filename)
        except ImportError:
            print('E: cannot read graph from file in GML format.')
            print('Please install GML or other similar package '
                  'to use this functionality.')
            raise IOError
        else:
            print('Read graph from {0} in GML format.'.format(filename))
    elif filename.endswith('.net'):
        graph = nx.read_pajek(filename)
        print('Read graph from {0} in PAJECK format.'.format(filename))
    elif filename.endswith('.gexf'):
        graph = nx.read_gexf(filename)
        print('Read graph from {0} in GEXF format.'.format(filename))
    elif filename.endswith('.graphml'):
        graph = nx.read_graphml(filename)
        print('Read graph from {0} in GraphML format.'.format(filename))
    else:
        with open(filename, 'rb') as f:
            graph = pickle.load(f)
        print('Read graph from {0} in pickle format.'.format(filename))
    return graph
开发者ID:budnyjj,项目名称:vkstat,代码行数:38,代码来源:io.py


示例17: main

def main():
    print "\n\nPrograma per l'analisi de xarxes complexes i la deteccio de comunitats."
   
    #print glob.glob('./networks/*.*')
    ruta = glob.glob('./networks/*.*') #troba la ruta dels arxius que indiquem
        
    print "\nXarxes disponibles a la carpeta networks:"
        
    llista = []
        
    for i in range(len(ruta)):
        stemp = ruta[i].split('/')
        semp = stemp[2].split('.')
        llista.append(semp)
        llista.sort() #Afegit per linux, ja que no ordena la llista per defecte
    conta = 1
    for y in range(len(llista)):
        if llista[y][0]!=llista[y-1][0]:
            print '[',conta,']',llista[y][0]
            print 'disponible en format: ',llista[y][1]
            conta+=1 #per tal de que el numero de xarxa apareixi correcte
        else:
            print '                      ',llista[y][1]
        
    nb = raw_input("\nEscriu el nom de la xarxa a llegir, 'conversor' per entrar al conversor o 'sortir' per tancar el programa\n")

    if nb == 'sortir':
        sys.exit()

    elif nb == 'conversor':
        con.main()
        main()
    
    global nom
    nom = nb #per passar-ho al gephi
    #print ('Xarxa %s' % (nb))
    print "\n"
    formats = list() #llista dels formats disponibles buida
    conex = False #inicialment no sabem si el nom es correcte 
    pes = False # Variable per saber si la xarxa es amb pesos o sense
    
    for o in range(len(ruta)):
        stemp = ruta[o].split('/')
        semp = stemp[2].split('.')
        if(semp[0] == nb): #comprovo si coincideix amb el nom de l'arxiu
            #print "catch"
            #print semp[1]
            formats.append(semp[1]) #afegeixo format a la llista
            conex = True #el nom coincideix
    if len(formats) > 1:
        print "Tria en quin format vols cargar l'arxiu.\n Formats disponibles: ",formats
        #print formats
        fm = raw_input("Escriu el nom del format escollit\n")
    elif conex == False: # si el nom no existeix
        print "Nom de arxiu incorrecte"
        main()
    else:
        fm = formats
        fm = fm[0] #converteixo de list a string
   
    ######  cargar el graf depenent del format de l'arxiu #####
    if fm == 'graphml':
        try:
            #print 'estic dins del graphml'
            arllegit = Graph.Read_GraphML("./networks/"+nb+".graphml") #llegit per igraph
            nllegit = nx.read_graphml("./networks/"+nb+".graphml") #llegit per networkx
            #ft.save_jsonfile()#######
            
            info = GraphSummary(arllegit)
            infor = info.__str__()
            if infor[7] == 'U' and infor[9] == '-':
                print "La xarxa carregada es indirecte i sense pesos"
            elif infor[7] == 'D' and infor[9] == '-':
                print "La xarxa carregada es directe i sense pesos"
            elif infor[7] == 'U' and infor[9] == 'W':
                print "La xarxa carregada es indirecte i amb pesos"
                pes = True
            elif infor[7] == 'D' and infor[9] == 'W':
                print "La xarxa carregada es directe i amb pesos"
                pes = True
            
        except IOError:
            print 'Error', arllegit
        else:
            print 'Arxiu carregat\n'
       
        
        menugraphml(arllegit,nllegit,pes)
        ####CRIDO FUNCIO DE ESCOLLIR L'ALGORISME PER GRAPHML###
        #num = escollir(arllegit,nllegit)
        #print num
      
    elif fm == 'net':
        try:
            #print 'estic dins del net'
            arllegitnet = Graph.Read_Pajek("./networks/"+nb+".net") #llegit per igraph
            nllegitnet = nx.read_pajek("./networks/"+nb+".net") #llegit per networkx
            info = GraphSummary(arllegitnet)
            infor = info.__str__()
            #de moment aquesta opcio de amb o sense pesos nomes esta implementada aqui
#.........这里部分代码省略.........
开发者ID:Peri86,项目名称:tesismaster,代码行数:101,代码来源:comparador.py


示例18: EdgeAttackErdosNetwork

def EdgeAttackErdosNetwork():
    start_time = time.time()
  
    n = 429
    fraction = 0.2
    E = 1312
    E_rm = int(0.2 * E)
    run_cnt = 30

    #******** Run Node Attack 1 ********#
    tot_ND1 = [0] * (E_rm + 1)
    tot_T1 = [0] * (E_rm + 1)
    rndseed = 1
    for i in range(run_cnt):
        G = nx.read_pajek("dataset/Erdos971_revised.net")
        G1 = max(nx.connected_component_subgraphs(G),key=len)
        print ">>>>>>>>>>>>>>> Random Attack run time count: ", i + 1, "<<<<<<<<<<<<<<<<<<"
        print "graph info", nx.info(G1)
        random.seed(rndseed)
        ND1, T1 = RandomEdgeAttack(G1, remove_fraction=fraction)
        tot_ND1 = [x + y for x, y in zip(tot_ND1, ND1)]
        rndseed += 1

    tot_ND1 = [((x + 0.0) / run_cnt) for x in tot_ND1]
    tot_T1 = T1
    tot_ND1 = [(x + 0.0) / (n + 0.0) for x in tot_ND1]
    tot_T1 = [(x + 0.0) / (E + 0.0) for x in tot_T1]

    with open("results2/edge_attack1_ErdosNetwork.csv", "w") as f:
        writer = csv.writer(f, delimiter=',')
        writer.writerows(zip(tot_T1, tot_ND1))

    run_cnt = 1
    random.seed()
    #******** Run Node Attack 2 ********#
    tot_ND1 = [0] * (E_rm + 1)
    tot_T1 = [0] * (E_rm + 1)
    for i in range(run_cnt):
        G = nx.read_pajek("dataset/Erdos971_revised.net")
        G1 = max(nx.connected_component_subgraphs(G),key=len)
        print ">>>>>>>>>>>>>>> Initial Degree Attack run time count: ", i + 1, "<<<<<<<<<<<<<<<<<<"
        print "graph info", nx.info(G1)
        ND1, T1 = InitialEdgeDegreeAttack(G1, remove_fraction=fraction)
        tot_ND1 = [x + y for x, y in zip(tot_ND1, ND1)]

    tot_ND1 = [((x + 0.0) / run_cnt) for x in tot_ND1]
    tot_T1 = T1
    tot_ND1 = [(x + 0.0) / (n + 0.0) for x in tot_ND1]
    tot_T1 = [(x + 0.0) / (E + 0.0) for x in tot_T1]

    with open("results2/edge_attack2_ErdosNetwork.csv", "w") as f:
        writer = csv.writer(f, delimiter=',')
        writer.writerows(zip(tot_T1, tot_ND1))

    run_cnt = 1
    random.seed()
    #******** Run Node Attack 3 ********#
    tot_ND1 = [0] * (E_rm + 1)
    tot_T1 = [0] * (E_rm + 1)
    for i in range(run_cnt):
        G = nx.read_pajek("dataset/Erdos971_revised.net")
        G1 = max(nx.connected_component_subgraphs(G),key=len)
        print ">>>>>>>>>>>>>>> Recalculated Degree Attack run time count: ", i + 1, "<<<<<<<<<<<<<<<<<<"
        print "graph info", nx.info(G1)
        ND1, T1 = RecalculatedEdgeDegreeAttack(G1, remove_fraction=fraction)
        tot_ND1 = [x + y for x, y in zip(tot_ND1, ND1)]

    tot_ND1 = [((x + 0.0) / run_cnt) for x in tot_ND1]
    tot_T1 = T1
    tot_ND1 = [(x + 0.0) / (n + 0.0) for x in tot_ND1]
    tot_T1 = [(x + 0.0) / (E + 0.0) for x in tot_T1]

    with open("results2/edge_attack3_ErdosNetwork.csv", "w") as f:
        writer = csv.writer(f, delimiter=',')
        writer.writerows(zip(tot_T1, tot_ND1))

    run_cnt = 1
    random.seed()
    #******** Run Node Attack 4 ********#
    tot_ND1 = [0] * (E_rm + 1)
    tot_T1 = [0] * (E_rm + 1)
    for i in range(run_cnt):
        G = nx.read_pajek("dataset/Erdos971_revised.net")
        G1 = max(nx.connected_component_subgraphs(G),key=len)
        print ">>>>>>>>>>>>>>> Initial Betweenness Attack run time count: ", i + 1, "<<<<<<<<<<<<<<<<<<"
        print "graph info", nx.info(G1)
        ND1, T1 = InitialEdgeBetweennessAttack(G1, remove_fraction=fraction)
        tot_ND1 = [x + y for x, y in zip(tot_ND1, ND1)]

    tot_ND1 = [((x + 0.0) / run_cnt) for x in tot_ND1]
    tot_T1 = T1
    tot_ND1 = [(x + 0.0) / (n + 0.0) for x in tot_ND1]
    tot_T1 = [(x + 0.0) / (E + 0.0) for x in tot_T1]

    with open("results2/edge_attack4_ErdosNetwork.csv", "w") as f:
        writer = csv.writer(f, delimiter=',')
        writer.writerows(zip(tot_T1, tot_ND1))

    run_cnt = 1
    random.seed()
#.........这里部分代码省略.........
开发者ID:python27,项目名称:NetworkControllability,代码行数:101,代码来源:TempTempTempFlowEdgeBetweenness.py


示例19: EdgeAttackUSAir

def EdgeAttackUSAir():
    start_time = time.time()
  
    n = 332
    fraction = 0.2
    E = 2126
    E_rm = int(0.2 * E)
    run_cnt = 100

    #******** Run Edge Attack 1 ********#
    tot_ND1 = [0] * (E_rm + 1)
    tot_T1 = [0] * (E_rm + 1)
    rndseed = 1;
    for i in range(run_cnt):
        G1 = nx.read_pajek("dataset/USAir97.net")
        print ">>>>>>>>>>>>>>> Random Attack run time count: ", i + 1, "<<<<<<<<<<<<<<<<<<"
        print "graph info", nx.info(G1)
        random.seed(rndseed)
        ND1, T1 = RandomEdgeAttack(G1, remove_fraction=fraction)
        tot_ND1 = [x + y for x, y in zip(tot_ND1, ND1)]
        rndseed += 1;

    tot_ND1 = [((x + 0.0) / run_cnt) for x in tot_ND1]
    tot_T1 = T1
    tot_ND1 = [(x + 0.0) / (n + 0.0) for x in tot_ND1]
    tot_T1 = [(x + 0.0) / (E + 0.0) for x in tot_T1]

    with open("results2/edge_attack1_USAir.csv", "w") as f:
        writer = csv.writer(f, delimiter=',')
        writer.writerows(zip(tot_T1, tot_ND1))

    run_cnt = 3
    #******** Run Edge Attack 2 ********#
    tot_ND1 = [0] * (E_rm + 1)
    tot_T1 = [0] * (E_rm + 1)
    for i in range(run_cnt):
        G1 = nx.read_pajek("dataset/USAir97.net")
        print ">>>>>>>>>>>>>>> Initial Degree Attack run time count: ", i + 1, "<<<<<<<<<<<<<<<<<<"
        print "graph info", nx.info(G1)
        ND1, T1 = InitialEdgeDegreeAttack(G1, remove_fraction=fraction)
        tot_ND1 = [x + y for x, y in zip(tot_ND1, ND1)]

    tot_ND1 = [((x + 0.0) / run_cnt) for x in tot_ND1]
    tot_T1 = T1
    tot_ND1 = [(x + 0.0) / (n + 0.0) for x in tot_ND1]
    tot_T1 = [(x + 0.0) / (E + 0.0) for x in tot_T1]

    with open("results2/edge_attack2_USAir.csv", "w") as f:
        writer = csv.writer(f, delimiter=',')
        writer.writerows(zip(tot_T1, tot_ND1))

    run_cnt = 3
    #******** Run Edge Attack 3 ********#
    tot_ND1 = [0] * (E_rm + 1)
    tot_T1 = [0] * (E_rm + 1)
    for i in range(run_cnt):
        G1 = nx.read_pajek("dataset/USAir97.net")
        print ">>>>>>>>>>>>>>> Recalculated Degree Attack run time count: ", i + 1, "<<<<<<<<<<<<<<<<<<"
        print "graph info", nx.info(G1)
        ND1, T1 = RecalculatedEdgeDegreeAttack(G1, remove_fraction=fraction)
        tot_ND1 = [x + y for x, y in zip(tot_ND1, ND1)]

    tot_ND1 = [((x + 0.0) / run_cnt) for x in tot_ND1]
    tot_T1 = T1
    tot_ND1 = [(x + 0.0) / (n + 0.0) for x in tot_ND1]
    tot_T1 = [(x + 0.0) / (E + 0.0) for x in tot_T1]

    with open("results2/edge_attack3_USAir.csv", "w") as f:
        writer = csv.writer(f, delimiter=',')
        writer.writerows(zip(tot_T1, tot_ND1))

    run_cnt = 3
    #******** Run Edge Attack 4 ********#
    tot_ND1 = [0] * (E_rm + 1)
    tot_T1 = [0] * (E_rm + 1)
    for i in range(run_cnt):
        G1 = nx.read_pajek("dataset/USAir97.net")
        print ">>>>>>>>>>>>>>> Initial Betweenness Attack run time count: ", i + 1, "<<<<<<<<<<<<<<<<<<"
        print "graph info", nx.info(G1)
        ND1, T1 = InitialEdgeBetweennessAttack(G1, remove_fraction=fraction)
        tot_ND1 = [x + y for x, y in zip(tot_ND1, ND1)]

    tot_ND1 = [((x + 0.0) / run_cnt) for x in tot_ND1]
    tot_T1 = T1
    tot_ND1 = [(x + 0.0) / (n + 0.0) for x in tot_ND1]
    tot_T1 = [(x + 0.0) / (E + 0.0) for x in tot_T1]

    with open("results2/edge_attack4_USAir.csv", "w") as f:
        writer = csv.writer(f, delimiter=',')
        writer.writerows(zip(tot_T1, tot_ND1))

    run_cnt = 3
    #******** Run Edge Attack 5 ********#
    tot_ND1 = [0] * (E_rm + 1)
    tot_T1 = [0] * (E_rm + 1)
    for i in range(run_cnt):
        G1 = nx.read_pajek("dataset/USAir97.net")
        print ">>>>>>>>>>>>>>> Recalculated Betweenness Attack run time count: ", i + 1, "<<<<<<<<<<<<<<<<<<"
        print "graph info", nx.info(G1)
        ND1, T1 = RecalculatedEdgeBetweennessAttack(G1, remove_fraction=fraction)
#.........这里部分代码省略.........
开发者ID:python27,项目名称:NetworkControllability,代码行数:101,代码来源:TempTempTempFlowEdgeBetweenness.py


示例20: print

import networkx as nx
import sys

if __name__ == '__main__':
    usage = "usage: python %prog pajek_filename tagert_filename"
    print("# loading input...")
    h = nx.read_pajek(sys.argv[1])
    print("Finding cliques...")
    cliques = list(nx.find_cliques(h))
    f = open(sys.argv[2], 'w')
    print("Printing the cliques...")
    for item in cliques:
        if(len(item))>=4:
	    f.writelines(', '.join(str(j) for j in item) + '\n')
    f.close()
开发者ID:nilizadeh,项目名称:de-anonymization,代码行数:15,代码来源:find-cliques.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python networkx.read_shp函数代码示例发布时间:2022-05-27
下一篇:
Python networkx.read_multiline_adjlist函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap