`networkx`

¶I came across this 1927 graphic showing the musical descendants of Czerny:

What follows is my attempt to create a similar music-ancestry graph directly from data.

Fortunately for us, Wikipedia has an incredible comprehensive series of lists of music students by teacher that is perfect for our purposes – each teacher is given a heading and followed by a list of students.

Let's try scraping it.

In [1]:

```
%matplotlib notebook
import matplotlib.pyplot as plt
```

In [2]:

```
import codecs
import json
import urllib
from requests import get
from bs4 import BeautifulSoup
import networkx as nx
```

In [3]:

```
pages = [
'https://en.wikipedia.org/wiki/List_of_music_students_by_teacher:_A_to_B',
'https://en.wikipedia.org/wiki/List_of_music_students_by_teacher:_C_to_F',
'https://en.wikipedia.org/wiki/List_of_music_students_by_teacher:_G_to_J',
'https://en.wikipedia.org/wiki/List_of_music_students_by_teacher:_K_to_M',
'https://en.wikipedia.org/wiki/List_of_music_students_by_teacher:_N_to_Q',
'https://en.wikipedia.org/wiki/List_of_music_students_by_teacher:_R_to_S',
'https://en.wikipedia.org/wiki/List_of_music_students_by_teacher:_T_to_Z'
]
```

We'll go through each of the 7 pages and build up an adjacency list of teacher->student edges.

We'll skip over students or teachers that don't have an associated Wikipedia link to ensure that the people we're getting are all notable enough to have Wikipedia entries.

In [4]:

```
adjlist = ''
for url in pages:
response = get(url)
soup = BeautifulSoup(response.text, 'html.parser')
for heading in soup.find_all('h3'):
if not heading.find('a'):
continue
url = heading.find('a')['href']
if '/wiki/' not in url:
continue
teacher_name = url.split('/wiki/')[1].split('_(')[0].split('#')[0]
student_entries = heading.find_next_sibling("div", class_="columns").find_all('li')
student_names = []
for student in student_entries:
if not student.find('a'):
continue
url = student.find('a')['href']
if '/wiki/' in url:
student_names.append(url.split('/wiki/')[1].split('_(')[0].split('#')[0])
adjlist += '{} {}\n'.format(teacher_name, ' '.join(student_names))
```

In [5]:

```
adjlist[:1000]
```

Out[5]:

The names are URL-encoded because we took them from the link `href`

s, so let's decode as UTF-8.

In [6]:

```
adjlist = urllib.unquote(adjlist).decode('utf-8')
```

In [7]:

```
print adjlist[:1000]
```

Let's write this adjacency list to a file, and load it into `networkx`

.

In [8]:

```
with codecs.open("adjlist.txt", "w", "utf-8") as temp:
temp.write(adjlist)
```

In [9]:

```
G = nx.read_adjlist('adjlist.txt', create_using=nx.DiGraph())
```

In [10]:

```
G.number_of_nodes()
```

Out[10]:

Let's also export our graph to a JSON format that Cytoscape.js can understand. This might be useful later on if we want to make a JavaScript visualization of the data.

In [11]:

```
def pretty_node(node):
"""Given a node name, format it for display purposes - e.g. 'Carl_Friedrich_Abel' => 'C. Abel'."""
return u'{}. {}'.format(node[0], node.split('_I')[0].split('_')[-1])
```

In [12]:

```
def export_to_cytoscape_json(graph, filename, weight_fn=None):
def exported_node(node, weight_fn=None):
return {
'data': {
'id': unicode(pretty_node(node)),
'fullName': unicode(node.replace('_', ' ')),
'weight': weight_fn(node) if weight_fn else 1
}
}
# Topologically sort the nodes if possible (i.e. the graph is acyclic)
try:
nodes = [exported_node(i, weight_fn) for i in nx.topological_sort(graph)]
except:
nodes = [exported_node(i, weight_fn) for i in graph.nodes()]
links = [{'data': {'source': pretty_node(u[0]), 'target': pretty_node(u[1])}} for u in graph.edges()]
with codecs.open(filename, "w", "utf-8") as file:
json.dump(nodes + links, file, indent=2)
```

In [13]:

```
export_to_cytoscape_json(G, 'cytoscape.json')
```

Now that we have our graph, let's analyze it!

For starters, let's see if we can figure out who the most influential teacher is.

But how do we quantify "influence"? One natural metric to use is Katz centrality, which works similarly to Google's PageRank – nodes that are connected to influential nodes themselves gain influence, and so on.

Katz centrality is a directional measure, and it turns out we need to compute it over the reversed graph to find the most influential teachers – otherwise we just end up getting the most "influential students".

In [14]:

```
c = nx.katz_centrality(G.reverse())
```

In [16]:

```
for teacher in sorted(c, key=c.get)[::-1][:20]:
print teacher, c[teacher]
```

There's a lot of famous names there, but in the end, it's not even close. Nadia Boulanger has more than double the centrality of anybody else. Given that Boulanger taught everyone from Copland to Piazzolla to Quincy Jones, her rank is well-deserved.

And let's make a subgraph of just the 100 most-influential teachers – it'll be easier to work with than the whole graph of ~5,000 people.

In [17]:

```
most_important_teachers = sorted(c, key=c.get)[::-1][:100]
```

In [18]:

```
important_teachers_graph = nx.subgraph(G, most_important_teachers)
```

I stole some code from StackOverflow to visualize hierarchical graphs in a pretty way:

In [19]:

```
# https://stackoverflow.com/questions/29586520/can-one-get-hierarchical-graphs-from-networkx-with-python-3/29597209
def hierarchy_pos(G, root, levels=None, width=1., height=1.):
'''If there is a cycle that is reachable from root, then this will see infinite recursion.
G: the graph
root: the root node
levels: a dictionary
key: level number (starting from 0)
value: number of nodes in this level
width: horizontal space allocated for drawing
height: vertical space allocated for drawing'''
TOTAL = "total"
CURRENT = "current"
def make_levels(levels, node=root, currentLevel=0, parent=None):
"""Compute the number of nodes for each level
"""
if not currentLevel in levels:
levels[currentLevel] = {TOTAL : 0, CURRENT : 0}
levels[currentLevel][TOTAL] += 1
try:
neighbors = G.neighbors(node)
for neighbor in neighbors:
if not neighbor == parent:
levels = make_levels(levels, neighbor, currentLevel + 1, node)
except:
pass
return levels
def make_pos(pos, node=root, currentLevel=0, parent=None, vert_loc=0):
dx = 1.0/levels[currentLevel][TOTAL]
left = dx/2
pos[node] = ((left + dx*levels[currentLevel][CURRENT])*width, vert_loc)
levels[currentLevel][CURRENT] += 1
try:
neighbors = G.neighbors(node)
for neighbor in neighbors:
if not neighbor == parent:
pos = make_pos(pos, neighbor, currentLevel + 1, node, vert_loc-vert_gap)
except:
pass
return pos
if levels is None:
levels = make_levels({})
else:
levels = {l:{TOTAL: levels[l], CURRENT:0} for l in levels}
vert_gap = height / (max([l for l in levels])+1)
return make_pos({})
```

And wrapped some helpful logic around it:

In [20]:

```
def draw_hierarchical_graph(graph, root=None):
plt.figure(figsize=(10, 10))
root = root or nx.topological_sort(graph).next()
pos = hierarchy_pos(graph, root)
reduced_graph = nx.subgraph(graph, pos.keys())
relabeled_graph = nx.relabel_nodes(reduced_graph, pretty_node)
relabeled_pos = {pretty_node(node): p for node, p in pos.items()}
nx.draw(relabeled_graph, pos=relabeled_pos, with_labels=True, node_size=500, node_color='w', font_size=9, arrowsize=8)
```

Ok, let's try it! Note that if we don't provide a root node, the graph will be drawn from the first node in topological order (in other words, any node that doesn't have any parents):

In [21]:

```
draw_hierarchical_graph(important_teachers_graph)
```

A bit messy, but on the whole, that's a reasonable looking graph! It starts from the influential 19th-century French teacher and pianist Marmontel, and proceeds through his various students to such names as Boulanger, Messiaen, Milhaud, and Cage.

Let's expand our graph a little bit.

One thing we could do is simply add more teachers from the most-influential list – say, take the top 150 instead of the top 100. But let's try something else.

What if we find all the people who are "in between" influential teachers but not influential teachers themselves – that is, people who both taught and were taught by people on the influential-teachers list?

In [22]:

```
most_important_teachers_students = set([n for t in most_important_teachers for n in G.successors(t)])
```

In [23]:

```
def has_important_students(teacher):
students = [s for s in G.successors(teacher)]
return any([student in most_important_teachers for student in students])
most_important_teachers_and_important_students = \
set(most_important_teachers) | set([p for p in most_important_teachers_students if has_important_students(p)])
```

In [24]:

```
len(most_important_teachers_and_important_students) - len(most_important_teachers)
```

Out[24]:

Looks like there are 32 of these students who are "in between" influential teachers. Who are they?

In [25]:

```
most_important_teachers_and_important_students - set(most_important_teachers)
```

Out[25]:

Ah yeah, some big names here, like Beethoven (taught by Salieri and Albrechtsberger and in turn taught Czerny).

Let's make a slightly bigger subgraph consisting of both the 100 most influential teachers and their "in-between" students:

In [26]:

```
teacher_and_student_subgraph = nx.subgraph(G, most_important_teachers_and_important_students)
```

Unfortunately, by bringing these extra people into the graph, we introduce some cycles, making a topological sort (which we need to visualize the graph) no longer possible:

In [27]:

```
try:
print [x for x in nx.topological_sort(teacher_and_student_subgraph)]
except Exception:
import traceback
traceback.print_exc()
```

How many cycles are there, anyway?

In [28]:

```
for cycle in nx.simple_cycles(teacher_and_student_subgraph):
print cycle
```

Removing individual edges seems to be a bit of a pain in networkx, so let's just take the easy way out and arbitrarily remove one node from each of the cycles:

In [29]:

```
most_important_teachers_and_important_students.remove(u'Orpha-F._Deveaux')
most_important_teachers_and_important_students.remove(u'Henri_Vieuxtemps')
```

In [30]:

```
teacher_and_student_subgraph = nx.subgraph(G, most_important_teachers_and_important_students)
```

And now we can finally visualize this augmented subgraph. Unfortunately all the extra links introduced by the "in-between" students make it a little messy:

In [31]:

```
draw_hierarchical_graph(teacher_and_student_subgraph)
```