Showing posts with label networkx. Show all posts
Showing posts with label networkx. Show all posts

Sunday, October 1, 2017

How to set individual line widths in network-style Plotly figure (Python 3.6 | plot.ly)?

Leave a Comment

I'm working on a plot.ly wrapper for my networkx plots adapted from https://plot.ly/python/network-graphs/. I can't figure out how to change the width for each connection based on the weights. The weights are in the attr_dict as weight. I tried setting go.Line objects but it wasn't working :(. Any suggestions? (and links to tutorials if possible :) ). Attaching an example of the network structure from a plot I made in matplotlib.

How can I set individual line widths for each connection in plotly?

enter image description here

import requests from ast import literal_eval import plotly.offline as py from plotly import graph_objs as go py.init_notebook_mode(connected=True)  # Import Data pos = literal_eval(requests.get("https://pastebin.com/raw/P5gv0FXw").text) df_plot = pd.DataFrame(pos).T df_plot.columns = list("xy") edgelist = literal_eval(requests.get("https://pastebin.com/raw/2a8ErW7t").text) _fig_kws={"figsize":(10,10)}  # Plotting Function def plot_networkx_plotly(df_plot, pos, edgelist, _fig_kws):     # Nodes     node_trace = go.Scattergl(                          x=df_plot["x"],                          y=df_plot["y"],                          mode="markers",     )     # Edges     edge_trace = go.Scattergl(                          x=[],                           y=[],                          line=[],                          mode="lines"     )      for node_A, node_B, attr_dict in edgelist:         xA, yA = pos[node_A]         xB, yB = pos[node_B]         edge_trace["x"] += [xA, xB, None]         edge_trace["y"] += [yA, yB, None]         edge_trace["lines"].append(go.Line(width=attr_dict["weight"],color='#888'))      # Data     data = [node_trace, edge_trace]     layout = {                 "width":_fig_kws["figsize"][0]*100,                 "height":_fig_kws["figsize"][1]*100,      }     fig = dict(data=data, layout=layout)      py.iplot(fig)     return fig plot_networkx_plotly(df_plot, pos, edgelist, _fig_kws)  # --------------------------------------------------------------------------- # PlotlyDictValueError                      Traceback (most recent call last) # <ipython-input-72-4a5d0e26a71d> in <module>() #      46     py.iplot(fig) #      47     return fig # ---> 48 plot_networkx_plotly(df_plot, pos, edgelist, _fig_kws)  # <ipython-input-72-4a5d0e26a71d> in plot_networkx_plotly(df_plot, pos, edgelist, _fig_kws) #      25                          y=[], #      26                          line=[], # ---> 27                          mode="lines" #      28     ) #      29   # ~/anaconda/lib/python3.6/site-packages/plotly/graph_objs/graph_objs.py in __init__(self, *args, **kwargs) #     375         d = {key: val for key, val in dict(*args, **kwargs).items()} #     376         for key, val in d.items(): # --> 377             self.__setitem__(key, val, _raise=_raise) #     378  #     379     def __dir__(self):  # ~/anaconda/lib/python3.6/site-packages/plotly/graph_objs/graph_objs.py in __setitem__(self, key, value, _raise) #     430  #     431         if self._get_attribute_role(key) == 'object': # --> 432             value = self._value_to_graph_object(key, value, _raise=_raise) #     433             if not isinstance(value, (PlotlyDict, PlotlyList)): #     434                 return  # ~/anaconda/lib/python3.6/site-packages/plotly/graph_objs/graph_objs.py in _value_to_graph_object(self, key, value, _raise) #     535             if _raise: #     536                 path = self._get_path() + (key, ) # --> 537                 raise exceptions.PlotlyDictValueError(self, path) #     538             else: #     539                 return  # PlotlyDictValueError: 'line' has invalid value inside 'scattergl'  # Path To Error: ['line']  # Current path: [] # Current parent object_names: []  # With the current parents, 'line' can be used as follows:  # Under ('figure', 'data', 'scattergl'):  #     role: object 

Update with Ian Kent's Answer:

I don't think the code below can change the weights for all of the lines. I tried making all of the widths 0.1 with the weights list and got the following plot: enter image description here

but then when I did width=0.1 it worked for all of the lines: enter image description here

1 Answers

Answers 1

I think the issue is in the following line of your code:

edge_trace["lines"].append(go.Line(width=attr_dict["weight"],color='#888')) 

Try it with "line" instead of "lines". This is a bit of a confusing aspect of the Plotly API, but in scatter plots, the mode is plural and the argument name to change attributes of the trace is singular. So,

trace = go.Scatter(mode = 'markers', marker = dict(...)) trace = go.Scatter(mode = 'lines', line = dict(...)) 

Edit: Okay so there turned out to be more issues than just the "lines" now that I've sat down with it:

You have the line argument as a list of dict-like objects, whereas plotly expects it to be a single dict-like. Building a list of weights then adding all the weights to the line attribute at once seems to work:

edge_trace = go.Scattergl(                      x=[],                      y=[],                      mode="lines" )  weights = [] for node_A, node_B, attr_dict in edgelist:     xA, yA = pos[node_A]     xB, yB = pos[node_B]     edge_trace["x"] += [xA, xB, None]     edge_trace["y"] += [yA, yB, None]     weights.append(attr_dict["weight"])  edge_trace['line'] = dict(width=weights,color='#888') 

Also, you are plotting the lines in front of the nodes and thus obstructing them. You should change

data = [node_trace, edge_trace] 

to

data = [edge_trace, node_trace] 

to avoid this.

Read More

Sunday, October 9, 2016

How to use the `pos` argument in `networkx` to create a flowchart-style Graph? (Python 3)

Leave a Comment

I am trying create a linear network graph using Python (preferably with matplotlib and networkx although would be interested in bokeh) similar in concept to the one below.

enter image description here

How can this graph plot be constructed efficiently (pos?) in Python using networkx? I want to use this for more complicated examples so I feel that hard coding the positions for this simple example won't be useful :( . Does networkx have a solution to this?

pos (dictionary, optional) – A dictionary with nodes as keys and positions as values. If not specified a spring layout positioning will be computed. See networkx.layout for functions that compute node positions.

I haven't seen any tutorials on how this can be achieved in networkx which is why I believe this question will be a reliable resource for the community. I've extensively gone through the networkx tutorials and nothing like this is on there. The layouts for networkx would make this type of network impossible to interpret without careful use of the pos argument... which I believe is my only option. None of the precomputed layouts on the https://networkx.github.io/documentation/networkx-1.9/reference/drawing.html documentation seem to handle this type of network structure well.

Simple Example:

(A) every outer key is the iteration in the graph moving from left to the right (e.g. iteration 0 represents samples, iteration 1 has groups 1 - 3, same with iteration 2, iteration 3 has Groups 1 - 2, etc.). (B) The inner dictionary contains the current grouping at that particular iteration, and the weights for the previous groups merging that represent the current group (e.g. iteration 3 has Group 1 and Group 2 and for iteration 4 all of iteration 3's Group 2 has gone into iteration 4's Group 2 but iteration 3's Group 1 has been split up. The weights always sum to 1.

My code for the connections w/ weights for the plot above:

D_iter_current_previous =    {         1: {             "Group 1":{"sample_0":0.5, "sample_1":0.5, "sample_2":0, "sample_3":0, "sample_4":0},             "Group 2":{"sample_0":0, "sample_1":0, "sample_2":1, "sample_3":0, "sample_4":0},             "Group 3":{"sample_0":0, "sample_1":0, "sample_2":0, "sample_3":0.5, "sample_4":0.5}             },         2: {             "Group 1":{"Group 1":1, "Group 2":0, "Group 3":0},             "Group 2":{"Group 1":0, "Group 2":1, "Group 3":0},             "Group 3":{"Group 1":0, "Group 2":0, "Group 3":1}             },         3: {             "Group 1":{"Group 1":0.25, "Group 2":0, "Group 3":0.75},             "Group 2":{"Group 1":0.25, "Group 2":0.75, "Group 3":0}             },         4: {             "Group 1":{"Group 1":1, "Group 2":0},             "Group 2":{"Group 1":0.25, "Group 2":0.75}             }         } 

This is what happened when I made the Graph in networkx:

import networkx import matplotlib.pyplot as plt  # Create Directed Graph G = nx.DiGraph()  # Iterate through all connections for iter_n, D_current_previous in D_iter_current_previous.items():     for current_group, D_previous_weights in D_current_previous.items():         for previous_group, weight in D_previous_weights.items():             if weight > 0:                 # Define connections using `|__|` as a delimiter for the names                 previous_node = "%d|__|%s"%(iter_n - 1, previous_group)                 current_node = "%d|__|%s"%(iter_n, current_group)                 connection = (previous_node, current_node)                 G.add_edge(*connection, weight=weight)  # Draw Graph with labels and width thickness nx.draw(G, with_labels=True, width=[G[u][v]['weight'] for u,v in G.edges()]) 

enter image description here

Note: The only other way, I could think of to do this would be in matplotlib creating a scatter plot with every tick representing a iteration (5 including the initial samples) then connecting the points to each other with different weights. This would be some pretty messy code especially trying to line up the edges of the markers w/ the connections...However, I'm not sure if this and networkx is the best way to do it or if there is a tool (e.g. bokeh or plotly) that is designed for this type of plotting.

1 Answers

Answers 1

Networkx has decent plotting facilities for exploratory data analysis, it is not the tool to make publication quality figures, for various reason that I don't want to go into here. I hence rewrote that part of the code base from scratch, and made a stand-alone drawing module called netgraph that can be found here (like the original purely based on matplotlib). The API is very, very similar and well documented, so it should not be too hard to mold to your purposes.

Building on that I get the following result:

enter image description here

I chose colour to denote the edge strength as you can
1) indicate negative values, and
2) distinguish small values better.
However, you can also pass an edge width to netgraph instead (see netgraph.draw_edges()).

The different order of the branches is a result of your data structure (a dict), which indicates no inherent order. You would have to amend your data structure and the function _parse_input() below to fix that issue.

Code:

import itertools import numpy as np import matplotlib.pyplot as plt import netgraph; reload(netgraph)  def plot_layered_network(weight_matrices,                          distance_between_layers=2,                          distance_between_nodes=1,                          layer_labels=None,                          **kwargs):     """     Convenience function to plot layered network.      Arguments:     ----------         weight_matrices: [w1, w2, ..., wn]             list of weight matrices defining the connectivity between layers;             each weight matrix is a 2-D ndarray with rows indexing source and columns indexing targets;             the number of sources has to match the number of targets in the last layer          distance_between_layers: int          distance_between_nodes: int          layer_labels: [str1, str2, ..., strn+1]             labels of layers          **kwargs: passed to netgraph.draw()      Returns:     --------         ax: matplotlib axis instance      """     nodes_per_layer = _get_nodes_per_layer(weight_matrices)      node_positions = _get_node_positions(nodes_per_layer,                                          distance_between_layers,                                          distance_between_nodes)      w = _combine_weight_matrices(weight_matrices, nodes_per_layer)      ax = netgraph.draw(w, node_positions, **kwargs)      if not layer_labels is None:         ax.set_xticks(distance_between_layers*np.arange(len(weight_matrices)+1))         ax.set_xticklabels(layer_labels)         ax.xaxis.set_ticks_position('bottom')      return ax  def _get_nodes_per_layer(weight_matrices):     nodes_per_layer = []     for w in weight_matrices:         sources, targets = w.shape         nodes_per_layer.append(sources)     nodes_per_layer.append(targets)     return nodes_per_layer  def _get_node_positions(nodes_per_layer,                         distance_between_layers,                         distance_between_nodes):     x = []     y = []     for ii, n in enumerate(nodes_per_layer):         x.append(distance_between_nodes * np.arange(0., n))         y.append(ii * distance_between_layers * np.ones((n)))     x = np.concatenate(x)     y = np.concatenate(y)     return np.c_[y,x]  def _combine_weight_matrices(weight_matrices, nodes_per_layer):     total_nodes = np.sum(nodes_per_layer)     w = np.full((total_nodes, total_nodes), np.nan, np.float)      a = 0     b = nodes_per_layer[0]     for ii, ww in enumerate(weight_matrices):         w[a:a+ww.shape[0], b:b+ww.shape[1]] = ww         a += nodes_per_layer[ii]         b += nodes_per_layer[ii+1]      return w  def test():     w1 = np.random.rand(4,5) #< 0.50     w2 = np.random.rand(5,6) #< 0.25     w3 = np.random.rand(6,3) #< 0.75      import string     node_labels = dict(zip(range(18), list(string.ascii_lowercase)))      fig, ax = plt.subplots(1,1)     plot_layered_network([w1,w2,w3],                          layer_labels=['start', 'step 1', 'step 2', 'finish'],                          ax=ax,                          node_size=20,                          node_edge_width=2,                          node_labels=node_labels,                          edge_width=5,     )     plt.show()     return  def test_example(input_dict):     weight_matrices, node_labels = _parse_input(input_dict)     fig, ax = plt.subplots(1,1)     plot_layered_network(weight_matrices,                          layer_labels=['', '1', '2', '3', '4'],                          distance_between_layers=10,                          distance_between_nodes=8,                          ax=ax,                          node_size=300,                          node_edge_width=10,                          node_labels=node_labels,                          edge_width=50,     )     plt.show()     return  def _parse_input(input_dict):     weight_matrices = []     node_labels = []      # initialise sources     sources = set()     for v in input_dict[1].values():         for s in v.keys():             sources.add(s)     sources = list(sources)      for ii in range(len(input_dict)):         inner_dict = input_dict[ii+1]         targets = inner_dict.keys()          w = np.full((len(sources), len(targets)), np.nan, np.float)         for ii, s in enumerate(sources):             for jj, t in enumerate(targets):                 try:                     w[ii,jj] = inner_dict[t][s]                 except KeyError:                     pass          weight_matrices.append(w)         node_labels.append(sources)         sources = targets      node_labels.append(targets)     node_labels = list(itertools.chain.from_iterable(node_labels))     node_labels = dict(enumerate(node_labels))      return weight_matrices, node_labels  # -------------------------------------------------------------------------------- # script # --------------------------------------------------------------------------------  if __name__ == "__main__":      # test()      input_dict =   {         1: {             "Group 1":{"sample_0":0.5, "sample_1":0.5, "sample_2":0, "sample_3":0, "sample_4":0},             "Group 2":{"sample_0":0, "sample_1":0, "sample_2":1, "sample_3":0, "sample_4":0},             "Group 3":{"sample_0":0, "sample_1":0, "sample_2":0, "sample_3":0.5, "sample_4":0.5}             },         2: {             "Group 1":{"Group 1":1, "Group 2":0, "Group 3":0},             "Group 2":{"Group 1":0, "Group 2":1, "Group 3":0},             "Group 3":{"Group 1":0, "Group 2":0, "Group 3":1}             },         3: {             "Group 1":{"Group 1":0.25, "Group 2":0, "Group 3":0.75},             "Group 2":{"Group 1":0.25, "Group 2":0.75, "Group 3":0}             },         4: {             "Group 1":{"Group 1":1, "Group 2":0},             "Group 2":{"Group 1":0.25, "Group 2":0.75}             }         }      test_example(input_dict)      pass 
Read More

Sunday, April 24, 2016

Networkx as a task queue?

Leave a Comment

I have a directed acyclic graph in networkx. Each node represents a task and a nodes' predecessors are task dependencies (a given task cannot execute until its' dependencies have executed).

I'd like to 'execute' the graph in an asynchronous task queue, similar to what celery offers (so that I can poll jobs for their status, retrieve results etc). Celery doesnt offer the ability to create DAG's (as far as I know) and having the ability to move on to a task as soon as all dependencies are complete would be crucial (a DAG may have multiple paths and even if one task is slow/blocking, it may be possible to move on to other tasks etc).

Are there any simple examples as to how I could achieve this, or perhaps even integrate networkx with celery?

1 Answers

Answers 1

I think this function may help:

  # The graph G is represened by a dictionnary following this pattern:   # G = { vertex: [ (successor1: weight1), (successor2: weight2),...   ]  }   def progress ( G, start ):      Q = [ start ] # contain tasks to execute      done = [ ]    # contain executed tasks      while len (Q) > 0: # still there tasks to execute ?         task = Q.pop(0) # pick up the oldest one          ready = True         for T in G:     # make sure all predecessors are executed            for S, w in G[T]:               if S == task and and S not in done:# found not executed predecessor                   ready = False                  break            if not ready : break         if not ready:            Q.appen(task) # the task is not ready for execution         else:            done.appen(task) # execute the task            for S, w in G[task]:# and explore all its successors               Q.append(S) 
Read More

Wednesday, April 13, 2016

Using a graph-tool efficiently

Leave a Comment

After a long thought, I finally decided to post this question here. Few days back I started using graph-tool to do various things. I have been using Networkx before that. I have already seen the impressive performance comparision and thought that everything would be simple enough. However, I immediately ran into the speed issue and asked a question related to a particular aspect of it. I got a quick answer that satisfied me. However, now this speed issue is bugging me every now and then and I can't find any documentation about graph-tool that is related to efficiently using it. For example, from the answer to my last question, I came to realize that it is better to add all edges together instead of one by one which is a very important point to note but hasn't been mentioned anywhere! I am now having two more similar issues:

(1) How do I choose a random neighbour of a given node? I can only see the following solution:

nbr = np.random.choice(list(v.all_neighbours())) 

since v.all_neighbours() is a generator, I must convert it into the list to choose a random element. This slows down the code but I don't see any better way.

(2) I want to assign a 1d vector (is list okay?) to each of the vertices in the graph and later I am exchanging and modifying them in a particular way. This is simply a property map and I would like to see some documentation about how to use this efficiently. However, I can't locate anything.

(3) I am trying to simulate a triadic closure in some network which itself is changing with time. Thus, at every time step, I need an information about the neighbours of each vertex in the graph. Again, I must create a list (or numpy array):

nbrs = [w for w in v.neighbours()] 

which decreases the speed of my code substantially. This means that I am not doing this correctly but I couldn't find any documentation that would tell me how to use neighbours efficiently in graph-tool.

Somehow Networkx programs that I have written for same tasks have completely outperformed the graph-tool codes I simply can't buy this.

This list might increase and hence I would be very glad if somebody could point me to some documentation about using graph-tool efficiently apart from answering the above mentioned specific questions.

Thanks in advance.

2 Answers

Answers 1

  1. To choose a random item from a list of items, you can use numpy.random.choice. It also allows for the definition of value for probability of occurrence. See the documentations here. The alternative would be to get a random number between the boundaries of your data and use it as an index against your list / generator. This can be done using numpy.random.randint. Read more on this here.

    data = range(100) max_data = max(data) min_data = min(data) index = np.randint(min_data, max_data) random_choice = data[index] 
  2. From what I understand, I think your best option is to use a non-relational table, either in the memory, or a CSV file, or a SQLite database. You may store functions and variables (serialise them) using pickle. You can find out more about it from here.

  3. One way to avoid iterating through your data and increase the speed of your code is as follows:

    data = [1, 2, 3, 4, 5, 6, 7]  # or: data = range(1, 8) query = [1,4, 9]  answer = list(set(query) & set(data)) print(answer) 

    which returns:

    [1, 4] 

    Note that this works for a generator objects too and takes a fraction of the time otherwise spent iterating. The alternative, however, would be to use the map function, which is explained here.

    Another alternative is to use the numpy.in1d function:

    data = np.array(range(100)) query = np.array([1, 52, 121])  answer = np.in1d(data, query)  # Returns a logical array. new_array = data[answer]  print(new_array) 

    which returns:

    array([ 1, 52]) 

    This is the most efficient method, as it uses vectorisation algorithms. For this set of data, it takes an average of 11.7 µs for 100k loops; whereas the one using set takes 12.4 µs. Bear in mind that both set and map cache the data, and do not perform operations until the answer is requested. NumPy, on the other hand, performs all operations immediately and as such, may be beneficial in some circumstances. Although if you're using generators, other methods are probably just as valid.

You indicate in your question that networkx outperforms graph-tools, and that you "don't buy" this. I take it you say this because the latter is chiefly implemented in C++. If it is, here is why: Whilst this is a valid argument, it is often taken for granted that anything implemented in C is necessarily better in performance when compared to Python. This is generally true, however, when it comes to mathematical operations that do NOT involve iterations, Python might actually be faster. The reason for this is that unlike many well-known languages (namely C, C++ and Java), Python takes advantage of vectorisation (as do, for instance, Julia, MATLAB, and R). This means that a mathematical operation is applied collectively to an entire array, as opposed to inducing an iteration that goes through individual elements. A single line of operation in Python using NumPy can require pages and pages in Java for this very reason.

I hope this helps to an extent. To give you a tailored help, however, I would need to see your code.

Answers 2

I'll try to make more "graph-tool-specific" answers:

1) well actually this one is related to python, so you might want to use the solution from this thread using random.shuffle However, if you are going to do this repeatedly, (and if you have enough available memory), I think it might be better to get the adjacency matrix as a scipy sparse matrix then use that matrix:

import graph_tool from graph_tool.spectral import adjacency import numpy as np  g = graph_tool.Graph() g.add_vertex(100) edges = np.random.randint(0, 100, (500,2)) g.add_edge_list(edges)  mat = adjacency(g).tolil() rows = mat.rows.copy() # mat.rows = in-neighbours for each vertex map(np.random.shuffle, rows) rnd_neighbours = { i:row[0] for i, row in enumerate(rows) if row } 

Where rnd_neighbours contains the index of one random neighbour for each vertex of nonzero out-degree.

2) reading the graph-tool documentation regarding PropertyMaps and the detailed version, lists are accepted as python::object or simply object. You can then access them as elements in the PropertyMap.

3) For triadic closure, look at the clustering module and at this thread on the mailing list.

EDIT: by the way, I forgot to mention it, but you can access and change the number of OpenMP threads with openmp_enabled, openmp_get_num_threads, and openmp_set_num_threads in graph-tool. Can't find it in the doc, though... But here is the source.

Read More