Graph Theory in Networkx - python

I am starting to use this interface now, I have some experience with Python but nothing extensive. I am calculating the transitivity and community structure of a small graph:
import networkx as nx
G = nx.read_edgelist(data, delimiter='-', nodetype=str)
nx.transitivity(G)
#find modularity
part = best_partition(G)
modularity(part, G)
I get the transitivity just fine, however - there is the following error with calculating modularity.
NameError: name 'best_partition' is not defined
I just followed the documentation provided by the networkx site, is there something I am doing wrong?

As far as I can tell best_partition isn't part of networkx. It looks like you want to use https://sites.google.com/site/findcommunities/ which you can install from https://bitbucket.org/taynaud/python-louvain/src
Once you've installed community try this code:
import networkx as nx
import community
import matplotlib.pyplot as plt
G = nx.random_graphs.powerlaw_cluster_graph(300, 1, .4)
nx.transitivity(G)
#find modularity
part = community.best_partition(G)
mod = community.modularity(part,G)
#plot, color nodes using community structure
values = [part.get(node) for node in G.nodes()]
nx.draw_spring(G, cmap = plt.get_cmap('jet'), node_color = values, node_size=30, with_labels=False)
plt.show()
edit: How I installed the community detection library
ryan#palms ~/D/taynaud-python-louvain-147f09737714> pwd
/home/ryan/Downloads/taynaud-python-louvain-147f09737714
ryan#palms ~/D/taynaud-python-louvain-147f09737714> sudo python3 setup.py install

I just met the same error NameError: name 'best_partition' is not defined when using this example code.
This error occurs because I named my python file as networkx.py, then when we execute this program
import networkx as nx
This program may import the networkx we defined instead of the library. In the program, best_partition is not defined. So this error occur.
Having same name with library is not appropriate. Maybe you should check this!

Related

Python: How can I import waterways from OpenStreetMaps as a graph so I can do graph analysis with networkx

Thanks at first for actually taking the time to help me :-)
I want to create a undirected graph from waterways for example from the canals of Venice or Amsterdam.
OpenStreetMaps has such a graph of a waterway network of these cities, but the OSMnx package does not have such a filter to filter the waterways (or maybe I don't know it yet ;-) ).
import osmnx as ox
G = ox.graph_from_bbox(52.36309012572587,4.890326718121118,52.36590601699889,4.898316757037793, network_type='all')
G_projected = ox.project_graph(G)
ox.plot_graph(G_projected)
I thought I was possible to just download the whole map, and then filter on just the waterway network. But I don't know how to go further about this. OSMnx would be the best as I then immediately have a graph which I can use for functions of networksx such as Dijkstra's shortest path.
Another way I was thinking of was overpass package:
import overpass
import networkx as nx
import matplotlib.pyplot as plt
api= overpass.API()
data = api.get('way(52.36309012572587,4.890326718121118,52.36590601699889,4.898316757037793);(._;>;)', verbosity='geom')
[f for f in data.features if f.geometry['type'] == "LineString"]
But this still doesn't work, because I haven't figured out how to filter the data and transform it to a graph for so that networkx can use it.
Hope you guys (and girls :-) ) can help me, because I have no clue how to go further.
Kind regards,
Jeroen
You can use OSMnx to get other types of infrastructure such as canals, railways, powerlines, etc, as described in this example, using the custom_filter parameter:
import osmnx as ox
ox.config(use_cache=True, log_console=True)
G = ox.graph_from_place('Amsterdam', retain_all=False, truncate_by_edge=False,
simplify=True, custom_filter='["waterway"~"canal"]')
fig, ax = ox.plot_graph(G)

LFR in python-igraph 0.7.1.post.6

I recently installed python-igraph (version=0.7.1.post6 on windows 10) and I would like to generate networks with communities using LFR benchmark, but I didn't find the specific function to do that.
Is there a function (in igraph) that create LFR benchmark? If not, are there any other recommended modules that enables generating such graphs (and contain SOTA community detection algorithms as in igraph)?
Thanks,
Gal
from networkx.algorithms.community import LFR_benchmark_graph
As pointed out, it is defined inside the networkx package and this means that you can import it to igraph. A minimum working example would go like this.
import igraph as ig
from networkx.algorithms import community
def import_nx_network(net):
graph = ig.Graph(n=net.number_of_nodes(), directed=False)
graph.add_edges(net.edges())
return graph
def LFR_graph(N, τ1, τ2, μ, **kwargs):
net = community.LFR_benchmark_graph(N, τ1, τ2, μ, **kwargs)
graph = import_nx_network(net)
return graph

How to make community detection with networkx module works?

I am working with networkx library for graph optimization problems. However, when I try running the example on their documentation it says in my PyCharm IDE after executing the example:
Traceback (most recent call last):
File "/home/PycharmProjects/testing_things.py", line 1, in <module>
import community
ImportError: No module named community
Does anyone knows how to get rid of this error? I am using Python 2.7
It would seem that your python installation doesn't have community installed.
You can install it by running:
pip install python-louvain
Cheers!
you can use :
conda install python-louvain
Use pip to install Python-Louvain:
pip install python_louvain
then in your script import the module directly using:
from community import community_louvain
In your code, use the function in the following way:
partition = community_louvain.best_partition(G)
Here's the sample community detection on the famous karate club graph based on Louvain Community Detection Algorithm:
# Replace this with your networkx graph loading depending on your format!
r = nx.karate_club_graph()
#first compute the best partition
partition = community.best_partition(r)
#drawing
size = float(len(set(partition.values())))
pos = nx.spring_layout(r)
count = 0
for com in set(partition.values()) :
count = count + 1.
list_nodes = [nodes for nodes in partition.keys()
if partition[nodes] == com]
nx.draw_networkx_nodes(r, pos, list_nodes, node_size = 20,
node_color = str(count / size))
nx.draw_networkx_edges(r, pos, alpha=0.5)
plt.show()

Using networkX to output a tree structure

I am using networkX to generate a tree structure as follows (I am following the answer of this question).
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
G.add_node("ROOT")
for i in range(5):
G.add_node("Child_%i" % i)
G.add_node("Grandchild_%i" % i)
G.add_node("Greatgrandchild_%i" % i)
G.add_edge("ROOT", "Child_%i" % i)
G.add_edge("Child_%i" % i, "Grandchild_%i" % i)
G.add_edge("Grandchild_%i" % i, "Greatgrandchild_%i" % i)
# write dot file to use with graphviz
# run "dot -Tpng test.dot >test.png"
nx.write_dot(G,'test.dot')
# same layout using matplotlib with no labels
plt.title('draw_networkx')
pos=nx.graphviz_layout(G, prog='dot')
nx.draw(G, pos, with_labels=False, arrows=False)
plt.savefig('nx_test.png')
I want to draw a tree as in the following figure.
However, I am getting an error saying AttributeError: module 'networkx' has no attribute 'write_dot'. My networkx version is 1.11 (using conda). I tried different hacks, but none of them worked.
So, I am interested in knowing if there is another way of drawing tree structures using networkx to get an output similar to the one mentioned in the figure. Please let me know.
You can draw digraph entirely with pygraphviz.
Following steps needs to be followed first as pygraphviz does not work without graphviz (as of now).
Download graphviz-2.38.msi from http://www.graphviz.org/Download_windows.php and install
Download the 2.7 or 3.4 pygraphviz wheel file from http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygraphviz
Navigate to the directory that you downloaded the wheel file and run your platform specific wheel
pip install pygraphviz‑1.3.1‑cp34‑none‑win32.whl
Add dot.exe to host path
e.g. on windows control-panel ->system -> edit environment variables -> Modify PATH
After that dot and png files can be created as below.
Working Code
import pygraphviz as pgv
G=pgv.AGraph(directed=True)
#Attributes can be added when adding nodes or edge
G.add_node("ROOT", color='red')
for i in range(5):
G.add_node("Child_%i" % i, color='blue')
G.add_node("Grandchild_%i" % i, color='blue')
G.add_node("Greatgrandchild_%i" % i, color='blue')
G.add_edge("ROOT", "Child_%i" % i, color='blue')
G.add_edge("Child_%i" % i, "Grandchild_%i" % i, color='blue')
G.add_edge("Grandchild_%i" % i, "Greatgrandchild_%i" % i, color='blue')
# write to a dot file
G.write('test.dot')
#create a png file
G.layout(prog='dot') # use dot
G.draw('file.png')
PNG File
I think this issue was solved on networkx 2.x, but before that you should be explicit import of the function like this.
from networkx.drawing.nx_agraph import write_dot
or
from networkx.drawing.nx_pydot import write_dot
I hope this works.

python, networkx 2.0 'girvan_newman' is not defined

I get the error
NameError: name 'girvan_newman' is not defined
when try to use this algorithm in networkx 2.0.
Could someone help to fix this problem?
davedwards is right , you need to provide the missing import statements:
import networkx as nx
from networkx.algorithms import community
communities_generator = community.girvan_newman(G)
Check https://networkx.github.io/documentation/latest/reference/algorithms/community.html

Categories

Resources