library(ggplot2)
library(sqldf)
library(plyr)
library(cowplot)

cellssec <- c("1","2","10","20")
tor_bw <- read.csv("tor_bw_2.csv")
tor_bw <- sqldf("select run,conf,latency, CAST(latency as real) / 1000. as lat_ms from tor_bw")
tor_bw$conf <- factor(
  mapvalues(tor_bw$conf, c(0,1,2,3), cellssec),
  levels = cellssec,
  ordered = TRUE)
gbw1 <- ggplot(data = tor_bw, aes(x = conf, y=lat_ms)) +
  geom_boxplot() +
  ylim(0,1000) +
  ylab("latency (in ms)") +
  xlab("cells / second") +
  theme_minimal()

gbw2 <- ggplot(data = tor_bw, aes(x = conf, y=lat_ms)) +
  geom_boxplot() +
  scale_y_log10() +
  ylab("latency (in ms)") +
  xlab("cells / second") +
  theme_minimal()

new_values <- c("1","2","3","4","5","6","7","8","∞")
tor_guards <- read.csv("tor_guards.csv")
tor_guards <- sqldf("select run,conf,latency, CAST(latency as real) / 1000. as lat_ms from tor_guards")
tor_guards$conf <- factor(
  mapvalues(tor_guards$conf, c(0,1,2,3,4,5,6,7,8), new_values),
  levels = new_values,
  ordered = TRUE)

gguard1 <- ggplot(data = tor_guards, aes(x = conf, y=lat_ms)) +
  geom_boxplot() +
  ylim(0,1000) +
  ylab("latency (in ms)") +
  xlab("guards") +
  theme_minimal()

gguard2 <- ggplot(data = tor_guards, aes(x = conf, y=lat_ms)) +
  geom_boxplot() +
  scale_y_log10() +
  ylab("latency (in ms)") +
  xlab("guards") +
  theme_minimal()

relay_count <- c("6","4","3")
tor_relays <- read.csv("tor_relays.csv")
tor_relays <- sqldf("select run,conf,latency, CAST(latency as real) / 1000. as lat_ms from tor_relays")
tor_relays$conf <- factor(
  mapvalues(tor_relays$conf, c(0,1,2), relay_count),
  levels = relay_count,
  ordered = TRUE)

grelay1 <- ggplot(data = tor_relays, aes(x = conf, y=lat_ms)) +
  geom_boxplot() +
  ylim(0,1000) +
  #scale_y_log10() +
  ylab("latency (in ms)") +
  xlab("relay count") +
  theme_minimal()

grelay2 <- ggplot(data = tor_relays, aes(x = conf, y=lat_ms)) +
  geom_boxplot() +
  scale_y_log10() +
  ylab("latency (in ms)") +
  xlab("relay count") +
  theme_minimal()

t1 <- plot_grid(gbw1, gguard1, grelay1, labels = c('D', 'E', 'F'), nrow=1, rel_widths = c(5, 8, 4))
t1 + ggsave("tor_latency_crop.png", dpi=300, dev='png', height=5, width=15, units="cm")

t2 <- plot_grid(gbw2, gguard2, grelay2, labels = c('A', 'B', 'C'), nrow=1, rel_widths = c(5, 8, 4))
t2 + ggsave("tor_latency_log.png", dpi=300, dev='png', height=5, width=15, units="cm")