In [18]:
import networkx as nx
import matplotlib.pyplot as plt
import warnings
from custom import custom_funcs as cf
warnings.filterwarnings('ignore')
#import __future__
import itertools
%matplotlib inline
%load_ext autoreload
%autoreload 2


The autoreload extension is already loaded. To reload it, use:
  %reload_ext autoreload

Load Data

As usual, let's start by loading some network data. This time round, we have a physician trust network, but slightly modified such that it is undirected rather than directed.

This directed network captures innovation spread among 246 physicians in for towns in Illinois, Peoria, Bloomington, Quincy and Galesburg. The data was collected in 1966. A node represents a physician and an edge between two physicians shows that the left physician told that the righ physician is his friend or that he turns to the right physician if he needs advice or is interested in a discussion. There always only exists one edge between two nodes even if more than one of the listed conditions are true.


In [19]:
# Load the network.
G = cf.load_physicians_network()

In [20]:
# Make a Circos plot of the graph
import numpy as np
from circos import CircosPlot

nodes = sorted(G.nodes())
edges = G.edges()
edgeprops = dict(alpha=0.1)
nodecolor = plt.cm.viridis(np.arange(len(nodes)) / len(nodes)) 
fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(111)
c = CircosPlot(nodes, edges, radius=10, ax=ax, edgeprops=edgeprops, nodecolor=nodecolor)
c.draw()


<matplotlib.figure.Figure at 0x28dabef65f8>

Question

What can you infer about the structure of the graph from the Circos plot?

Structures in a Graph

We can leverage what we have learned in the previous notebook to identify special structures in a graph.

In a network, cliques are one of these special structures.

Cliques

In a social network, cliques are groups of people in which everybody knows everybody. Triangles are a simple example of cliques. Let's try implementing a simple algorithm that finds out whether a node is present in a triangle or not.

The core idea is that if a node is present in a triangle, then its neighbors' neighbors' neighbors should include itself.


In [22]:
# Example code.
def in_triangle(G, node):
    """
    Returns whether a given node is present in a triangle relationship or not.
    """
    # We first assume that the node is not present in a triangle.
    is_in_triangle = False
    
    # Then, iterate over every pair of the node's neighbors.
    for nbr1, nbr2 in itertools.combinations(G.neighbors(node), 2):
        # Check to see if there is an edge between the node's neighbors.
        # If there is an edge, then the given node is present in a triangle.
        if G.has_edge(nbr1, nbr2):
            is_in_triangle = True
            # We break because any triangle that is present automatically 
            # satisfies the problem requirements.
            break
    return is_in_triangle

in_triangle(G, 3)


Out[22]:
True

In reality, NetworkX already has a function that counts the number of triangles that any given node is involved in. This is probably more useful than knowing whether a node is present in a triangle or not, but the above code was simply for practice.


In [23]:
nx.triangles(G, 3)


Out[23]:
3

Exercise

Can you write a function that takes in one node and its associated graph as an input, and returns a list or set of itself + all other nodes that it is in a triangle relationship with? Do not return the triplets, but the set/list of nodes.

Possible Implementation: If my neighbor's neighbor's neighbor includes myself, then we are in a triangle relationship.

Possible Implementation: If I check every pair of my neighbors, any pair that are also connected in the graph are in a triangle relationship with me.

Hint: Python's itertools module has a combinations function that may be useful.

Hint: NetworkX graphs have a .has_edge(node1, node2) function that checks whether an edge exists between two nodes.

Verify your answer by drawing out the subgraph composed of those nodes.


In [25]:
# Possible answer
def get_triangles(G, node):
    neighbors = set(G.neighbors(node))
    triangle_nodes = set()
    """
    Fill in the rest of the code below.
    """
    triangle_nodes.add(node)
    is_in_triangle = False
    
    # Then, iterate over every pair of the node's neighbors.
    for nbr1, nbr2 in itertools.combinations(neighbors, 2):
        # Check to see if there is an edge between the node's neighbors.
        # If there is an edge, then the given node is present in a triangle.
        if G.has_edge(nbr1, nbr2):
            # We break because any triangle that is present automatically 
            # satisfies the problem requirements.
            triangle_nodes.add(nbr1)
            triangle_nodes.add(nbr2)
            
    return triangle_nodes

# Verify your answer with the following funciton call. Should return something of the form:
# {3, 9, 11, 41, 42, 67}
get_triangles(G, 3)


Out[25]:
{3, 9, 11, 41, 42, 67}

In [26]:
# Then, draw out those nodes.
nx.draw(G.subgraph(get_triangles(G, 3)), with_labels=True)



In [28]:
# Compare for yourself that those are the only triangles that node 3 is involved in.
neighbors3 = G.neighbors(3)
neighbors3.append(3)
nx.draw(G.subgraph(neighbors3), with_labels=True)


Friend Recommendation: Open Triangles

Now that we have some code that identifies closed triangles, we might want to see if we can do some friend recommendations by looking for open triangles.

Open triangles are like those that we described earlier on - A knows B and B knows C, but C's relationship with A isn't captured in the graph.

What are the two general scenarios for finding open triangles that a given node is involved in?

  1. The given node is the centre node.
  2. The given node is one of the termini nodes.

Exercise

Can you write a function that identifies, for a given node, the other two nodes that it is involved with in an open triangle, if there is one?

Note: For this exercise, only consider the case when the node of interest is the centre node.

Possible Implementation: Check every pair of my neighbors, and if they are not connected to one another, then we are in an open triangle relationship.


In [35]:
# Fill in your code here.
def get_open_triangles(G, node):
    """
    There are many ways to represent this. One may choose to represent only the nodes involved 
    in an open triangle; this is not the approach taken here.
    
    Rather, we have a code that explicitly enumrates every open triangle present.
    """
    open_triangle_nodes = []
    neighbors = set(G.neighbors(node))
    
    #for n in neighbors:
    for nbr1, nbr2 in itertools.combinations(neighbors, 2):
        # Check to see if there is an edge between the node's neighbors.
        # If there is an edge, then the given node is present in a triangle.
        if not G.has_edge(nbr1, nbr2):
            # We break because any triangle that is present automatically 
            # satisfies the problem requirements.
            open_triangle_nodes.append([nbr1,node,nbr2])
    return open_triangle_nodes

In [36]:
# # Uncomment the following code if you want to draw out each of the triplets.
nodes = get_open_triangles(G, 2)
for i, triplet in enumerate(nodes):
    fig = plt.figure(i)
    nx.draw(G.subgraph(triplet), with_labels=True)
print(get_open_triangles(G, 3))
len(get_open_triangles(G, 3))


[[1, 3, 67], [1, 3, 101], [1, 3, 9], [1, 3, 41], [1, 3, 42], [1, 3, 11], [1, 3, 112], [1, 3, 91], [67, 3, 101], [67, 3, 9], [67, 3, 41], [67, 3, 11], [67, 3, 112], [67, 3, 91], [101, 3, 9], [101, 3, 41], [101, 3, 42], [101, 3, 11], [101, 3, 112], [101, 3, 91], [9, 3, 42], [9, 3, 112], [9, 3, 91], [41, 3, 42], [41, 3, 11], [41, 3, 112], [41, 3, 91], [42, 3, 11], [42, 3, 112], [42, 3, 91], [11, 3, 112], [11, 3, 91], [112, 3, 91]]
Out[36]:
33

Triangle closure is also the core idea behind social networks' friend recommendation systems; of course, it's definitely more complicated than what we've implemented here.

Cliques

We have figured out how to find triangles. Now, let's find out what cliques are present in the network. Recall: what is the definition of a clique?

  • NetworkX has a clique-finding algorithm implemented.
  • This algorithm finds all maximally-sized cliques for a given node.
  • Note that maximal cliques of size n include all cliques of size < n

In [37]:
list(nx.find_cliques(G))


Out[37]:
[[1, 72],
 [1, 2],
 [1, 3],
 [1, 4, 5, 6],
 [1, 7],
 [2, 41],
 [2, 10],
 [2, 11, 40],
 [2, 11, 39],
 [2, 42, 110],
 [3, 67, 42],
 [3, 101],
 [3, 9, 41],
 [3, 9, 11],
 [3, 112],
 [3, 91],
 [4, 6, 32],
 [4, 6, 109],
 [4, 104],
 [4, 74, 116],
 [4, 46, 55],
 [4, 22],
 [4, 55, 32],
 [4, 59],
 [5, 38, 69],
 [5, 39],
 [5, 9, 8],
 [5, 9, 89],
 [5, 9, 66],
 [5, 9, 69],
 [5, 9, 85],
 [5, 45],
 [5, 91],
 [6, 31, 109],
 [7, 102],
 [8, 9, 10],
 [8, 9, 11],
 [8, 12, 11],
 [9, 70, 41],
 [9, 70, 10],
 [9, 40, 89, 11],
 [9, 40, 66],
 [9, 40, 69],
 [9, 40, 85],
 [9, 41, 69],
 [9, 10, 89],
 [9, 82, 85],
 [9, 53, 89],
 [10, 67, 89],
 [10, 102, 94],
 [10, 108],
 [10, 77, 89],
 [10, 77, 45],
 [10, 77, 38],
 [10, 83, 91],
 [10, 54],
 [10, 91, 94],
 [11, 65, 15],
 [11, 39, 12],
 [11, 40, 12, 15],
 [11, 40, 94],
 [11, 43, 15],
 [11, 79],
 [11, 87],
 [11, 28, 12],
 [11, 93],
 [12, 97, 19],
 [12, 97, 100],
 [12, 97, 47],
 [12, 67, 66],
 [12, 100, 28],
 [12, 40, 66],
 [12, 40, 75],
 [12, 40, 69, 73],
 [12, 108],
 [12, 19, 75],
 [13, 47, 16, 17],
 [13, 47, 43],
 [13, 15, 16, 22],
 [13, 15, 59],
 [13, 15, 18, 65],
 [13, 15, 18, 74, 14],
 [13, 15, 43],
 [13, 17, 16, 19],
 [13, 17, 16, 22],
 [13, 17, 74, 14],
 [13, 86, 18],
 [13, 92, 16, 22],
 [13, 30],
 [14, 56, 57],
 [14, 56, 18],
 [14, 51],
 [14, 74, 57, 101],
 [14, 75],
 [15, 96, 16],
 [15, 96, 54],
 [15, 74, 60],
 [15, 74, 54],
 [15, 16, 49],
 [15, 16, 34, 29],
 [15, 16, 60],
 [15, 81],
 [15, 83],
 [15, 23, 33, 34],
 [15, 23, 34, 29],
 [15, 23, 80],
 [15, 23, 22],
 [15, 23, 54, 40, 37],
 [15, 23, 54, 115],
 [15, 59, 60],
 [15, 60, 33],
 [15, 62],
 [16, 19, 63],
 [16, 27],
 [16, 63, 29],
 [17, 64, 47],
 [17, 84],
 [18, 35, 74],
 [18, 28],
 [19, 36, 63],
 [19, 63, 75],
 [20, 24],
 [20, 25, 112],
 [20, 25, 21, 117, 95],
 [20, 25, 21, 23],
 [20, 22, 23],
 [21, 36],
 [21, 37, 25, 23],
 [21, 38],
 [23, 25, 111],
 [23, 51, 63],
 [23, 63, 29],
 [23, 102, 40],
 [24, 32, 92],
 [24, 32, 93],
 [24, 35, 92],
 [24, 39],
 [24, 75],
 [24, 81],
 [24, 90],
 [25, 98, 111],
 [25, 41],
 [25, 27],
 [25, 93, 112],
 [26, 109, 33],
 [26, 109, 31],
 [26, 48, 29],
 [26, 48, 31],
 [26, 30, 27],
 [26, 28, 32],
 [26, 28, 33],
 [26, 28, 31],
 [26, 62],
 [27, 54],
 [27, 55, 46],
 [27, 55, 30],
 [28, 100, 31],
 [28, 44],
 [28, 71],
 [29, 104],
 [29, 105],
 [29, 106],
 [29, 113],
 [29, 53, 63],
 [29, 57],
 [30, 104],
 [30, 99, 84, 55],
 [30, 100],
 [31, 41, 109],
 [31, 60],
 [31, 49, 48],
 [31, 49, 100],
 [32, 47],
 [32, 55, 92],
 [33, 35, 34],
 [33, 35, 109],
 [35, 105],
 [35, 98],
 [35, 100, 74],
 [36, 106],
 [36, 44, 43],
 [36, 44, 76],
 [36, 45, 43, 47],
 [36, 45, 76],
 [36, 45, 63],
 [36, 78, 76],
 [36, 79, 47],
 [38, 86, 78],
 [38, 58],
 [38, 101, 69],
 [39, 78],
 [40, 102, 94],
 [40, 71, 73, 54],
 [40, 75, 89],
 [41, 68, 69],
 [41, 68, 70],
 [41, 109, 69],
 [41, 94],
 [41, 103],
 [42, 83],
 [42, 74],
 [42, 67, 72, 103],
 [42, 58, 110],
 [43, 46, 44],
 [44, 64],
 [44, 48],
 [45, 72],
 [45, 80],
 [45, 93],
 [46, 84, 82],
 [46, 84, 55, 87],
 [46, 60],
 [47, 97, 79],
 [48, 50],
 [48, 51],
 [48, 116, 52],
 [49, 68],
 [49, 103],
 [50, 89],
 [51, 104],
 [51, 73],
 [51, 114],
 [52, 63],
 [53, 68],
 [53, 84],
 [53, 78],
 [54, 105],
 [55, 94],
 [55, 86],
 [56, 58],
 [57, 68],
 [58, 104],
 [58, 99],
 [58, 91],
 [58, 88],
 [59, 61],
 [60, 113],
 [60, 114],
 [61, 87],
 [62, 64],
 [62, 63],
 [63, 81],
 [63, 86],
 [67, 103, 98],
 [69, 98, 111],
 [69, 101, 87],
 [69, 79],
 [69, 93],
 [71, 72, 73],
 [72, 78],
 [73, 99, 84],
 [74, 97, 106],
 [74, 97, 100],
 [74, 108],
 [74, 101, 87],
 [75, 80],
 [75, 77, 89],
 [75, 103],
 [77, 81],
 [78, 88],
 [78, 85],
 [78, 87],
 [81, 82],
 [82, 83],
 [84, 107, 87],
 [86, 106],
 [87, 105],
 [89, 90],
 [91, 98, 94],
 [92, 107, 108],
 [93, 113],
 [97, 98],
 [101, 102],
 [102, 112],
 [118, 137, 122],
 [118, 121, 120],
 [118, 121, 131],
 [118, 119],
 [123, 120],
 [123, 124, 160, 126],
 [123, 124, 125],
 [126, 137],
 [126, 121, 160, 136],
 [126, 121, 161, 162],
 [126, 119, 160],
 [127, 130, 144, 141],
 [127, 130, 151],
 [127, 133, 128, 156],
 [127, 133, 128, 141],
 [127, 133, 128, 157],
 [127, 133, 131],
 [127, 133, 142],
 [127, 134, 132, 128],
 [127, 134, 132, 125],
 [127, 134, 132, 144],
 [127, 137, 142],
 [127, 141, 128, 129],
 [127, 141, 128, 145],
 [127, 144, 156, 132],
 [127, 145, 128, 132],
 [127, 145, 148],
 [127, 149, 148],
 [127, 149, 157, 128],
 [127, 149, 157, 158],
 [127, 150, 156],
 [127, 150, 151, 155],
 [127, 150, 151, 148],
 [127, 119, 129, 128],
 [127, 119, 129, 158],
 [127, 119, 125],
 [127, 121, 161, 120],
 [127, 121, 161, 162],
 [127, 121, 161, 125],
 [127, 121, 131, 159],
 [127, 121, 131, 129],
 [127, 121, 131, 151],
 [127, 121, 132, 128, 129],
 [127, 121, 132, 120],
 [127, 121, 132, 125, 142],
 [127, 121, 136, 120],
 [127, 121, 148, 151],
 [127, 121, 158, 129],
 [127, 155, 129],
 [127, 155, 162],
 [127, 156, 128, 132],
 [127, 157, 136],
 [135, 136, 121],
 [135, 137],
 [138, 144, 130, 140],
 [138, 144, 130, 141],
 [138, 121, 136],
 [138, 121, 129, 128],
 [138, 121, 129, 158],
 [138, 121, 140],
 [138, 141, 128, 129],
 [139, 136],
 [139, 162],
 [139, 152],
 [139, 134],
 [139, 151],
 [143, 161],
 [143, 137],
 [143, 145],
 [143, 134, 144],
 [143, 151],
 [146, 128, 145],
 [146, 128, 163],
 [147, 145],
 [147, 153],
 [147, 155, 151],
 [152, 128, 164],
 [152, 128, 133],
 [152, 128, 149],
 [152, 153, 154, 133],
 [152, 150],
 [153, 148],
 [163, 128, 121, 132],
 [163, 128, 149],
 [164, 131],
 [165, 128],
 [165, 162],
 [165, 159],
 [166, 168, 167],
 [166, 169, 170, 173],
 [166, 169, 172],
 [166, 171, 172],
 [166, 171, 167],
 [167, 178],
 [167, 194, 192],
 [167, 194, 171],
 [167, 194, 190],
 [167, 194, 168],
 [167, 204],
 [167, 174, 171],
 [168, 185],
 [168, 194, 200, 179],
 [168, 194, 197, 203, 179],
 [168, 194, 197, 196],
 [168, 194, 198, 203],
 [168, 194, 198, 196],
 [169, 197, 173],
 [170, 193, 192],
 [170, 193, 185, 202],
 [170, 193, 188],
 [170, 187, 185],
 [170, 204, 185],
 [170, 173, 188],
 [170, 189, 192],
 [170, 189, 202],
 [171, 194, 196, 197],
 [171, 194, 196, 199],
 [171, 174, 175],
 [172, 200],
 [172, 198],
 [174, 176, 177],
 [174, 176, 175],
 [175, 183, 191],
 [175, 190, 176],
 [176, 198, 186],
 [177, 196, 197],
 [177, 206],
 [178, 179],
 [178, 180, 181],
 [179, 188],
 [182, 186, 184, 183],
 [182, 186, 185, 187],
 [182, 188, 184],
 [182, 189],
 [183, 195, 192],
 [183, 195, 184, 186],
 [183, 195, 184, 202],
 [183, 204, 184],
 [183, 191, 192],
 [183, 191, 202],
 [184, 193, 195, 186],
 [184, 193, 195, 202],
 [184, 193, 188],
 [185, 193, 202, 195],
 [185, 193, 202, 191],
 [185, 193, 186, 195],
 [187, 194, 200, 201],
 [187, 194, 200, 199],
 [187, 194, 197],
 [190, 197, 194],
 [191, 193, 192],
 [192, 193, 195],
 [192, 194, 201],
 [192, 194, 198],
 [192, 206],
 [194, 205, 197],
 [194, 205, 198],
 [195, 197],
 [198, 202],
 [207, 209, 208, 210, 211],
 [207, 209, 213],
 [207, 212],
 [208, 210, 228, 225, 220, 216],
 [208, 210, 228, 225, 220, 209, 221],
 [208, 210, 228, 227, 216],
 [208, 210, 228, 211, 216],
 [208, 210, 228, 211, 209],
 [208, 210, 223, 216, 211],
 [208, 210, 223, 216, 220],
 [208, 210, 223, 221, 220],
 [208, 226, 209, 220, 221],
 [208, 229, 209, 220],
 [208, 229, 227],
 [208, 229, 231],
 [209, 217, 211, 228],
 [209, 217, 221, 218],
 [209, 217, 221, 220, 225, 228],
 [209, 217, 221, 220, 226],
 [209, 218, 213],
 [209, 213, 229],
 [209, 213, 214],
 [209, 214, 210],
 [210, 233, 216, 220],
 [210, 219, 220, 228, 221],
 [210, 214, 216],
 [211, 232],
 [211, 240, 234],
 [213, 230],
 [213, 233, 234],
 [213, 233, 235],
 [213, 233, 229],
 [213, 240, 234],
 [213, 240, 235],
 [213, 214, 215],
 [213, 215, 218],
 [213, 223],
 [215, 226],
 [215, 231, 237, 236],
 [215, 231, 237, 238],
 [216, 235, 233],
 [216, 230],
 [217, 219, 220, 221, 226],
 [217, 219, 220, 221, 228],
 [217, 222, 218],
 [219, 240, 234],
 [219, 240, 235],
 [219, 226, 224, 220, 221],
 [219, 226, 235],
 [220, 224, 223, 221],
 [220, 232],
 [220, 233, 229],
 [224, 227],
 [229, 241],
 [229, 231, 233],
 [230, 232, 231],
 [231, 232, 237, 236],
 [231, 232, 237, 238],
 [231, 233, 235],
 [232, 239, 237],
 [235, 241]]

Exercise

This should allow us to find all n-sized maximal cliques. Try writing a function maximal_cliques_of_size(size, G) that implements this.


In [ ]:
def maximal_cliqes_of_size(size, G):
    return ______________________

maximal_cliqes_of_size(2, G)

Connected Components

From Wikipedia:

In graph theory, a connected component (or just component) of an undirected graph is a subgraph in which any two vertices are connected to each other by paths, and which is connected to no additional vertices in the supergraph.

NetworkX also implements a function that identifies connected component subgraphs.

Remember how based on the Circos plot above, we had this hypothesis that the physician trust network may be divided into subgraphs. Let's check that, and see if we can redraw the Circos visualization.


In [ ]:
ccsubgraphs = list(nx.connected_component_subgraphs(G))
len(ccsubgraphs)

Exercise

Play a bit with the Circos API. Can you colour the nodes by their subgraph identifier?


In [ ]:
# Start by labelling each node in the master graph G by some number
# that represents the subgraph that contains the node.
for i, g in enumerate(_____________):
    # Fill in code below.
        
# Then, pass in a list of nodecolors that correspond to the node order.
# Feel free to change the colours around!
node_cmap = {0: 'red', 1:'blue', 2: 'green', 3:'yellow'}
nodecolor = [__________________________________________]

nodes = sorted(G.nodes())
edges = G.edges()
edgeprops = dict(alpha=0.1)

In [ ]:
fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(111)
c = CircosPlot(nodes, edges, radius=10, ax=ax, fig=fig, edgeprops=edgeprops, nodecolor=nodecolor)
c.draw()
plt.savefig('images/physicians.png', dpi=300)

And "admire" the division of the US congress over the years...


In [ ]: