# Homework 5: Networks and Congress¶

Due Friday, November 15, 11:59pm

In [10]:
%matplotlib inline

import json

import numpy as np
import networkx as nx
import requests
from pattern import web
import matplotlib.pyplot as plt

# set some nicer defaults for matplotlib
from matplotlib import rcParams

#these colors come from colorbrewer2.org. Each is an RGB triplet
dark2_colors = [(0.10588235294117647, 0.6196078431372549, 0.4666666666666667),
(0.8509803921568627, 0.37254901960784315, 0.00784313725490196),
(0.4588235294117647, 0.4392156862745098, 0.7019607843137254),
(0.9058823529411765, 0.1607843137254902, 0.5411764705882353),
(0.4, 0.6509803921568628, 0.11764705882352941),
(0.9019607843137255, 0.6705882352941176, 0.00784313725490196),
(0.6509803921568628, 0.4627450980392157, 0.11372549019607843),
(0.4, 0.4, 0.4)]

rcParams['figure.figsize'] = (10, 6)
rcParams['figure.dpi'] = 150
rcParams['axes.color_cycle'] = dark2_colors
rcParams['lines.linewidth'] = 2
rcParams['axes.grid'] = False
rcParams['axes.facecolor'] = 'white'
rcParams['font.size'] = 14
rcParams['patch.edgecolor'] = 'none'

def remove_border(axes=None, top=False, right=False, left=True, bottom=True):
"""
Minimize chartjunk by stripping out unnecessary plot borders and axis ticks

The top/right/left/bottom keywords toggle whether the corresponding plot border is drawn
"""
ax = axes or plt.gca()
ax.spines['top'].set_visible(top)
ax.spines['right'].set_visible(right)
ax.spines['left'].set_visible(left)
ax.spines['bottom'].set_visible(bottom)

#turn off all ticks
ax.yaxis.set_ticks_position('none')
ax.xaxis.set_ticks_position('none')

#now re-enable visibles
if top:
ax.xaxis.tick_top()
if bottom:
ax.xaxis.tick_bottom()
if left:
ax.yaxis.tick_left()
if right:
ax.yaxis.tick_right()


The website govtrack.us collects data on activities in the Senate and House of Representatives. It's a great source of information for making data-driven assessments about Congress.

### Problem 1.¶

The directories at http://www.govtrack.us/data/congress/113/votes/2013 contain JSON information about every vote cast for the current (113th) Congress. Subdirectories beginning with "S" correspond to Senate votes, while subdirectories beginning with "H" correspond to House votes.

Write two functions: one that downloads and parses a single Senate vote page given the vote number, and another that repeatedly calls this function to build a full collection of Senate votes from the 113th Congress.

In [11]:
"""
Function
--------
get_senate_vote

Scrapes a single JSON page for a particular Senate vote, given by the vote number

Parameters
----------
vote : int
The vote number to fetch

Returns
-------
vote : dict
The JSON-decoded dictionary for that vote

Examples
--------
>>> get_senate_vote(11)['bill']
{u'congress': 113,
u'number': 325,
u'title': u'A bill to ensure the complete and timely payment of the obligations of the United States Government until May 19, 2013, and for other purposes.',
u'type': u'hr'}
"""

In [12]:
"""
Function
--------

and returns a list of dicts

Parameters
-----------
None

Returns
--------
List of JSON-parsed dicts for each senate vote
"""

In [13]:
vote_data = get_all_votes()


### Problem 2¶

Now, turn these data into a NetworkX graph, according to the spec below. For details on using NetworkX, consult the lab materials for November 1, as well as the NetworkX documentation.

In [14]:
"""
Function
--------
vote_graph

Parameters
----------
data : list of dicts
The vote database returned from get_vote_data

Returns
-------
graph : NetworkX Graph object, with the following properties
1. Each node in the graph is labeled using the display_name of a Senator (e.g., 'Lee (R-UT)')
2. Each node has a color attribute set to 'r' for Republicans,
'b' for Democrats, and 'k' for Independent/other parties.
3. The edges between two nodes are weighted by the number of
times two senators have cast the same Yea or Nay vote
4. Each edge also has a difference attribute, which is set to 1 / weight.

Examples
--------
>>> graph = vote_graph(vote_data)
>>> graph.node['Lee (R-UT)']
{'color': 'r'}  # attributes for this senator
>>> len(graph['Lee (R-UT)']) # connections to other senators
101
>>> graph['Lee (R-UT)']['Baldwin (D-WI)']  # edge relationship between Lee and Baldwin
{'difference': 0.02, 'weight': 50}
"""

In [15]:
votes = vote_graph(vote_data)


### How (and how not) to visualize networks¶

Network plots often look impressive, but creating sensible network plots is tricky. From Ben Fry, the author of the Processing program:

Usually a graph layout isn’t the best option for data sets larger than a few dozen nodes. You’re most likely to wind up with enormous spider webs or balls of string, and the mess seen so far is more often the case than not. Graphs can be a powerful way to represent relationships between data, but they are also a very abstract concept, which means that they run the danger of meaning something only to the creator of the graph. Often, simply showing the structure of the data says very little about what it actually means, even though it’s a perfectly accurate means of representing the data. Everything looks like a graph, but almost nothing should ever be drawn as one.

Let's look at bad and better ways of visualizing the senate vote network.

First, consider the "default" plot from networkx.

In [32]:
#this makes sure draw_spring results are the same at each call
np.random.seed(1)

#determine position of each node using a spring layout

#plot the edges

#plot the nodes

#draw the labels
lbls = nx.draw_networkx_labels(votes, pos, alpha=5, font_size=8)

#coordinate information is meaningless here, so let's remove it
plt.xticks([])
plt.yticks([])
remove_border(left=False, bottom=False)


The spring layout tries to group nodes with large edge-weights near to each other. In this context, that means it tries to organize the Senate into similarly-voting cliques. However, there's simply too much going on in this plot -- we should simplify the representation.

### Problem 3¶

Compute the Minimum Spanning Tree of this graph, using the difference edge attribute as the weight to minimize. A Minimum Spanning Tree is the subset of edges which trace at least one path through all nodes ("spanning"), with minimum total edge weight. You can think of it as a simplification of a network.

Plot this new network, making modifications as necessary to prevent the graph from becoming too busy.

In [33]:
#Your code here


### Problem 4¶

While this graph has less information, the remaining information is easier to digest. What does the Minimum Spanning Tree mean in this context? How does this graph relate to partisanship in the Senate? Which nodes in this graph are the most and least bi-partisan?

### Problem 5¶

(For this problem, use the full graph for centrality computation, and not the Minimum Spanning Tree)

Networkx can easily compute centrality measurements.

Briefly discuss what closeness_centrality means, both mathematically and in the context of the present graph -- how does the centrality relate to partisanship? Choose a way to visualize the closeness_centrality score for each member of the Senate, using edge difference as the distance measurement. Determine the 5 Senators with the highest and lowest centralities.

Comment on your results. In particular, note the outliers John Kerry (who recently resigned his Senate seat when he became Secretary of State), Mo Cowan (Kerry's interim replacement) and Ed Markey (Kerry's permanent replacement) have low centrality scores -- why?

In [12]:
#Your code here


### Problem 6¶

Centrality isn't a perfect proxy for bipartisanship, since it gauges how centralized a node is to the network as a whole, and not how similar a Democrat node is to the Republican sub-network (and vice versa).

Can you come up with another measure that better captures bipartisanship than closeness centrality? Develop your own metric -- how does it differ from the closeness centrality? Use visualizations to support your points.

In [13]:
#your code here


There are many metrics to quantify the leadership in the Senate.

2. Leaders sit on many committees, as well as more important committees
3. Leaders usually have been in office for a long time

Another approach uses the philosophy behind how Google ranks search results. The core idea behind Google's PageRank algorithm is:

1. A "good" website (i.e. one to rank highly in search results) is linked to by many other websites
2. A link found on a "good" website is more important than a link found on a "bad" website

The PageRank algorithm thus assigns scores to nodes in a graph based on how many neighbors a node has, as well as the score of those neighbors.

This technique can be adapted to rank Senate leadership. Here, nodes correspond to Senators, and edges correspond to a senator co-sponsoring a bill sponsored by another Senator. The weight of each edge from node A to B is the number of times Senator A has co-sponsored a bill whose primary sponsor is Senator B. If you interpret the PageRank scores of such a network to indicate Senate leadership, you are then assuming:

### Problem 7¶

Govtrack stores information about each Senate bill in the current congress at http://www.govtrack.us/data/congress/113/bills/s/. As in problem 1, write two functions to scrape these data -- the first function downloads a single bill, and the second function calls the first to loop over all bills.

In [42]:
"""
Function
--------
get_senate_bill

Scrape the bill data from a single JSON page, given the bill number

Parameters
-----------
bill : int
Bill number to fetch

Returns
-------
A dict, parsed from the JSON

Examples
--------
>>> bill = get_senate_bill(10)
{u'district': None,
u'name': u'Reid, Harry',
u'state': u'NV',
u'thomas_id': u'00952',
u'title': u'Sen',
u'type': u'person'}
>>> bill['short_title']
u'Agriculture Reform, Food, and Jobs Act of 2013'
"""

In [43]:
"""
Function
--------
get_all_bills

Scrape all Senate bills at http://www.govtrack.us/data/congress/113/bills/s

Parameters
----------
None

Returns
-------
A list of dicts, one for each bill
"""

In [44]:
bill_list = get_all_bills()


### Problem 8¶

Write a function to builded a Directed Graph (DiGraph) from these data, according to the following spec:

In [45]:
"""
Function
--------
bill_graph

Turn the bill graph data into a NetworkX Digraph

Parameters
----------
data : list of dicts
The data returned from get_all_bills

Returns
-------
graph : A NetworkX DiGraph, with the following properties
* Each node is a senator. For a label, use the 'name' field
* Each edge from A to B is assigned a weight equal to how many
"""

In [46]:
bills = bill_graph(bill_list)


### Problem 9¶

Using nx.pagerank_numpy, compute the PageRank score for each senator in this graph. Visualize the results. Determine the 5 Senators with the highest PageRank scores. How effective is this approach at identifying leaders? How does the PageRank rating compare to the degree of each node?

Note: you can read about individual Senators by searching for them on the govtrack website.

In [47]:
#Your code here

In [56]:
#Your code here


### Interactive Visualization¶

Producing a good node link layout is not quite so simple. Nevertheless, we will give it a try.

We will use Gephi for interactive graph visualization. Gephi supports a wide variety of graph file formats, and NetworkX exports to several of them. We'll use the Graph Exchange XML Format (GEXF).

In [118]:
nx.write_gexf(votes, 'votes.gexf')


### Problem 10: Analysis with Gephi¶

Download and install Gephi. See the lab for a brief introduction. Load the exported votes file. Try to produce a layout that clearly separates Democrats from Republicans (hint: filter on edge weight and re-layout once you filtered). Run PageRank and some other statistics and try encoding them with node color and node size. Run the "Modularity" statistic and encode the results in color.

Include a screenshot of your "best" visualization and embed the image here with IPython.display.Image. Make sure to include this image in your submission.

Explain your observations. Is the network visualization very helpful? Try to visualize your LinkedIn network (see the lab) or the one provided in the lab. Which dataset is more suitable for visualization and why is there a difference?

In [ ]:
from IPython.display import Image

path = 'name_of_your_screenshot'
Image(path)