Coder Social home page Coder Social logo

igraph / python-igraph Goto Github PK

View Code? Open in Web Editor NEW
1.2K 34.0 248.0 34.52 MB

Python interface for igraph

License: GNU General Public License v2.0

Python 52.25% Shell 0.27% C 47.40% Makefile 0.01% C++ 0.01% Dockerfile 0.06%
complex-networks graph-algorithms graph-theory mathematics network-analysis network-graph python

python-igraph's Introduction

Build Status on Azure Pipelines Build Status on Github Actions codecov DOI

The igraph library

igraph is a C library for complex network analysis and graph theory, with emphasis on efficiency, portability and ease of use.

See https://igraph.org for installation instructions and documentation.

igraph can also be used from:

igraph is a collaborative work of many people from all around the world — see the list of contributors here. If you would like to contribute yourself, click here to see how you can help.

Citation

If you use igraph in your research, please cite

Csardi, G., & Nepusz, T. (2006). The igraph software package for complex network research. InterJournal, Complex Systems, 1695.

python-igraph's People

Contributors

adriankhl avatar ah00ee avatar albertoalcolea avatar casperdcl avatar deeenes avatar dependabot[bot] avatar ebraminio avatar flange-ipb avatar frederik-h avatar fwitter avatar gaborcsardi avatar gomango999 avatar gruebel avatar horvatha avatar iggisv9t avatar iosonofabio avatar isaac-lee avatar jankatins avatar jboynyc avatar lauzadis avatar limburgher avatar luav avatar martinomensio avatar naviddianati avatar nickeubank avatar ntamas avatar peterscott avatar sriram-pattabiraman avatar szhorvat avatar vtraag avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-igraph's Issues

shortest_paths error: Runtime to terminate it in an unusual way

I am trying to call the shortest_paths() function for a relatively large network ( IGRAPH DN-- 13679 76741 -- ). Unexpectedly

, I got the following error:

"Assertion failed: q->stor_begin != 0, file c:\dev\igraph\igraph-0.6.5-msvc\src\dqueue.pmt, line 284

This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. "

what does this error mean?


here is the code:
g = Graph.Read_Ncol('file.edgelist')
g.delete_vertices(g.vs.select(_degree=0))
g.vs["color"] = "Green"
summary(g)
t = time.time()
g.shortest_paths()
print time.time() - t


and here is a link to the network that I used when this error occurred: https://github.com/medoos/files/blob/master/network.rar

pickle format memory leaks

From @gaborcsardi on May 4, 2013 18:58

the pickle format (or at least the reading) leaks memory - pickle_loop(large_graph, True) in the attached test demonstrates this.

I don't know if this is igraph's fault, or pickle's fault, but I also found that:

  • pickle with a simpler data structure doesn't memory leak - pickle_loop(large_range, True) in the attached test
  • igraph using (eg) write_graphml, doesn't memory leak either. - write_loop(large_graph, True) in the attached test

This is probably low priority, but I thought I'd report this bug anyway, since it's hopefully useful to people that need to un/serialise lots of graphs, that come up against this memory leak issue. If you don't need pickle's ability to eg. serialise almost any python object as an attribute in the graph, then graphml+zlib performs better than pickle (both in terms of speed, and size of serialised format), and doesn't memory leak either.


Imported from Launchpad using lp2gh.

Copied from original issue: igraph/igraph#271

easy_install python-igraph fails on an Ubuntu box due to sandbox violation

From Stack Overflow: http://stackoverflow.com/questions/28838599/failed-igraph-installation-on-a-ubuntu-box

The log is as follows:

sudo easy_install python-igraph
Searching for python-igraph
Reading https://pypi.python.org/simple/python-igraph/
Best match: python-igraph 0.7.1-2
Downloading https://pypi.python.org/packages/source/p/python-igraph/python-igraph-0.7.1-2.tar.gz#md5=4b1f4dc621fc938434836e59dea31173
Processing python-igraph-0.7.1-2.tar.gz
Writing /tmp/easy_install-R2pEQ_/python-igraph-0.7.1-2/setup.cfg
Running python-igraph-0.7.1-2/setup.py -q bdist_egg --dist-dir /tmp/easy_install-R2pEQ_/python-igraph-0.7.1-2/egg-dist-tmp-bl3Z_7
Cannot find the C core of igraph on this system using pkg-config.
We will now try to download and compile the C core from scratch.
Version number of the C core: 0.7.1-2
We will also try: 0.7.1

error: Setup script exited with error: SandboxViolation: mkdir('/usr/local/bin/tmp', 511) {}

The package setup script has attempted to modify files on your system
that are not within the EasyInstall build area, and has been aborted.

This package cannot be safely installed by EasyInstall, and may not
support alternate installation locations even if you run its setup
script by hand.  Please inform the package's author and the EasyInstall
maintainers to find out if a fix or workaround is available.

Graph.write_graphml does not store tuple attributes in python-igraph 0.6

From @gaborcsardi on May 4, 2013 18:56

Tuple graph, vertex and edge attributes are not stored when exported to GraphML (I don't know about other formats) in python-igraph 0.6 (0.5 works fine).

See the attachment for a minimal example.


Imported from Launchpad using lp2gh.

Copied from original issue: igraph/igraph#221

Seg Fault When Importing scipy

From @Lab41PaulM on June 30, 2014 18:43

There appears to be an issue with importing scipy separately into projects that use igraph when scipy is imported after the igraph import.

The following code causes a seg fault:

import igraph
import scipy

f = "test.graphml"
G = igraph.Graph.Erdos_Renyi(n=20, m=30)
G.write_graphml(f)
G_ = igraph.Graph.Read_GraphML(f)
layout = G_.layout("fr") # Fruchterman-Reingold layout
igraph.plot(G_, layout=layout)

However, if you swap the import order it does not cause a seg fault.

Copied from original issue: igraph/igraph#638

summary function throwing an error

This is the line that is causing the bug:

ig.summary(myg1.components(mode="weak").subgraphs()[1], verbosity=1,width=None,edge_list_format="edgelist")

This is the error message:

  File "build/bdist.linux-x86_64/egg/igraph/__init__.py", line 4091, in summary

  File "build/bdist.linux-x86_64/egg/igraph/__init__.py", line 3191, in summary

  File "build/bdist.linux-x86_64/egg/igraph/summary.py", line 369, in __str__
  File "build/bdist.linux-x86_64/egg/igraph/summary.py", line 210, in _construct_edgelist_edgelist
  File "build/bdist.linux-x86_64/egg/igraph/vendor/texttable.py", line 315, in add_rows
  File "build/bdist.linux-x86_64/egg/igraph/summary.py", line 285, in _edge_attribute_iterator
  File "build/bdist.linux-x86_64/egg/igraph/summary.py", line 285, in <genexpr>
NameError: free variable 'names' referenced before assignment in enclosing scope
when using the following line:
ig.summary(myg1.components(mode="weak").subgraphs()[1], \
 verbosity=1,width=None,edge_list_format="edgelist"
)

write_gml throwing exception: iterable must yield numbers

I am adding some vertices to a graph using g.add_vertex(name='bla') and afterwards the mentioned error comes upo when I try to write the graph to gml.

It does work if I remove the id attribute by del g.vs['id'] beforehand.

May it be that the ids of the added vertices are "None" or such?

VertexDendrogram.as_clustering() sometimes fails?

From @nadesai on August 27, 2014 20:5

Most of the time VertexDendrogram.as_clustering() has worked fine for me, but I recently encountered a VertexDendrogram that persistently fails when I try to call as_clustering() on it. The traceback is

---------------------------------------------------------------------------
InternalError                             Traceback (most recent call last)
<ipython-input-14-f8101bd3b52b> in <module>()
----> 1 dendrogram.as_clustering()

/usr/local/lib/python3.4/site-packages/igraph/clustering.py in as_clustering(self, n)
    957         idgen = UniqueIdGenerator()
    958         membership = community_to_membership(self._merges, num_elts, \
--> 959                                              num_elts - n)
    960         membership = [idgen[m] for m in membership]
    961         return VertexClustering(self._graph, membership,

InternalError: Error at community.c:769: `steps' to big or `merges' matrix too short, Invalid value

which comes from src/community.c#L769.

The VertexDendrogram in question is the result of calling community_edge_betweenness() on the network science collaboration graph, available from the "Coauthorships in network science" dataset available at http://www-personal.umich.edu/~mejn/netdata/.

Is this failure behavior expected? Is is impossible to convert some VertexDendrograms into clusterings?

Copied from original issue: igraph/igraph#675

To implement graph union and graph difference by vertex names in Python, in the same way it is already implemented in R

The native C core of igraph supports graph union only by IDs and not
by vertex names. The R interface contains an implementation of "graph
union by vertex names", and it is selected automatically if your graph
has vertex names. However, There is no equivalent function in the Python
interface.

It would be great if you could implement graph union and graph difference by vertex names in Python, in the same way it is already implemented in R.

This issue was also discussed here: https://lists.nongnu.org/archive/html/igraph-help/2015-09/msg00083.html

Thanks

igraph crashes when drawing an edge between two vertices with objects for names

I'm using igraph 0.7.1 with Python 3.4 under Windows 7, and the following code crashes:

import igraph

class Person:
    def __init__(self, name):
        self.name = name

alice = Person('Alice')
bob = Person('Bob')
g = igraph.Graph()
g.add_vertex(alice)
g.add_vertex(bob)
print(g.vs[0]['name'] == alice)
print(g.vs[1]['name'] == bob)
g.add_edge(alice, bob)

The output is as follows:

True
True
File "C:\Python34\lib\site-packages\igraph\__init__.py", line 237, in add_edge
return self.add_edges([(source, target)])
File "C:\Python34\lib\site-packages\igraph\__init__.py", line 255, in add_edges
return GraphBase.add_edges(self, es)
TypeError: only numbers, vertex names or igraph.Vertex objects can be converted to vertex IDs

It seems that this code should work, as both alice and bob are vertex names in this case. Is this a bug?

incorrect handling of igraph warnings if the user turns them into an exception

From Stack Overflow. A short code fragment to reproduce:

warnings.simplefilter('error', 'Cannot shuffle graph')
degseq = [1,2,2,3]
try:
    testgraph = igraph.Graph.Degree_Sequence(degseq,method = "vl")
except RuntimeWarning:
    print degseq
else:
    print "go on"

This will print:

MemoryError: Error at src/attributes.c:284: not enough memory to allocate attribute hashes, Out of memory

The problem is that the C core of igraph never anticipates that some warnings are turned into errors, therefore it does not bail out from igraph_degree_sequence_game at the point where the warning was raised.

Non-string vertex names fail to be found

As of python-igraph 0.7.1 (73a295e to be specific) it appears giving a vertex a name that is something other than a string doesn't work anymore.

import igraph

g = igraph.Graph.Full(3)

g.vs["name"] = ["a", "b", "c"]
print g
print g.vs.find(name="a") # works

g.vs["name"] = [(0, 0), (1, 1), (2, 2)]
print g
print g.vs.find(name=(0, 0)) # fails

@ntamas fyi

Explain installing igraph on Linux virtualenv, and cairocffi in particular

I had a hard time figuring out how to get igraph running on Ubuntu Linux 14.04 in a virtualenv.

The igraph documentation at Installing igraph doesn't cover installing on Linux at all yet. I just noticed that it is covered a bit at python-igraph so that should be referred to or included in the tutorial. Perhaps it would have even worked for me! But I had started the tutorial already and that didn't work for me, as I describe here.

It was easy to install using the Ubuntu package for python-igraph, but that is out-of-date, and doesn't address my need to install in a particular virtualenv which has other more up-to-date ipython packages, and which does not include site-packages.

First, like some other people, when I did pip install igraph, I also ran into a UnicodeDecodeError, and this error:

/usr/bin/ld: cannot find -lxml2

as described in more detail at Error installing python-igraph on Ubuntu (from command line) - Stack Overflow, and also at Re: [igraph] Installing igraph on ubuntu 14.04 64 bit.

The approach I describe there worked for installing in the virtualenv.

Then I wanted to get plot working, and needed Cairo bindings for python. Web searches led me to the logically-named "pycairo" package, and it is listed in pip, but it didn't work for me, saying

Could not find any downloads that satisfy the requirement pycairo
Some externally hosted files were ignored (use --allow-external pycairo to allow).

which led me on more frustrating web searches.

It turns out that pip install cairocffi works fine, in a virtualenv as well as elsewhere. See Install pycairo in virtualenv - Stack Overflow.

"from igraph._igraph import" fails

From @VladimirAlexiev on February 18, 2014 18:31

I build and install igraph and interfaces/python from this git repo. Then I'm trying to use this program: https://github.com/specgen/specgen. I get this error:

File "./specgen6.py", line 51, in <module>
    from libgroups import Grouping
  File "/cygdrive/c/prog/specgen/libgroups.py", line 25, in <module>
    from igraph import *
  File "/usr/lib/python2.7/site-packages/python_igraph-0.6.6-py2.7-cygwin-1.7.28-x86_64.egg/igraph/__init__.py", line 34, in <module>
    from igraph._igraph import *

I got a similar error when trying to use the "official" stable version 0.6.5

Traceback (most recent call last):
  File "./specgen6.py", line 51, in <module>
    from libgroups import Grouping
  File "/cygdrive/c/prog/specgen/libgroups.py", line 25, in <module>
    from igraph import *
  File "build/bdist.cygwin-1.7.28-x86_64/egg/igraph/__init__.py", line 34, in <module>
  File "build/bdist.cygwin-1.7.28-x86_64/egg/igraph/_igraph.py", line 7, in <module>
  File "build/bdist.cygwin-1.7.28-x86_64/egg/igraph/_igraph.py", line 6, in __bootstrap__
ImportError: No such file or directory

This seems to be reported in http://lists.gnu.org/archive/html/igraph-help/2013-04/msg00100.html but I can't figure out if it's fixed.

I even tried with the 0.7 nightlies but got missing subdirs .deps, eg make fails with

lapack/.deps/liblapack_la-iladlr.Plo: No such file or directory

Please help!!

Copied from original issue: igraph/igraph#581

python-igraph install fails.

Hi folks, thanks for the great library. The following is my issue:

Running

 $ git clone https://github.com/igraph/python-igraph.git
 $ python setup.py install --user 

leads to the following compilation error in src/convert.h. I was able to do a pip install python-igraph however. It seems that the version of python-igraph available on pip does not contain the functionality of random_walk. So I guess that somehow the C core: 0.7.1.post6 is not compatible with the head of igraph-python. So probably the C core version that python-igraph tries to build should be bumped up? The log of the build is here

running build_ext
Cannot find the C core of igraph on this system using pkg-config.
We will now try to download and compile the C core from scratch.
Version number of the C core: 0.7.1.post6
We will also try: 0.7.1
Using temporary directory: /home/hltcoe/prastogi/data/python-igraph/tmp/igraph.mGUepB
Downloading igraph-0.7.1.tar.gz... 100.00%
Extracting igraph-0.7.1.tar.gz...
Configuring igraph...
building 'igraph._igraph' extension
creating build/temp.linux-x86_64-2.7
creating build/temp.linux-x86_64-2.7/src
gcc -pthread -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -Iigraphcore/include -I/opt/anaconda/include/python2.7 -c src/igraphmodule.c -o build/temp.linux-x86_64-2.7/src/igraphmodule.o
In file included from src/igraphmodule.c:30:
src/convert.h:63: error: expected declaration specifiers or ‘...’ before ‘igraph_layout_grid_t’
src/convert.h:66: error: expected declaration specifiers or ‘...’ before ‘igraph_random_walk_stuck_t’
error: command 'gcc' failed with exit status 1

Igraph compilation fails with pip install due to false usage of static libraries

From @neuralyzer on July 9, 2014 18:19

When I pip install pyton-igraph, not having the igraph c core already installed I get the following error message:

gcc -pthread -shared build/temp.linux-x86_64-2.7/src/arpackobject.o build/temp.linux-x86_64-2.7/src/attributes.o build/temp.linux-x86_64-2.7/src/bfsiter.o build/temp.linux-x86_64-2.7/src/common.o build/temp.linux-x86_64-2.7/src/convert.o build/temp.linux-x86_64-2.7/src/edgeobject.o build/temp.linux-x86_64-2.7/src/edgeseqobject.o build/temp.linux-x86_64-2.7/src/error.o build/temp.linux-x86_64-2.7/src/filehandle.o build/temp.linux-x86_64-2.7/src/graphobject.o build/temp.linux-x86_64-2.7/src/igraphmodule.o build/temp.linux-x86_64-2.7/src/indexing.o build/temp.linux-x86_64-2.7/src/py2compat.o build/temp.linux-x86_64-2.7/src/pyhelpers.o build/temp.linux-x86_64-2.7/src/random.o build/temp.linux-x86_64-2.7/src/vertexobject.o build/temp.linux-x86_64-2.7/src/vertexseqobject.o igraphcore/lib/libigraph.a /usr/lib64/libxml2.a /usr/lib64/libz.a /usr/lib64/libm.a -Ligraphcore/lib -L/usr/local/lib64 -L/usr/local/lib -L/usr/lib64 -L/usr/lib -L/lib64 -L/lib -L../../build/src/.libs -L../../src/.libs -L/usr/local/lib -L/usr/lib -L/home/anaconda/lib -lstdc++ -lpython2.7 -o build/lib.linux-x86_64-2.7/igraph/_igraph.so

/usr/lib64/gcc/x86_64-suse-linux/4.3/../../../../x86_64-suse-linux/bin/ld: /usr/lib64/libxml2.a(entities.o): relocation R_X86_64_32 against `.text' can not be used when making a shared object; recompile with -fPIC

/usr/lib64/libxml2.a: could not read symbols: Bad value

collect2: ld returned 1 exit status

error: command 'gcc' failed with exit status 1

Apparently libxml2.a is mixed up with libxml2.so. The following very dirty workaround made igraph compile for me. I modified the setup.py as follows:

I changed the line

variants = ["lib{0}.a", "{0}.a", "{0}.lib", "lib{0}.lib"]

to

variants = ["lib{0}.so", "{0}.so"]

pip setup.py install did then finish. However igraph did still not work, since libigraph.so.0 was not copied to its destination. So I manually copied

cp ./igraphcore/lib/libigraph.so.0 ~/anaconda/lib

to python's lib. As you can see, I'm using the anaconda Python distribution.

Copied from original issue: igraph/igraph#640

/usr/bin/igraph exception in cls.progressbar.update

$ /usr/bin/igraph
No configuration file, using defaults
igraph 0.7.1 running inside  Python 3.4.2 (default, Jul  9 2015, 17:24:30) 
[GCC 5.1.1 20150618 (Red Hat 5.1.1-4)] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> g = Graph.Full(300)
>>> g.write_svg('/tmp/save2.svg')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/lib64/python3.4/site-packages/igraph/__init__.py", line 1938, in write_svg
    layout = self.layout(layout, *args, **kwds)
  File "/usr/lib64/python3.4/site-packages/igraph/__init__.py", line 1422, in layout
    l = method(self, *args, **kwds)
  File "/usr/lib64/python3.4/site-packages/igraph/__init__.py", line 1492, in layout_auto
    return self.layout(algo, *args, **kwds)
  File "/usr/lib64/python3.4/site-packages/igraph/__init__.py", line 1422, in layout
    l = method(self, *args, **kwds)
  File "/usr/lib64/python3.4/site-packages/igraph/__init__.py", line 3949, in result
    layout = func(*args, **kwds)
  File "/usr/lib64/python3.4/site-packages/igraph/app/shell.py", line 382, in _progress_handler
    cls.progress_bar.update(percentage, message)
AttributeError: type object 'ClassicPythonShell' has no attribute 'progress_bar'

This is in Fedora's mock (buildroot). When running under python2, the same sequence works fine.

Python interface: make the graph import functions accept URLs or Python file objects

From @gaborcsardi on May 4, 2013 18:59

Originally suggested by Chris Wj.

The igraph functions expect a FILE* and they want to call 'fread' (fscanf, etc.) on it. A possible way to go is to write the string to a temporary file and read that back -- another alternative is fmemopen() or open_memstream(), but we have to implement the temporary file solution anyway because of portability issues. [...] I have two possibilities in mind:

  1. We could add another function to convert.c (say, igraphmodule_PyString_or_PyFile_to_fileptr()) that always returns an appropriate file pointer -- although we also have to take care of cleaning up the temporary file at some point.
  2. We could simply override IO-related methods one level "above" in the Python layer (remember, the C layer implemeents igraph.core.GraphCore, igraph.Graph is inherited from that) to handle strings and files appropriately. This way we could maybe also handle URLs (i.e., if the string given is a URL, igraph could open a network connection and use the socket).

Imported from Launchpad using lp2gh.

Copied from original issue: igraph/igraph#384

igraph doc vanished

iGraph Python tutorial at http://igraph.org/python/doc/tutorial/tutorial.html references ("In the meanwhile, check out the full API documentation which should provide information about almost every igraph class, function or method. A good starting point is the documentation of the Graph class.") to http://igraph.org/doc/python/, which renders 404 error from Gator hoster.

The whole http://igraph.org/doc/ does not exist. Is it possible to fix with the links to correct urls on pyton page at http://igraph.org/python/doc/tutorial/tutorial.html or restore documentations in http://igraph.org/doc/ ?

How to add vertex labels for graphs read using Graph.Read_Edgelist

I am trying to plot communities based on a given membership for a graph. My graph has vertices from 0-|V-1| and hence I am using Graph.Read_Edgelist for reading my graph.

In order to plot the communities, I simply load the membership list to a vertexClustering object and plot it using plot as follows:

v = VertexClustering(g,membership) #here g is a graph read via edge list
plot(v, mark_groups=True).save("graph.png")

Now, I need to add vertex labels. One way to do this is to use the argument vertex_labels. However, I don't have any attribute name with the graph. What is a good way to give the vertex_labels using the graph g?

One workaround is to create a list of numbers from 0-|V-1|. But I don't know if it is the only way.

Strange behavior of Barabasi Albert Graph

Hi,

I have realised that Barabasi Albert Graph implementation in iGraph has a strange behaviour. The easiest way to see it is by looking at the average degree distribution.

In the simplest case, let's take n=3 and m=1. We should then start with two nodes connected (nodes 0 and 1) and then add a third node (node 2) linked with either 0 or 1 with a probability of 1/2 (because all nodes have the same degree : 1).
Hence if we repeat the graph creation many times we should have, on average:
avg_degree(0) = avg_degree(1) = 3/2
and avg_degree(2) = 1.

What has surprised me was to see that this is not what I am observing after doing multiple launches. I rather get
avg_degree(0) = 5/6
avg_degree(1) = 4/6
and avg_degree(2) = 1

import numpy as np
import igraph as ig

n = 3
m = 1

n_launch = 10000

degrees = np.zeros(n)
for _ in xrange(n_launch):
    G = ig.Graph.Barabasi(n, m)
    degrees += G.degree()

print "igraph average degree of nodes 0, 1, 2\t\t", degrees/n_launch

import networkx as nx

degrees = np.zeros(n)
for _ in xrange(n_launch):
    G = nx.barabasi_albert_graph(n, m)
    g_degree = G.degree()
    degrees += np.array([g_degree[i] for i in xrange(n)])

print "networkx average degree of nodes 0, 1, 2\t", degrees/n_launch

This snippet returns
igraph average degree of nodes 0, 1, 2 [ 1.6671 1.3329 1. ]
networkx average degree of nodes 0, 1, 2 [ 1.4977 1.5023 1. ]

PS : One could notice that networkx starts with an empty graph and igraph with a complete graph but this does not affect our example here because in both case we have node 0 and 1 connected at t=1, just before we add node 2.

Adding labels to vertices causes python crash

From @DSblizzard on May 23, 2014 7:58

This program crashes python 2.6:

def gr():
from igraph import Graph
res = Graph(0)
res.add_vertices(1)
res.vs["label"] = ['1']
return res

def draw_graph():
from igraph import plot
gr1 = gr()
layout = gr1.layout("fr")
plot_ = plot(gr1, layout = layout)

draw_graph()

Copied from original issue: igraph/igraph#623

What does community_leading_eigenvector() do?

I have been having trouble with the community_leading_eigenvector() function. I am not allowed to share the data I am working on yet, but I hope I can get some help anyway.

My troubles are:
Problem number 1: For networks bigger than about 8000 nodes the algorithm returns splits with very low modularity compared to other algorithms. The weird thing is that the bigger the network, the fewer communities are created (my networks range from 1000-16000 in size with an average degree of about 3 and are unweighted and undirected). The biggest network gets only one cluster from leading_eigenvector(). When I run the algorithm in Mathematica, even the big networks can be partitioned using leading_eigenvector.

These are my results for leading_eigenvector and infomap for comparison (some of the axis labels are swapped around - I am sorry about that)
nr_communities_lead_eig
modularity_lead_eig

nr_communities_infomap

modularity_infomap

Problem number 2: When I use the "clusters = ..." to decide for the algorithm how many clusters should be created, it does not always oblige. It often does, but then every now and then it creates a split with 9 clusters, even though I asked for 11, and the optimal partition has 23. I ran the following script

optimalcluster = g.community_leading_eigenvector()
print len(optimalcluster)
for i in range(30):
clustered = g.community_leading_eigenvector(clusters= i+1)
print len(clustered)

And it produced
23
1
2
3
4
5
6
7
8
9
9
9
10
11
12
13
14
15
16
16
16
16
16
16
16
16
16
16
16
17
18

igraph pip install error from source ERROR: unknown type name "igraph_random_walk_stuck_t"

I am running sudo pip install . --upgrade from the source directory of python-igraph but am getting the following error:

$ sudo pip install . --upgrade
[sudo] password for smishra8: 
Processing /content/smishra8/SOFTWARE/python-igraph
Installing collected packages: python-igraph
  Found existing installation: python-igraph 0.7.1.post6
    Uninstalling python-igraph-0.7.1.post6:
      Successfully uninstalled python-igraph-0.7.1.post6
  Running setup.py install for python-igraph
    Complete output from command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-n8Lrwd-build/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-7oJKWF-record/install-record.txt --single-version-externally-managed --compile:
    running install
    running build
    running build_py
    creating build
    creating build/lib.linux-x86_64-2.7
    creating build/lib.linux-x86_64-2.7/igraph
    copying igraph/summary.py -> build/lib.linux-x86_64-2.7/igraph
    copying igraph/matching.py -> build/lib.linux-x86_64-2.7/igraph
    copying igraph/cut.py -> build/lib.linux-x86_64-2.7/igraph
    copying igraph/__init__.py -> build/lib.linux-x86_64-2.7/igraph
    copying igraph/layout.py -> build/lib.linux-x86_64-2.7/igraph
    copying igraph/formula.py -> build/lib.linux-x86_64-2.7/igraph
    copying igraph/clustering.py -> build/lib.linux-x86_64-2.7/igraph
    copying igraph/compat.py -> build/lib.linux-x86_64-2.7/igraph
    copying igraph/statistics.py -> build/lib.linux-x86_64-2.7/igraph
    copying igraph/configuration.py -> build/lib.linux-x86_64-2.7/igraph
    copying igraph/utils.py -> build/lib.linux-x86_64-2.7/igraph
    copying igraph/datatypes.py -> build/lib.linux-x86_64-2.7/igraph
    creating build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/isomorphism.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/indexing.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/edgeseq.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/iterators.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/games.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/operators.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/bipartite.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/walks.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/flow.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/rng.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/matching.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/foreign.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/separators.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/structural.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/layouts.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/__init__.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/vertexseq.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/spectral.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/attributes.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/homepage.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/generators.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/basic.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/colortests.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/conversion.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/decomposition.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/cliques.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/utils.py -> build/lib.linux-x86_64-2.7/igraph/test
    copying igraph/test/atlas.py -> build/lib.linux-x86_64-2.7/igraph/test
    creating build/lib.linux-x86_64-2.7/igraph/app
    copying igraph/app/shell.py -> build/lib.linux-x86_64-2.7/igraph/app
    copying igraph/app/__init__.py -> build/lib.linux-x86_64-2.7/igraph/app
    creating build/lib.linux-x86_64-2.7/igraph/drawing
    copying igraph/drawing/vertex.py -> build/lib.linux-x86_64-2.7/igraph/drawing
    copying igraph/drawing/metamagic.py -> build/lib.linux-x86_64-2.7/igraph/drawing
    copying igraph/drawing/edge.py -> build/lib.linux-x86_64-2.7/igraph/drawing
    copying igraph/drawing/baseclasses.py -> build/lib.linux-x86_64-2.7/igraph/drawing
    copying igraph/drawing/colors.py -> build/lib.linux-x86_64-2.7/igraph/drawing
    copying igraph/drawing/text.py -> build/lib.linux-x86_64-2.7/igraph/drawing
    copying igraph/drawing/__init__.py -> build/lib.linux-x86_64-2.7/igraph/drawing
    copying igraph/drawing/graph.py -> build/lib.linux-x86_64-2.7/igraph/drawing
    copying igraph/drawing/shapes.py -> build/lib.linux-x86_64-2.7/igraph/drawing
    copying igraph/drawing/coord.py -> build/lib.linux-x86_64-2.7/igraph/drawing
    copying igraph/drawing/utils.py -> build/lib.linux-x86_64-2.7/igraph/drawing
    creating build/lib.linux-x86_64-2.7/igraph/remote
    copying igraph/remote/nexus.py -> build/lib.linux-x86_64-2.7/igraph/remote
    copying igraph/remote/gephi.py -> build/lib.linux-x86_64-2.7/igraph/remote
    copying igraph/remote/__init__.py -> build/lib.linux-x86_64-2.7/igraph/remote
    creating build/lib.linux-x86_64-2.7/igraph/vendor
    copying igraph/vendor/texttable.py -> build/lib.linux-x86_64-2.7/igraph/vendor
    copying igraph/vendor/__init__.py -> build/lib.linux-x86_64-2.7/igraph/vendor
    running build_ext
    Build type: dynamic extension
    Include path: /usr/local/include/igraph
    Library path: /usr/local/lib
    Runtime library path:
    Linked dynamic libraries: igraph
    Linked static libraries:
    Extra compiler options:
    Extra linker options:
    building 'igraph._igraph' extension
    creating build/temp.linux-x86_64-2.7
    creating build/temp.linux-x86_64-2.7/src
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/local/include/igraph -I/usr/include/python2.7 -c src/pyhelpers.c -o build/temp.linux-x86_64-2.7/src/pyhelpers.o
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/local/include/igraph -I/usr/include/python2.7 -c src/edgeobject.c -o build/temp.linux-x86_64-2.7/src/edgeobject.o
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/local/include/igraph -I/usr/include/python2.7 -c src/graphobject.c -o build/temp.linux-x86_64-2.7/src/graphobject.o
    In file included from src/graphobject.c:27:0:
    src/convert.h:63:57: error: unknown type name ‘igraph_layout_grid_t’
    src/convert.h:66:63: error: unknown type name ‘igraph_random_walk_stuck_t’
    src/graphobject.c: In function ‘igraphmodule_Graph_get_all_simple_paths’:
    src/graphobject.c:4702:3: warning: implicit declaration of function ‘igraph_get_all_simple_paths’ [-Wimplicit-function-declaration]
    src/graphobject.c: In function ‘igraphmodule_Graph_neighborhood’:
    src/graphobject.c:4824:3: error: too many arguments to function ‘igraph_neighborhood’
    In file included from /usr/local/include/igraph/igraph.h:65:0,
                     from src/graphobject.h:27,
                     from src/arpackobject.h:28,
                     from src/graphobject.c:24:
    /usr/local/include/igraph/igraph_neighborhood.h:42:5: note: declared here
    src/graphobject.c: In function ‘igraphmodule_Graph_neighborhood_size’:
    src/graphobject.c:4879:3: error: too many arguments to function ‘igraph_neighborhood_size’
    In file included from /usr/local/include/igraph/igraph.h:65:0,
                     from src/graphobject.h:27,
                     from src/arpackobject.h:28,
                     from src/graphobject.c:24:
    /usr/local/include/igraph/igraph_neighborhood.h:39:5: note: declared here
    src/graphobject.c: In function ‘igraphmodule_Graph_layout_circle’:
    src/graphobject.c:6171:5: error: too many arguments to function ‘igraph_layout_circle’
    In file included from /usr/local/include/igraph/igraph.h:69:0,
                     from src/graphobject.h:27,
                     from src/arpackobject.h:28,
                     from src/graphobject.c:24:
    /usr/local/include/igraph/igraph_layout.h:52:5: note: declared here
    src/graphobject.c: In function ‘igraphmodule_Graph_layout_kamada_kawai’:
    src/graphobject.c:6438:21: warning: passing argument 8 of ‘igraph_layout_kamada_kawai’ makes integer from pointer without a cast [enabled by default]
    In file included from /usr/local/include/igraph/igraph.h:69:0,
                     from src/graphobject.h:27,
                     from src/arpackobject.h:28,
                     from src/graphobject.c:24:
    /usr/local/include/igraph/igraph_layout.h:72:5: note: expected ‘igraph_bool_t’ but argument is of type ‘struct igraph_vector_t *’
    src/graphobject.c:6438:21: error: too few arguments to function ‘igraph_layout_kamada_kawai’
    In file included from /usr/local/include/igraph/igraph.h:69:0,
                     from src/graphobject.h:27,
                     from src/arpackobject.h:28,
                     from src/graphobject.c:24:
    /usr/local/include/igraph/igraph_layout.h:72:5: note: declared here
    src/graphobject.c:6442:21: warning: passing argument 8 of ‘igraph_layout_kamada_kawai_3d’ makes integer from pointer without a cast [enabled by default]
    In file included from /usr/local/include/igraph/igraph.h:69:0,
                     from src/graphobject.h:27,
                     from src/arpackobject.h:28,
                     from src/graphobject.c:24:
    /usr/local/include/igraph/igraph_layout.h:119:5: note: expected ‘igraph_bool_t’ but argument is of type ‘struct igraph_vector_t *’
    src/graphobject.c:6442:21: warning: passing argument 9 of ‘igraph_layout_kamada_kawai_3d’ makes integer from pointer without a cast [enabled by default]
    In file included from /usr/local/include/igraph/igraph.h:69:0,
                     from src/graphobject.h:27,
                     from src/arpackobject.h:28,
                     from src/graphobject.c:24:
    /usr/local/include/igraph/igraph_layout.h:119:5: note: expected ‘igraph_bool_t’ but argument is of type ‘struct igraph_vector_t *’
    src/graphobject.c:6442:21: error: too few arguments to function ‘igraph_layout_kamada_kawai_3d’
    In file included from /usr/local/include/igraph/igraph.h:69:0,
                     from src/graphobject.h:27,
                     from src/arpackobject.h:28,
                     from src/graphobject.c:24:
    /usr/local/include/igraph/igraph_layout.h:119:5: note: declared here
    src/graphobject.c: In function ‘igraphmodule_Graph_layout_davidson_harel’:
    src/graphobject.c:6536:3: warning: implicit declaration of function ‘igraph_layout_davidson_harel’ [-Wimplicit-function-declaration]
    src/graphobject.c: In function ‘igraphmodule_Graph_layout_fruchterman_reingold’:
    src/graphobject.c:6663:3: error: unknown type name ‘igraph_layout_grid_t’
    src/graphobject.c:6663:31: error: ‘IGRAPH_LAYOUT_AUTOGRID’ undeclared (first use in this function)
    src/graphobject.c:6663:31: note: each undeclared identifier is reported only once for each function it appears in
    src/graphobject.c:6698:3: warning: implicit declaration of function ‘igraphmodule_PyObject_to_layout_grid_t’ [-Wimplicit-function-declaration]
    src/graphobject.c:6761:8: error: incompatible type for argument 7 of ‘igraph_layout_fruchterman_reingold’
    In file included from /usr/local/include/igraph/igraph.h:69:0,
                     from src/graphobject.h:27,
                     from src/arpackobject.h:28,
                     from src/graphobject.c:24:
    /usr/local/include/igraph/igraph_layout.h:56:5: note: expected ‘igraph_real_t’ but argument is of type ‘struct igraph_vector_t *’
    src/graphobject.c:6761:8: warning: passing argument 8 of ‘igraph_layout_fruchterman_reingold’ makes integer from pointer without a cast [enabled by default]
    In file included from /usr/local/include/igraph/igraph.h:69:0,
                     from src/graphobject.h:27,
                     from src/arpackobject.h:28,
                     from src/graphobject.c:24:
    /usr/local/include/igraph/igraph_layout.h:56:5: note: expected ‘igraph_bool_t’ but argument is of type ‘struct igraph_vector_t *’
    src/graphobject.c:6761:8: error: too few arguments to function ‘igraph_layout_fruchterman_reingold’
    In file included from /usr/local/include/igraph/igraph.h:69:0,
                     from src/graphobject.h:27,
                     from src/arpackobject.h:28,
                     from src/graphobject.c:24:
    /usr/local/include/igraph/igraph_layout.h:56:5: note: declared here
    src/graphobject.c:6765:8: error: incompatible type for argument 6 of ‘igraph_layout_fruchterman_reingold_3d’
    In file included from /usr/local/include/igraph/igraph.h:69:0,
                     from src/graphobject.h:27,
                     from src/arpackobject.h:28,
                     from src/graphobject.c:24:
    /usr/local/include/igraph/igraph_layout.h:105:5: note: expected ‘igraph_real_t’ but argument is of type ‘struct igraph_vector_t *’
    src/graphobject.c:6765:8: error: incompatible type for argument 7 of ‘igraph_layout_fruchterman_reingold_3d’
    In file included from /usr/local/include/igraph/igraph.h:69:0,
                     from src/graphobject.h:27,
                     from src/arpackobject.h:28,
                     from src/graphobject.c:24:
    /usr/local/include/igraph/igraph_layout.h:105:5: note: expected ‘igraph_real_t’ but argument is of type ‘struct igraph_vector_t *’
    src/graphobject.c:6765:8: warning: passing argument 8 of ‘igraph_layout_fruchterman_reingold_3d’ makes integer from pointer without a cast [enabled by default]
    In file included from /usr/local/include/igraph/igraph.h:69:0,
                     from src/graphobject.h:27,
                     from src/arpackobject.h:28,
                     from src/graphobject.c:24:
    /usr/local/include/igraph/igraph_layout.h:105:5: note: expected ‘igraph_bool_t’ but argument is of type ‘struct igraph_vector_t *’
    src/graphobject.c:6765:8: error: too few arguments to function ‘igraph_layout_fruchterman_reingold_3d’
    In file included from /usr/local/include/igraph/igraph.h:69:0,
                     from src/graphobject.h:27,
                     from src/arpackobject.h:28,
                     from src/graphobject.c:24:
    /usr/local/include/igraph/igraph_layout.h:105:5: note: declared here
    src/graphobject.c: In function ‘igraphmodule_Graph_random_walk’:
    src/graphobject.c:11553:3: error: unknown type name ‘igraph_random_walk_stuck_t’
    src/graphobject.c:11553:38: error: ‘IGRAPH_RANDOM_WALK_STUCK_RETURN’ undeclared (first use in this function)
    src/graphobject.c:11566:3: warning: implicit declaration of function ‘igraphmodule_PyObject_to_random_walk_stuck_t’ [-Wimplicit-function-declaration]
    src/graphobject.c:11572:3: warning: implicit declaration of function ‘igraph_random_walk’ [-Wimplicit-function-declaration]
    error: command 'gcc' failed with exit status 1

    ----------------------------------------
  Rolling back uninstall of python-igraph
Command "/usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip-n8Lrwd-build/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-7oJKWF-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-n8Lrwd-build

I have already installed the current igraph package from source.

igraph installer does not detect 64-bit version of Python

From @gaborcsardi on May 4, 2013 18:58

Running Python 2.6 on a 64-bit Windows machine, igraph installer does not find Python26 directory. This appears to be related to the thread discussed here: http://bugs.python.org/issue6792 regarding disutils-based installers.

I installed the 32-bit version of Python, and problem was solved.


Imported from Launchpad using lp2gh.

Copied from original issue: igraph/igraph#270

community_spinglass with negative weights gives error in pyhton

I had previously posted this on the main igraph issue list but it is still not working for me so I thought I would post here, since its a python issue. Basically if you try to call spinglass=graph.community_spinglass(weights=graph.es['weight']) where some of the weights are negative, you will get the following error if you try to then call spinglass.modularity

InternalError: Error at community.c:900: negative weight in weight vector, Invalid value

I am no C programmer, but after a little digging, I think I might have a solution. I just don't know how to implement it. The program community.c (the one which throws the error), has a function to calculate the modularity which cannot tolerate negative weights. In this case, it may be better to catch the return value (which in this case is a pointer to the modularity) of the call to igraph_i_community_spinglass_negative in clustertool.cpp and not allow the recalculate_modularity python functionality to work. It might even be possible to regain this functionality by wrapping the PottsModel::calculate_Q() call in pottsmodel_2.cpp in the python layer. Let me know if this makes sense or if you have any advice on how to do this. Thanks!

please support reading/writing from stream-like objects, such as StringIO

From @gaborcsardi on May 4, 2013 18:59

this would save having to write temporary files everywhere

$ python
Python 2.5.5 (r255:77872, Feb 2 2010, 00:25:36)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.

from igraph import Graph
g = Graph()
from cStringIO import StringIO
f = StringIO()
print >>f, "test"
f.getvalue()
'test\n'
f = StringIO()
g.write_graphml(f)
Traceback (most recent call last):
File "", line 1, in
TypeError: string or file handle expected


Imported from Launchpad using lp2gh.

Copied from original issue: igraph/igraph#326

Vertex names are assigned double datatype when written to disk in graphml format

Here is the header of the graphml file created by write_graphml function:

<?xml version="1.0" encoding="UTF-8"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
         http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
<!-- Created by igraph -->
  <key id="v_name" for="node" attr.name="name" attr.type="double"/>
  <key id="e_wd" for="edge" attr.name="wd" attr.type="double"/>
  <key id="e_weight" for="edge" attr.name="weight" attr.type="double"/>
  <key id="e_sec" for="edge" attr.name="sec" attr.type="double"/>
  <key id="e_mon" for="edge" attr.name="mon" attr.type="double"/>
  <key id="e_year" for="edge" attr.name="year" attr.type="double"/>
  <key id="e_day" for="edge" attr.name="day" attr.type="double"/>
  <graph id="G" edgedefault="undirected">
    <node id="n0">
      <data key="v_name">15110</data>
    </node>
    <node id="n1">
      <data key="v_name">21914</data>
    </node>
    <node id="n2">
      <data key="v_name">1981</data>
    </node>
    <node id="n3">
      <data key="v_name">507</data>
    </node>

I would have ideally preferred to see long int for my vertex names, since they are actually integers. They are non-consecutive, though, so string would have been perfect as well instead of double.

I have for the time being tinkered with the graphml file to set the datatypes to correct values. For example, my "wd" attribute is ordinal, so it should be unsigned int. It would be great to have this flexibility in python-igraph.

For some reason, I am not seeing the full output I pasted, so I am attaching the screenshot.
graphml_alldouble

hash(graph) is not deterministic

The following seems to result in different hashes each time I restart the interpreter and, much more importantly, all three prints result in the same hash, although they clearly represent different graphs:

import igraph
mygraph = {"A" : {"B" : 2, "C" : 4}, "B" : {"A" : 2}, "C" : {"A" : 4}, "D":{}}
g = igraph.Graph(directed=False)
print(hash(g))
g.add_vertices(mygraph.keys())
print(hash(g))
edges = [(start, end) for start in mygraph.keys() for end in mygraph[start].keys()]
edges = [edge for edge in edges if edge[0] > edge[1]]
g.add_edges(edges)
print(hash(g)) 

[Prints out three times the same hash, but the hash changes between interpreter runs and sometimes also between executions]

IMO: if igraph can't/won't do deterministic hashes based on edges/vertices and their properties, then __hash__() should raise a TypeError. Note: pandas.DataFrames does error out the same way as lists.

I was just bitten by this as I implemented a caching decorator based on hashed inputs to a function and when I used a graph as input sometimes it used the cached values and sometimes recomputed the values (which takes 15min...).

Make python-igraph easy_installable at least on Linux and Mac OS X

From @gaborcsardi on May 4, 2013 18:42

easy_install python-igraph works only when the C core library has already been compiled and installed. Most users do not bother to read the documentation and do not realize that the C core has to be compiled beforehand.

The setup script should do at least the following before trying to build igraph:

  • Check whether the library and the include files are already there.
  • If they are not, the user should be asked whether he wants to download and compile it or whether he wants to specify an alternate location where these files are to be found.

Imported from Launchpad using lp2gh.

Copied from original issue: igraph/igraph#83

Segmentation Fault under Python Django Dev Server

From @gaborcsardi on May 4, 2013 18:58

The following code would generate a segmentation fault error when calling the "project" function for the second time, using Django (python) development server :

from igraph import *
from django.http import HttpResponse

def project(request):
print "creating graph"
g = Graph()
print "reading graph"
summary(g)
print "returning response"
return HttpResponse("Test")

The segfault occurs when reading the graph under the same variable name (i.e. "g" here) on the second call. If the name of the variable is changed (e.g. from "g" to "g1") between the first and the second call, no segfault occurs (it may be artefact though since the script is reloaded) by the server.

I am not familiar with segfault, Django dev server and C-alike problematics, but my feeling is that a memory segment is not freed when it should have been (if, of course, the goal is to emulate a production server process).

Neither do I know if the problem lies within igraph of Django. But since both libraries seem quite used - and dev bug a thorn in the foot, it seems useful to set it up as soon as possible.


Tested on Linux Mandriva 2011 (i686), Python 2.7.2, Django 1.4.3
and Debian 6.0 (x86_64), Python 2.6.6, Django 1.4.1
using igraph-6.0 (and python_igraph-6.0) libraries both compiled from source.


Python mod_wsgi apache server is not affected, though. And the following bunch code works without any problem.

! /usr/bin/env python

from wsgiref.simple_server import make_server
from igraph import *

def application(environ, start_response):
graph = Graph()
summary(graph)
response_headers = [('Content-Type', 'text/plain'),
('Content-Length', str(0))]
start_response('200 OK', response_headers)

return ["test"]

httpd = make_server('localhost', 8051, application)
httpd.handle_request()
httpd.serve_forever()


Imported from Launchpad using lp2gh.

Copied from original issue: igraph/igraph#251

segfaults writing unicode

From @gaborcsardi on May 4, 2013 18:58

writing unicode output causes igraph to segfault:

$ python
Python 2.5.5 (r255:77872, Feb 2 2010, 00:25:36)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.

import sys, igraph
igraph.version
'0.5.3'
gg = igraph.Graph(n=1, edges=[], vertex_attrs={'id': [u'\u0391\u03b8\u03ae\u03bd\u03b1']})
gg.write_dot(sys.stdout)
/* Created by igraph 0.5.3 */
graph {
0 [
Segmentation fault

the unicode string in the example is just "Αθήνα" ("Athens") and not some obscure construct.

the segfault occurs for all the write formats i tested (dot, graphml, graphmlz, pajek), except pickle, and for python 2.6 on debian.


as a side note, write_pickle gives
File "/usr/lib/python2.5/site-packages/igraph/init.py", line 844, in write_pickle
if file_was_opened: fname.close()
UnboundLocalError: local variable 'file_was_opened' referenced before assignment

which can fixed by adding "else: file_was_opened=False" to the appropriate if-block; write_pickle() succeeds without segfaulting after this


Imported from Launchpad using lp2gh.

Copied from original issue: igraph/igraph#269

Plot communities with mark_groups

The mark_groups argument to the igraph.plot function currently accepts a quite specific format. Although it is not too difficult to create this format, it would be logical to accept here igraph.VertexClustering and igraph.VertexCover as arguments.

segfault when interacting with a moderately large layout object

on os x 10.9.5, python 2.7.8, ipython 3.0.0, python-igraph 0.7.1-2

interacting in a variety of ways with a layout object of moderate size (439835 edges, 216943 vertices) is causing a segfault. I encountered the error when trying to serial a layout created with layout_lgl to disc via cPickle. However I have subsequently gotten a segfault under a variety of suspiciously similar circumstances, but with a random layout. I am yet to sucessfully get the object to serialize to disc via any means. See screens for various paths to segfaults.
image
image
image

untitled

Iterating through Python VertexClustering

I am trying to do community detection on a graph. When I try to iterate through the vertexCluster obtained from my graph, I get different membership as compared to printing the vertexCluster directly. Where am I going wrong in my understanding?

The following is the piece of code:

from igraph import * 
g = Graph.Read_Ncol("network.txt", directed=False)
communityCluster = g.community_infomap()

print communityVertexClustering  \\Gives a different list when compared to the following lines
print communityVertexClustering[0]
Output:
[ 0] 740, 15, 991, 994, 996, 997, 998, 999, 1000, 48, 985, 59, 995, 132, 138,
     606, 182, 188, 982, 976, 936, 243, 932, 496, 255, 271, 278, 959, 589,
     329, 745, 414, 417, 420, 422, 434, 898, 983, 499, 933, 596, 620, 640,
     678, 693, 915, 759, 815, 829
[ 1] 275, 238, 953, 758, 76, 956, 969, 975, 986, 989, 992, 909, 96, 770, 103,
     937, 856, 162, 910, 960, 203, 767, 922, 206, 643, 858, 260, 551, 286,
     343, 426, 870, 435, 443, 725, 534, 482, 488, 517, 544, 623, 575, 581,
     708, 605, 655
....

78 99 100 101 102 103 104 105 106 255 256 295 296 545 558 570 637 650 651 699 722 729 739 740 744 764 772 821 829 830 881 897 902 903 904 915 949 953 954 962 986 989 992 993 995 996 997 998 999

If you notice the set of nodes in the first line of communityVertexClustering is different from the output of the second print statement.

I have attached the network.txt file.

network.txt

Pandas interface for reading files

Since the R-version of igraph makes reading files (for example, in csv format) easy, could the Python version use something similar? Something like igraph.read_csv?

canonical labels for colored graph

For colored graphs the canonical labeling does not work (this is supported by bliss I believe). An example script is included below. The last canonical labeling printed is [3, 1, 2, 0], but this does not respect the coloring.

import igraph
g = igraph.Graph()
for ii in range(4):
    g.add_vertex()

print( g.canonical_permutation() )
g.add_edge(0,0)
g.add_edge(2,2)

print( g.canonical_permutation() )

g.vs[0]['color']=0
g.vs[1]['color']=0
g.vs[2]['color']=1
g.vs[3]['color']=1

print( g.canonical_permutation() )

`Graph.add_vertex()` should return created vertex object

From @aconrad on March 25, 2014 16:35

Why doesn't Graph.add_vertex() return the created vertex object? When I look at the source code it seems that there is a return statement but it always returns None for me.

It would be much nicer if I could do this:

>>> import igraph
>>> g = igraph.Graph()
>>> v1 = g.add_vertex()
>>> v1
igraph.Vertex(<igraph.Graph object at 0x1591148>,0,{})

Rather than doing this crazy thing:

>>> import igraph
>>> g = igraph.Graph()
>>> g.add_vertex()
>>> v1 = g.vs[g.vcount()-1]

The same should be done for Graph.add_edge() and their plural counter parts which would return a list of the created items, so:

>>> import igraph
>>> g = igraph.Graph()
>>> v1, v2, v3 = g.add_verticies(3)
>>> v1
igraph.Vertex(<igraph.Graph object at 0x1f9e148>,0,{})
>>> v2
igraph.Vertex(<igraph.Graph object at 0x1f9e148>,1,{})
>>> v3
igraph.Vertex(<igraph.Graph object at 0x1f9e148>,2,{})

Copied from original issue: igraph/igraph#602

Unclear error when ig.Graph.Read() given bad file path

In python 3.4, when one uses ig.Read.Graph('file', format='pickle') and passes a bad file name (with a typo or something), the error is very hard to understand -- the error is:

TypeError: 'str' does not support the buffer interface"

The error occurs at line ~1801 of init.py at the line result = pickle.loads(fname)

I've offered one solution in PR #41

How does community_spinglass work exactly?

I want to use community_spinglass for my research, but I cannot figure out exactly what it does. I read the reference "Statistical Mechanics of Community Detection", which states that they use simulated annealing, but not exactly how. So I would like to know what update rules are used for the simulated annealing: How are the nodes moved between communities in each time step?

Different IPython interface

I've found that the svg rendering becomes a real performance hog when the plotted graph gets big.

I've build the following functions, which are enabled similar to the version which manages the image plotting of matplotlib figures:

def render_igraph_plot(plot, fmt):
    """returns a image representation of this plot as a string.

    Parameters
    ==========
    plot : igraph.Plot
        The plot which should be converted
    formats : str or set
        The image format: 'png', 'svg', 'pdf'.
    """
    import igraph
    from igraph.drawing.utils import find_cairo, BoundingBox
    from io import BytesIO

    cairo = find_cairo()
    io = BytesIO()

    width = plot.bbox.width
    height = plot.bbox.height
    orig_bbox = None
    orig_obj = None 

    # This is an ugly hack :-( Unfortunately I see no other way to change 
    # the size of a already existing igraph plot. 
    # We only change the size if this is a "normal" plot, meaning that the 
    # plot has exactly one object to plot and the bbox of this object is a 
    # "standard" one, i.e., size is 2*20 lower than the one from the plot   
    if len(plot._objects) == 1:
        if (plot.bbox.width == plot._objects[0][1].width + 40 and 
            plot.bbox.height == plot._objects[0][1].height + 40):
            orig_bbox = plot.bbox
            orig_obj = plot._objects[0]

            figsize = getattr(igraph, "figsize", (6,4)) # same as matplotlib
            dpi = getattr(igraph, "dpi", 80) # same as matplotlib

            if fmt == "png":
                width = figsize[0] * dpi
                height = figsize[1] * dpi
            else:
                width = figsize[0] * 72
                height = figsize[1] * 72

            new_bbox = BoundingBox(width, height)
            new_obj = (orig_obj[0], new_bbox.contract(20), orig_obj[2], orig_obj[3], orig_obj[4], orig_obj[5])
            plot.bbox = new_bbox
            plot._objects[0] = new_obj

    if fmt == "png":
        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, int(width), int(height))
    elif fmt == "svg":
        surface = cairo.SVGSurface(io, width, height)
    elif fmt == "pdf":
        surface = cairo.PDFSurface(io, width, height)
    else:
        raise ValueError("Unknown format: %s" % fmt)

    context = cairo.Context(surface)
    plot.redraw(context)

    if fmt != "png":
         # No idea why this is needed but python crashes without
        context.show_page()
        surface.finish()
    else:
        # png is treated differently, the rest has the IO in the surface creation
        surface.write_to_png(io)

    ret = io.getvalue()

    if fmt == "svg":
        # the same does ipython with matplotlib figures
        ret = ret.encode("utf-8")

    if orig_bbox or orig_obj:
        plot.bbox = orig_bbox
        plot._objects[0] = orig_obj

    return ret

def set_igraph_figsize_in_ipython(figsize=(8,6), dpi=80):
    import igraph
    if not isinstance(figsize, tuple):
        raise ValueError("figsize must be a tuple (width, heigh) in inch")

    try: 
        dpi = int(dpi)
    except:
        raise ValueError("dpi must be an int")

    igraph.figsize = figsize
    igraph.dpi = dpi

def select_igraph_plot_formats(formats):
    """Select figure formats for the inline backend.

    Parameters
    ==========
    formats : str or set
        One or a set of figure formats to enable: 'png', 'svg', 'pdf'.
    """
    from IPython.core.interactiveshell import InteractiveShell
    from IPython.utils import py3compat
    from igraph import Plot

    shell = InteractiveShell.instance()

    svg_formatter = shell.display_formatter.formatters['image/svg+xml']
    png_formatter = shell.display_formatter.formatters['image/png']
    pdf_formatter = shell.display_formatter.formatters['application/pdf']

    if isinstance(formats, py3compat.string_types):
        formats = {formats}
    # cast in case of list / tuple
    formats = set(formats)

    [ f.pop(Plot, None) for f in shell.display_formatter.formatters.values() ]

    supported = {'png', 'svg', 'pdf'}
    bad = formats.difference(supported)
    if bad:
        bs = "%s" % ','.join([repr(f) for f in bad])
        gs = "%s" % ','.join([repr(f) for f in supported])
        raise ValueError("supported formats are: %s not %s" % (gs, bs))

    if 'png' in formats:
        png_formatter.for_type(Plot, lambda plot: render_igraph_plot(plot, "png") )
    if 'svg' in formats:
        svg_formatter.for_type(Plot, lambda plot: render_igraph_plot(plot, "svg") )
    if 'pdf' in formats:
        pdf_formatter.for_type(Plot, lambda plot: render_igraph_plot(plot, "pdf") )

Usage:

import igraph
select_igraph_plot_formats(["svg"])
set_igraph_figsize_in_ipython(figsize=(4,3), dpi=80)
g = igraph.Graph.Barabasi(5,6)
plot = igraph.plot(g)
plot

Would you take such a patch?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.