# Extract and create fingerprints from national IO accounts
# Assuming here that the folder 'raw_z_zm' contains the raw Z and ZM files
# and that this folder is in the current working directory

folder <- "raw_z_zm"

years <- 1995:2011
countries <- c(
  "AUS","AUT","BEL","BGR","BRA","CAN","CHN","CYP","CZE","DEU",
  "DNK","ESP","EST","FIN","FRA","GBR","GRC","HUN","IDN","IND",
  "IRL","ITA","JPN","KOR","LTU","LUX","LVA","MEX","MLT","NLD",
  "POL","PRT","ROU","RUS","SVK","SVN","SWE","TUR","TWN","USA"
)

# Define function for calculating euclidean distance between two vectors (fingerprints)
eucldist <- function(x, y) sqrt(sum((x-y)^2))

# Prepare list of fingerprints
fps <- list()

for (country in countries) {
  for (year in years) {
    # Load raw Z and ZM files
    cy <- paste0(country,"_",year)
    zm <- as.matrix(read.csv(paste0(folder,"/",cy,"_ZM.txt"),row.names = 1,header = TRUE, sep="\t")) # For upstream
    z <- as.matrix(read.csv(paste0(folder,"/",cy,"_Z.txt"),row.names = 1,header = TRUE, sep="\t"))   # For downstream

    # Calculate eigen-stuff for each, make sure to first transpose ZM so I get the left-hand (?)
    eigen_up <- eigen(t(zm))
    eigen_down <- eigen(z)
    
    # Extract the first eigenvectors, for up/in and down/out
    fp_up <- round(Re(eigen_up$vectors[,1]),4)
    fp_down <- round(Re(eigen_down$vectors[,1]),4)

    # Make sure that values are positive
    if (sum(fp_down)<0)
      fp_down <- -fp_down
    if (sum(fp_up)<0)
      fp_up <- -fp_up
    
    # Store fingerprint (concatenated up and down)
    fps[[cy]] <- c(fp_up, fp_down)
  }
}

# Get fingerprint labels and number of fps
fp_labels <- names(fps)
n_fp <- length(fps)

# Prepare matrix for storing euclidean distances
mat <- matrix(0, nrow = n_fp, ncol=n_fp,dimnames = list(fp_labels,fp_labels))

# Calculate pairwise euclidean distances and populate matrix
for (r in 1:n_fp) {
  if (r != n_fp)
    for (c in (r+1):n_fp) {
      dist <- round(eucldist(fps[[fp_labels[r]]], fps[[fp_labels[c]]]),3)
      mat[r,c] <- dist
      mat[c,r] <- dist
    }
}

# Save euclidean distance matrix