## Row.

World Map of Routes

Flows by ‘Supplier’

## Row

Sankley Graph: Trade

Sankley Graph: Arms

TII Distro

TIV Distro

---
title: "EPPS 6356.501 - Final Project Dashboard"
author: "Team Maitreyi"
output: 
  flexdashboard::flex_dashboard:
    orientation: rows
    social: menu
    source_code: embed
---

```{r setup, include=FALSE}
library(plotly)
library(flexdashboard)
library(dplyr)
library(ggplot2)
library(tidyr)
library(gtools)
library(dplyr)
library(tidyverse)
library(ggplot2)
library(tidyr)
library(ggthemes)
library(ggdark)
library(naniar)
# Load ds
full <- read.csv('Merged_redux.csv')
# Set blanks to 'NA':
fult <- full %>% replace_with_na(replace = list(Armament.category = 0)) 
fult2 <- fult %>% replace_with_na(replace = list(Armament.category = ""))
# Rename cols.
names(fult2)[names(fult2) == 'Partner.Name'] <- 'Partner'
names(fult2)[names(fult2) == 'Armament.category'] <- 'Armament'
```

## Row.{.tabset .tabset-fade}
-----------------------------------------------------
### World Map of Routes

```{r, fig.width=20, fig.height=9}
#options(width = 1400)
library(ggplot2)
library(dplyr)
library(maps)
library(tibble)

trade_data <- read.csv("Merged_redux.csv")

region_mapping <- tibble(
  Region = c("North America", "North America", "North America", "South and Central America", "Europe & Eurasia", "Asia", "Asia",
             "South and Central America", "Asia", "Asia", "Africa", "Europe & Eurasia", "Africa", "Middle East",  "Europe & Eurasia", "Middle East"),
  Country = c("United States", "China", "Russia", "United States", "China", "Russia",
              "United States", "China", "Russia", "United States", "China", "Russia",
              "United States", "China", "Russia", "United States"),
  Partner = c("Afghanistan", "Belarus", "Bangladesh", "India", "Iran", "Bangladesh", "India", "Iran",
               "Iraq", "Israel", "Japan", "Myanmar", "Pakistan", "Qatar", "Saudi Arabia", "South Korea"),
  Latitude = c(37.0902, 56.130366, 23.634501, -14.235004, 51.165691, 35.8617, 20.5937,
               -1.8312, 23.6850, 30.3753,9.0820, 52.1326, -1.2864, 15.552727, 55.378051,23.885942),
  Longitude = c(-95.7129,  -106.346771, -102.552784, -51.92528, 10.451526, 104.1954, 78.96288,
                -78.1834, 90.3563, 69.3451, 8.6753, 5.2913,37.9062, 48.5164,-3.4359, 45.0792))

trade_data_coords <- trade_data %>%
  left_join(region_mapping, by = c("Supplier" = "Country")) %>%
  rename(Export_Lat = Latitude, Export_Lon = Longitude, Region_Export = Supplier) %>%
  left_join(region_mapping, by = c("Recipient" = "Partner")) %>%
  rename(Import_Lat = Latitude, Import_Lon = Longitude, Region_Import = Recipient)

trade_data_clean = trade_data_coords %>%
  filter(!is.na(Region_Export), !is.na(Region_Import)) %>%
  mutate(Route = paste(Region_Export, "to", Region_Import)) %>%
  filter(!is.na(Export_Lon), !is.na(Export_Lat), !is.na(Import_Lon), !is.na(Import_Lat))  %>%
  filter(!(Export_Lon == Import_Lon & Export_Lat == Import_Lat))

# create map
world <- map_data("world")

world_regions <- world %>%
  mutate(Region = case_when(
    region %in% c("USA", "Canada", "Mexico") ~ "North America",
    region %in% c("Brazil", "Argentina", "Ecuador") ~ "South and Central America",
    region %in% c("Germany", "Russia", "France", "Netherlands", "UK") ~ "Europe & Eurasia",
    region %in% c("China", "India", "Bangladesh", "Pakistan") ~ "Asia",
    region %in% c("Japan", "Australia") ~ "Asia Pacific",
    region %in% c("Nigeria", "South Africa", "Kenya") ~ "Africa",
    region %in% c("Saudi Arabia", "Yemen") ~ "Middle East",
    TRUE ~ "Other"
  ))
# Color palette for regions
region_colors <- c(
  "North America" = "mistyrose1",
  "South and Central America" = "tomato",
  "Europe & Eurasia" = "lightskyblue3",
  "Asia" = "antiquewhite",
  "Asia Pacific" = "sandybrown",
  "Middle East" = "pink",
  "Africa" = "aquamarine",
  "Other" = "gray90")

# Create base map
ggplot() +
  geom_polygon(data = world_regions, aes(x = long, y = lat, group = group, fill = Region), color = "black") +
  geom_curve(data = trade_data_clean, aes(x = Export_Lon, y = Export_Lat,
                                          xend = Import_Lon, yend = Import_Lat, color = Route, size = Amount), 
             size = 0.3 ,curvature = 0.1, arrow = arrow(length = unit(0.1, "cm"))) +
  scale_fill_manual(values = region_colors, name = "Region") +  
  coord_fixed(1.3) +
  labs(title = "Routes of Arms Partners",
       x = "Longitude",
       y = "Latitude",
       subtitle = "A Global 'Network' View",
       caption = "Sources: WITS and SIPRI") +
  theme_few() +
  theme(text = element_text(family = "Optima")) +
  theme(legend.position = "right") +
  theme(legend.key.size = unit(0.5, 'cm'))
```

### Flows by 'Supplier'

```{r}
library(hrbrthemes)
fult22 <- fult2 %>% filter(Armament != 'NA' )
fult222 <- fult22 %>% filter(Armament != 'Other')

f2 <- fult222 %>%
  arrange(desc(SIPRI.estimate)) %>%
  #mutate(country = factor(country, country)) %>%
  ggplot(aes(x=Amount, y=TII.Score, size=TIV.delivery.values, color=Armament)) +
  geom_point(alpha=0.5) +
  scale_colour_ft() +
  scale_x_log10(labels=scales::dollar) +
  scale_size(range = c(.1, 24), name="") +
  dark_theme_light() +
  theme(text = element_text(family = "Optima")) +
  labs(x = "Overall Trade Amount per Year (Logged, Thousand $)", y = "TII Rank",
       title = "Trade Flows and Weapons by 'Supplier'",
       subtitle = "How Trade Levels Relate to\nWeapons Transfered (sans 'Other')\nImplicit TIV Value Range",
       caption = "Sources: SIPRI and WITS") +
  geom_hline(aes(yintercept=1.67),
             color="red", linetype="dashed", linewidth=0.5) +
  facet_wrap(~Country, ncol = 2)
ggplotly(f2)
```

## Row {.tabset .tabset-fade}
-------------------------------------------------
### Sankley Graph: Trade

```{r}
library(tidyverse)
library(viridis)
library(patchwork)
library(hrbrthemes)
library(circlize)
library(networkD3)
nodes <- data.frame(name=c(as.character(fult2$Country), as.character(fult2$Partner)) %>% unique())
fult2$IDsource=match(fult2$Country, nodes$name)-1
fult2$IDtarget=match(fult2$Partner, nodes$name)-1
ColourScal ='d3.scaleOrdinal() .range(["#FDE725FF","#B4DE2CFF","#6DCD59FF","#35B779FF","#1F9E89FF","#26828EFF","#31688EFF","#3E4A89FF","#482878FF","#440154FF"])'

# Trade
links = data.frame(data.frame(
                     source = fult2$Country, 
                      target = fult2$Partner,
                      value = fult2$Amount))
nodes <- data.frame(
  name=c(as.character(links$source), 
         as.character(links$target)) %>% unique()
)
links$IDsource <- match(links$source, nodes$name)-1 
links$IDtarget <- match(links$target, nodes$name)-1

p8 <- sankeyNetwork(Links = links, Nodes = nodes,
                   Source = "IDsource", Target = "IDtarget",
                   Value = "value", NodeID = "name", 
                   nodeWidth=40, fontSize=15, 
                   nodePadding=5,
                   height = 300,
                   width = 500,
                   iterations = 32, 
                   sinksRight=FALSE)

p8
```

### Sankley Graph: Arms

```{r}
# TIVs
links = data.frame(data.frame(
  source = fult2$Country, 
  target = fult2$Partner,
  value = fult2$TIV.delivery.values))
nodes <- data.frame(
  name=c(as.character(links$source), 
         as.character(links$target)) %>% unique()
)
links$IDsource <- match(links$source, nodes$name)-1 
links$IDtarget <- match(links$target, nodes$name)-1

p9 <- sankeyNetwork(Links = links, Nodes = nodes,
                    Source = "IDsource", Target = "IDtarget",
                    Value = "value", NodeID = "name", 
                    nodeWidth=40, fontSize=23, 
                    nodePadding=30,
                    height = 800,
                    width = 800,
                    sinksRight=FALSE)
p9
```

### Trade Trends

```{r}

Paired2 <- fult2 %>% filter(Year != "2022")
Paired22 <- Paired2 %>% filter(Year >= "1996")

set.seed(123)
sampled_trade <- Paired22 %>%
  sample_n(500)  # Sample 500 observations for a clearer plot

aggregated_trade <- Paired22 %>% 
  group_by(Year, Trade.Flow) %>%
  summarise(Mean_Value = mean(Amount, na.rm = TRUE), .groups = 'drop')

p7 <- ggplot(aggregated_trade, aes(x = Year, y = Mean_Value, color = Trade.Flow)) +
  geom_line(size = 1) +
  scale_y_continuous(labels=scales::dollar) +
  geom_point() +
  labs(
    title = "Trade Trends Over Time",
    x = "Year",
    y = "Mean Trade Value (Thousand)",
    subtitle = "An Overall View",
    caption = "Sources: WITS",
    color = "Trade Flow"
  ) +
  theme_few()
ggplotly(p7)

```

### TII Distro

```{r}
wpns3 <- c("Aircraft", "Sensors", "Armoured vehicles",
           "Air defense systems", "Artillery",
           "Engines", "Missles",
           "Naval weapons", "Ships",
           "Other")
p5 <- ggplot(data = subset(fult2, subset = Armament %in% wpns3),
       mapping = aes(x = TIV.delivery.values, fill = Armament, color = Armament)) +
  theme(text = element_text(family = "Optima")) +
  labs(x = "TIV Values", y = "Density Estimate",
       title = "Distro of TIVs",
       subtitle = "Getting an Sense of Composition (Upto ~ 300)",
       caption = "Sources: SIPRI") +
  geom_vline(aes(xintercept=mean(TIV.delivery.values)),
             color="blue", linetype="dashed", linewidth=0.5) +
  theme_few() +
  xlim(0, 300) +
  geom_density(alpha = 0.3)
ggplotly(p5)

```

### TIV Distro

```{r}
p4 <- ggplot(data = (fult2),
       mapping = aes(x = TII.Score, fill = Country, color = Country)) +
  theme(text = element_text(family = "Optima")) +
  labs(x = "TII Rank", y = "Proportional Density Estimate",
       title = "Distro of TIIs",
       subtitle = "Getting an Sense of Composition (Upto ~ 10)",
       caption = "Sources: WITS") +
  geom_vline(aes(xintercept=1.67),
             color="red", linetype="dashed", linewidth=0.5) +
  theme_few() +
  xlim(0, 10) +
  geom_density(alpha = 0.3, mapping = aes(y = ..scaled..))
ggplotly(p4)

```