Below are few "toy" examples demonstrating how to use the package for both counting network motifs (triads) and visualizing the results.
import netsci.models.random as nsr
import netsci.metrics.motifs as nsm
import netsci.visualization as nsv
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.dpi'] = 144
First, let's generate a sample adjacency matrix using the Erdős–Rényi model.
n = 500 # The number of nodes
p = 0.1 # The probability for a connection (or, "sparsity")
A = nsr.erdos_renyi(n, p)
Count all 16 triplet motifs using a naïve brute-force algorithm (complexity of O($n^3$)).
nsm.motifs(A, algorithm='brute-force')
array([11040390, 7301442, 425147, 805446, 400906, 401677, 88803, 94130, 93852, 29547, 5329, 10337, 5181, 5053, 1236, 24])
Efficient counting of all 13 connected triplets (using the algorithm given in Itzhack et al. (2007)).
f = nsm.motifs(A)
print(f)
[ -1 -1 -1 805446 400906 401677 88803 94130 93852 29547 5329 10337 5181 5053 1236 24]
nsv.bar_motifs(f)
[ 1 2 3 4 5 6 7 8 9 10 11 12 13]
[<matplotlib.axes._subplots.AxesSubplot at 0x1165d6438>, <matplotlib.axes._subplots.AxesSubplot at 0x116678860>]
The plotted order is by the convention as in Gal et al. (2017). We can also use different order (see below).
To get the patterns explicitely:
nsm.triad_patterns()
[array([[0, 0, 0], [0, 0, 0], [0, 0, 0]]), array([[0, 1, 0], [0, 0, 0], [0, 0, 0]]), array([[0, 1, 0], [1, 0, 0], [0, 0, 0]]), array([[0, 1, 0], [0, 0, 0], [1, 0, 0]]), array([[0, 0, 0], [1, 0, 0], [1, 0, 0]]), array([[0, 1, 1], [0, 0, 0], [0, 0, 0]]), array([[0, 1, 1], [0, 0, 1], [0, 0, 0]]), array([[0, 0, 0], [0, 0, 1], [1, 1, 0]]), array([[0, 1, 0], [0, 0, 1], [0, 1, 0]]), array([[0, 1, 0], [0, 0, 1], [1, 0, 0]]), array([[0, 1, 1], [1, 0, 0], [1, 0, 0]]), array([[0, 1, 0], [0, 0, 1], [1, 1, 0]]), array([[0, 0, 0], [1, 0, 1], [1, 1, 0]]), array([[0, 1, 1], [0, 0, 1], [0, 1, 0]]), array([[0, 1, 1], [1, 0, 1], [1, 0, 0]]), array([[0, 1, 1], [1, 0, 1], [1, 1, 0]])]
To visualize them:
plt.figure(figsize=(10, 3), dpi=300)
nsv.plot_all_triads(ax=plt.gca())
The mean frequencies of triads in an Erdős–Rényi model can be computed analytically.
from scipy.special import comb
C3n = comb(n, 3)
f_analytic = C3n * nsm.triad_proba(p)
print("Counting motifs..")
f = nsm.motifs(A)
print("Plotting..")
nsv.bar_motifs(f, f_analytic)
Counting motifs.. Plotting.. [ 1 2 3 4 5 6 7 8 9 10 11 12 13]
[<matplotlib.axes._subplots.AxesSubplot at 0x11668b748>, <matplotlib.axes._subplots.AxesSubplot at 0x116a1bcf8>]
For instance, the convention used in Rubinov and Sporns (2010):
nsv.bar_motifs(f, order=nsm.triad_order_bct, title='Brain Connectivity Toolbox (BCT) triad order')
[ 1 2 3 4 5 6 7 8 9 10 11 12 13]
[<matplotlib.axes._subplots.AxesSubplot at 0x116ac5dd8>, <matplotlib.axes._subplots.AxesSubplot at 0x116a43cf8>]