Esempio n. 1
0
	def __save_composed(self):
		alist = nx.generate_adjlist(self.__composed_graph)
		with open('data/'+self.__prefix+'_composed_graph.csv', 'wb') as f:
			writer = csv.writer(f, delimiter=' ',quotechar='|', \
				quoting=csv.QUOTE_MINIMAL)
			for x in alist:
				writer.writerow(x.split())
    def _get_dreadnaught_for_graph(self,graph):
        """
        Constructs a representation of the adjacency structure of the graph in the format
        that dreadnaught/nauty understands.  This employs the networkx "adjlist" format but
        extends it slightly.

        Only adjacency information is preserved in this format -- no additional vertex or edge
        attributes, so "primary" storage of graphs should use the GraphML format.

        """
        linefeed = chr(10)
        n = graph.number_of_nodes()
        dn = "n="
        dn += str(n)
        dn += ' g'
        dn += linefeed
        for line in nx.generate_adjlist(graph):
            edges = line.split()
            #if len(edges) == 1:
            #    dn += ';\n'

            if len(edges) == 1:
                dn += ";"
                dn += linefeed
            else:
                dn += " ".join(edges[1:])
                dn += ";"
                dn += linefeed
        dn += 'x o';
        dn += linefeed
        return dn
def convert_to_csv(graph,
                   c_obj,
                   c_nodes,
                   output_path=config.path,
                   adj_mat=False):
    if adj_mat:
        df_matrix = nx.to_pandas_adjacency(graph, dtype=np.uint8)
        df_matrix.to_csv(output_path + 'Adj_matrix_bbike_map.csv', index=False)

    adj_list = list(nx.generate_adjlist(graph))
    df_list = pd.DataFrame(adj_list, columns=['row'])
    df_list = pd.DataFrame(df_list.row.str.split(' ').tolist())
    df_list = df_list.rename(columns={0: 'Source'})
    df_list.to_csv(output_path + 'Adj_list_bbike_map.csv', index=False)
    df_nodes = pd.DataFrame(dict(graph.nodes(data=True))).T
    df_nodes.to_csv(output_path + 'All.csv', index=False)
    to_dict_nodes = df_nodes.loc[df_nodes['osmid'].isin(c_nodes)]
    to_dict_nodes.to_csv(output_path + 'Nodes_bbike_map.csv', index=False)
    to_dict_objects = df_nodes.loc[df_nodes['osmid'].isin(c_obj)]
    to_dict_objects.to_csv(output_path + 'Objects_bbike_map.csv', index=False)
    adj_list = pd.read_csv(output_path + 'Adj_list_bbike_map.csv')
    df_graph = df_nodes.merge(adj_list, left_on='osmid', right_on='Source')
    adj = df_graph.iloc[:, 6:].to_numpy()
    adj = [node[~pd.isnull(node)] for node in adj]
    df_graph['adj'] = adj
    df_graph = df_graph[['osmid', 'x', 'y', 'weight',
                         'adj']].set_index('osmid')

    with open(output_path + 'Chel_simp.pickle', 'wb') as f:
        pickle.dump(graph, f)

    return df_graph
Esempio n. 4
0
def prep_input_dynTriad(graphs, length, dataname):
    if not os.path.exists(outdir):
        os.mkdir(outdir)
    dirname = outdir + '/' + dataname

    if not os.path.exists(dirname):
        os.mkdir(dirname)

    dirname = dirname + '/' + 'dynTriad'

    if not os.path.exists(dirname):
        os.mkdir(dirname)

    for i in range(length):
        G = graphs[i]

        outName = dirname + '/' + str(i)

        with open(outName, "w") as text_file:

            for i, adj in enumerate(nx.generate_adjlist(G)):

                text_file.write(str(i))
                for nodes in adj.split(" "):
                    weight = 1.0
                    text_file.write(" ")
                    text_file.write(str(nodes))
                    text_file.write(" ")
                    text_file.write(str(weight))
                text_file.write("\n")
    return os.path.abspath(dirname)
Esempio n. 5
0
        def makeEnoughBuses():
            priorityDict = {}
            adjlist = list(nx.generate_adjlist(graph))
            for lst in adjlist:
                key = lst.split(' ')[0]
                #all of the following are needed to calculate the priority
                friendsInGraph = len(lst.split(
                    ' ')) - 1  #total number of friends remaining in the Graph
                priority = friendsInGraph
                priorityDict[key] = priority

            #add dictionary entries to a priority queue
            PQ = Q.PriorityQueue()
            tiebreaker = 0  #arbitrary counter to break ties if entries have the same priority
            for key in priorityDict.keys():
                entry = (priorityDict[key], tiebreaker, key)
                PQ.put(entry)
                tiebreaker += 1

            for bus in buses:
                if len(bus) == 0:
                    student = PQ.get()[2]
                    for bus in buses:
                        if student in bus:
                            bus.remove(student)
                    bus.append(student)
Esempio n. 6
0
def hamilton_cycle(graph):
    startVertex = list(nx.nodes(graph))[0]  #стартовая вершина
    N = list()  #список вершин смежных с текущей вершиной
    #ребро между которыми еще не рассматривалось
    cycle = list()  #текущий список вершин в цикле
    cycle.append(startVertex)

    for line in nx.generate_adjlist(graph):  #генерирум список смежных вершин
        N.append(list(line.replace(' ', '')))

    for elem in N:
        for i in range(len(elem)):
            elem[i] = int(elem[i])

    while (len(cycle) != 0):
        x = cycle.pop()  #
        cycle.append(x)  # top()
        if (len(N[x]) != 0):
            y = N[x].pop()
            if (not (y in cycle)):
                cycle.append(y)
                if (len(cycle) == nx.number_of_nodes(graph)):
                    if (startVertex in N[cycle.pop()]):
                        return cycle
                    elif (len(cycle) == nx.number_of_nodes(graph)):
                        cycle.pop()
        else:
            cycle.pop()
    return False
def adjlist_display(G):
    print("Generating adjacency list...\n")
    adj_list = nx.generate_adjlist(
        G, delimiter='->')  # Generate the adjacency list
    print("Writing adjacency list to output file...\n")
    f = open("Output Text Files\Graph_AdjList.txt",
             "w")  # File to save the adjacency list to
    # Write the adjacency list to the file
    for data in adj_list:
        f.write(str(data) + '\n')
    f.close()  # Close the file
    print("Showing the Adjacency List:")
    # Display the adjacency list
    for line in nx.generate_adjlist(G, delimiter='->'):
        print(str(line))
    print()
    def _get_dreadnaught_for_graph(self, graph):
        """
        Constructs a representation of the adjacency structure of the graph in the format
        that dreadnaught/nauty understands.  This employs the networkx "adjlist" format but
        extends it slightly.

        Only adjacency information is preserved in this format -- no additional vertex or edge
        attributes, so "primary" storage of graphs should use the GraphML format.

        """
        linefeed = chr(10)
        n = graph.number_of_nodes()
        dn = "n="
        dn += str(n)
        dn += ' g'
        dn += linefeed
        for line in nx.generate_adjlist(graph):
            edges = line.split()
            #if len(edges) == 1:
            #    dn += ';\n'

            if len(edges) == 1:
                dn += ";"
                dn += linefeed
            else:
                dn += " ".join(edges[1:])
                dn += ";"
                dn += linefeed
        dn += 'x o'
        dn += linefeed
        return dn
Esempio n. 9
0
	def __save_layer(self, graph, layer):
		alist = nx.generate_adjlist(graph)

		with open('data/'+self.__prefix+'_'+str(layer)+'_graph.csv', 'wb') as f:
			writer = csv.writer(f, delimiter=' ',quotechar='|', \
				quoting=csv.QUOTE_MINIMAL)
			for x in alist:
				writer.writerow(x.split())
Esempio n. 10
0
 def write_data(self, path, stored_users=None):
     if (stored_users == None):
         stored_users = []
     with open(path, 'w', encoding='utf-8') as f:
         for line in nx.generate_adjlist(self.__dg):
             username = line[0]
             if username not in stored_users:
                 f.write(line + '\n')
Esempio n. 11
0
def print_edges(g):
    """
    Print all edges in the graph
    For testing.
    """
    logging.debug("print_edges function called.")
    for line in nx.generate_adjlist(g):
        print(line)
Esempio n. 12
0
def random_network(nodes):
    n = Network(nx.erdos_renyi_graph(nodes, 0.15))
    print(
        "\n# ---------------------------- Network : ----------------------------- #"
    )
    for line in nx.generate_adjlist(n.graph):
        print(" " * 4 + line.split()[0] + " → " + " - ".join(line.split()[1:]))
    return n
Esempio n. 13
0
    def toBSON(self):
        doc = {
            "seed_id": bson.int64.Int64(self.seed_id),
            "params": self.params,
            "adj_list": list(nx.generate_adjlist(self.graph))
        }

        return doc
Esempio n. 14
0
def dis_graph(graph):
    # print the adjacency list
    for line in nx.generate_adjlist(graph):
        print(line)

    # write edgelist to grid.edgelist
    nx.write_edgelist(graph, path="grid.edgelist", delimiter=" ")

    # read edgelist from grid.edgelist
    H = nx.read_edgelist(path="grid.edgelist", delimiter=" ")

    nx.draw(H)
    plt.show()
    nx.write_edgelist(graph, "connected_componets.csv", delimiter=",")
Esempio n. 15
0
def constructPreferentialAttachmentGraph(num_nodes, num_edges_per_node):
    graph = nx.barabasi_albert_graph(num_nodes, num_edges_per_node)
    adj_list = nx.generate_adjlist(graph)

    new_graph = {}
    for vertex in range(num_nodes): 
        new_graph[vertex] = []

    for line in adj_list:
        values = line.split()
        vertex = int(values[0])
        values.pop(0)
        for node in values:
            new_graph[vertex].append(int(node))
            new_graph[int(node)].append(vertex)

    return new_graph, num_nodes
Esempio n. 16
0
    def __dump_graph(self, directory):

        with open(directory.joinpath('adjedges.txt'), 'w') as docs:
            for line in nx.generate_adjlist(self.graph):
                if self.graph.nodes[int(line.split()[0])]['is_main']:
                    docs.write(f'{line}\n')

        texts = [t.replace('\n', ' ') for t in self.features]

        with open(directory.joinpath('docs.txt'), 'w') as docs:
            for _id, text in zip(self.graph.nodes(), texts):
                if self.graph.nodes[_id]['is_main']:
                    docs.write(f'{_id} {text}\n')

        with open(directory.joinpath('labels.txt'), 'w') as docs:
            for _id, label in zip(self.graph.nodes(), self.labels):
                if self.graph.nodes[_id]['is_main']:
                    docs.write(f'{_id} {label}\n')
Esempio n. 17
0
	def __init__(self,layout):

		'''
			Initialize the class with layout name
			(layout name is the name of the file without .rndf extesion
			only 'spiral' is the file name is spiral.rndf)
		'''

		self.layout = layout

		# load all the segments into a dictionary 
		rndf = segmentsDict('src/{}.rndf'.format(self.layout))
		a = rndf.dict()

		# load all the waypoints into a dictionary
		rndfwp = waypointsDict('src/{}.rndf'.format(self.layout))
		self.wpd = rndfwp.dict()

		self.bezsegs = []

		# crate a graph to generate the adjacency list
		graph = nx.DiGraph()
		for k,v in a.items():
			# print v
			seg = rndfSegments(v)
			seg.info()
			ld = seg.laneDict()
			for key,val in ld.items():
				lane = rndfLanes(val)
				lane.info()
				lwpd = lane.waypointDict
				wpk = lwpd.keys()
				for i in range(len(wpk)-1):
					graph.add_edge(wpk[i],wpk[i+1])
				for exitpoint in lane.exitPoints:
					graph.add_edge(exitpoint[0],exitpoint[1])

		self.adjacencyList = {}
		for t in nx.generate_adjlist(graph):
			adl = t.split()
			key = adl[0]
			val = adl[1:]
			self.adjacencyList[key] = val
Esempio n. 18
0
 def store_user_friends_graph(self, user, graph):
     adj_list = [item for item in nx.generate_adjlist(graph)]
     
     # Note: we only want to store one social graph per user
     user_doc = self.user_friends_graph_collection.find_one({
         'user': user
     })
     
     if user_doc:
         # Update adj list
         user_doc['adj_list'] = adj_list
         self.user_friends_graph_collection.replace_one({
             'user': user
         }, user_doc)
     else:
         self.user_friends_graph_collection.insert_one({
             'user': user, 
             'adj_list': adj_list
         })
Esempio n. 19
0
    def display_network_system(self, master, canvas, network):
        self.x = 200  # self.node_start_x
        self.y = self.network_frame_height / 2
        # self.direction = "NE"
        self.nodes_id = {}
        self.nodes_covered = {}
        self.coordinates_occupied = []
        self.node_names_dictionary = {}
        # self.create_nodes_on_canvas(master,canvas,network)
        # self.display_rings(network, canvas)
        for line in nx.generate_adjlist(network.topology.graph, delimiter=","):
            node_list = line.split(",")
            print(node_list)
            node0 = node_list[0]  ##### node0 is node object in the string form
            print("here new node is ", node0)
            if node0 not in self.nodes_covered.keys():
                direction = 0
                node0_id = self.create_new_node(
                    canvas, network.topology.node_objects[node0]
                )  # , direction)  # ,radius=0)
                self.nodes_covered[
                    node0] = node0_id  # node_id is the node id returned create_oval function of canvas
                self.node_names_dictionary[node0_id] = node0
                # self.x,self.y=
                # self.next_node_coordinates()

            else:
                node0_id = self.nodes_covered[node0]
            for node1 in node_list[1:]:
                if node1 not in self.nodes_covered.keys():
                    direction = network.topology.node_objects[
                        node0].direction  # self.node_direction[node0]
                    node1_id = self.create_new_node(
                        canvas, network.topology.node_objects[node1]
                    )  # , direction)  # ,radius=0)
                    self.nodes_covered[node1] = node1_id
                    self.node_names_dictionary[node1_id] = node1
                    # self.x,self.y=\
                    # self.next_node_coordinates()

                else:
                    node1_id = self.nodes_covered[node1]
                self.create_edge(canvas, node0_id, node1_id)
Esempio n. 20
0
def measure_neighbors(g, metric, method):
    for county in nx.generate_adjlist(g, delimiter="|"):
        split_county = county.split("|")
        if g.nodes[split_county[0]].get(metric, -1) > 0:
            neighbor_metrics = [
                g.nodes[neighbor].get(metric, None)
                for neighbor in split_county[1:]
            ]
            if method == 'abs_dist':
                neighbor_metrics = [abs(g.nodes[split_county[0]][metric] - \
                    neighbor_value) for neighbor_value in filter(None, neighbor_metrics)]
            elif method == 'raw_dist':
                # neighbor_metrics = []
                neighbor_metrics = [g.nodes[split_county[0]][metric] - \
                    neighbor_value for neighbor_value in filter(None, neighbor_metrics)]
            g.nodes[split_county[0]]['{}_{}'.format(
                method,
                metric)] = sum(neighbor_metrics) / len(neighbor_metrics)
    return g
Esempio n. 21
0
def generate_output(graph, output_format, filename):
    """
    Send the graph to console as adjacency list text, or to a file in a specified format.
    :param graph: The networkX graph object
    :param output_format: how to format the output graph data
    :param filename: the file to write to. if output_format is None, then this is ignored.
    :return:
    """
    def _get_output_funcs_list():
        """
        get a sequence of conversion functions.
        :return: list of conversion functions.
        """
        return [
            convert_graph_to_text, convert_graph_to_graphml,
            convert_graph_to_gml, convert_graph_to_gexf, convert_graph_to_yaml
        ]

    if output_format is None:
        for text in networkx.generate_adjlist(graph):

            print(text)
    elif output_format not in OUTPUT_FORMATS:
        raise RuntimeError(
            """Error in generate_output(g, o, f): 'o' has an unrecognised value.
                           value of 'o'=""" + output_format)
    else:
        # temporary mapping of format codes to formatter funcs.
        output_funcs = _get_output_funcs_list()
        output_mapping = dict()
        for index in range(len(OUTPUT_FORMATS)):
            try:
                output_mapping[OUTPUT_FORMATS[index]] = output_funcs[index]
            # do not test: exists as catch
            except IndexError:  # pragma: no cover
                break
        # now convert to the format and write to file.
        output_mapping[output_format](graph, filename)
    return
def generate_output(graph, output_format, filename):
    """
    Send the graph to console as adjacency list text, or to a file in a specified format.
    :param graph: The networkX graph object
    :param output_format: how to format the output graph data
    :param filename: the file to write to. if output_format is None, then this is ignored.
    :return:
    """

    def _get_output_funcs_list():
        """
        get a sequence of conversion functions.
        :return: list of conversion functions.
        """
        return [convert_graph_to_text, convert_graph_to_graphml, convert_graph_to_gml,
                convert_graph_to_gexf, convert_graph_to_yaml]

    if output_format is None:
        for text in networkx.generate_adjlist(graph):

            print(text)
    elif output_format not in OUTPUT_FORMATS:
        raise RuntimeError("""Error in generate_output(g, o, f): 'o' has an unrecognised value.
                           value of 'o'=""" + output_format)
    else:
        # temporary mapping of format codes to formatter funcs.
        output_funcs = _get_output_funcs_list()
        output_mapping = dict()
        for index in range(len(OUTPUT_FORMATS)):
            try:
                output_mapping[OUTPUT_FORMATS[index]] = output_funcs[index]
            # do not test: exists as catch
            except IndexError:      # pragma: no cover
                break
        # now convert to the format and write to file.
        output_mapping[output_format](graph, filename)
    return
Esempio n. 23
0
======================

Read and write graphs.
"""
# Author: Aric Hagberg ([email protected])

#    Copyright (C) 2004-2019 by
#    Aric Hagberg <*****@*****.**>
#    Dan Schult <*****@*****.**>
#    Pieter Swart <*****@*****.**>
#    All rights reserved.
#    BSD license.

import sys

import matplotlib.pyplot as plt
import networkx as nx

G = nx.grid_2d_graph(5, 5)  # 5x5 grid

# print the adjacency list
for line in nx.generate_adjlist(G):
    print(line)
# write edgelist to grid.edgelist
nx.write_edgelist(G, path="grid.edgelist", delimiter=":")
# read edgelist from grid.edgelist
H = nx.read_edgelist(path="grid.edgelist", delimiter=":")

nx.draw(H)
plt.show()
Esempio n. 24
0
def draw_3d_network(networkx_object, file_name, mode):
    '''take networkX object and draw it in 3D'''
    Edges = list(networkx_object.edges)
    L=len(Edges)
    distance_list = [distance[2] for distance in list(networkx_object.edges.data("distance"))]
    weight_list = [int(float(weight[2])) for weight in list(networkx_object.edges.data("weight"))]
    labels= list(networkx_object.nodes)
    N = len(labels)
    adjc= [len(one_adjc) for one_adjc in list((nx.generate_adjlist(networkx_object)))] ### instead of "group"
    pos_3d=nx.spring_layout(networkx_object, weight="weight", dim=3)
    nx.set_node_attributes(networkx_object, pos_3d, "pos_3d")
    layt = [list(array) for array in pos_3d.values()]
    N= len(networkx_object.nodes)
    Xn=[layt[k][0] for k in range(N)]# x-coordinates of nodes
    Yn=[layt[k][1] for k in range(N)]# y-coordinates
    Zn=[layt[k][2] for k in range(N)]# z-coordinates
    Xe=[]
    Ye=[]
    Ze=[]
    for Edge in Edges:
        Xe+=[networkx_object.nodes[Edge[0]]["pos_3d"][0],networkx_object.nodes[Edge[1]]["pos_3d"][0], None]# x-coordinates of edge ends
        Ye+=[networkx_object.nodes[Edge[0]]["pos_3d"][1],networkx_object.nodes[Edge[1]]["pos_3d"][1], None]
        Ze+=[networkx_object.nodes[Edge[0]]["pos_3d"][2],networkx_object.nodes[Edge[1]]["pos_3d"][2], None]

        ### to get the hover into the middle of the line
        ### we have to produce a node in the middle of the line
        ### based on https://stackoverflow.com/questions/46037897/line-hover-text-in-plotly

    middle_node_trace = go.Scatter3d(
            x=[],
            y=[],
            z=[],
            opacity=0,
            text=weight_list,
            mode='markers',
            hoverinfo='text',
            marker=dict(
                opacity=0
            )
        )

    for Edge in Edges:

        x0,y0,z0 = networkx_object.nodes[Edge[0]]["pos_3d"]
        x1,y1,z1 = networkx_object.nodes[Edge[1]]["pos_3d"]
        ###trace3['x'] += [x0, x1, None]
        ###trace3['y'] += [y0, y1, None]
        ###trace3['z'] += [z0, z1, None]
        ###trace3_list.append(trace3)
        middle_node_trace['x'] += tuple([(x0+x1)/2])
        middle_node_trace['y'] += tuple([(y0+y1)/2])#.append((y0+y1)/2)
        middle_node_trace['z'] += tuple([(z0+z1)/2])#.append((z0+z1)/2)
        

    ### edge trace
    trace1=go.Scatter3d(x=Xe,
                       y=Ye,
                       z=Ze,
                       mode='lines',
                       line=dict(color='rgb(125,125,125)', width=1),
                       text=distance_list,
                       hoverinfo='text',
                       textposition="top right"
                       )
    ### node trace
    trace2=go.Scatter3d(x=Xn,
                       y=Yn,
                       z=Zn,
                       mode='markers+text',
                       ###name=labels,
                       marker=dict(symbol='circle',
                                     size=6,
                                     color=adjc,
                                     colorscale='Earth',
                                     reversescale=True,
                                     line=dict(color='rgb(50,50,50)', width=0.5)
                                     ),
                       text=[],
                       #textposition='bottom center',
                       #hovertext=adjc,
                       #hoverinfo='text'
                       )
    for node in networkx_object.nodes():
        trace2["text"] += tuple([node])
    
    axis=dict(showbackground=False,
                  showline=False,
                  zeroline=False,
                  showgrid=False,
                  showticklabels=False,
                  title=''
                  )
    layout = go.Layout(
                plot_bgcolor='rgba(0,0,0,0)',
                 title="",
                 width=900,
                 height=700,
                 showlegend=False,
                 scene=dict(
                     xaxis=dict(axis),
                     yaxis=dict(axis),
                     zaxis=dict(axis),
                ),
             margin=dict(
                t=100
            ),
            hovermode='closest',
            annotations=[
                   dict(
                   showarrow=False,
                    text="",
                    xref='paper',
                    yref='paper',
                    x=0,
                    y=0.1,
                    xanchor='left',
                    yanchor='bottom',
                    font=dict(
                    size=14
                    )
                    )
                ],    )
    data=[trace1, trace2, middle_node_trace]
    fig=go.Figure(data=data, layout=layout)
    if mode=="offline":
        return iplot(fig) ###, filename=file_name+".html")
    if mode=="online":
        return iplot(fig, filename=file_name)
    if mode=="eps":
        return pio.write_image(fig, "images/" + file_name + "_3D.eps" , scale=1)
Esempio n. 25
0
# for i in range(start_p, end_p, steps):
i = int(sys.argv[1])
rep_p = int(sys.argv[2])
size = int(sys.argv[3])

# open('list.txt', 'w').close()
with open("list.txt", "a+") as file:
    file.write(str(rep_p - 1) + " " + str(size) + '\n')
    for j in range(1, rep_p):
        if int(sys.argv[4]) == 1:
            G = nx.gnp_random_graph(size, i / 100.0, seed=None, directed=False)
        elif int(sys.argv[4]) == 2:
            G = nx.fast_gnp_random_graph(size,
                                         i / 100.0,
                                         seed=None,
                                         directed=False)
        adjlist = nx.generate_adjlist(G)
        for row in adjlist:
            file.write(row + '\n')
        file.write('\n')

        # plt.subplot(121)
        # nx.draw(G, with_labels=True, font_weight='bold')
        # plt.subplot(122)
        # nx.draw_shell(G, nlist=[range(5, 10), range(5)], with_labels=True, font_weight='bold')
        # plt.show()

    with open("out.txt", "a+") as file2:
        file2.write(str(float(i / 100.0)) + ',')
Esempio n. 26
0
of the graph created.
"""

import networkx as nx
from keyname import keyname as kn

dims = [3, 4, 7, 10]


def make_filename(dim):
    return kn.pack({
        'name': 'dyadic',
        'ndims': '1',
        'dim0': str(dim),
        'ext': '.adj',
    })


for dim in dims:
    if dim % 2:
        procon = [(i, i + 1)
                  for i in range(0, dim - 1, 2)] + [(dim - 1, dim - 1)]
    else:
        procon = [(i, i + 1) for i in range(0, dim, 2)]

    G_dyatic = nx.Graph(procon).to_directed()

    with open("assets/" + make_filename(dim), "w") as file:
        for line in nx.generate_adjlist(G_dyatic):
            file.write(line + '\n')
Esempio n. 27
0
def print_g(G):
	for line in nx.generate_adjlist(G):
		print line
	print ""
Esempio n. 28
0
def draw_2d_network(networkx_object, width=500, height=500, fontsize=14):
    '''take networkX object and draw it'''
    pos_2d = nx.kamada_kawai_layout(networkx_object, weight="weight_norm")
    nx.set_node_attributes(networkx_object, pos_2d, "pos_2d")
    dmin = 1
    ncenter = 0
    Edges = list(networkx_object.edges)
    L = len(Edges)
    labels = list(networkx_object.nodes)
    N = len(labels)
    distance_list = [
        float(distance[2])
        for distance in list(networkx_object.edges.data("distance"))
    ]
    weight_list = [
        int(float(weight[2]))
        for weight in list(networkx_object.edges.data("weight"))
    ]
    for n in pos_2d:
        x, y = pos_2d[n]
        d = (x - 0.5)**2 + (y - 0.5)**2
        if d < dmin:
            ncenter = n
            dmin = d
    p = nx.single_source_shortest_path_length(networkx_object, ncenter)
    adjc = list(dict(networkx_object.degree()).values())
    middle_node_trace = go.Scatter(x=[],
                                   y=[],
                                   opacity=0,
                                   text=weight_list,
                                   mode='markers',
                                   hoverinfo='text',
                                   marker=dict(opacity=0))
    for Edge in Edges:
        x0, y0 = networkx_object.nodes[Edge[0]]["pos_2d"]
        x1, y1 = networkx_object.nodes[Edge[1]]["pos_2d"]
        middle_node_trace['x'] += tuple([(x0 + x1) / 2])
        middle_node_trace['y'] += tuple([(y0 + y1) / 2])
    edge_trace1 = go.Scatter(
        x=[],
        y=[],
        #hoverinfo='none',
        mode='lines',
        line=dict(width=4, color="#000000"),
    )
    edge_trace2 = go.Scatter(
        x=[],
        y=[],
        #hoverinfo='none',
        mode='lines',
        line=dict(width=2, color="#404040"),
    )
    edge_trace3 = go.Scatter(
        x=[],
        y=[],
        #hoverinfo='none',
        mode='lines',
        line=dict(width=1, color="#C0C0C0"),
    )
    best_5percent_norm_weight = sorted(
        list(networkx_object.edges.data("norm_weight")),
        key=lambda x: x[2],
        reverse=True)[int(
            (len(networkx_object.edges.data("norm_weight")) / 100) * 5)][2]
    best_20percent_norm_weight = sorted(
        list(networkx_object.edges.data("norm_weight")),
        key=lambda x: x[2],
        reverse=True)[int(
            (len(networkx_object.edges.data("norm_weight")) / 100) * 20)][2]
    for edge in networkx_object.edges.data():
        if edge[2]["norm_weight"] >= best_5percent_norm_weight:
            x0, y0 = networkx_object.nodes[edge[0]]['pos_2d']
            x1, y1 = networkx_object.nodes[edge[1]]['pos_2d']
            edge_trace1['x'] += tuple([x0, x1, None])
            edge_trace1['y'] += tuple([y0, y1, None])
        else:
            if edge[2]["norm_weight"] >= best_20percent_norm_weight:
                x0, y0 = networkx_object.nodes[edge[0]]['pos_2d']
                x1, y1 = networkx_object.nodes[edge[1]]['pos_2d']
                edge_trace2['x'] += tuple([x0, x1, None])
                edge_trace2['y'] += tuple([y0, y1, None])
            else:
                x0, y0 = networkx_object.nodes[edge[0]]['pos_2d']
                x1, y1 = networkx_object.nodes[edge[1]]['pos_2d']
                edge_trace3['x'] += tuple([x0, x1, None])
                edge_trace3['y'] += tuple([y0, y1, None])

    node_trace = go.Scatter(
        x=[],
        y=[],
        #name=[],
        text=[],
        textposition='bottom center',
        textfont_size=fontsize,
        mode='markers+text',
        hovertext=adjc,
        hoverinfo='text',
        marker=dict(
            ###showscale=True,
            showscale=False,  ### change to see scale
            colorscale='Greys',
            #reversescale=True,
            color=[],
            size=15,
            colorbar=dict(thickness=30,
                          title='degree',
                          xanchor='left',
                          titleside='right'),
            line=dict(width=1.5)))

    for node in networkx_object.nodes():
        x, y = networkx_object.nodes[node]['pos_2d']
        node_trace['x'] += tuple([x])
        node_trace['y'] += tuple([y])
        node_trace["text"] += tuple([node])
        ### original version: node_trace["text"] += tuple([node])

    ### Color Node Points
    for node, adjacencies in enumerate(nx.generate_adjlist(networkx_object)):
        node_trace['marker']['color'] += tuple([len(adjacencies)])
        ###node_info = ' of connections: '+str(len(adjacencies))
        ###node_trace['something'].append(node_info)

    fig = go.Figure(
        data=[
            edge_trace1, edge_trace2, edge_trace3, node_trace,
            middle_node_trace
        ],
        layout=go.Layout(
            plot_bgcolor='rgba(0,0,0,0)',
            autosize=False,
            width=width,
            height=height,
            #title=file_name,
            titlefont=dict(size=16),
            showlegend=False,
            hovermode='closest',
            margin=dict(b=10, l=10, r=10, t=10),
            xaxis=dict(range=[-1.15, 1.05],
                       showgrid=False,
                       zeroline=False,
                       showticklabels=False),
            yaxis=dict(range=[-1.15, 1.05],
                       showgrid=False,
                       zeroline=False,
                       showticklabels=False)))
    return fig
Esempio n. 29
0
def all_simple_path(g, host1, host2):
    return cached_all_simple_path(";".join(list(nx.generate_adjlist(g))), host1, host2)
Esempio n. 30
0
This script makes use of NetworkX to generate
ring graphs (nodes are connected in a ring).

This tool creates adjacency list files (.adj)
whose filename represent the characteristics
of the graph created.
"""

import networkx as nx
from keyname import keyname as kn

dims = [3, 10, 15, 27, 56, 99]


def make_filename(dim):
    return kn.pack({
        'name': 'ring',
        'ndims': '1',
        'dim0': str(dim),
        'ext': '.adj',
    })


for dim in dims:
    ring = [edge for edge in zip(range(dim), range(1, dim))] + [(dim - 1, 0)]
    G_ring = nx.DiGraph(ring)

    with open("assets/" + make_filename(dim), "w") as file:
        for line in nx.generate_adjlist(G_ring):
            file.write(line + '\n')
]


def make_filename(dim):
    return kn.pack({
        'name': 'navigable_small_world',
        'ndims': '1',
        'dim0': str(dim),
        'ext': '.adj',
    })


for dim in dims:

    G = nx.generators.geometric.navigable_small_world_graph(
        dim,
        seed=1,
        dim=1,
    )

    # relabel nodes to numeric indices from previous coordinate labels
    H = nx.relabel_nodes(
        G,
        {label: idx
         for idx, label in enumerate(G.nodes())},
    )

    with open("assets/" + make_filename(dim), "w") as file:
        for line in nx.generate_adjlist(H):
            file.write(line + '\n')
Esempio n. 32
0
"""Generate loop graphs.

This script makes use of NetworkX to generate
complete graphs (each node connected to all others).

This tool creates adjacency list files (.adj)
whose filename represent the characteristics
of the graph created.
"""

import networkx as nx
import matplotlib.pyplot as plt
from keyname import keyname as kn

dims = [3, 10, 15, 27, 56, 99]

def make_filename(dim):
    return kn.pack({
        'name'  : 'complete',
        'ndims' : '1',
        'dim0'  : str(dim),
        'ext'   : '.adj',
    })

for dim in dims:
    G_complete = nx.complete_graph(dim, nx.DiGraph())

    with open("assets/" + make_filename(dim), "w") as file:
        for line in nx.generate_adjlist(G_complete):
            file.write(line + '\n')
Esempio n. 33
0
#Graph1 is a directed graph
node_list1 = [2,3,5,7,8,9,10,11]
edges_list1 = [(3,8),(3,10),(5,11),(7,11),(7,8),(8,9),(11,2),(11,9),(11,10)]

#Creating Directed Graph  
print "*************"
print "Graph1"
print "*************"
G1=nx.DiGraph()
G1.add_nodes_from(node_list1)
G1.add_edges_from(edges_list1)
print "Adjacency Matrix for Graph1:"
print nx.adjacency_matrix(G1)
print "\nAdjacency List for Graph1:"
for line in nx.generate_adjlist(G1,delimiter=','):
    print line
print "\nMy own representation of Adjacency List for Graph1:"
for line in nx.generate_adjlist(G1, ):
    print"{}===>{}".format(line.strip().split()[0], line.strip().split()[1:])
print "\nAnother representation of Graph1:"
for n,adj_nodes in G1.adjacency_iter():
    print "{}, {}".format(n,adj_nodes.keys())
#drawing graph using matplotlib    
nx.draw(G1)
plt.draw()
plt.savefig("graph1.png")
plt.close()

#Graph2 is an undirected graph
print "\n\n"
Esempio n. 34
0
# To Run this script: python run_generate_adjlist_largestcomponent.py

import networkx as nx
import matplotlib.pyplot as plt
import sys
from matplotlib.legend_handler import HandlerLine2D
from matplotlib.font_manager import FontProperties

x = int(sys.argv[1])
year = []
largestcomponent = []

fh=open("../data/adjlistfile_till_year_"+str(x))
G = nx.read_adjlist(fh, create_using=nx.DiGraph())
G = G.to_undirected()
#print "Year "+str(x)+":"
#print "Number of nodes:", G.number_of_nodes()
#print "Number of isolates:", len(nx.isolates(G))
G.remove_nodes_from(nx.isolates(G))
#print "Number of nodes after removing isolates:", G.number_of_nodes()
components = sorted(nx.connected_components(G), key = len, reverse=True)
largestcomponent = G.subgraph(components[0])
year.append(x)

for line in nx.generate_adjlist(largestcomponent):
	print(line)
Esempio n. 35
0
def to_adj(net):
    return '\n'.join(nx.generate_adjlist(net))
Esempio n. 36
0
def nx_to_adj_list(nx_obj):
    # generate adjacency list
    adj_list = nx.generate_adjlist(nx_obj, delimiter=' ')

    return adj_list
Esempio n. 37
0
from keyname import keyname as kn

dims = [[1, 1], [2, 2], [3, 3], [8, 8], [9, 9]]


def make_filename(dims):
    pack = {
        **{
            'name': 'toroidal_grid',
            'ndims': len(dims),
            'ext': '.adj',
        },
        **{'dim' + str(i): dim
           for i, dim in enumerate(dims)},
    }

    return kn.pack(pack)


for dim in dims:
    G_torus = nx.grid_graph(dim=dim, periodic=True).to_directed()

    nodes = sorted(list(G_torus.nodes()))
    map = {edge: idx for idx, edge in enumerate(nodes)}

    nx.relabel_nodes(G_torus, mapping=map, copy=False)

    with open("assets/" + make_filename(dim), "w") as file:
        for line in nx.generate_adjlist(G_torus):
            file.write(line + '\n')