The size and structure of international trade flows varies
significantly over time. This exercise is based in part on

    Luca De Benedictis and Lucia Tajoli. (2011). 'The World Trade
    Network.' *The World Economy*, 34:8, pp.1417-1454. 
    
The trade data are from Katherine Barbieri and Omar
    
    Keshk. (2012). *Correlates of War Project Trade Data Set*,
    Version 3.0. available at 
    [http://correlatesofwar.org](http://correlatesofwar.org).
  
The volume of goods traded between countries has grown rapidly over the
past century, as technological advances lowered the cost of shipping
and countries adopted more liberal trade policies.  At times, however,
trade flows have decreased due to disruptive events such as major wars
and the adoption of protectionist trade policies.  In this exercise,
we will explore some of these changes by examining the network of
international trade over several time periods.  The data file
`trade.csv` contains the value of exports from one country to
another in a given year.  The names and descriptions of variables in
this data set are:

--------------------------------------------------------------------------------
 Name                 Description
 -------------------- ----------------------------------------------------------
 `country1`           Country name of exporter 
 
 `country2`           Country name of importer
 
 `year`               Year
 
 `exports`            Total value of exports (in tens of millions of dollars)
--------------------------------------------------------------------------------

The data are given for years 1900, 1920, 1940, 1955, 1980, 2000, and 2009.

## Question 1

We begin by analyzing international trade as an unweighted,
  directed network.  For every year in the data set, create an
  adjacency matrix whose entry $(i,j)$ equals 1 if country $i$ exports
  to country $j$.  If this export is zero, then the entry equals 0.
  We assume that missing data, indicated by `NA`, represents
  zero trade.  Plot the 'network density', which is defined over
  time as follows,
  $$
    \text{network density}  =  \frac{\text{number of edges}}{\text{number of potential edges}}
  $$
  The `graph.density` function can compute this measure given
  an adjacency matrix.  Interpret the result.  
  
## Answer 1

```{r}
par(cex = 1.5)
trade <- read.csv("./data/trade.csv", stringsAsFactors = FALSE)

library(igraph)
trade$exports[is.na(trade$exports)] <- 0
years <- unique(trade$year)
density <- rep(NA, length(years))
adj.mat <- list()

for(i in 1:length(years)){  
trade.year <- trade[trade$year == years[i],]
countries <- unique(c(trade.year$country1, trade.year$country2))
adj.year <- matrix(0,nrow=length(countries),ncol=length(countries))
rownames(adj.year) <- countries
colnames(adj.year) <- countries

for(j in 1:nrow(trade.year)){
  exporter <- trade.year$country1[j]
importer <- trade.year$country2[j]
adj.year[exporter,importer] <-  trade.year$exports[j]
}

adj.year <- ifelse(adj.year >0 , 1, 0)
net <- graph.adjacency(adj.year, diag = FALSE)
density[i] <- edge_density(net)
adj.mat[[i]] <- net
}

length(density)

plot(x=years, y = density, type = "b", main = "density of trade")
```


## Visulizing the networks

Let's plot a random subset of the network in the year of 2009, using igraph. 
```{r}
library(igraph)
set.seed(02138)

trade09 <- trade[trade$year=="2009",]

countries <- unique(c(trade09$country1, trade09$country2))
adj09 <- matrix(0, nrow=length(countries), ncol = length(countries))
colnames(adj09) <- rownames(adj09) <- countries


for(j in 1:nrow(trade09)){
  exporter <- trade09$country1[j]
  importer <- trade09$country2[j]
  adj09[exporter,importer] <-  trade09$exports[j]
}

adj09 <- ifelse(adj09 >0 , 1,0)
adj_comp <- adj09[-which(rowSums(adj09,na.rm=T)==0) , ]

ss <- sample(1:nrow(adj_comp),11)
adj_comp <- adj_comp[ss,ss]
network <- graph_from_adjacency_matrix(adj_comp, mode=c("directed"), 
                                       weighted = NULL, diag = FALSE)

par(mar = c(1,1,1,1))
plot(network,edge.arrow.size = 0.01, vertex.size = 0.001)
```




## Question 2

For the years 1900, 1955, and 2009, compute the measures of
  centrality based on degree, betweenness, and closeness (based on
  total degree) for each year.  For each year, list the five countries
  that have the largest values of these centrality measures.  How do
  the countries on the lists change over time?  Briefly comment on the
  results.
  
```{r}
degree.1900 <- degree(adj.mat[[1]])
between.1900 <- betweenness(adj.mat[[1]])
close.1900 <- closeness(adj.mat[[1]])

sort(degree.1900, decreasing = TRUE)[1:5]
sort(between.1900, decreasing = TRUE)[1:5]
sort(close.1900, decreasing = TRUE)[1:5]
```
  


## Question 3
  
We now analyze the international trade network as a weighted,
  directed network in which each edge has a non-negative weight
  proportional to its corresponding trade volume.  Create an adjacency
  matrix for such network data.  For the years 1900, 1955, and 2009,
  compute the centrality measures from above for the weighted trade
  network.  Instead of degree, however, compute the *graph strength*, 
  which in this case equals the sum of imports and
  exports with all adjacent nodes.  The `graph.strength`
  function can be used to compute this weighted version of degree.
  For betweenness and closeness, we use the same function as before,
  i.e., `closeness` and `betweenness`, which can handle
  weighted graphs appropriately.  Do the results differ from those of
  the unweighted network?  Examine the top five countries.  Can you
  think of another way to calculate centrality in this network that
  accounts for the value of exports from each country?  Briefly
  discuss.

```{r}
wadj.mat <- list()
years <- c(1900, 1955, 2009)
for(i in 1:length(years)){
  trade.year <- trade[trade$year == years[i],]
  countries <- unique(c(trade.year$country1, trade.year$country2))
adj.year <- matrix(0,nrow=length(countries),
                   ncol=length(countries))
rownames(adj.year) <- colnames(adj.year) <-  countries
#for(j)
for(j in 1:nrow(trade.year)){
  exporter <- trade.year$country1[j]
  importer <- trade.year$country2[j]
  adj.year[exporter,importer] <-  trade.year$exports[j]
}
 
wadj.mat[[i]] <-  graph.adjacency(adj.year,  weighted = TRUE,diag=FALSE)
}
names(wadj.mat) <- years

strength.2009 <- strength(wadj.mat$`2009`)
between.2009 <- betweenness(wadj.mat$`2009`)
close.2009 <- closeness(wadj.mat$`2009`)

sort(strength.2009, decreasing = TRUE)[1:5]
sort(between.2009, decreasing = TRUE)[1:5]
sort(close.2009, decreasing = TRUE)[1:5]

```


## Question 4

Apply the PageRank algorithm to the weighted trade network
  separately for each year.  For each year, identify the 5 most
  influential countries according to this algorithm.  In addition,
  examine how the ranking of PageRank values has changed over time for
  each of the following five countries -- US, United Kingdom, Russia,
  Japan, and China.  Briefly comment on the patterns you observe.
  
 