Parens for Python - Network Analysis and Visualization
with IGraph and Lieden
We are going to explore some more Python libraries through the use of libpython-clj.
This time, we are going to look at IGraph and Lieden.
{:deps
{org.clojure/clojure {:mvn/version "1.10.1"}
cnuernber/libpython-clj {:mvn/version "1.36"}}}
Install the python dependencies and display
sudo apt-get update
sudo apt-get install eog
conda install -c conda-forge python-igraph cairocffi leidenalg
IGraph
IGraph is a library for network analysis and visualization.
Here we use python require to load it in as well as its supporting plotting library cario.
We then create a graph and add some vertices and edges to it.
(require [libpython-clj.require :refer [require-python]]
[libpython-clj.python :as py :refer [py. py.. py.-]])
(require-python [igraph :as igraph])
(require-python [cairocffi])
(def g (igraph/Graph))
(py. g add_vertices 3)
(py. g add_edges [[0 1] [1 2]])
From there we, can continue to add edges and vertices using a interop doto
for the graphics. Finally, we can print out a summary of the graph.
(doto g
(py. add_edges [[2 0]])
(py. add_vertices 3)
(py. add_edges [[2 3] [3 4] [4 5] [5 3]]))
(igraph/summary g)
Let's get a more interesting graph using one of the preloaded "Famous" petersen graph and we can plot what it looks like.
(def g2 (py. (igraph/Graph) Famous "petersen"))
(igraph/plot g2, "results/test.png")
Leidenalg
The leindenalg library provides clustering and community detection with graphs. The core function is find_partition
which finds the optimal partition using the Leiden algorithm
(require-python [leidenalg :as la])
(def G (py. (igraph/Graph) Famous "Zachary"))
;;;Now detecting communities with modularity is straightforward
(def la-partition (la/find_partition G la/ModularityVertexPartition))
(igraph/plot la-partition, "results/partition.png")