Esempio n. 1
0
    def saveGraphPajek(self, filename=None):
        if filename is not None:
            self.filename = filename

        nx.write_pajek(self.G, self.filename)

        logger.info(u"Saved - %s" % self.filename)
def make_network(raw_file_list):

# handles the individual nodes
    collect_nodes_by_source = []
    list_of_source_names = []
    node_list = []

    GB = nx.Graph()

# for all the nodes...
    for i in range(len(raw_file_list)):    
        # check whether they are name, source or else (not returned). "i" works as an index to identify the respective node when it comes back
        checker, a = my_containsAny(raw_file_list[i], i)

        # raw data starts with a source, all following non-source lines refer to names or tags. So all returned nodes should be linked to each other
        
        if checker == "source":
            GB.add_node(raw_file_list[a], bipartite = 0)
            source = raw_file_list[a]

        while source == raw_file_list[a]:
            if checker == "node":
                GB.add_node(raw_file_list[a], bipartite = 1)  
                GB.add_edge(raw_file_list[a], raw_file_list[a+1])


    G = bnx.weighted_projected_graph(GB, GB.nodes(["bipartite"]==1))

    #nx.write_graphml(GB, "abolitionists_bipartite.graphml")
    nx.write_pajek(G, "abolitionists.net")

    print "done!"
Esempio n. 3
0
def save_pajek(i, graphs, file, graphs_pajek, ego_id, uw, ud, net, g_type):
    if not os.path.exists(graphs_pajek):
        os.makedirs(graphs_pajek)

    if os.path.isfile(str(graphs_pajek) + str(ego_id) + ".pajek"):
        print(
            str(i) + " - Arquivo PAJEK já existe: " + str(graphs_pajek) +
            str(ego_id) + ".pajek")
    else:
        print(
            str(g_type) + " - " + str(net) + " - Convertendo grafo do ego: " +
            str(i) + " para formato PAJEK: " + str(ego_id) + ".pajek")

        if ud is False and uw is False:  # Direcionado e ponderado
            G = nx.read_weighted_edgelist(graphs + file,
                                          nodetype=int,
                                          create_using=nx.DiGraph())

        elif ud is False and uw is True:  # Direcionado e Não ponderado
            G = nx.read_edgelist(graphs + file,
                                 nodetype=int,
                                 create_using=nx.DiGraph())

        elif ud is True and uw is False:  # Não direcionado e ponderado
            G = nx.read_weighted_edgelist(graphs + file,
                                          nodetype=int,
                                          create_using=nx.Graph())

        else:  # Não direcionado e Não Ponderado
            G = nx.read_edgelist(graphs + file,
                                 nodetype=int,
                                 create_using=nx.Graph())

        nx.write_pajek(G, str(graphs_pajek) + str(ego_id) + ".pajek")
Esempio n. 4
0
def divide(G1):
    RandomG = nx.Graph()  #creating an empty graph
    ScalefreeG = nx.Graph()  #creating an empty graph
    G = nx.Graph()  #creating an empty graph
    G.add_nodes_from(G1)
    G.add_edges_from(G1.edges)
    ScalefreeG.add_nodes_from(G1)
    ScalefreeG.add_edges_from(G1.edges)
    i = 0

    for node in G.nodes():
        j = 0
        v = node
        for node in G.nodes():
            u = node
            t1 = G.neighbors(u)
            t2 = G.neighbors(v)

            if (v != u and t1 == t2):
                #RandomG.add_nodes_from(G.neighbors(u))
                ScalefreeG.add_node(u)
                ScalefreeG.add_node(v)
                ScalefreeG.add_edge(v, u)

    RandomG.remove_nodes_from(ScalefreeG.nodes)
    nx.write_pajek(RandomG, "RandomG2.net", encoding='UTF-8')
    nx.write_pajek(ScalefreeG, "ScalefreeG2.net", encoding='UTF-8')
Esempio n. 5
0
def addTracks(artist, tracks, artistGraph):
	for track in tracks:
	# get list of users who have favorited this user's track
		favoriters = client.get('/tracks/' + str(track) + '/favoriters')
		print "Add Favoriters"
		for user in favoriters:
			addWeight(user.id, artist, artistGraph, 'fav_weight')
		try:
			print "Writing out new artists..."
			nx.write_pajek(artistGraph, 'artistGraph.net')
			print "New artists written successfully!"
			print "The artist graph currently contains " + str(len(artistGraph)) + " artists."
			print "The artist graph currently contains " + str(nx.number_strongly_connected_components(artistGraph)) + " strongly connected components."
		except IOError:
			print "New artists could not be written..."
	
	# get list of users who have commented on this user's track			
		commenters = client.get('/tracks/' + str(track) + '/comments')
		print "Add Commenters"
		for user in commenters:
			addWeight(user.user_id, artist, artistGraph, 'com_weight')
		try:
			print "Writing out new artists..."
			nx.write_pajek(artistGraph, 'artistGraph.net')
			print "New artists written successfully!"
			print "The artist graph currently contains " + str(len(artistGraph)) + " artists."
			print "The artist graph currently contains " + str(nx.number_strongly_connected_components(artistGraph)) + " strongly connected components."
		except IOError:
			print "New artists could not be written..."			
Esempio n. 6
0
def main():
    g = net.Graph()
    #read_lj_friends(g,'kozel_na_sakse')
    snowball_sampling(g, 'kozel_na_sakse', 2)
    net.draw(g)
    plot.show()
    net.write_pajek(g, 'lj_friends.net')
Esempio n. 7
0
def _write_network_file(graph,
                        out_name,
                        out_format=None,
                        data=False,
                        weight=False):
    """
    Write the graph representation on file using a user specified format

    :param graph: networkx graph
    :param out_name: pattern for the output filename
    :param out_format: output format. Accepted values: edges(edgelist)|ncol|gefx|gml|pajek|graphML
    """

    if out_format == None:
        out_format = "edges"
    os.makedirs(os.path.dirname(out_name), exist_ok=True)
    #print("writing graph of format " + out_format + " at " + out_name)
    if out_format == 'edges':
        nx.write_edgelist(graph, "%s.edges" % (out_name), data=data)
    elif out_format == 'gefx':
        nx.write_gexf(graph, "%s.gefx" % (out_name))
    elif out_format == 'gml':
        nx.write_gml(graph, "%s.gml" % (out_name))
    elif out_format == 'pajek':
        nx.write_pajek(graph, "%s.pajek" % (out_name))
    elif out_format == 'ncol':
        nx.write_edgelist(graph,
                          "%s.ncol" % (out_name),
                          delimiter='\t',
                          data=weight)
    elif out_format == 'graphML':
        g = nx.write_graphml(graph, "%s.graphML" % (out_name))
    else:
        raise Exception("UNKNOWN FORMAT " + out_format)
Esempio n. 8
0
def write_graph(graph, filename, file_type=None):
    if not file_type:
        file_type = get_graph_type(filename)
        if not file_type:
            raise RuntimeError("Unable to determine graph file type.")

    if file_type == "adjlist":
        networkx.write_adjlist(graph, filename)
    elif file_type == "edgelist":
        networkx.write_edgelist(graph, filename)
    elif file_type == "gexf":
        networkx.write_gexf(graph, filename)
    elif file_type == "gml":
        networkx.write_gml(graph, filename)
    elif file_type == "gpickle":
        networkx.write_gpickle(graph, filename)
    elif file_type == "graphml":
        networkx.write_graphml(graph, filename)
    elif file_type == "yaml":
        networkx.write_yaml(graph, filename)
    elif file_type == "pajek" or file_type == "net":
        networkx.write_pajek(graph, filename)
    elif file_type == "adjmat":
        #sparse_matrix = networkx.adjacency_matrix(graph)
        #dense_matrix = sparse_matrix.todense()
        #dense_matrix.tofile(filename, sep=",", format="%g")

        matrix = networkx.to_numpy_matrix(graph)
        numpy.savetxt(filename, matrix, delimiter=",", newline="\n", fmt="%g")
    else:
        raise RuntimeError("Unrecognized output graph file type.")
Esempio n. 9
0
def save_graph(graph, save_name):
    menu = {'1': "GEXF", '2': "GML", '3': "GraphML", '4': "Pajek", '5': "Exit"}
    while True:
        print("\nSupported formats: ")

        for number in sorted(menu.keys()):
            print(number, menu[number])

        selection = input("Select format [1-6]:").strip()
        if selection == '1':
            nx.write_gexf(graph, save_name + ".gexf")
            print("Saved in GEXF format")
        elif selection == '2':
            nx.write_gml(graph, save_name + ".gml")
            print("Saved in GML format")
        elif selection == '3':
            nx.write_graphml(graph, save_name + ".graphml")
            print("Saved in GraphML format")
        elif selection == '4':
            nx.write_pajek(graph, save_name + ".net")
            print("Saved in Pajek format")
        elif selection == '5':
            return
        else:
            print("Unknown Format Selected!")
def generate_graphs_from_baited_loci():
    
    # Adjacent duplets
    print "Loading adjacent duplets"
    graph, duplets = load_adjacent_duplets_graph()
    linked_list_file = os.path.join(work_dir, "baited_adj_duplets.txt")
    with open(linked_list_file, "w") as outf:
        outf.write("#From\tTo\tWeight\n")
        for edge in graph.edges_iter(data=True):
            _from = edge[0]
            _to = edge[1]
            _weight = edge[2]["weight"]
            outf.write("%s\t%s\t%s\n" % (_from, _to, _weight))
    print "Writing adjacent duplets"
    pajek_file = os.path.join(work_dir, "baited_adj_duplets.net")
    nx.write_pajek(graph, pajek_file)
    
    # duplets
    print "Loading duplets"
    graph, duplets = load_duplets_graph()
    print "Writing duplets"
    linked_list_file = os.path.join(work_dir, "baited_duplets.txt")
    with open(linked_list_file, "w") as outf:
        outf.write("#From\tTo\tWeight\n")
        for edge in graph.edges_iter(data=True):
            _from = edge[0]
            _to = edge[1]
            _weight = edge[2]["weight"]
            outf.write("%s\t%s\t%s\n" % (_from, _to, _weight))
    pajek_file = os.path.join(work_dir, "baited_duplets.net")
    nx.write_pajek(graph, pajek_file)
Esempio n. 11
0
def convert_to_Pajek(G, filename):
    """
	Convert Graph into Pajek Format
	"""
    print("Writing In pajek Format to ", filename)
    nx.write_pajek(G, filename, encoding='UTF-8')
    print("Written To", filename, "in Pajek Format")
Esempio n. 12
0
def ministro_ministro(G):
    """
    Cria um grafo de ministros conectados de acordo com a sobreposição de seu uso da legislação
    Construido a partir to grafo ministro_lei
    """
    GM = nx.Graph()
    for m in G:
        try:
            int(m)
        except ValueError:# Add only if node is a minister
            if m != "None":
                GM.add_node(m.decode('utf-8'))
#    Add edges
    for n in GM:
        for m in GM:
            if n == m: continue
            if GM.has_edge(n,m) or GM.has_edge(m,n): continue
            # Edge weight is the cardinality of the intersection each node neighbor set.
            w = len(set(nx.neighbors(G,n.encode('utf-8'))) & set(nx.neighbors(G,m.encode('utf-8')))) #encode again to allow for matches
            if w > 5:
                GM.add_edge(n,m,{'weight':w})
    # abreviate node names
    GMA = nx.Graph()
    GMA.add_weighted_edges_from([(o.replace('MIN.','').strip(),d.replace('MIN.','').strip(),di['weight']) for o,d,di in GM.edges_iter(data=True)])
    P.figure()
    nx.draw_spectral(GMA)
    nx.write_graphml(GMA,'ministro_ministro.graphml')
    nx.write_gml(GMA,'ministro_ministro.gml')
    nx.write_pajek(GMA,'ministro_ministro.pajek')
    nx.write_dot(GMA,'ministro_ministro.dot')
    return GMA
Esempio n. 13
0
def NETplusCOM():
    G = nx.read_gml(sys.argv[1])
    # myedge = readfile(sys.argv[1]) 
    # G = nx.Graph()                                        
    # for i in range (len(myedge)):                                                                 
    #     G.add_edge(myedge[i][0],myedge[i][1])  
    nx.write_pajek(G,sys.argv[1][:len(sys.argv[1])-3]+"net")
    graph = readfile(sys.argv[1][:len(sys.argv[1])-3]+"net") 
    community = readfile(sys.argv[1][:len(sys.argv[1])-4]+"_comm_comboC++.txt") 
    f = open(sys.argv[1][:len(sys.argv[1])-4]+"_combo.txt","w")
    i = 0
    for com in community:
        trigger = 0
        for j in range (1,len(graph[i+1])):
            if graph[i+1][j].startswith("\""):
                f.write("%s " % graph[i+1][j][1:])
                trigger = 1
                continue
            if graph[i+1][j].endswith("\""):
                f.write("%s" % graph[i+1][j][:len(graph[i+1][j])-1])
                break
            if trigger == 1 :
                f.write("%s " % graph[i+1][j])
            if trigger == 0:
                f.write("%s" % graph[i+1][j])
                break
        f.write(",%s\n" % com[0])
        i+=1
Esempio n. 14
0
def generate_graphs_from_baited_loci():

    # Adjacent duplets
    print "Loading adjacent duplets"
    graph, duplets = load_adjacent_duplets_graph()
    linked_list_file = os.path.join(work_dir, "baited_adj_duplets.txt")
    with open(linked_list_file, "w") as outf:
        outf.write("#From\tTo\tWeight\n")
        for edge in graph.edges_iter(data=True):
            _from = edge[0]
            _to = edge[1]
            _weight = edge[2]["weight"]
            outf.write("%s\t%s\t%s\n" % (_from, _to, _weight))
    print "Writing adjacent duplets"
    pajek_file = os.path.join(work_dir, "baited_adj_duplets.net")
    nx.write_pajek(graph, pajek_file)

    # duplets
    print "Loading duplets"
    graph, duplets = load_duplets_graph()
    print "Writing duplets"
    linked_list_file = os.path.join(work_dir, "baited_duplets.txt")
    with open(linked_list_file, "w") as outf:
        outf.write("#From\tTo\tWeight\n")
        for edge in graph.edges_iter(data=True):
            _from = edge[0]
            _to = edge[1]
            _weight = edge[2]["weight"]
            outf.write("%s\t%s\t%s\n" % (_from, _to, _weight))
    pajek_file = os.path.join(work_dir, "baited_duplets.net")
    nx.write_pajek(graph, pajek_file)
def getGraph(fileRef):
    data = getFiles(fileName)
    nodes = getNodes(data)
    edges = getEdges(data)
    graph = createNetwork(edges, nodes)

    gml_output_path = os.path.join('output', 'network',
                                   fileRef.
                                   split('.')[0].
                                   split('/')[1] + '.gml')

    print "Writing GML file to %s" % gml_output_path
    nx.write_gml(graph, gml_output_path)

    net_output_path = os.path.join('output', 'network',
                                   fileRef.
                                   split('.')[0].
                                   split('/')[1] + '.net')

    print "Writing net file to %s" % net_output_path
    nx.write_pajek(graph, net_output_path)

    params = (graph.number_of_nodes(), graph.number_of_edges())
    print "Graph has %s nodes, %s edges" % params
    print
Esempio n. 16
0
def lei_vs_lei(nedges=None):
    """
    Grafo de todas com todas (leis)
    """
    # Verão original Flávio comentada
    # curgrafo.execute('select lei_id_1,esfera_1,lei_1,lei_id_2,esfera_2, lei_2, peso from vw_gr_lei_lei where  peso >300 and lei_id_2>2')
    # curgrafo.execute('select lei_id_1,lei_tipo_1,lei_nome_1,lei_id_2,lei_tipo_2, lei_nome_2, peso from vw_gr_lei_lei where lei_count <= 20 and lei_id_1 = 1 and lei_id_2 <= 20 limit 0,1000')
    # curgrafo.execute('select lei_id_1,lei_tipo_1,lei_nome_1,lei_id_2,lei_tipo_2, lei_nome_2, peso from vw_gr_lei_lei where lei_count <= 8 and lei_id_1 <= 20 and lei_id_2 <= 20 limit 0,1000')
    curgrafo.execute('select lei_id_1,esfera_1,lei_1,lei_id_2,esfera_2, lei_2, peso from vw_gr_lei_lei where lei_count <= 10 and lei_id_1 <= 50 and lei_id_2 <= 200 limit 0,10000')
    if not nedges:
        res = curgrafo.fetchall()
        nedges = len(res)
    else:
        res = curgrafo.fetchmany(nedges)
    eds = [(i[0],i[3],i[6]) for i in res]
    G = nx.Graph()
    #eds = [i[:3] for i in res]
    G.add_weighted_edges_from(eds)
    print "== Grafo Lei_Lei =="
    print "==> Order: ",G.order()
    print "==> # Edges: ",len(G.edges())
    # Adding attributes to nodes
    for i in res:
        G.node[i[0]]['esfera'] = i[1]
        G.node[i[0]]['lei'] = i[2]
        G.node[i[3]]['esfera'] = i[4]
        G.node[i[3]]['lei'] = i[5]
    nx.write_graphml(G,'lei_lei.graphml')
    nx.write_gml(G,'lei_lei.gml')
    nx.write_pajek(G,'lei_lei.pajek')
    nx.write_dot(G,'lei_lei.dot')
    return G,res
Esempio n. 17
0
def convert_to_Pajek(G, filename):
    """
	Convert Graph into Pajek Format
	"""
    print("Writing In pajek Format to ", filename)
    nx.write_pajek(G, "Data/collusive_users_graph_Pajek.net", encoding='UTF-8')
    print("Written to Pajek")
Esempio n. 18
0
def saveNet(rScores, threshold, doGraph, doDst, rows, gen, filePrefix):
    filePrefix = formatFilePrefix(filePrefix)

    matrix = matrixFromR(rScores, threshold, rows)

    if doGraph:
        # Graph
        graph = nx.from_numpy_matrix(matrix, create_using=nx.Graph)
        # Name nodes (change graph)
        mapNames = dict(zip(graph, list(gen.index[0:rows])))
        graphNamed = nx.relabel_nodes(graph, mapNames)

        nx.write_pajek(graphNamed, filePrefix + ".net")
        nx.write_gml(graphNamed, filePrefix + ".gml")
        # Without isolates
        graphNoIsolNamed = graphNamed.copy()
        graphNoIsolNamed.remove_nodes_from(list(nx.isolates(graphNoIsolNamed)))
        nx.write_pajek(graphNoIsolNamed, filePrefix + "_NoIsolates.net")
        nx.write_gml(graphNoIsolNamed, filePrefix + "_NoIsolates.gml")

    if doDst:
        # Write to file dst
        matrixD = 1 - matrix
        f = open(filePrefix + '.dst', "wt")
        tsvWriter = csv.writer(f, delimiter='\t')
        tsvWriter.writerow([rows, "labelled"])
        for row in range(0, rows):
            writeArr = [[gen.index[row]], matrixD[row, :row]]
            flattened = [val for sublist in writeArr for val in sublist]
            tsvWriter.writerow(flattened)
        f.close()
Esempio n. 19
0
def write_export(output_directory, export_ref_annotated_format, span, graph):
    if not os.path.exists(output_directory):
        os.mkdir(output_directory)
    if export_ref_annotated_format == "gexf":
        log("write gexf export", span)
        networkx.write_gexf(
            graph, os.path.join(output_directory, "%s_annotated.gexf" % span))
    elif export_ref_annotated_format == "edgelist":
        log("write csv export", span)
        networkx.write_weighted_edgelist(graph,
                                         os.path.join(
                                             output_directory,
                                             "%s_annotated.csv" % span),
                                         delimiter="\t")
    elif export_ref_annotated_format == "pajek":
        log("write pajek export", span)
        networkx.write_pajek(
            graph, os.path.join(output_directory, "%s_annotated.net" % span))
    elif export_ref_annotated_format == "graphml":
        log("write pajek export", span)
        networkx.write_graphml(
            graph, os.path.join(output_directory,
                                "%s_annotated.graphml" % span))
    else:
        log("no compatible export format specified", span)
Esempio n. 20
0
def export(graph, span):
    if CONFIG["export_ref_format"] == "gexf":
        print("Writing .gexf export")
        networkx.write_gexf(graph,
                            os.path.join(CONFIG["parsed_data"], span,
                                         "%s.gexf" % span),
                            encoding="UTF-8")
    elif CONFIG["export_ref_format"] == "edgelist":
        print("Writing .csv export")
        networkx.write_weighted_edgelist(graph,
                                         os.path.join(CONFIG["parsed_data"],
                                                      span, "%s.csv" % span),
                                         delimiter="\t")
    elif CONFIG["export_ref_format"] == "pajek":
        print("Writing .pajek export")
        networkx.write_pajek(graph,
                             os.path.join(CONFIG["parsed_data"], span,
                                          "%s.net" % span),
                             encoding='UTF-8')
    elif CONFIG["export_ref_format"] == "json":
        print("Writing .json export")
        data = json_graph.node_link_data(graph)
        json.dump(data,
                  open(
                      os.path.join(CONFIG["parsed_data"], span,
                                   "%s.json" % span), "w"),
                  encoding='UTF-8')
    else:
        print("No export compatible with the specified export format!")
Esempio n. 21
0
    def simulate_for_prob_infection_range(self, n_reps,
                                          prob_being_initially_infected, t_max,
                                          t_trans):
        avrgs_of_infections = []
        #network = ER().ER(500, 0.4)
        network = nx.configuration_model(
            nx.utils.create_degree_sequence(n=500,
                                            exponent=2.7,
                                            sfunction=powerlaw_sequence))

        self.filename = os.path.join(self.output_path, 'A4' + 'CM_500_27')
        nx.write_pajek(network, self.filename + '.net')

        adjacency_matrix = nx.to_numpy_matrix(network)
        infected_nodes = self.infecting_the_network(
            network, prob_being_initially_infected)
        for index, prob_infection in enumerate(self.prob_infection_range):
            avrgs_of_infections.append(
                self.simulate_for_prob_infection(network, infected_nodes,
                                                 n_reps, prob_infection, t_max,
                                                 t_trans, adjacency_matrix))
            print '\t{} infection probability ({}) = {}'.format(
                index, prob_infection, avrgs_of_infections[-1])

        return avrgs_of_infections
 def export_graph_to_pajek(self, file=False, graph=False):
     if not file:
         file_pajek = 'graphs/graph_' + self.type + '.net'
     else:
         file_pajek = file
     if not graph:
         graph = self.graph
     print("export_graph_to_pajek - " + str(file_pajek))
     # pos = nx.spring_layout(self.graphs)
     # nx.draw_networkx_nodes(self.graphs, pos, node_size=100, node_color='red')
     # nx.draw_networkx_edges(self.graphs, pos)
     # nx.draw_networkx_labels(self.graphs, pos, font_size='8', font_color='blue')
     # plt.show()
     nx.write_pajek(graph, file_pajek)
     # functions.replace(file_pajek, '0.0 0.0 ellipse', '')
     functions.replace(file_pajek, '0.0 0.0 ellipse',
                       '" 0.0 0.0 box ic Red fos 25')
     functions.replace_if_type_node(file_pajek, ' SEG_', ' "SEG_', 'Red',
                                    'Red')
     functions.replace_if_type_node(file_pajek, ' IO_', ' "IO_', 'Red',
                                    'Grey')
     functions.replace_if_type_node(file_pajek, ' ARTW_', ' "ARTW_', 'Red',
                                    'Blue')
     functions.replace_if_type_node(file_pajek, ' CH_', ' "CH_', 'Red',
                                    'Orange')
     functions.replace_if_type_node(file_pajek, ' REF_', ' "REF_', 'Red',
                                    'Purple')
     functions.replace_if_type_node(file_pajek, ' EV_', ' "EV_', 'Red',
                                    'Yellow')
     functions.replace_if_type_node(file_pajek, ' E_', ' "E_', 'Red',
                                    'Grey')
Esempio n. 23
0
 def exportPajek(self, filename):
     """
     Método exportar la red a formato GML
     
     Args:
         filename: ruta del nuevo fichero
     """
     nx.write_pajek(self.__G, filename)
def main(max_depth = 2, graphfile='music_network.net', id_mapfile='artist_id_map.p'):
    g = net.Graph()
    id_map = []
    for artist_id, artist_name in get_playlist_artists('science'):
        id_map.append({'id': artist_id, 'name':artist_name})
        snowball_sampling(g, artist_search, artist_id, id_map=id_map, max_depth=max_depth)
    net.write_pajek(g, graphfile)
    pickle.dump(id_map, open(id_mapfile,'wb')) 
Esempio n. 25
0
def write_pajek_file(output_path, data_filename, graph):
    pajek_filepath = os.path.join(output_path, data_filename + ".net")
    # write_pajek requires string attributes
    weights = nx.get_node_attributes(graph, 'weight')
    new_weights = {k:utils.to_str(v) for k,v in weights.items()}
    nx.set_node_attributes(graph, name='weight', values=new_weights)
    nx.write_pajek(graph, pajek_filepath)
    return pajek_filepath
Esempio n. 26
0
 def test_write_pajek(self):
     import io
     G = nx.parse_pajek(self.data)
     fh = io.BytesIO()
     nx.write_pajek(G, fh)
     fh.seek(0)
     H = nx.read_pajek(fh)
     assert_nodes_equal(list(G), list(H))
     assert_edges_equal(list(G.edges()), list(H.edges()))
def download_as_pajek(modeladmin, request, queryset):
    with tempfile.SpooledTemporaryFile() as tmp:
        g = social_network(queryset)
        nx.write_pajek(g, tmp)
        tmp.seek(0)
        response = HttpResponse(tmp.read(), content_type="text/net")
        response['Content-Disposition'] \
            = 'attachment; filename="social_network.net"'
        return response
Esempio n. 28
0
def write_graph(G, gfile):
    try:
        print "Writing out new artists..."
        nx.write_pajek(G, gfile)
        print "New artists written 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 "New artists could not be written..."
Esempio n. 29
0
def preprocessing(fn_data, fn_net, is_undir, des_avg_deg, des_avg_deg_tol):

    print("    reading network")
    if is_undir:
        G = nx.read_edgelist(fn_data,
                             data=(('weight', float), ),
                             create_using=nx.Graph())
    else:
        G = nx.read_edgelist(fn_data,
                             data=(('weight', float), ),
                             create_using=nx.DiGraph())

    N = G.number_of_nodes()
    L = G.number_of_edges()
    avg_deg = L / N
    print("    number of nodes: %d" % N)
    print("    number of edges: %d" % L)
    print("    average degree : %.4f" % avg_deg)

    if avg_deg > des_avg_deg:
        print("    pruning")
        max_edges = int(N * des_avg_deg)
        if max_edges < L:
            wh = [d for (i, j, d) in G.edges(data='weight')]
            wh.sort()
            wh_min = wh[L - max_edges]
            # prune edges with lowest weights
            prune_list = []
            for (i, j, d) in G.edges(data='weight'):
                if d < wh_min:
                    prune_list.append((i, j))
            G.remove_edges_from(prune_list)
            Lg = G.number_of_edges()
            avgk_g = Lg / N
            if abs(avgk_g - des_avg_deg) / des_avg_deg > des_avg_deg_tol:
                H = G.copy()
                prune_list = []
                for (i, j, d) in H.edges(data='weight'):
                    if d <= wh_min:
                        prune_list.append((i, j))
                H.remove_edges_from(prune_list)
                Lh = H.number_of_edges()
                avgk_h = Lh / N
                if abs(avgk_h - des_avg_deg) / des_avg_deg < des_avg_deg_tol:
                    G = H

        new_L = G.number_of_edges()
        new_avg_deg = new_L / N
        print("    weights cutoff     : %.4f" % wh_min)
        print("    new number of edges: %d" % new_L)
        print("    new average degree : %.4f" % new_avg_deg)

    print("    normalizing network")
    normalize_weights(G)

    print("    writting network")
    nx.write_pajek(G, fn_net)
    def save_graph(self, path):
        """
        Saves the networkx graph stored in self.graph.

        :param path: Location to store the network.
        """

        # Save the network self.graph in 'path' with the name 'Graph'
        nx.write_pajek(G=self.graph, path=os.path.join(path, 'Graph'))
def processDirectory(dir_path, top_number, lemma_flag):
    """
        Process the directory the user inputs
    """
    if (not lemma_flag):
        print 'NO LEMMATIZING'
    
    cross_graph = nx.MultiDiGraph()

    for file_name in os.listdir(dir_path):
        file_path = os.path.join(dir_path, file_name)
        if os.path.isfile(file_path) and file_name.endswith('.txt'):
            print 'analyzing ' + file_name, '...'
            try:
                file_open = io.open(file_path, 'r')
            except IOError:
                print 'OPEN FILE ' + file_path + ' ERROR'
                sys.exit(1)
            sent_seg = preprocessSent(file_open.read())
            sent_depend = produceDepend(sent_seg, lemma_flag)
            # print sent_seg
            # print sent_depend
            file_open.close()
            
            single_graph = drawDependGraph(sent_depend, sent_seg, dir_path, file_name, lemma_flag)
            
            # Doing the combination
            cross_graph.add_nodes_from([v for v, d in  single_graph.nodes(data = True) if v not in cross_graph.nodes()], freq = 0)
            
            for u, v, d in single_graph.edges(data = True):
                if (u, v) not in cross_graph.edges():
                    cross_graph.add_edge(u, v, dependency = d['dependency'], label = d['label'], freq = 0)
                else:
                    list_dif_depend = [cross_graph[u][v][i]['dependency'] for i in range(len(cross_graph[u][v].items()))]
                    if d['dependency'] not in list_dif_depend:
                        cross_graph.add_edge(u, v, dependency = d['dependency'], label = d['label'], freq = 0)
                    

            for v, d in cross_graph.nodes(data = True):
                if v in single_graph.nodes():
                    d['freq'] += single_graph.node[v]['freq']
            
            for u, v, d in cross_graph.edges(data = True):
                if (u, v) in single_graph.edges():
                    list_dif_depend = [single_graph[u][v][i]['dependency'] for i in range(len(single_graph[u][v].items()))]
                    dict_dif_depend = dict(zip(list_dif_depend, range(len(single_graph[u][v].items()))))
                    if d['dependency'] in list_dif_depend:
                        depend_index = dict_dif_depend[d['dependency']]
                        d['freq'] += single_graph[u][v][depend_index]['freq']

    if lemma_flag:
        nx.write_pajek(cross_graph, dir_path + 'syntactic_lemma/' + 'syntactic_graph_cross_txt_lemma.net')
        graphAnalysis(cross_graph, top_number, dir_path + 'syntactic_lemma/' + 'syntactic_graph_lemma_analysis.csv')
    else:
        nx.write_pajek(cross_graph, dir_path + 'syntactic_no_lemma/' + 'syntactic_graph_cross_txt_no_lemma.net')
        graphAnalysis(cross_graph, top_number, dir_path + 'syntactic_no_lemma/' + 'syntactic_graph_analysis_no_lemma.csv')
Esempio n. 32
0
def writepajek(A, filename):
    SP = np_to_scipy_matrix(A)
    edges = []
    for i in range(0, A.shape[0]):
        for j in range(0, A.shape[1]):
            if A[i, j] != 0:
                edges.append(['A' + str(i), 'B' + str(j)])

    G = nx.bipartite.from_biadjacency_matrix(SP, create_using=None)
    nx.write_pajek(G, filename + '.net')
def save_graph_in_pajek_format(G, file_name):
    # Print graph details
    print(file_name)
    print(G.nodes(), G.edges())
    # Build the containing directory in case it doesn't exist
    output_file = settings.output_graphs + file_name + '_graph.net'
    os.makedirs(os.path.dirname(output_file), exist_ok=True)
    # Write network to file
    nx.write_pajek(G, output_file)
    return
Esempio n. 34
0
def main():
    while (True):
        n = int(raw_input('Enter the number of nodes '))
        p = float(raw_input('Enter the probability '))
        graph = generate_erdos_renyi(n, p)
        draw_graph(graph, n, p)
        draw_theoretical_degree_distribution(graph, p)
        draw_empirical_degree_distribution(graph, p)
        nx.write_pajek(graph,
                       "results/er_graph_" + str(n) + "_" + str(p) + ".net")
def writepajek(A,filename):
    SP = np_to_scipy_matrix(A)
    edges = []
    for i in range(0,A.shape[0]):
        for j in range(0,A.shape[1]):
            if A[i,j]!=0:
                edges.append(['A'+str(i),'B'+str(j)])

    G = nx.bipartite.from_biadjacency_matrix(SP,create_using=None)
    nx.write_pajek(G, filename + '.net')
Esempio n. 36
0
def GMLtoNET():
    G = nx.read_gml(sys.argv[1])
    # myedge = readfile(sys.argv[1]) 
    # G = nx.Graph()                                        
    # for i in range (len(myedge)):                                                                 
    #     G.add_edge(myedge[i][0],myedge[i][1])  
    nx.write_pajek(G,sys.argv[1][:len(sys.argv[1])-3]+"net")

    data = readfile(sys.argv[1][:len(sys.argv[1])-3]+"net") 
    writefile(sys.argv[1][:len(sys.argv[1])-3]+"net",data)
Esempio n. 37
0
 def write_graph_in_format(self, filerootname, fileformat='gexf'):
     fileformat = fileformat.lower()
     filename = "%s.%s" % (filerootname.replace(" ", "_"), fileformat)
     if fileformat == 'json':
         with open(filename, 'w') as f:
             json.dump(json_graph.node_link_data(self), f)
     elif fileformat == 'net':
         nx.write_pajek(self, filename)
     elif fileformat == 'gexf':
         nx.write_gexf(self, filename)
Esempio n. 38
0
 def write_graph_in_format(self, filerootname, fileformat='gexf'):
     fileformat = fileformat.lower()
     filename = "%s.%s" % (filerootname.replace(" ", "_"), fileformat)
     if fileformat == 'json':
         with open(filename, 'w') as f:
             json.dump(json_graph.node_link_data(self), f)
     elif fileformat == 'net':
         nx.write_pajek(self, filename)
     elif fileformat == 'gexf':
         nx.write_gexf(self, filename)
def save_friend_list(friend_list,path='/home/pj/Python/social_analysis/',filename='friend.net'):
    fullpath=path+filename
    print '开始保存社交关系'
    g=networkx.Graph()
    for name in friend_list.keys():
        for node in friend_list[name]:
            g.add_edge(name,node[1])
    networkx.write_pajek(g,fullpath)
    print '好友列表存储在%s'%(fullpath)
    return 1
def writeToFile(file, format):
    tree = createNxGraphFromConsensus(file)
    if format == 'edgelist':
        nx.write_edgelist(tree, file.split('.')[0] + '.edgelist')
    elif format == 'gml':
        nx.write_gml(tree, file.split('.')[0] + '.gml')
    elif format == 'graphml':
        nx.write_graphml(tree, file.split('.')[0] + '.graphml')
    elif format == 'pajek':
        nx.write_pajek(tree, file.split('.')[0] + '.net')
def generate_output(args: argparse.Namespace,
                    base_graph: Union[nx.Graph, nx.DiGraph]) -> None:
    """Have NetworkX write to the output file given the parsed graph."""

    outputtype = args.outputfile.split('.')[-1].lower()

    # write to output file
    if outputtype == 'net':
        nx.write_pajek(base_graph, args.outputfile)
    elif outputtype == 'gexf':
        nx.write_gexf(base_graph, args.outputfile)
def main():
    badges = user_badge_extract('Badges.xml')
    G = create_graph(badges)
    
#    draw_graph(G)
    
    # Saving the graph in Pajek format
    nx.write_pajek(G, "graph.net")
    
    # Saving the graph as AdjList
    nx.write_adjlist(G, "graph.adjlist")
  def run(self):
    # Run simulation for several type of networks, in this case Erdos-Renyi and Random Network
    self.networks = [
      {
        'network': nx.scale_free_graph(n = self.nodes),
        'name': 'ScaleFree'
      },
      {
        'network': nx.erdos_renyi_graph(n = self.nodes, p = 0.1), # 0.2, 0.5
        'name': 'ErdosRenyi'
      },
      {
        'network': nx.random_regular_graph(n = self.nodes, d = 10),
        'name': 'RandomNetwork'
      }
    ]

    for network in self.networks:
      nxgraph = network['network']
      graph = helper.convert_nxgraph_to_dict(nxgraph)

      # write network in pajek
      filename = 'pajek/'+ network['name'] + '_' + str(self.nodes) + '.net'
      nx.write_pajek(nxgraph, filename)
      
      for mu in self.mu_values:
        print 'Starting...'
        start_time = time.time()

        # B beta (at least 51 values, B=0.02)
        beta = 0.0
        betas = []
        averages = []
        for i in range(0, 51):
          start_time_beta = time.time()
          sis_initial_model = sis.SIS(graph, mu, beta, self.p0)
          simulation = mc.MonteCarlo(sis_initial_model, self.rep, self.t_max, self.t_trans)
          total_average = simulation.run()

          total_time_beta = time.time() - start_time_beta
          betas.append(beta)
          averages.append(total_average)

          print 'B: {}, average: {}, time: {}s'.format(beta, total_average, total_time_beta)
          beta += 0.02

        total_time = time.time() - start_time
        print 'total time: {}'.format(total_time)

        # plot results and save in file
        helper.plot_results(network['name'], self.nodes, mu, betas, averages)
        helper.write_results(network['name'], self.nodes, mu, betas, averages)

      break 
Esempio n. 44
0
def main(argv):
    # Read the arguments
    parser = argparse.ArgumentParser(description="Convert linklist to Pajek format")
    parser.add_argument('-d', '--data-filename', type=str,
            help="the .tsv file to use as the source", required=True)
    parser.add_argument('-o', '--output-filename', type=str,
            help="the .net output file", required=True)
    options = parser.parse_args(argv[1:])

    G = readdata(options.data_filename)
    nx.write_pajek(G,options.output_filename)
Esempio n. 45
0
def addComments(artist, comments, artistGraph):
	print "Add Comments"
	for user in comments:
		addWeight(artist, user, artistGraph, 'com_weight')
	try:
		print "Writing out new artists..."
		nx.write_pajek(artistGraph, 'artistGraph.net')
		print "New artists written successfully!"
		print "The artist graph currently contains " + str(len(artistGraph)) + " artists."
		print "The artist graph currently contains " + str(nx.number_strongly_connected_components(artistGraph)) + " strongly connected components."
	except IOError:
		print "New artists could not be written..."	
Esempio n. 46
0
    def grapher(self, infomap_command, file_name):
    ### this Method produces two files that are useful: a .net file and a .tree file.
    ### .net a) connects nodes names to ids b) lists vertices with weights
    ### .tree contains modularity information via ids

        #here we write graph data into pajek form from edgelist, which can be used by infomap to do more network analysis.
        G = nx.Graph()
        G.add_edges_from(self.edgelist)
        nx.write_pajek(G,'temporary_folder/' + file_name + '.net')   ### #change would have to change

        #here, we're executing infomap in the shell to get infomap's capability (access to modularity)
        os.system(infomap_command)
Esempio n. 47
0
def HACK_convert_nx_igraph(nx_graph):
    """ 
        There exist no current method to convert a nx graph to an igraph.
        So this is a hack which does sp.
        Args:
            nx_graph: input nx_graph to be converted to igraph
        Returns:
            ig_graph: converted igraph
    """
    nx.write_pajek(nx_graph, "/tmp/rohan.net")
    ig_graph = igraph.Graph()
    ig_graph = igraph.read("/tmp/rohan.net", format="pajek")
    return ig_graph
Esempio n. 48
0
def analisa_ministro_lei(G):
    """
    Makes some analyses of the graph
    """
#    print "++> Page rank for the laws"
#    print nx.pagerank_numpy(G,weight='weight')
#    print "++> Google Matrix"
#    print nx.google_matrix(G,weight='weight')
    plot_hubs_and_authorities(G)
    #saves the graph in graphml format
    nx.write_graphml(G,'ministro_lei.graphml')
    nx.write_gml(G,'ministro_lei.gml')
    nx.write_pajek(G,'ministro_lei.pajek')
    nx.write_dot(G,'ministro_lei.dot')
Esempio n. 49
0
def run(bm, maxt=100, output=None, graph_format='edgelist',
        comm_format='bynode',
        opts={}):
    """Main loop to do a running."""
    for t in range(maxt+1):
        g = bm.graph(t)
        comms = bm.comms(t)
        grammar = bm.grammar()
        for stmt in grammar:
            print '   ', stmt
        if output:
            prefix = output + '.t%05d'%t
            # write graph
            if graph_format == 'edgelist':
                nx.write_edgelist(g, prefix+'.graph', data=False)
            elif graph_format == 'pajek':
                for n in g:
                    g.node[n]['id'] = n+1
                nx.write_pajek(g, prefix+'.graph')
            elif graph_format == 'null':
                pass
            elif graph_format == 'tedgelist':
                write_temporal_edgelist(bm, g, output+'.tgraph', t)
            else:
                try:
                    graphwriter = getattr(nx, 'write_'+graph_format)
                except AttributeError:
                    raise ValueError("Unknown graph format: %s"%graph_format)
                graphwriter(g, prefix+'.graph')
            # write communities, in desired format.
            if comm_format == 'oneline':  comm_writer = write_comms_oneline
            elif comm_format == 'bynode': comm_writer = write_comms_bynode
            elif comm_format == 'pajek':  comm_writer = write_comms_pajek
            elif comm_format == 'null':   comm_writer = None
            elif comm_format == 'tmatrix':
                write_tmatrix_line(bm, output+'.tcomms', comms, t)
                comm_writer = None
            elif comm_format == 'tcommlist':
                write_temporal_commlist(bm, output+'.tcomms', comms, t)
                comm_writer = None
            else:
                raise ValueError("Unknown comm format: %s"%comm_format)
            # Delay opening the file until here, so we can skip it
            # using the 'null' option.
            if comm_writer:
                f = open(prefix+'.comms', 'w')
                label = 't=%s, command line: %s'%(t, ' '.join(sys.argv))
                comm_writer(f, comms, label)
        print t, len(g), g.number_of_edges(), len(comms), \
            dict((k, len(v)) for k,v in comms.iteritems())
def  processDirectory(dir_path, top_number, window_size, occurrence_frequency, bound_flag, lemma_flag):
    """
        Process the directory the user inputs
    """
    if (not bound_flag):
        print 'NO SENTENCE BOUNDARY'
    
    if (not lemma_flag):
        print 'NO LEMMATIZING'

    cross_graph = nx.Graph()

    for file_name in os.listdir(dir_path):
        file_path = os.path.join(dir_path, file_name)
        if os.path.isfile(file_path) and file_name.endswith('.txt'):
            print 'analyzing ' + file_name, '...'
            try:
                file_open = io.open(file_path, 'r')
            except IOError:
                print 'OPEN FILE ' + file_path + ' ERROR'
                sys.exit(1)
            list_word_no_stopword = preprocessSent(file_open.read(), bound_flag, lemma_flag)

            file_open.close()
            
            single_graph = drawCOGraph(list_word_no_stopword, window_size, bound_flag, lemma_flag, dir_path, file_name)
            
            # Doing the combination
            cross_graph.add_nodes_from([v for v, d in single_graph.nodes(data = True) if v not in cross_graph.nodes()], freq = 0)
            cross_graph.add_edges_from([(u, v) for u, v, d in single_graph.edges(data = True) if (u, v) not in cross_graph.edges() and (v, u) not in cross_graph.edges()], freq = 0)

            for v, d in cross_graph.nodes(data = True):
                if v in single_graph.nodes():
                    d['freq'] += single_graph.node[v]['freq']

            for u, v, d in cross_graph.edges(data = True):
                if (u, v) in single_graph.edges():
                    d['freq'] += single_graph[u][v]['freq']
                elif (v, u) in single_graph.edges():
                    d['freq'] += single_graph[v][u]['freq']

    # occurrence_frequency to filter final graph edges
    if occurrence_frequency > 1:
        cross_graph.remove_edges_from([(u, v) for u, v, d in cross_graph.edges(data = True) if d['freq'] < occurrence_frequency])
        cross_graph.remove_nodes_from([v for v, degree in cross_graph.degree().items() if degree == 0])

    if lemma_flag and bound_flag:
        nx.write_pajek(cross_graph, dir_path + 'co_lemma_bound/' + 'co_graph_cross_txt_lemma_bound.net')
        graphAnalysis(cross_graph, top_number, dir_path + 'co_lemma_bound/' + 'co_graph_lemma_bound_analysis.csv')
    elif lemma_flag and not bound_flag:
        nx.write_pajek(cross_graph, dir_path + 'co_lemma_no_bound/' +'co_graph_cross_txt_lemma_no_bound.net')
        graphAnalysis(cross_graph, top_number, dir_path + 'co_lemma_no_bound/' + 'co_graph_lemma_no_bound_analysis.csv')
    elif not lemma_flag and bound_flag:
        nx.write_pajek(cross_graph, dir_path + 'co_bound_no_lemma/' + 'co_graph_cross_txt_bound_no_lemma.net')
        graphAnalysis(cross_graph, top_number, dir_path + 'co_bound_no_lemma/' + 'co_graph_bound_no_lemma_analysis.csv')
    else:
        nx.write_pajek(cross_graph, dir_path + 'co_no_lemma_no_bound/' + 'co_graph_cross_txt_no_lemma_no_bound.net')
        graphAnalysis(cross_graph, top_number, dir_path + 'co_no_lemma_no_bound/' + 'co_graph_no_lemma_no_bound_analysis.csv')
Esempio n. 51
0
def plotGraph(BIG, tmpscc, tmpFolder='./', tmpFilename='_catprod.net', imgname='_catprod.png', savegraphimage=False, par_node_size=300, par_font_size=12):
	'''
		Plot normal graphs
	'''

	if savegraphimage:
		pos=nx.spring_layout(BIG)
		nx.draw_networkx_nodes(BIG,pos, alpha=0.5, node_size=par_node_size, node_shape='o')
		if tmpscc is not None and len(tmpscc) > 0: map(lambda x: nx.draw_networkx_nodes(BIG, pos, nodelist=list(x), alpha=0.5, node_size=par_node_size, node_shape='o', node_color="blue"), tmpscc)
		nx.draw_networkx_edges(BIG,pos, width=0.5, alpha=0.5)
		nx.draw_networkx_labels(BIG,pos, font_size=par_font_size)
		plt.axis('off')	
		#plt.show()
		plt.savefig(os.path.join(tmpFolder, imgname))

	nx.write_pajek(BIG, os.path.join(tmpFolder, tmpFilename))
Esempio n. 52
0
def getGraph(fileRef):
    data = getFiles(fileName)
    nodes = getNodes(data)
    edges = getEdges(data)
    graph = createNetwork(edges, nodes)

    fileOut = fileRef.split(".")[0] + ".gml"
    print "Writing GML file to %s" % fileOut
    nx.write_gml(graph, fileOut)

    fileOutNet = fileRef.split(".")[0] + ".net"
    print "Writing net file to %s" % fileOutNet
    nx.write_pajek(graph, fileOutNet)

    params = (graph.number_of_nodes(), graph.number_of_edges())
    print "Graph has %s nodes, %s edges" % params
    print
def write_to_pajek(author_graph, filename="author_graph.net"):
    # Write Pajek file compatible with the Infomap Community Detection module
    nx.write_pajek(author_graph, filename)
    lines_in_file= list()
    with open(filename, 'r') as pajek_file:
        for line in pajek_file:
            lines_in_file.append(line)
    num_vertices = int(lines_in_file[0].split()[1])
    for i in range(1, num_vertices+1):
        line = lines_in_file[i].split()
        line[1] = "\"" + line[1] + "\""
        del line[2:]
        line.append("\n")
        lines_in_file[i] = " ".join(line)
    with open(filename, 'w') as pajek_file:
        for line in lines_in_file:
            pajek_file.write(line)
    print("Written to:", filename)
Esempio n. 54
0
def main():
    G = nx.Graph()
    G.add_edge("Mohamed Atta", "Khalid Al-Midhar")
    G.add_edge("Mohamed Atta", "Marwan Al-Sher")
    G.add_edge("Mohamed Atta", "Majed Moqed")
    G.add_edge("Mohamed Atta", "Salem Alhamzi")
    G.add_edge("Mohamed Atta", "Abdulaziz Aloma")
    G.add_edge("Mohamed Atta", "Ziad Jarrahi")
    G.add_edge("Mohamed Atta", "Satam Al Suqan")
    G.add_edge("Mohamed Atta", "Waleed M. Alshe")
    G.add_edge("Mohamed Atta", "Wail Alshehri")
    G.add_edge("Mohamed Atta", "Fayez Ahmed")
    G.add_edge("Khalid Al-Midhar", "Marwan Al-Sher")
    G.add_edge("Marwan Al-Sher", "Majed Moqed")
    G.add_edge("Majed Moqed", "Salem Alhamzi")
    G.add_edge("Salem Alhamzi", "Abdulaziz Aloma")
    G.add_edge("Abdulaziz Aloma", "Ziad Jarrahi")
    G.add_edge("Ziad Jarrahi", "Satam Al Suqan")
    G.add_edge("Satam Al Suqan", "Waleed M. Alshe")
    G.add_edge("Waleed M. Alshe", "Wail Alshehri")
    G.add_edge("Wail Alshehri", "Fayez Ahmed")
    G.add_edge("Khalid Al-Midhar", "Nawaq Alhamzi")
    G.add_edge("Khalid Al-Midhar", "Hani Hanjour")
    G.add_edge("Majed Moqed", "Nawaq Alhamzi")
    G.add_edge("Majed Moqed", "Hani Hanjour")
    G.add_edge("Majed Moqed", "Ahmed Alghamdi")
    G.add_edge("Salem Alhamzi", "Nawaq Alhamzi")
    G.add_edge("Salem Alhamzi", "Hani Hanjour")
    G.add_edge("Salem Alhamzi", "Ahmed Alghamdi")
    G.add_edge("Abdulaziz Aloma", "Hani Hanjour")
    G.add_edge("Abdulaziz Aloma", "Ahmed Algamdi")
    G.add_edge("Ziad Jarrahi", "Mohald Alshehri")
    G.add_edge("Fayez Ahmed", "Mohald Alshehri")
    G.add_edge("Nawaq Alhamzi", "Hani Hanjour")
    G.add_edge("Hani Hanjour", "Ahmed Alghamdi")
    G.add_edge("Ahmed Alghamdi", "Hamza Alghamdi")
    G.add_edge("Mohald Alshehri", "Hamza Alghamdi")
    G.add_edge("Hamza Alghamdi", "Saeed Alghamdi")
    G.add_edge("Saeed Alghamdi", "Ahmed Alnami")
    G.add_edge("Saeed Alghamdi", "Ahmed Alhaznawi")
    nx.write_graphml(G, "ronen-feldman.graphml")
    nx.write_pajek(G, "ronen-feldman.pajek.net")
    
    return G
Esempio n. 55
0
File: io.py Progetto: budnyjj/vkstat
def write_graph(graph, filename):
    """Write graph to file, raise IOError if cannot do it."""
    if filename.endswith('.yaml'):
        try:
            nx.write_yaml(graph, filename)
        except ImportError:
            print('E: cannot write graph to file in YAML format.')
            print('Please install PyYAML or other similar package '
                  'to use this functionality.')
            raise IOError
        else:
            print('Write constructed graph to: {0} '
                  'in YAML format.'.format(filename))
    elif filename.endswith('.gml'):
        try:
            nx.write_gml(graph, filename)
        except ImportError:
            print('E: cannot write graph to file in GML format.')
            print('Please install pyparsing package '
                  'to use this functionality.')
            raise IOError
        else:
            print('Write constructed graph to: {0} '
                  'in GML format.'.format(filename))
    elif filename.endswith('.net'):
        nx.write_pajek(graph, filename)
        print('Write constructed graph to: {0} '
              'in PAJEK format.'.format(filename))
    elif filename.endswith('.gexf'):
        graph = exclude_complex_attrs(graph)
        nx.write_gexf(graph, filename)
        print('Write constructed graph to: {0} '
              'in GEXF format.'.format(filename))
    elif filename.endswith('.graphml'):
        graph = exclude_complex_attrs(graph)
        nx.write_graphml(graph, filename)
        print('Write constructed graph to: {0} '
              'in GraphML format.'.format(filename))
    else:
        with open(filename, 'wb') as f:
            pickle.dump(graph, f, protocol=pickle.HIGHEST_PROTOCOL)
        print('Write constructed graph to: {0} '
              'in pickle format.'.format(filename))
Esempio n. 56
0
def getGraph(fileRef):
    data = getFiles(fileName)
    nodes = getNodes(data)
    edges = getEdges(data)
    graph = createNetwork(edges,nodes)
    
    fileOut = fileRef.split('.')[0]+'.gml'
    print "Writing GML file to %s" % fileOut
    nx.write_gml(graph, fileOut)
    
    fileOutNet = fileRef.split('.')[0]+'.net'
    print "Writing net file to %s" % fileOutNet
    nx.write_pajek(graph, fileOutNet)
    
    components = nx.connected_components(graph)
    components = list(components)
    isolated = [entry[0] for entry in components if len(entry)==1]
    params = (graph.number_of_nodes(),graph.number_of_edges(),len(components),len(isolated))
    print "Graph has %s nodes, %s edges, %s connected components, and %s isolated nodes" % params
    print
Esempio n. 57
0
def snowball_sample(g, center, max_depth=1, current_depth=0, taboo_list=[]):
    print(center, current_depth, max_depth, taboo_list)
    print('number of nodes: %d' % len(g))
    net.write_pajek(g, '/Users/brucehao/Desktop/facebook_network.net')
    if current_depth == max_depth:
        # if we have reached the depth limit of the search, return
        print('out of depth')
        return taboo_list
    if center in taboo_list:
        # we've been here before -- return right away
        return taboo_list
    else:
        taboo_list.append(center)  # we shall never return to the same node

    get_friends(g, center)

    for node in g.neighbors(center):
        # iterate through all friends of central node, call snowball_sample recursively
        taboo_list = snowball_sample(g, node, current_depth=current_depth+1,
                                     max_depth=max_depth, taboo_list=taboo_list)
    return taboo_list
Esempio n. 58
0
 def write_graph(self, G=None, subgraph_file=None):
     if G is None:
         G = self.context_graph
     if subgraph_file is None:
         subgraph_file = self.context_graph_file
     logging.info("Writing graph.")
     # write the graph out
     file_format = subgraph_file.split(".")[-1]
     if file_format == "graphml":
         nx.write_graphml(G, subgraph_file)
     elif file_format == "gml":
         nx.write_gml(G, subgraph_file)
     elif file_format == "gexf":
         nx.write_gexf(G, subgraph_file)
     elif file_format == "net":
         nx.write_pajek(G, subgraph_file)
     elif file_format == "yaml":
         nx.write_yaml(G, subgraph_file)
     elif file_format == "gpickle":
         nx.write_gpickle(G, subgraph_file)
     else:
         print "File format not found, writing graphml."
         nx.write_graphml(G, subgraph_file)