In the code below I create a graph. Then I get the distances of each node from that graph. Then I invert that so that instead for each distance I have a list of nodes at that distance. Then for each distance I plot the nodes with a given color....

According to the document, find_cliques returns all maximal cliques. In your case there are cliques with size greater than 3 (abcde)(cdeg) and you will need to also have all possible 3-combination in that bigger clique. This is because each sub-clique of a clique is also a clique but it's not...

python-2.7,igraph,networkx,bipartite,sna

There is an example in the documentation you reference at https://networkx.github.io/documentation/latest/reference/generated/networkx.algorithms.bipartite.projection.generic_weighted_projected_graph.html of how to do exactly this. It goes like this: import networkx as nx from networkx.algorithms import bipartite edges = [('A1','B1',3), ('A1','B2',7), ('A2','B1',2), ('A2','B2',4), ] B = nx.Graph() B.add_weighted_edges_from(edges) def my_weight(G, u, v, weight='weight'): w = 0 for nbr...

python,networkx,topological-sort

One approach is to build a dependency graph containing a directed edge between A and B if and only if A strongly depends upon B, or A weakly depends upon B and B is strongly depended upon by some other task. Here's some code that does just that. In this...

python,graph,networkx,minimum-spanning-tree,subgraph

You can get the edges in G that appear in the MST T with a simple comprehension: E = set(T.edges()) # optimization [e for e in G.edges() if e in E or reversed(e) in E] You can then build a new graph from this....

There isn't a simple way to do that with matplotlib and networkx (of course it is possible with enough code). Graphviz does a really excellent job with labels and it is easy to write dot format files from networkx to process with Graphviz. Also take a look at https://github.com/chebee7i/nxpd which...

Take a look at heapq.nlargest It takes an iterable and returns the n largest things in that iterable. Since I don't have your coauthor list, I'll use the karate graph. Instead of looking at all non-edges right away (as adamic_adar_index does by default), I'm going to go through each node...

Networkx and python-igraph both support a wide range of read/write algorithms (networkx, python-igraph). At least two formats (GML and pajek) appear to be common between the two, although I haven't tried this....

python,graph,matplotlib,networkx,graphml

Assign the x and y values to the a dictionary with node keys In [1]: pos = {} In [2]: for n,data in G.node.items(): ...: pos[n] = (data['x'],data['y']) ...: ...

python,flask,networkx,gunicorn

It looks like the easiest way to do this is to tell gunicorn to preload your application using the preload_app option. This assumes that you can load the data structure as a module-level variable: from flask import Flask from your.application import CustomDataStructure CUSTOM_DATA_STRUCTURE = CustomDataStructure('/data/lives/here') # @app.routes, etc. Alternatively, you...

There is probably a more concise way, but this works. The main trick is just to normalize the data such that User1 is always the lower number ID. Then you can use groupby since 11,12 and 12,11 are now recognized as representing the same thing. In [330]: df = pd.DataFrame({"User1":[11,12,13,14],"User2":[12,11,14,13],"W":[1,2,1,2]})...

The positions of the nodes are defined in a dictionary, with key the name of the node and value a tuple with the x and y coords. You can see this by printing the pos variable once created: pos=nt.graphviz_layout(graph,prog='dot') print pos # EXAMPLE RESULT {'A': (51.5, 15.3), 'B': (20.0, 60.4)}...

Here is an example of how to use a colormap. It's a little tricky. And if you want a customized discrete colormap you can try this SO answer Matplotlib discrete colorbar import matplotlib.pyplot as plt # create number for each group to allow use of colormap from itertools import count...

The documentation outlines that you have to use the edge_labels argument to specify custom labels. By default it the string representation of the edge data is used. In the example below such a dictionary is created: It has the edge tuples as keys and the formatted strings as values. To...

python,python-3.x,graph,networkx

You can change the color of the nodes in the graph using networkx.draw_networkx_nodes. You can color nodes diffrerently by providing a list of colors to draw_networkx_nodes, one per node. In your case, you could construct the node_colors list as follows: node_colors = ["blue" if n in shortestPath else "red" for...

Without knowing what you have attempted and without an example graph I will give you a simple example. It might clear things up for you. I will make a 4 node, 4 edge graph from an adjacency matrix using newtworkx and numpy. import matplotlib.pyplot as plt import networkx as nx...

I tried your snippet and I can reproduce the issue. This works as it should: edges, colors = zip(*nx.get_edge_attributes(G,'weight').items()) nx.draw(G, pos, edgelist=edges, edge_color=colors, width=10, edge_cmap = plt.cm.jet, vmin = 0.0, vmax = max(weights.values())) My guess is that draw_edges does not keep the order of edges as defined by get_edge_attributes, but...

In your comment you say this started happening after you started adding edges. I think that's where the problem is. You'll get this error if even one node doesn't have the 'category' defined. I think adding edges is resulting in the addition of a few nodes that don't have category...

It depends on how random is defined. If random is the module from the standard library, then: import random random.choice(G.nodes()) will work. If random is numpy.random, then from numpy import random random.choice(G.nodes()) will raise /usr/lib/python2.7/dist-packages/numpy/random/mtrand.so in mtrand.RandomState.choice (numpy/random/mtrand/mtrand.c:7850)() ValueError: a must be 1-dimensional Note the path in the error message...

I had the same problem here. This is how I solved it: Try installing networkx from source instead of installing it through pip. Source Install Step by Step Download the source (tar.gz or zip file) from https://pypi.python.org/pypi/networkx/ or get the latest development version from https://github.com/networkx/networkx/ Unpack and change directory to...

It could be that graphviz doesn't allow node IDs to start with a %? Here is a workaround: import networkx as nx import matplotlib.pyplot as plt G = nx.DiGraph() n = "%%%%% \n% % % \n%%%%%" G.add_node(1,label=n) G.add_node(2,label=2) G.add_node(3,label=3) G.add_edge(1,2) G.add_edge(1,3) print G.edges() nx.write_dot(G,'test.dot') pos=nx.graphviz_layout(G,prog='dot') nx.draw(G,pos) labels = nx.get_node_attributes(G,"label") nx.draw_networkx_labels(G,pos,labels=labels)...

You can test it pretty quickly, but it only adds them once. Edges and nodes are represented as a dictionaries inside the graph structure, and they are only added if they don't actually exist. For already existing edges, adding them again has no effect....

To create a graph and set a few positions: import networkx as nx G=nx.Graph() G.add_edges_from([(1,2),(2,3),(3,1),(1,4)]) #define G fixed_positions = {1:(0,0),2:(-1,2)}#dict with two of the positions set fixed_nodes = fixed_positions.keys() pos = nx.spring_layout(G,pos=fixed_positions, fixed = fixed_nodes) nx.draw_networkx(G,pos) Your problem appears to be that you calculate the positions of all the nodes...

python,networkx,namespace-package

What should be the changes in the networkx core package? Where should I put empty __init__.py files? Add a __init__.py inside networkx/addons/ with the single line of code in it __import__('pkg_resources').declare_namespace(__name__) What should be the value of namespace_packages in setup() of the setup.py of networkx-metis? It should be namespace_packages...

You'll have to do some kind of loop. But if you are using an undirected graph you can eliminate half of the graph.add_edge() (only need to add u-v and not v-u). Also as @EdChum suggests you can use graph.add_weighted_edges_from() to make it go faster. Here is a nifty way to...

python,graph,social-networking,networkx

(i) The Average degree of the network. (The only one I could find was average_degree_connectivity, which returns a dictionary and not a single float with the average degree of the whole network) Assuming your Graph object is G. degrees = G.degree() sum_of_edges = sum(degrees.values()) Calculating the average is just...

There is no built-in function for this but it is pretty simple: import networkx as nx G = nx.Graph() G.add_node(1,color='red') G.add_node(2,color='red') G.add_node(3,color='blue') G.add_node(4,color='blue') G.add_edges_from([(1,2),(1,3),(3,4)]) for (u,v) in G.edges_iter(): if G.node[u]['color'] != G.node[v]['color']: print u,v ...

Not sure if this contravenes your desire not to manually play with ticks, but you can use matplotlib.ticker to set the ticks to your given interval: import matplotlib.pyplot as plt import matplotlib.ticker as plticker fig,ax=plt.subplots() #Spacing between each line intervals = float(sys.argv[1]) loc = plticker.MultipleLocator(base=intervals) ax.xaxis.set_major_locator(loc) ax.yaxis.set_major_locator(loc) # Add the...

The source code for the reverse method looks like this: def reverse(self, copy=True): """Return the reverse of the graph. The reverse is a graph with the same nodes and edges but with the directions of the edges reversed. Parameters ---------- copy : bool optional (default=True) If True, return a new...

You can just use networkx.shortest_path(G) with the weight='weight' keyword. e.g. In [1]: import networkx as nx In [2]: G = nx.Graph() In [3]: G.add_edge(1,2,weight=7) In [4]: G.add_edge(1,4,weight=3) In [5]: G.add_edge(2,3,weight=1) In [6]: G.add_edge(3,4,weight=100) In [7]: nx.adjacency_matrix(G).todense() Out[7]: matrix([[ 0, 7, 0, 3], [ 7, 0, 1, 0], [ 0, 1,...

The problem you are seeing is caused by IPList = [[] for i in range (20)] which leads to parsePcap() returning a list of sequences with an empty list or lists at the end when len(pkts) is less than 20: parseOutput = [ ('172.16.254.128', '216.58.208.206'), ... ('172.16.254.128', '216.58.208.227'), [], #<----------------...

python,geometry,networkx,sympy

I found a solution that sped the process up by about 13x (for a polygon with 35 points (like the data listed above), the old method from the code in the question took about 4hours to find all line segments inside the polygon. This new method took 18 minutes instead.)...

This appears to be a bug in IronPython - types.FunctionType resolves to a constructor call that throws a NotImplementedException (see https://github.com/IronLanguages/main/blob/master/Languages/IronPython/IronPython/Runtime/PythonFunction.cs#L72). It's old code, so I'm not sure why it does that. I've opened issue #35180 to track it....

Just add a print statement to your last line: for u, v, p in preds: print '(%d, %d) -> %.8f' % (u, v, p) ...

Your code won't run without more info. I think you want something like the function networkx.get_node_attributes(): In [1]: import networkx as nx In [2]: G = nx.Graph() In [3]: G.add_node(1,profit=17) In [4]: G.add_node(2,profit=42) In [5]: a = nx.get_node_attributes(G,'profit') In [6]: a.items() Out[6]: [(1, 17), (2, 42)] ...

Matplotlib wants Python unicode (for Python2). So you can use labels = {1:'King Bolaños'.decode('utf-8'), 2:'Lancelot', 3:'shopkeeper', 4:'dead parrot', 5:'Brian', 6:'Sir Robin'} ...

tl/dr: just add with_labels=True to the nx.draw call. So the main reason for the extra complexity on that page was that it was showing how to set lots of different things as the labels as well as give different nodes different colors, and careful control over where the nodes appear....

python,matplotlib,attributes,nodes,networkx

I am afraid that this would have to be done using multiple passes. The main idea is to use a layout to get the positions of the nodes and then use draw_networkx_nodes repeatedly for the n different classes of nodes. For example: import networkx import pylab #Build a graph (Node...

python,import,attributes,networkx,edge

A. if your data is in a text file, then you need to open it as text rather than binary. import networkx as nx fh=open("test.edgelist", 'r') # ------------------------|----- note 'r' not 'rb' G=nx.read_weighted_edgelist(fh, nodetype=int) fh.close() With the sample data that you provided, both methods work fine for me. It is...

algorithm,graph,dynamic-programming,graph-theory,networkx

If you must go from A to G in an efficient way, you aren't looking for a minimum spanning tree algorithm. A simple shortest path algorithm is enough. You just have to adapt you graph to put the weights in the edges instead of the nodes. But it's just a...

python,networkx,deep-copy,shallow-copy

You can make a shallow copy by using the class constructor. E.g. for graphs, In [1]: import networkx as nx In [2]: G = nx.Graph() In [3]: G.add_edge(1,2,l=['a','b','c']) In [4]: H = nx.Graph(G) # shallow copy In [5]: H[1][2]['l'] Out[5]: ['a', 'b', 'c'] In [6]: H[1][2]['l'].append('d') In [7]: H[1][2]['l'] Out[7]:...

This isn't a great answer, but it gives the basics. Someone else may come by who actually knows the Fruchterman-Reingold algorithm and can describe it. I'm giving an explanation based on what I can find in the code. From the documentation, weight : string or None optional (default=’weight’) The edge...

The networkx-1.9 documentation is here http://networkx.github.io/documentation/networkx-1.9/reference/generated/networkx.algorithms.components.connected.connected_components.html#networkx.algorithms.components.connected.connected_components The interface was changed to return a generator (as you figured out). The example in the documentation shows how to do what you ask. Generate a sorted list of connected components, largest first. >> G = nx.path_graph(4) >>> G.add_path([10, 11, 12]) >>>...

The trouble you're having is that you're adding the neighbors list to the end of randomnodes, rather than adding elements from the list. This leads a later iteration to try to get the neighbors of the nested neighbor list, resulting in an exception. If you don't mind the randomnodes list...

python,python-2.7,networkx,planar-graph

There is a Python wrapper for part of of John Boyer's planarity code (https://code.google.com/p/planarity/) that might be what you are looking for. It is at https://github.com/hagberg/planarity. It has a NetworkX interface that allows you to test for planarity and find the Kurotowki subgraphs if not. e.g. https://github.com/hagberg/planarity/blob/master/examples/networkx_interface.py import planarity import...

This: for edge in G.edges(data=True): edge = list(edge) edge[2] = OrderedDict(sorted(edge[2].items())) edge=tuple(edge) has no effect on the output (or the contents of the object pointed to by G), because by doing: edge = tuple(edge) you are only modifying the local variable edge; this will not affect the value returned by...

writerows expect a list of lists of values, where each "outer" list is a row of values. You are, however, passing a list of strings. writerows just iterates over each string's elements, so each letter becomes its own column. Commas need to be quoted when they are csv values, so...

For this case here is a way to do it without making a copy of the graph. Instead it creates a new function to compute the degree. In [1]: import networkx as nx In [2]: from collections import defaultdict In [3]: G = nx.Graph() In [4]: G.add_edges_from([(1,2),(3,4),(4,5)], color='red') In [5]:...

python,exception-handling,networkx

If all you're doing is ensuring you don't try to get the path length of a non-existent node then why not just use has_node: if G.has_node(uNode) and G.has_node(vNode): path_len = nx.shortest_path_length(G,uNode, vNode) EDIT The following worked for me: In [76]: import networkx as nx G=nx.Graph() G.add_edge(2,3) try: nx.shortest_path_length(G,0,1) except nx.NetworkXError:...

python,algorithm,graph,graph-theory,networkx

Wait if the graph is actually a representation of a city, then there's one embedding of it, already. Just take t the faces of that embedding. You can't remove one face (ie. It's minimal) and the minimal cycle base is unique (first lemma of the paper you cite), so there's...

python,matplotlib,tree,graphviz,networkx

Before getting to the colormap, the node color values are normalized to the interval [0, 1]. This is presumably meant to use the full range of colors, regardless of the range of the values given. To use a different interval for scaling, you can set the vmin and vmax parameters:...

python,graph,networkx,modularity

From the documentation: Node color. Can be a single color format string, or a sequence of colors with the same length as nodelist. If numeric values are specified they will be mapped to colors using the cmap and vmin,vmax parameters. See matplotlib.scatter for more details. part = community.best_partition(G) assigns a...

You can do it this way without the CSV writer. with open('some_file.csv', 'wb') as f: for n in G: f.write("%s %f %f\n"%(n,betweenness_centr[n],eigenvector_centr[n])) $ cat some_file.csv 1 0.000000 0.455318 2 0.800000 0.628284 3 0.000000 0.455318 4 0.000000 0.134714 5 0.000000 0.263998 6 0.400000 0.320604 Follow up: tab is \t and you...

python,graph,networkx,dijkstra

The problem is that you have to write the word "weight" for assigning it to an edge. You are giving labels to the edges but no weights. The next code works printing 9 when you calculate the distance between nodes A and C. import networkx as nx G = nx.MultiDiGraph()...

An ordered graph data structure is available in NetworkX since inclusion on Jan 1 2015. The OrderedGraph class will output nodes and edges from the NetworkX data structure in the order they are added. You'll need to get the latest development version at https://github.com/networkx/networkx/ for the following to work. import...

You can use the Graph.degree() method with the weight= keyword like this: In [1]: import networkx as nx In [2]: G = nx.Graph() In [3]: G.add_edge(1,2,weight=7) In [4]: G.add_edge(1,3,weight=42) In [5]: G.degree(weight='weight') Out[5]: {1: 49, 2: 7, 3: 42} In [6]: G.degree(weight='weight').items() Out[6]: [(1, 49), (2, 7), (3, 42)] ...

If you look at the source nxpd.draw (function draw_pydot) calls to_pydot which filters the graph attributes like: if attr_type == 'edge': accepted = pydot.EDGE_ATTRIBUTES elif attr_type == 'graph': accepted = pydot.GRAPH_ATTRIBUTES elif attr_type == 'node': accepted = pydot.NODE_ATTRIBUTES else: raise Exception("Invalid attr_type.") d = dict( [(k,v) for (k,v) in attrs.items()...

The docs are a bit ambiguous about where this resides but the following worked for me: In [4]: G = nx.complete_graph(4) from networkx.algorithms.approximation import clique clique.max_clique(G) Out[4]: {0, 1, 2, 3} ...

python,python-2.7,graph,networkx,graph-drawing

The X,Y data is not being treated as numbers. You can fix it with this: xy = attributes.values() G.add_node(attributes.pop('id'), dict([('pos', (float(xy[0]),float(xy[1])) )])) Note: this answer was edited into the question by the OP. I've moved it down here into the answers section and made it a community wiki so I...

python,algorithm,animation,matplotlib,networkx

If your graph isn't too big you could try the following approach that sets the properties for individual nodes and edges. The trick is to save the output of the drawing functions which gives you a handle to the object properties like color, transparency, and visibility. import networkx as nx...

python,graph,generator,networkx

You might like connected_component_subgraphs() better since it will give you subgraphs instead of just the nodes. In [1]: import networkx as nx In [2]: G = nx.Graph() In [3]: G.add_path([1,2,3,4]) In [4]: G.add_path([10,20,30,40]) In [5]: components = nx.connected_component_subgraphs(G) In [6]: components Out[6]: [<networkx.classes.graph.Graph at 0x102ca7790>, <networkx.classes.graph.Graph at 0x102ca77d0>] In [7]:...

You can just inspect your object 'one' In [1]: import networkx as nx In [2]: %paste class myObject(object): def __init__(self, name): self.name = name def __str__(self): return self.name one = myObject("ONE") Graph = nx.Graph() Graph.add_node(one) ## -- End pasted text -- In [3]: print(one) ONE You can store arbitrary data...

python,matplotlib,graphviz,networkx,digraphs

As this is old and Lack answered the question in the comments I am copying his answer here and accepting: I can't run your code without errors (TypeError: 'complex' object has no attribute '__getitem__' on j[t]) but it's the same problem as your other question which I answered (stackoverflow.com/questions/27831022/…). Because...

data-mining,networkx,large-data,jung,spark-graphx

So this is a way to do it in networkx. It's roughly based on the solution I gave here. I'm assuming that a->b and a<-b are two distinct paths you want. I'm going to return this as a list of lists. Each sublist is the (ordered) edges of a path....

python,python-3.x,python-3.4,networkx

Analysis of your current approach You are using subscript notation via the square brackets. Normally, you would type my_object[key], which is translated as a first approximation* into my_object.__getitem__(key). In particular, if the type(my_object) does not define the __getitem__ attribute, then you effectively get an error that says that type(my_object) is...

The problem you're having is that your subgraph command is telling it to make a subgraph with a nodelist where each element is not just the node name, but also the data about that node name. The command G.subgraph needs just the list of node names. The easiest way to...

You can also try Graphviz via PyDot (I prefer this one) or PyGraphviz. In case you are interested in a publication-ready result, you can use the toolchain networkx -> pydot + dot -> dot2tex + dot -> dot2texi.sty -> TikZ. Instead of this fragile toolchain, you can alternatively export directly...

Both of your links are to the 'development' part of networkx (check the url), so I don't think it's in the standard release yet. Probably your best option is to copy the relevant code into a file in your working directory and import it separately. Otherwise, look to download the...

python,matplotlib,graphviz,networkx

I think all you need to do is build a series of thick lines using your start and end values as x, and zeros as y (if I understand you correctly). Ex: import matplotlib.pyplot as plt x=[(0.15119, 0.43909), (0.43909, 0.72698), (0.72698, 1.01189), (1.01189, 1.2968)] for i in x: plt.plot(i,[0,0],linewidth=10) plt.show()...

python,graph,matplotlib,networkx,graphml

You are right, GraphML want's simpler attributes (no numpy arrays or lists). You can set the x and y positions of the nodes as attributes like this G = nx.path_graph(4) pos = nx.spring_layout(G) for node,(x,y) in pos.items(): G.node[node]['x'] = float(x) G.node[node]['y'] = float(y) nx.write_graphml(G, "g.graphml") ...

(some of this answer addresses some things in your comments. Can you add those to your question so that later users get some more context) pos creates a dict with coordinates for each node. Doing nx.draw(G,pos) creates a pylab figure. But it doesn't display it, because pylab doesn't display automatically....

python,graph,beautifulsoup,label,networkx

You can convert the list, idvalue to dict using list comprehensions and dict() function labels = dict( [ value for value in enumerate(idvalue) ] ) Example >>> lst = ['a', 'b', 'c', 'd'] >>> dict([ x for x in enumerate(lst) ]) {0: 'a', 1: 'b', 2: 'c', 3: 'd'} Note...

I think you want the graph diameter which is the maximum of all-pairs shortest paths. https://networkx.github.io/documentation/latest/reference/generated/networkx.algorithms.distance_measures.diameter.html

It looks like you are already specifying filename.csv in your command line argument so you want to replace that with your special extension to do that you could: file_name = sys.argv[1].replace('.csv', '_folded.csv') ...

Here is how to draw just the number for a 'weight' attribute. import matplotlib.pyplot as plt import networkx as nx G = nx.Graph() G.add_edge(1,2,weight=7) G.add_edge(2,3,weight=42) labels = {} for u,v,data in G.edges(data=True): labels[(u,v)] = data['weight'] pos = nx.spring_layout(G) nx.draw(G,pos) nx.draw_networkx_edge_labels(G, pos, edge_labels=labels) plt.show() ...

for i in range(num_routes): while True: try: A = int(rand.choice(pos.keys())) B = int(rand.choice(pos.keys())) path = nx.dijkstra_path(X,A,B,weight='length') pathlength = round(nx.dijkstra_path_length(X,A,B,weight='length'),2) print path,A,B,pathlength ,i if 1.5 <= pathlength <= 2: break else: pathlength except:pass print pathlength,A,B This should work. If I understand you correctly that is! Edited my code, I was doing...

If you want to only keep unique elements in your list, Use set() mylist = list(graph.degree().values()) unique_elements_list = list(set(mylist)) Use list(): mylist = list(graph.degree().values()) unique_elements_list = list() # iterates all elements in mylist for element in mylist: # adds to unique elements list only current # element is not included....

python,list,nodes,networkx,edges

How about this: data = [('"$weepstake$" (1979) {(#1.2)}', '10.0'), ('"\'Til Death Do Us Part" (2006) {Pilot(#1.0)}', '3.7'), ('"\'Conversations with My Wife\'" (2010)', '4.2'), ('"\'Da Kink in My Hair" (2007)', '4.2')] import networkx as nx G = nx.Graph() G.add_edges_from(data) nx.draw(G) if you want a count of edges from a score. len(G.edges('4.2'))...

python,matplotlib,networkx,bottle,httpserver

I'm not particularly familiar with networkx, but it appears to take an ax kwarg that specifies the Axes object to draw on. In your case, that would be your P object, returned by fig.add_subplot. Typically, code that does that looks something like: def blah(data, ax=None): if ax is None: ax...

Just add with_labels=True to your code. import matplotlib.pyplot as plt import networkx as nx socialNetworl = nx.Graph() socialNetworl.add_nodes_from([1,2,3,4,5,6]) socialNetworl.add_edges_from([(1,2),(1,3),(2,3),(2,5),(2,6)]) nx.draw(socialNetworl, node_size = 800, node_color="cyan", with_labels = True) plt.show() If you want to change the labels, create a dict with the labels and pass labels=theLabelDict into nx.draw: import matplotlib.pyplot as plt...

As you are in python3 , use dict.items() instad of dict.iteritems() iteritems() was removed in python3, so you can't use this method anymore. Take a look at Python Wiki (Link) In Built-in Changes part, it is stated that Removed dict.iteritems(), dict.iterkeys(), and dict.itervalues(). Instead: use dict.items(), dict.keys(), and dict.values() respectively....

python,graph,permutation,networkx,isomorphism

To answer the algorithmic part of your question: Say your partition has k cells: C_1, ..., C_k. There is a 1 to 1 correspondence between permutations of the overall set that preserve the partition and the Cartesian product P_1 x P_2 x ... x P_k where P_i is the set...

import json data = [('king', 'governor'), ('governor', 'editor'), ('king', 'state'), ('state', 'collapse'), ('collapse', 'coverage'), ('collapse', 'author'), ('collapse', 'opening'), ('state', 'head'), ('state', 'lord')]; root = data[0][0] node2chilren = {root: []} for parent, child in data: childnode = {child: []} children = node2chilren[parent] children.append(childnode) node2chilren[child] = childnode[child] jsonstr = json.dumps({root: node2chilren[root]}, indent=4)...

python,graph,dataframes,networkx

You could use B.add_weighted_edges_from( [(row['domain'], row['subdomain'], 1) for idx, row in df.iterrows()], weight='weight') to add weighted edges, or you could use B.add_edges_from( [(row['domain'], row['subdomain']) for idx, row in df.iterrows()]) to add edges without weights. You may not need weights since the node degree is the number of edges adjacent to...

Here's an option for edge in {(u,v,data) for u,v,data in G.edges_iter(data=True) if data['edge_type']=='foo'}: ... ...

python,networkx,shapefile,digraphs

As best I can follow from your question, the following will do it, basically copied from the original read_shp command. def read_multi_shp(path): """ copied from read_shp, but allowing MultiDiGraph instead. """ try: from osgeo import ogr except ImportError: raise ImportError("read_shp requires OGR: http://www.gdal.org/") net = nx.MultiDiGraph() # <--- here is...

What about nx.shortest_path? distance = len(nx.shortest_path(G, source='aws_vpc', target='aws_subnet')) ...

How about this? You can use matplotlib's colormaps to map values to colors for the nodes. import matplotlib.pyplot as plt import networkx as nx graph = { '1': ['2', '3', '4'], '2': ['5','11','12','13','14','15'], '3' : ['6','7','66','77'], '5': ['6', '8','66','77'], '4': ['7','66','77'], '7': ['9', '10'] } MG = nx.DiGraph(graph) plt.figure(figsize=(8,8)) pos=nx.graphviz_layout(MG,prog="twopi",root='1')...

python,matplotlib,nodes,shape,networkx

This is a pragmatic, rather than purely mathematical answer. I think you have two issues - one with layout, the other with your network. 1. Network You have too many edges in your network for it to represent the unit tesseract. Caveat I'm not an expert on the maths here...

The networkx Pajek file reader can't handle the .paj format files with extra "partition" data in it. Unfortunately it seems like it works. But obviously you are getting extra nodes and edges. If you remove everything in the file SanJuanSur2.net starting at *Edges to the end you can read it...