# ======================================================================
# Digital Figures for Report 
# Estefania Vergara
# January 27, 2026
# ======================================================================
# install.packages("dplyr")
# install.packages("ggplot2")
# install.packages("sf", dependencies = TRUE)
# install.packages("rnaturalearth")
# install.packages("forcats")

cat("Running DigitalFigures.R\n")

library(dplyr)
library(ggplot2)
library(sf)
library(rnaturalearth)
library(scales)
library(forcats)
library(ggrepel)
library(stringr)
library(tidyr)
library(tibble)
library(readxl)
library(psych)
library(countrycode)
library(haven)
library(dplyr)

options(scipen = 0, digits = 7)
rm(list = ls())
gc()



# setwd("C:/Users/wb657580/OneDrive - WBG/INFCE Files - ReproduciblePackage/Data/Raw")
setwd("C:/Temp/reproducibility_workspace/reviews/FR_WLD_2026_601/Report_ReproduciblePackage/Report_ReproduciblePackage/Data/Raw")

Outputpath <- file.path("..", "..",  "Outputs")

infra_wide <- read.csv("04_AdditionalRestrictedData/digital_total_stock_february_23.csv")
names(infra_wide)[names(infra_wide) == "all_depcreciated_2024_cum"] <- "all_depreciated_2024_cum"

infra_wide_panel <- read.csv("04_AdditionalRestrictedData/digital_total_stock_february_23_time_series_panel.csv")
# -------------------
# Figure 6.9: Map Capital Stock Depreciated  
# -------------------
# this dataset is aggregated and depreciated 

last_year <- infra_wide 

# world polygons
world <- rnaturalearth::ne_countries(scale = "medium", returnclass = "sf")[, c("iso_a3","name_long")]

# Fix missing or incorrect ISO codes
world <- world %>%
  mutate(iso_a3 = case_when(
    name_long == "France" & iso_a3 == "-99" ~ "FRA",
    name_long == "Norway" & iso_a3 == "-99" ~ "NOR",
    name_long == "Serbia" & iso_a3 == "-99" ~ "SRB",
    name_long == "Venezuela" & iso_a3 == "-99" ~ "VEN",
    name_long == "Somaliland" ~ "SOM",
    name_long == "Kosovo" ~ "XKX",
    name_long == "United States of America" ~ "USA",
    TRUE ~ iso_a3
  ))

# join by ISO3
mapdf <- world %>%
  left_join(last_year %>% select(iso3, all_depreciated_2024_cum),
            by = c("iso_a3" = "iso3"))

# Winkel Tripel projection
crs_wintri <- "+proj=wintri +lon_0=0 +datum=WGS84 +units=m +no_defs"

# compute range for proportional breaks (7 color levels)
min_val <- min(mapdf$all_depreciated_2024_cum, na.rm = TRUE)
max_val <- max(mapdf$all_depreciated_2024_cum, na.rm = TRUE)
breaks7  <- exp(seq(log(min_val), log(max_val), length.out = 7))

# the following graph uses last year available per country, non depreciated, in 2024 usd terms
p <- ggplot(mapdf) +
  geom_sf(aes(fill = all_depreciated_2024_cum), linewidth = 0.1, color = "grey65") +
  coord_sf(crs = crs_wintri, datum = NA, expand = FALSE) +
  scale_fill_gradientn(
    colors = rev(RColorBrewer::brewer.pal(7, "Spectral")),
    trans = "log10",
    breaks = breaks7,
    labels = label_number(accuracy = 1, scale_cut = cut_short_scale()),
    limits = c(min_val, max_val),
    na.value = "grey90",
    name = "Cumulative depreciated\n digital capital stock\n(USD 2024 base year)"
  ) +
  theme_void() +
  theme(
    plot.background = element_rect(fill = "white", color = NA),  # 추가
    panel.background = element_rect(fill = "white", color = NA), # 추가
    plot.title = element_text(face = "plain", hjust = 0.5),
    legend.position = "bottom",
    legend.key.width = unit(3, "cm"),
    legend.title = element_text(size = 10),
    legend.text = element_text(size = 8)
  )

# --- Save output ---

file_name <- "Figure_6_9_Spatial_Distribution_of_Digital_Capital_Assets"
# PNG 
ggsave(
  filename = file.path(Outputpath, paste0(file_name, ".png")),
  plot = p,
  width = 15,
  height = 10,
  dpi = 300
)

# SVG 
ggsave(
  filename = file.path(Outputpath, paste0(file_name, ".svg")),
  plot = p,
  width = 15,
  height = 10,
  device = "svg"
)



# ---------------------------
# Figure 6.10: Capital Assets
# ---------------------------
# merge with ISO3 to get regions
class <- read_excel("00_Non Sectoral Data/Raw/WB_IncomeGroup_Regions/CLASS_2025_10_07.xlsx")
infra_wide_class <- infra_wide %>%
  left_join(class %>% select(Code, Region), 
            by = c("iso3" = "Code"), 
            keep = FALSE ,
            
            )


region_components <- infra_wide_class %>%
  mutate(
    dc  = coalesce(dc_depreciated_cum, 0),
    sub = coalesce(sub_depreciated_cum, 0),
    ixp = coalesce(ixp_depreciated_cum, 0),
    foc = coalesce(foc_depreciated_cost, 0),
    ran = coalesce(total_ran_stock_2024_depreciated, 0)
  ) %>%
  group_by(Region) %>%
  summarise(
    dc  = sum(dc,  na.rm = TRUE),
    sub = sum(sub, na.rm = TRUE),
    ixp = sum(ixp, na.rm = TRUE),
    foc = sum(foc, na.rm = TRUE),
    ran = sum(ran, na.rm = TRUE),
    .groups = "drop"
  ) %>%
  mutate(total_replace = dc + sub + ixp + foc + ran) %>%
  pivot_longer(dc:ran, names_to = "component", values_to = "value") %>%
  mutate(
    component = recode(component,
                       dc  = "Data centers",
                       sub = "Submarine cables",
                       ixp = "IXPs",
                       foc = "Fiber optic cables",
                       ran = "RAN"
    )
  )


region_order <- region_components %>%
  distinct(Region, total_replace) %>%
  arrange(total_replace) %>%
  pull(Region)

region_components <- region_components %>%
  mutate(Region = factor(Region, levels = region_order))

region_components <- region_components %>%
  mutate(Region = recode(Region,
                            "East Asia & Pacific" = "EAP",
                            "Europe & Central Asia" = "ECA",
                            "North America" = "NA",
                            "Latin America & Caribbean" = "LAC",
                            "South Asia" = "SAR",
                            "Middle East, North Africa, Afghanistan & Pakistan" = "MENAAP",
                            "Sub-Saharan Africa" = "SSA"
  ))

unique(infra_wide_class$Region)

nas <- infra_wide_panel %>% 
  filter(is.na(wb_region))

# Plot
p <- ggplot(region_components,
       aes(x = Region, y = value, fill = component)) +
  geom_col(width = 0.8) +
  coord_flip() +
  scale_y_continuous(labels = label_number(scale_cut = cut_short_scale())) +
  scale_fill_brewer(palette = "Set2", name = "Component") +
  labs(
    x = "",
    y = "Digital capital cost (USD, depreciated, 2024 base year)",
    caption = "Note: The graph does not include full RAN 
    stock for CHN and IND due to data unavailability."
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(size = 16, face = "plain"),
    axis.text = element_text(size = 13),
    axis.title = element_text(size = 13),
    legend.text = element_text(size = 12),
    legend.title = element_text(size = 13),
    plot.caption = element_text(size = 11),
    legend.position = "bottom"
  )

# --- Save output ---

file_name <- "Figure_6_10_Digital_Capital_Assets_by_Region_and_Component"
# PNG 
ggsave(
  filename = file.path(Outputpath, paste0(file_name, ".png")),
  plot = p,
  width = 15,
  height = 10,
  dpi = 300
)

# SVG 
ggsave(
  filename = file.path(Outputpath, paste0(file_name, ".svg")),
  plot = p,
  width = 15,
  height = 10,
  device = "svg"
)


# ----------------------------
# Figure 6.11: Per capita capital assets
# ----------------------------

pop <- read.csv("population_total.csv")
pop_latest <- pop %>%
  rowwise() %>%
  mutate(
    latest_pop = dplyr::last(na.omit(c_across(starts_with("X"))))
  ) %>%
  ungroup() %>%
  transmute(iso3 = Country.Code, latest_pop)

infra_wide_class <- infra_wide_class %>%
  left_join(pop_latest, by = "iso3")

infra_wide_class <- infra_wide_class %>%
  mutate(all_depre_2024_pc = all_depreciated_2024_cum / latest_pop)

# Graph
region_components <- infra_wide_class %>%
  mutate(
    dc  = coalesce(dc_depreciated_cum, 0),
    sub = coalesce(sub_depreciated_cum, 0),
    ixp = coalesce(ixp_depreciated_cum, 0),
    foc = coalesce(foc_depreciated_cost, 0),
    ran = coalesce(total_ran_stock_2024_depreciated, 0)
  ) %>%
  group_by(Region) %>%
  summarise(
    pop = sum(latest_pop, na.rm = TRUE),
    dc  = sum(dc,  na.rm = TRUE),
    sub = sum(sub, na.rm = TRUE),
    ixp = sum(ixp, na.rm = TRUE),
    foc = sum(foc, na.rm = TRUE),
    ran = sum(ran, na.rm = TRUE),
    .groups = "drop"
  ) %>%
  # convert to per capita (USD per person)
  mutate(across(dc:ran, ~ .x / pop)) %>%
  mutate(total_replace = dc + sub + ixp + foc + ran) %>%
  pivot_longer(dc:ran, names_to = "component", values_to = "value") %>%
  mutate(
    component = recode(component,
                       dc  = "Data centers",
                       sub = "Submarine cables",
                       ixp = "IXPs",
                       foc = "Fiber optic cables",
                       ran = "RAN"
    )
  )

region_order <- region_components %>%
  distinct(Region, total_replace) %>%
  arrange(total_replace) %>%
  pull(Region)

region_components <- region_components %>%
  mutate(Region = factor(Region, levels = region_order))

region_components <- region_components %>%
  mutate(Region = recode(Region,
                            "East Asia & Pacific" = "EAP",
                            "Europe & Central Asia" = "ECA",
                            "North America" = "NA",
                            "Latin America & Caribbean" = "LAC",
                            "South Asia" = "SAR",
                            "Middle East, North Africa, Afghanistan & Pakistan" = "MENAAP",
                            "Sub-Saharan Africa" = "SSA"
  ))

p <- ggplot(region_components,
       aes(x = Region, y = value, fill = component)) +
  geom_col(width = 0.8) +
  coord_flip() +
  scale_y_continuous(labels = label_number(scale_cut = cut_short_scale())) +
  scale_fill_brewer(palette = "Set2", name = "Component") +
  labs(
    x = "",
    y = "Digital capital stock per capita (USD, depreciated, 2024 base year)",
    caption = "Note: The graph does not include full RAN stock for CHN and IND due to data unavailability."
  ) +
  theme_minimal() +
  theme(
    plot.title = element_text(size = 16, face = "plain"),
    axis.text = element_text(size = 13),
    axis.title = element_text(size = 13),
    legend.text = element_text(size = 12),
    legend.title = element_text(size = 13),
    plot.caption = element_text(size = 11),
    legend.position = "bottom"
  )

# --- Save output ---

file_name <- "Figure_6_11_Per_Capita_Digital_Capital_Assets_by_Region_and_Component"
# PNG 
ggsave(
  filename = file.path(Outputpath, paste0(file_name, ".png")),
  plot = p,
  width = 15,
  height = 10,
  dpi = 300
)

# SVG 
ggsave(
  filename = file.path(Outputpath, paste0(file_name, ".svg")),
  plot = p,
  width = 15,
  height = 10,
  device = "svg"
)


# -----------
# Figure 4.13: Submarines landing points 
# -----------
submarines <- read_excel("04_AdditionalRestrictedData/submarine_clean_data.xlsx")

# Step 1: Calculate landing points per country
landing_counts <- submarines %>%
  filter(!is.na(country), !is.na(wb_income_group)) %>%
  distinct(country, cable_system) %>%
  count(country, name = "n_landing_points") %>%
  left_join(
    submarines %>% select(country, wb_income_group, wb_code) %>% distinct(),
    by = "country"
  )

# Step 2: Join with population and filter for >1M
landing_counts_pop <- landing_counts %>%
  left_join(
    infra_wide_class %>% select(iso3, latest_pop),
    by = c("wb_code" = "iso3")
  ) %>%
  filter(latest_pop > 1e6)

# Step 3: Prepare data for plot
landing_counts_plot <- landing_counts_pop %>%
  count(n_landing_points, wb_income_group) %>%
  mutate(
    landing_group = factor(n_landing_points, levels = sort(unique(n_landing_points)))
  )

# Step 4: Plot with default legend
# Define income group abbreviations
income_abbrev <- c(
  "Low income" = "LIC",
  "Lower middle income" = "LMIC",
  "Upper middle income" = "UMIC",
  "High income" = "HIC"
)

# Apply abbreviations
landing_counts_plot <- landing_counts_plot %>%
  mutate(wb_income_group = income_abbrev[wb_income_group])

# Plot
p <- ggplot(landing_counts_plot, aes(x = landing_group, y = n, fill = wb_income_group)) +
  geom_col() +
  labs(
    title = "Countries by Number of Submarine Cable Landing Points",
    subtitle = "Countries with >1M population",
    x = "Number of Landing Points",
    y = "Number of Countries",
    fill = "Income Group",
    caption = "Source: INFCE forthcoming report based on data from ITU"
  ) +
  theme_minimal(base_size = 16) +
  theme(
    legend.position = "bottom",
    axis.text.x = element_text(angle = 90, vjust = 0.5, size = 13),
    axis.text.y = element_text(size = 16),
    axis.title = element_text(size = 16),
    plot.title = element_text(size = 20),
    plot.subtitle = element_text(size = 16),
    legend.title = element_text(size = 16),
    legend.text = element_text(size = 16)
  )
# --- Save output ---

file_name <- "Figure_4_13_Countries_by_Number_of_Submarine_Cable_Landing Points"
# PNG 
ggsave(
  filename = file.path(Outputpath, paste0(file_name, ".png")),
  plot = p,
  width = 15,
  height = 10,
  dpi = 300
)

# SVG 
ggsave(
  filename = file.path(Outputpath, paste0(file_name, ".svg")),
  plot = p,
  width = 15,
  height = 10,
  device = "svg"
)


# -------------------------
# Figure 4.11: IXPs by capacity
# -------------------------

ixps <- read_excel("04_AdditionalRestrictedData/ixp_costs.xlsx")

ixps %>%
  mutate(
    miss_part = is.na(Participants) | Participants == "",
    miss_peak = is.na(Peak..Mbps.) | Peak..Mbps. == ""
  ) %>%
  summarise(
    n = n(),
    miss_part_n = sum(miss_part),
    miss_peak_n = sum(miss_peak),
    miss_either_n = sum(miss_part | miss_peak),
    miss_both_n = sum(miss_part & miss_peak),
    miss_part_pct = mean(miss_part) * 100,
    miss_peak_pct = mean(miss_peak) * 100,
    miss_either_pct = mean(miss_part | miss_peak) * 100,
    miss_both_pct = mean(miss_part & miss_peak) * 100
  )

income_avgs <- ixps %>%
  group_by(wb_income_group) %>%
  summarise(
    avg_participants = mean(Participants, na.rm = TRUE),
    avg_peak = mean(as.numeric(Peak..Mbps.), na.rm = TRUE)
  )

ixps <- ixps %>%
  mutate(
    Participants = as.numeric(Participants),
    Peak = as.numeric(Peak..Mbps.),
    wb_region = recode(wb_region,
                       "East Asia & Pacific" = "EAP",
                       "Europe & Central Asia" = "ECA",
                       "Latin America & Caribbean" = "LAC",
                       "Middle East & North Africa" = "MENAAP",
                       "North America" = "NA",
                       "South Asia" = "SAR",
                       "Sub-Saharan Africa" = "SSA")
  )

# Create tertile-based CapacityLevel directly
quantiles_part <- quantile(ixps$Participants, probs = c(1/3, 2/3), na.rm = TRUE)
quantiles_peak <- quantile(ixps$Peak, probs = c(1/3, 2/3), na.rm = TRUE)

ixps <- ixps %>%
  mutate(
    score_part = case_when(
      Participants <= quantiles_part[1] ~ 0,
      Participants <= quantiles_part[2] ~ 1,
      TRUE ~ 2
    ),
    score_peak = case_when(
      Peak <= quantiles_peak[1] ~ 0,
      Peak <= quantiles_peak[2] ~ 1,
      TRUE ~ 2
    ),
    avg_score = (score_part + score_peak) / 2,
    CapacityLevel = case_when(
      avg_score <= 0.5 ~ "Low",
      avg_score <= 1.5 ~ "Medium",
      TRUE ~ "High"
    )
  )

# Plot number of IXPs per region with average participants and peak
# title:  title = "Number of IXPs by Region and Capacity Level"
# caption = "Labels show average participants (P) and peak traffic (M) in thousands of Mbps"
p <- ixps %>%
  filter(!is.na(wb_region)) %>%
  group_by(wb_region, CapacityLevel) %>%
  summarise(
    num_ixps = n(),
    avg_participants = mean(Participants, na.rm = TRUE),
    avg_peak = mean(Peak, na.rm = TRUE),
    .groups = "drop"
  ) %>%
  ggplot(aes(x = reorder(wb_region, -num_ixps), y = num_ixps, fill = CapacityLevel)) +
  geom_bar(stat = "identity", position = "stack") +
  theme_minimal(base_size = 12) +
  labs(
    x = "Region",
    y = "Number of IXPs",
    fill = "Capacity Level"
  ) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))


# --- Save output ---

file_name <- "Figure_4_11_Numbers_of_IXPs_by_Region_and_Capacity"
# PNG 
ggsave(
  filename = file.path(Outputpath, paste0(file_name, ".png")),
  plot = p,
  width = 15,
  height = 10,
  dpi = 300
)

# SVG 
ggsave(
  filename = file.path(Outputpath, paste0(file_name, ".svg")),
  plot = p,
  width = 15,
  height = 10,
  device = "svg"
)

####################
# Figure 4.12: FOC median speed
#####################

foc <- read.csv("04_AdditionalRestrictedData/fibercables_costsestimates.csv")
# foc has Africa Bandwidth data already included in it

foc %>%
  summarise(
    unique_countries = n_distinct(country),
    total_km = sum(total_km, na.rm = TRUE)
  )

ookla_data <- haven::read_dta("04_AdditionalRestrictedData/Ookla_data_countrylevel.dta")

# Step 1: Prepare population data for 2023
pop_2023 <- pop %>%
  select(wb_code = Country.Code, population_2023 = X2023)

# Step 2: Merge population data into foc
foc <- foc %>%
  mutate(wb_code = trimws(toupper(wb_code))) %>%
  left_join(pop_2023, by = "wb_code")

# Step 1: Summarize Ookla data
ookla_summary <- ookla_data %>%
  group_by(iso3) %>%
  summarise(
    fixed_download = median(fixed_median_download_speed, na.rm = TRUE),
    .groups = "drop"
  )

# Step 2: Merge with fiber + population + region
fiber_download <- foc %>%
  select(wb_code, total_km, population_2023, country) %>%
  inner_join(ookla_summary, by = c("wb_code" = "iso3")) %>%
  left_join(infra_wide_class %>% select(iso3, Region), by = c("wb_code" = "iso3")) %>%
  filter(
    is.finite(total_km),
    is.finite(population_2023),
    is.finite(fixed_download),
    population_2023 > 1e6,
    !is.na(Region)  # Exclude countries with missing region
  ) %>%
  mutate(
    people_per_km = population_2023 / total_km,
    log_people_per_km = log1p(people_per_km),
    log_download = log1p(fixed_download),
    region_abbr = case_when(
      Region == "Sub-Saharan Africa" ~ "SSA",
      Region == "East Asia & Pacific" ~ "EAP",
      Region == "Latin America & Caribbean" ~ "LAC",
      Region == "Europe & Central Asia" ~ "ECA",
      Region == "Middle East, North Africa, Afghanistan & Pakistan" ~ "MENAAP",
      Region == "South Asia" ~ "SAR",
      Region == "North America" ~ "NA",
      TRUE ~ Region
    )
  )

# Step 3: Define manual colors for region abbreviations
region_colors <- c(
  "SSA" = "blue",
  "EAP" = "#33a02c",
  "LAC" = "magenta",
  "ECA" = "orange",
  "MENAAP" = "#6a3d9a",
  "SAR" = "red",
  "NA" = "#a6cee3"
)

# Step 4: Correlation
cor_result <- cor.test(fiber_download$log_people_per_km, fiber_download$log_download)
r_val <- round(cor_result$estimate, 2)
p_val <- cor_result$p.value

sig_text <- if (p_val < 0.001) {
  "p < 0.001"
} else if (p_val < 0.01) {
  "p < 0.01"
} else if (p_val < 0.05) {
  "p < 0.05"
} else {
  paste0("p = ", round(p_val, 3))
}


result <- data.frame(
  correlation = r_val,
  p_value = p_val,
  significance = sig_text
)
subtitle_text <- paste0("Pearson correlation = ", r_val, " (", sig_text, ")")

# Step 5: Plot

p <- ggplot(fiber_download, aes(x = log_people_per_km, y = log_download, color = region_abbr)) +
  geom_point(alpha = 0.8, size = 3) +
  geom_smooth(method = "lm", color = "black", se = FALSE, linewidth = 1.2) +
  scale_color_manual(values = region_colors) +
  labs(
    x = "People per Terrestrial Fiber Kilometer (log)",
    y = "Median Fixed Download Speed\n (log Mbps)",
    color = "Region"
  ) +
  theme_minimal(base_size = 16) +
  theme(
    legend.position = "bottom",
    legend.title = element_text(size = 16),
    legend.text = element_text(size = 15),
    axis.text = element_text(size = 14),
    axis.title = element_text(size = 16),
    plot.title = element_text(size = 18),
    plot.subtitle = element_text(size = 16),
    plot.caption = element_text(size = 11)
  )

# --- Save output ---

file_name <- "Figure_4_12_People_per_Fiber_km_and_Fixed_Download_Speed_by_Region"
# PNG 
ggsave(
  filename = file.path(Outputpath, paste0(file_name, ".png")),
  plot = p,
  width = 15,
  height = 10,
  dpi = 300
)

# SVG 
ggsave(
  filename = file.path(Outputpath, paste0(file_name, ".svg")),
  plot = p,
  width = 15,
  height = 10,
  device = "svg"
)

# ---------------------------------------
# Figure 5.10: Unit cost CTs
# ---------------------------------------

histclass <- read.csv("00_Non Sectoral Data/Raw/CountryData/historicincomegroups.csv")
classy <- read.csv("00_Non Sectoral Data/Raw/CountryData/classy.csv")

towerdeals <- read.csv("04_AdditionalRestrictedData/CT_dealvalues_towerxchange 1.csv")

# Merge regional and income data
tower_summary <- towerdeals %>%
  left_join(classy %>% select(iso3c = Code, Region, Income.group), by = "iso3c")

library(dplyr)
library(ggplot2)
library(scales)

td_reg <- towerdeals %>%
  left_join(classy %>% select(iso3c = Code, Region), by = "iso3c") %>%
  filter(!is.na(year), !is.na(cost_per_tower2024), !is.na(tower_amount)) %>%
  mutate(
    region_acr = case_when(
      Region == "East Asia & Pacific" ~ "EAP",
      Region == "Europe & Central Asia" ~ "ECA",
      Region == "Latin America & Caribbean" ~ "LAC",
      Region == "Middle East, North Africa, Afghanistan & Pakistan" ~ "MENAAP",
      Region == "North America" ~ "NA",
      Region == "South Asia" ~ "SAR",
      Region == "Sub-Saharan Africa" ~ "SSA",
      TRUE ~ NA_character_
    ),
    region_acr = factor(region_acr, levels = c("EAP","ECA","LAC","MENAAP","NA","SAR","SSA"))
  )

p <- ggplot(td_reg, aes(x = year, y = cost_per_tower2024, size = tower_amount, fill = region_acr)) +
  geom_point(alpha = 0.7, shape = 21, color = "gray20") +
  scale_y_log10(labels = label_dollar(accuracy = 1)) +
  scale_size_continuous(
    name = "Bubble size: towers per deal",
    breaks = c(100, 1000, 10000),
    labels = label_number(scale_cut = cut_short_scale())
  ) +
  labs(
    x = "Year",
    y = "Cost per tower\n (USD, log axis spacing)",
    fill = "Region:"
  ) +
  guides(
    fill = guide_legend(order = 1, title.position = "top", nrow = 1),
    size = guide_legend(order = 2, title.position = "top", nrow = 1)
  ) +
  theme_minimal(base_size = 14) +
  theme(
    plot.title = element_text(face = "plain", size = 16),
    axis.title = element_text(size = 13),
    axis.text = element_text(size = 13),
    legend.text = element_text(size = 13),
    legend.title = element_text(size = 13),
    legend.position = "bottom",
    legend.box = "vertical",
    legend.title.align = 0.5
  )
# --- Save output ---

file_name <- "Figure_5_10_Costs_of_Cell_Tower_by_Region"
# PNG 
ggsave(
  filename = file.path(Outputpath, paste0(file_name, ".png")),
  plot = p,
  width = 15,
  height = 10,
  dpi = 300
)

# SVG 
ggsave(
  filename = file.path(Outputpath, paste0(file_name, ".svg")),
  plot = p,
  width = 15,
  height = 10,
  device = "svg"
)
#################################
# Figure 5.11: DC observed costs
#################################

dc_raw <- read.csv('04_AdditionalRestrictedData/full_dataset_with_explanatory.csv')

# Make it in USD 2024 terms 
CPI <-  read_dta("../Interim/00_IndependentVar.dta") %>% 
  select(iso3c, year, WDI_CPI_) %>% 
  filter(iso3c == "USA") %>%
  select(-iso3c)

cpi_base <- CPI %>% filter(year == 2024) %>% pull(WDI_CPI_)

dc_raw <- dc_raw %>%
  mutate(year = if_else(year_end > 2024, 2024, year_end)) %>% 
  left_join(CPI, by = c("year")) 

dc_raw <- dc_raw %>% 
  mutate(project_cost_24 = project_cost * (cpi_base / WDI_CPI_))

# Get descriptive stats
Data_real <- dc_raw %>%
  filter(project_type == "Data Center", !is.na(project_cost_24))

desc_stats <- describe(Data_real$project_cost_24)[, c("n", "mean", "sd", "min", "median", "max")]
print(desc_stats)

desc_stats_million <- describe(Data_real$project_cost_24 / 1e6)[, c("n", "mean", "sd", "min", "median", "max")]
print(desc_stats_million)

dc_raw %>%
  filter(!is.na(project_cost)) %>%
  summarise(
    first_year = min(year_end, na.rm = TRUE),
    last_year  = max(year_end, na.rm = TRUE),
    total_years = last_year - first_year + 1,
    n_projects = n()
  )

Data_real <- dc_raw %>%
  filter(project_type == "Data Center",
         !is.na(project_cost_24),
         !is.na(wb_income_group),
         wb_income_group %in% c("High income","Upper middle income","Lower middle income","Low income")) %>%
  mutate(wb_income_group = recode(wb_income_group,
                                  "High income" = "HIC",
                                  "Upper middle income" = "UMIC",
                                  "Lower middle income" = "LMIC",
                                  "Low income" = "LIC"))
# Plot of observed unit cost
Data_real <- Data_real %>%
  mutate(wb_income_group = recode(wb_income_group,
                                  "High income" = "HIC",
                                  "Upper middle income" = "UMIC",
                                  "Lower middle income" = "LMIC",
                                  "Low income" = "LIC"
  ))

Data_real$wb_income_group <- factor(
  Data_real$wb_income_group,
  levels = c("LIC", "LMIC", "UMIC", "HIC")
)

# Note: caption = "Note: Distribution truncated at 35 billion USD (2024 terms)."
p <- ggplot(Data_real, aes(x = project_cost_24 / 1e6, fill = wb_income_group)) +
  geom_histogram(
    binwidth = 100,
    position = "stack",
    color = "white",
    alpha = 1
  ) +
  scale_fill_manual(
    values = c(
      "LIC"  = "#b2182b",
      "LMIC" = "#ef8a62",
      "UMIC" = "#67a9cf",
      "HIC"  = "#2166ac"
    ),
    drop = TRUE
  ) +
  scale_x_continuous(labels = scales::comma) +
  labs(
    x = "Project cost (million USD, 2024 base year)",
    y = "Number of projects",
    fill = "Income group"
  ) +
  coord_cartesian(xlim = c(0, 2000)) +
  theme_minimal(base_size = 14) +
  theme(legend.position = "bottom")

# --- Save output ---

file_name <- "Figure_5_11_Costs_of_Data_Centers_by_Region"
# PNG 
ggsave(
  filename = file.path(Outputpath, paste0(file_name, ".png")),
  plot = p,
  width = 15,
  height = 10,
  dpi = 300
)

# SVG 
ggsave(
  filename = file.path(Outputpath, paste0(file_name, ".svg")),
  plot = p,
  width = 15,
  height = 10,
  device = "svg"
)

#############################################################
# Figure 5.12: FOC observed costs
#############################################################


foc <- read.csv("04_AdditionalRestrictedData/train.csv")

foc_clean <- foc %>%
  mutate(
    cost_usd = valuesUSDm * 1e6,
    cost_per_km_usd = ifelse(km > 0, cost_usd / km, NA_real_)
  )

# Overall descriptive stats
overall_stats <- foc_clean %>%
  summarise(
    n_projects = n(),
    countries = n_distinct(COUNTRY),
    regions = n_distinct(REGION),
    years_span = paste0(min(Year_start, na.rm = TRUE), "-", max(Year_start, na.rm = TRUE)),
    total_cost_usd = sum(cost_usd, na.rm = TRUE),
    total_km = sum(km, na.rm = TRUE),
    avg_project_cost_usd = mean(cost_usd, na.rm = TRUE),
    median_project_cost_usd = median(cost_usd, na.rm = TRUE),
    avg_project_km = mean(km, na.rm = TRUE),
    median_project_km = median(km, na.rm = TRUE),
    unweighted_avg_cost_per_km_usd = mean(cost_per_km_usd, na.rm = TRUE),
    weighted_avg_cost_per_km_usd = total_cost_usd / total_km
  )

# Plot
wb_abbrev <- c(
  "East Asia & Pacific"        = "EAP",
  "Europe & Central Asia"      = "ECA",
  "Latin America & Caribbean"  = "LAC",
  "Middle East & North Africa" = "MENA",
  "North America"              = "NA",
  "South Asia"                 = "SAR",
  "Sub-Saharan Africa"         = "SSA"
)

plot_df <- foc_clean %>%
  mutate(
    cost_per_km = ifelse(is.finite(cost_per_km_usd), cost_per_km_usd, valuesUSDm * 1e6 / km),
    wb_region_full  = countrycode(COUNTRY, origin = "country.name", destination = "region"),
    wb_region_short = recode(wb_region_full, !!!wb_abbrev)
  ) %>%
  filter(is.finite(cost_per_km), cost_per_km > 0, !is.na(wb_region_short)) %>%
  mutate(log_cost = log10(cost_per_km))

binwidth_log <- 0.1  # in decades (0.1 ≈ ×1.26 step)
min_log <- floor(min(plot_df$log_cost))
max_log <- ceiling(max(plot_df$log_cost))
breaks_log <- seq(min_log, max_log, by = binwidth_log)

binned <- plot_df %>%
  mutate(
    bin = cut(log_cost, breaks = breaks_log, include.lowest = TRUE, right = FALSE),
    bin_id = as.integer(bin)
  ) %>%
  filter(!is.na(bin_id)) %>%
  group_by(bin_id) %>%
  arrange(log_cost, .by_group = TRUE) %>%
  mutate(count_y = row_number()) %>%
  ungroup() %>%
  mutate(bin_center_log = breaks_log[1] + (bin_id - 0.5) * binwidth_log,
         bin_center_usd = 10^bin_center_log)

p <- ggplot(binned, aes(x = bin_center_usd, y = count_y, color = wb_region_short)) +
  geom_point(alpha = 0.9, size = 2.6) +
  scale_x_log10(labels = dollar) +
  labs(
    title = "Frequency distribution of observed fiber cost per km",
    x = "Cost per km (USD, log scale)",
    y = "Count",
    color = "Region"
  ) +
  theme_minimal(base_size = 20) +
  theme(
    plot.title = element_text(size = 24, face = "plain"),
    axis.title = element_text(size = 20),
    axis.text  = element_text(size = 18),
    legend.position = "bottom",
    legend.title = element_text(size = 18),
    legend.text  = element_text(size = 16)
  )
# --- Save output ---

file_name <- "Figure_5_12_Costs_of_Terrestrial_FOC_by_Region"
# PNG 
ggsave(
  filename = file.path(Outputpath, paste0(file_name, ".png")),
  plot = p,
  width = 15,
  height = 10,
  dpi = 300
)

# SVG 
ggsave(
  filename = file.path(Outputpath, paste0(file_name, ".svg")),
  plot = p,
  width = 15,
  height = 10,
  device = "svg"
)


#################################
# Figure 5.13: Cost submarines
#################################

df <- read_excel("04_AdditionalRestrictedData/subcables_cost.xlsx")

df_clean <- df %>%
  mutate(
    cost_usd   = as.numeric(cost_usd),
    length_km  = as.numeric(length_km),
    capacity_gbps = as.numeric(capacity_gbps),
    fiber_pairs   = as.numeric(fiber_pairs)
  )

# Overall descriptive stats
overall_stats <- df_clean %>%
  summarise(
    n_projects              = n(),
    n_with_cost             = sum(!is.na(cost_usd)),
    share_with_cost         = n_with_cost / n_projects,
    service_year_min        = min(service_year, na.rm = TRUE),
    service_year_max        = max(service_year, na.rm = TRUE),
    total_length_km         = sum(length_km, na.rm = TRUE),
    total_cost_usd          = sum(cost_usd, na.rm = TRUE),
    avg_project_cost_usd    = mean(cost_usd, na.rm = TRUE),
    median_project_cost_usd = median(cost_usd, na.rm = TRUE),
    avg_project_km          = mean(length_km, na.rm = TRUE),
    median_project_km       = median(length_km, na.rm = TRUE),
    unweighted_avg_cost_per_km_usd = mean(cost_usd / length_km, na.rm = TRUE),
    weighted_avg_cost_per_km_usd   = sum(cost_usd, na.rm = TRUE) / sum(length_km, na.rm = TRUE),
    avg_capacity_gbps       = mean(capacity_gbps, na.rm = TRUE),
    median_capacity_gbps    = median(capacity_gbps, na.rm = TRUE),
    avg_fiber_pairs         = mean(fiber_pairs, na.rm = TRUE),
    median_fiber_pairs      = median(fiber_pairs, na.rm = TRUE),
    n_suppliers             = n_distinct(supplier),
    total_route_countries   = sum(num_countries, na.rm = TRUE)
  )

sum(df$num_countries[!is.na(df$cost_usd)], na.rm = TRUE)

# By service year
by_year <- df_clean %>%
  group_by(service_year) %>%
  summarise(
    n_projects = n(),
    n_with_cost = sum(!is.na(cost_usd)),
    total_length_km = sum(length_km, na.rm = TRUE),
    total_cost_usd  = sum(cost_usd, na.rm = TRUE),
    w_avg_cost_per_km_usd = total_cost_usd / total_length_km,
    .groups = "drop"
  ) %>%
  arrange(service_year)

# By supplier (optional)
by_supplier <- df_clean %>%
  group_by(supplier) %>%
  summarise(
    n_projects = n(),
    n_with_cost = sum(!is.na(cost_usd)),
    total_length_km = sum(length_km, na.rm = TRUE),
    total_cost_usd  = sum(cost_usd, na.rm = TRUE),
    w_avg_cost_per_km_usd = total_cost_usd / total_length_km,
    .groups = "drop"
  ) %>%
  arrange(desc(total_cost_usd))

# Plot
library(dplyr); library(ggplot2); library(scales); library(ggridges)

p2 <- df %>%
  filter(!is.na(cost_usd), cost_usd > 0, !is.na(service_year)) %>%
  mutate(
    log_cost = log10(cost_usd),
    decade = paste0(floor(service_year/10)*10, "s")
  ) %>%
  ggplot(aes(x = log_cost, y = decade, height = after_stat(density), fill = decade)) +
  geom_density_ridges(scale = 1.2, rel_min_height = 0.01, color = NA, alpha = 0.8) +
  scale_x_continuous(
    breaks = log10(c(1e6, 1e7, 1e8, 1e9, 1e10)),
    labels = dollar
  ) +
  scale_fill_viridis_d(option = "plasma", end = 0.9) +
  labs(
    x = "Project cost (USD)", y = "",
    fill = "Decade"
  ) +
  theme_minimal(base_size = 16) +
  theme(legend.position = "bottom")

p2 + 
  theme_minimal(base_size = 22) +
  theme(
    plot.title = element_text(size = 28, face = "plain"),
    axis.title = element_text(size = 22),
    axis.text  = element_text(size = 20),
    legend.position = "bottom",
    legend.title = element_text(size = 22),
    legend.text  = element_text(size = 20)
  )+
  scale_x_continuous(
    breaks = log10(c(1e6, 1e7, 1e8, 1e9, 1e10)),
    labels = function(x) scales::label_dollar(scale = 1e-6, suffix = "M")(10^x)
  )

# --- Save output ---

file_name <- "Figure_5_13_Costs_of_Submarine_Cables_by_Region"
# PNG 
ggsave(
  filename = file.path(Outputpath, paste0(file_name, ".png")),
  plot = p2,
  width = 15,
  height = 10,
  dpi = 300
)

# SVG 
ggsave(
  filename = file.path(Outputpath, paste0(file_name, ".svg")),
  plot = p2,
  width = 15,
  height = 10,
  device = "svg"
)

