################################### GLOBAL PATH SETUP #############################################
###################################################################################################

# --- Base path (Global Path) ---

global_path <- file.path("..",  "Data")
Outputpath <- file.path("..",  "Outputs")
base_raw    <- file.path("..",  "Data", "Raw")

## 🔶 🔶 🔶 🔶 🔶 🔶 🔶 
###🔶 🔶 Chapter 2🔶 🔶 ####################
## 🔶 🔶 🔶 🔶 🔶 🔶 🔶  



###################################################################################################
###################################################################################################
## 💠💠 Figure 2.2. Distribution of power generation capacity, by region and generation technology 💠💠
###################################################################################################
###################################################################################################
# ============================================================
# Installed Capacity by Type & Region (GW)
# ============================================================

# --- Load required packages ---
library(data.table)
library(ggplot2)
library(RColorBrewer)
library(dplyr)
library(rnaturalearth)
library(sf)
library(scales)

# ============================================================
#⃣ Load Main Dataset
# ============================================================

input_file <- file.path(
  base_raw,
  "Combined_PowerPlantsDataset_Share.csv"
)

print(input_file)
print(file.exists(input_file))

if (!file.exists(input_file)) {
  stop("Required input file is missing: ", input_file)
}

dt <- read.csv(input_file)
data.table::setDT(dt)
# ============================================================
#  Load WB Data
# ============================================================

wb <- read.csv(
  file.path(global_path, "Raw", "00_Non Sectoral Data", "Final", "00b_IndependentVar.csv")
)

setnames(wb,
         c("region_2025", "Incomegroup_", "iso3c"),
         c("region_wb", "income_wb", "country_code"))

# ============================================================
#  Country Harmonization 
# ============================================================

recode_to_wb <- c(
  "South Korea" = "Korea, Rep.",
  "North Korea" = "Korea, Dem. People's Rep.",
  "Russia" = "Russian Federation",
  "Egypt" = "Egypt, Arab Rep.",
  "Iran" = "Iran, Islamic Rep.",
  "Yemen" = "Yemen, Rep.",
  "Palestine" = "West Bank and Gaza",
  "Venezuela" = "Venezuela, RB",
  "Bahamas" = "Bahamas, The",
  "Republic of the Congo" = "Congo, Rep.",
  "DR Congo" = "Congo, Dem. Rep.",
  "Côte d'Ivoire" = "Côte d’Ivoire",
  "The Gambia" = "Gambia, The",
  "Slovakia" = "Slovak Republic",
  "Hong Kong" = "Hong Kong SAR, China",
  "Taiwan" = "Taiwan, China",
  "Brunei" = "Brunei Darussalam"
)

dt[, country_wb := ifelse(country %in% names(recode_to_wb),
                          recode_to_wb[country],
                          country)]

# ============================================================
#  Merge WB classification
# ============================================================

dt[wb, on = .(country_wb = country), region_wb := i.region_wb]
dt[wb, on = .(country_wb = country), income_wb := i.income_wb]
dt[wb, on = .(country_wb = country), country_code := i.country_code]

# ============================================================
# Manual Fix 
# ============================================================
region_manual <- c(
  
  # East Asia & Pacific
  "South Korea" = "East Asia & Pacific",
  "North Korea" = "East Asia & Pacific",
  "Taiwan" = "East Asia & Pacific",
  "Hong Kong" = "East Asia & Pacific",
  "Macao" = "East Asia & Pacific",
  "Brunei" = "East Asia & Pacific",
  "Laos" = "East Asia & Pacific",
  "Micronesia" = "East Asia & Pacific",
  
  # Europe & Central Asia
  "Türkiye" = "Europe & Central Asia",
  "Russia" = "Europe & Central Asia",
  "Kyrgyzstan" = "Europe & Central Asia",
  "Slovakia" = "Europe & Central Asia",
  
  # MENA
  "United Arab Emirates" = "Middle East, North Africa, Afghanistan & Pakistan",
  "Egypt" = "Middle East, North Africa, Afghanistan & Pakistan",
  "Iran" = "Middle East, North Africa, Afghanistan & Pakistan",
  "Yemen" = "Middle East, North Africa, Afghanistan & Pakistan",
  "Syria" = "Middle East, North Africa, Afghanistan & Pakistan",
  
  # Sub-Saharan Africa
  "Côte d'Ivoire" = "Sub-Saharan Africa",
  "Republic of the Congo" = "Sub-Saharan Africa",
  "Cabo Verde" = "Sub-Saharan Africa",
  "The Gambia" = "Sub-Saharan Africa",
  
  # Latin America & Caribbean
  "Venezuela" = "Latin America & Caribbean",
  "Trinidad and Tobago" = "Latin America & Caribbean",
  "Bahamas" = "Latin America & Caribbean",
  "Saint Kitts and Nevis" = "Latin America & Caribbean",
  "Saint Lucia" = "Latin America & Caribbean"
)

dt[country %in% names(region_manual),
   region_wb := region_manual[country]]


# Western Sahara
dt[country == "Western Sahara",
   region_wb := "Middle East, North Africa, Afghanistan & Pakistan"]

# Territories 
dt[country %in% c("Martinique", "Guadeloupe", "French Guiana",
                  "Curaçao", "Bonaire, Sint Eustatius, and Saba"),
   region_wb := "Latin America & Caribbean"]

dt[country %in% c("Réunion", "Mayotte"),
   region_wb := "Sub-Saharan Africa"]

dt[country %in% c("Norfolk Island", "Cook Islands",
                  "British Indian Ocean Territory"),
   region_wb := "East Asia & Pacific"]

dt[country %in% c("Åland Islands", "Isle of Man", "Faroe Islands"),
   region_wb := "Europe & Central Asia"]

dt[country %in% c("Kosovo"),
   region_wb := "Europe & Central Asia"]

dt[country %in% c("Palestine"),
   region_wb := "Middle East, North Africa, Afghanistan & Pakistan"]

dt[country %in% c("Timor-Leste"),
   region_wb := "East Asia & Pacific"]

dt[country %in% c("DR Congo"),
   region_wb := "Sub-Saharan Africa"]

dt[country %in% c("Andorra"),
   region_wb := "Europe & Central Asia"]


# ============================================================
#  Remaining NA 
# ============================================================
dt[is.na(region_wb), unique(country)]

dt[region_wb == "Unknown", unique(country)]
dt[is.na(region_wb), region_wb := "Unknown"]
dt[is.na(type), type := "Unknown"]

# ============================================================
#  RegiON
# ============================================================

dt[, region_wb := factor(region_wb,
                         levels = c(
                           "East Asia & Pacific",
                           "Europe & Central Asia",
                           "Latin America & Caribbean",
                           "Middle East, North Africa, Afghanistan & Pakistan",
                           "North America",
                           "South Asia",
                           "Sub-Saharan Africa"
                         )
)]

# ============================================================
#  Data Cleaning
# ============================================================

dt <- dt %>%
  filter(!is.na(capacity_mw)) %>%
  mutate(capacity_gw = capacity_mw / 1000)

# ============================================================
#  Aggregation
# ============================================================

data <- dt %>%
  group_by(type, region_wb) %>%
  summarise(capacity_gw = sum(capacity_gw, na.rm = TRUE), .groups = "drop")

data <- data %>%
  group_by(type) %>%
  mutate(total_capacity = sum(capacity_gw)) %>%
  ungroup()

# ============================================================
# Visualization
# ============================================================
scale_y_continuous(labels = scales::comma)

data <- data %>%
  mutate(type_label = case_when(
    type %in% c("oil", "gas", "oil/gas") ~ "Oil and gas",
    type == "coal" ~ "Coal",
    type == "hydro" ~ "Hydropower",
    type == "solar" ~ "Solar",
    type == "wind" ~ "Wind",
    TRUE ~ tools::toTitleCase(type)
  ))

data <- data %>%
  mutate(region_wb = recode(region_wb,
                            "East Asia & Pacific" = "East Asia and Pacific",
                            "Europe & Central Asia" = "Europe and Central Asia",
                            "Latin America & Caribbean" = "Latin America and the Caribbean",
                            "Middle East, North Africa, Afghanistan & Pakistan" =
                              "Middle East, North Africa, Afghanistan, and Pakistan",
                            "North America" = "North America",
                            "South Asia" = "South Asia",
                            "Sub-Saharan Africa" = "Sub-Saharan Africa"
  ))

region_levels_new <- c(
  "East Asia and Pacific",
  "Europe and Central Asia",
  "Latin America and the Caribbean",
  "Middle East, North Africa, Afghanistan, and Pakistan",
  "North America",
  "South Asia",
  "Sub-Saharan Africa"
)

data$region_wb <- factor(data$region_wb, levels = region_levels_new)


p <- ggplot(data, aes(x = reorder(type_label, -total_capacity),
                      y = capacity_gw,
                      fill = region_wb)) +
  geom_bar(stat = "identity") +
  scale_fill_brewer(palette = "Spectral", limits = region_levels_new) +
  scale_y_continuous(labels = scales::comma) +
  labs(x = "", y = NULL, fill = NULL) +
  theme_minimal(base_size = 18) +
  theme(
    axis.text.x = element_text(size = 16),
    axis.text.y = element_text(size = 16),
    legend.position = "bottom",
    panel.grid.major.x = element_blank()
  )

print(p)


# --- Save output ---



print(file.exists(Outputpath))

file_base <- "Chapter2_Figure2_Distribution_of_power_generation_capacity"

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

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











## 🔶 🔶 🔶 🔶 🔶 🔶 🔶 
###🔶 🔶 Chapter 5🔶 🔶 ####################
## 🔶 🔶 🔶 🔶 🔶 🔶 🔶  




###################################################################################################
## 💠💠 Figure 5.1 .Unit Cost for Fossil and Nuclear Technologies 💠💠
###################################################################################################

library(readr)
library(dplyr)
library(ggplot2)

# ---- Load data ----
df <- read_csv(file.path(base_raw,"1112_WEO_CAPEX.csv"))

df$capex <- df$capex |>
  gsub(",", "", x = _) |>
  gsub("\\$", "", x = _) |>
  trimws() |>
  as.numeric()

# ---- Factor ordering for type ----
df$type <- factor(df$type,
                  levels = c("gas/oil", "coal", "fuel cell", "nuclear"),
                  labels = c("Oil/Gas", "Coal", "Fuel Cell", "Nuclear"))

# ---- Combine 3 coal technologies into 'Steam Turbine' ----
df <- df %>%
  mutate(technology_group = case_when(
    technology_weo %in% c("subcritical", "supercritical", "ultrasupercritical") ~ "Steam Turbine",
    TRUE ~ technology_weo
  )) %>%
  group_by(type, technology_group, region) %>%
  summarise(capex = mean(capex, na.rm = TRUE), .groups = "drop")

# ---- Order technologies by CAPEX within each type ----
tech_order <- df %>%
  group_by(type, technology_group) %>%
  summarise(mean_capex = mean(capex, na.rm = TRUE), .groups = "drop") %>%
  arrange(type, mean_capex) %>%
  pull(technology_group)

df$technology_group <- factor(df$technology_group, levels = tech_order)
df$x_pos <- as.numeric(df$technology_group)

# ---- Type centers ----
type_centers <- df %>%
  group_by(type) %>%
  summarise(center = mean(x_pos, na.rm = TRUE))

# ---- Split lines ----
split_positions <- df %>%
  group_by(type) %>%
  summarise(max_x = max(x_pos)) %>%
  pull(max_x)
split_positions <- split_positions[-length(split_positions)]

# ---- Colors ----
custom_colors <- c(
  "Africa" = "#4e79a7", "Brazil" = "#f28e2b", "China" = "#e15759",
  "European Union" = "#76b7b2", "India" = "#59a14f", "Japan" = "#edc948",
  "Middle East" = "#af7aa1", "Russia" = "#ff9da7", "United States" = "#9c755f"
)

# ---- Axis buffer ----
y_min <- min(df$capex, na.rm = TRUE)
y_max <- max(df$capex, na.rm = TRUE)

# ---- Plot ----
p <- ggplot(df, aes(x = technology_group, y = capex, color = region)) +
  geom_hline(yintercept = 0, color = "black", linewidth = 0.7) +
  geom_point(shape = 21, fill = "white", stroke = 1.3, size = 4.8,
             position = position_jitter(width = 0.2, seed=42)) +
  scale_color_manual(values = custom_colors) +
  scale_y_continuous(expand = expansion(mult = c(0.08, 0.08))) +
  labs(
    title = NULL,   
    subtitle = NULL,
    x = NULL, y = "Installed Cost (USD/kW)", color = NULL   
  ) +
  theme_minimal(base_size = 25) +
  theme(
    panel.grid = element_blank(),
    axis.ticks = element_blank(),
    axis.text.x = element_text(angle = 45, hjust = 1, size = 22, face = "bold"),
    axis.text.y = element_text(size = 21),
    axis.title.y = element_text(size = 23, face = "bold"),
    legend.text = element_text(size = 25),
    legend.title = element_blank(),  
    axis.line.y = element_line(color = "black", linewidth = 0.8),
    plot.margin = margin(t = 30, r = 80, b = 120, l = 40),
    plot.title = element_blank(),    
    legend.position = "bottom"
  ) +
  annotate(
    "text",
    x = type_centers$center,
    y = - (y_max - y_min) * 0.03,
    label = type_centers$type,
    fontface = "bold",
    size = 7,
    vjust = 1
  ) +
  geom_vline(xintercept = split_positions + 0.5, linetype = "dashed",
             linewidth = 0.7, color = "black") +
  coord_cartesian(clip = "off")

print(p)

# ---- Save ----

file_base <- "Chapter5_Figure1_Unit Cost of Fossil and Nuclear Technologies"

# PNG 
ggsave(
  filename = file.path(Outputpath, paste0(file_base, ".png")),
  plot = p,
  width = 15,
  height = 15,
  dpi = 300
)

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





###################################################################################################
## 💠💠 Figure 5.2.Unit Cost of Selected Renewable Technologies (Million USD per MW, constant 2023 value) 💠💠
####### a.  Solar PV, by Country by Year
###################################################################################################


# ==== 1. Load packages ====
library(readxl)
library(tidyverse)

# ==== 2. File path ====
dr <- file.path(
  base_raw,
  "1112_IRENA_Total_Installed_Cost.xlsx"
)

# ==== 3. Load data ====
pv_world   <- read_excel(dr, sheet = "PV_World")
pv_world_t <- as.data.frame(t(pv_world))        # 추가
colnames(pv_world_t) <- "Weighted_avg"           # 추가
pv_world_t <- pv_world_t %>%                     # 추가
  rownames_to_column("Year") %>%
  mutate(
    Year = as.numeric(Year),
    Weighted_avg = as.numeric(Weighted_avg)
  ) %>%
  drop_na()

pv_country <- read_excel(dr, sheet = "PV_Country")

# ==== 4. Clean PV World ====
pv_world_t <- pv_world_t %>%
  rename(weighted_average = Weighted_avg) %>%
  mutate(
    weighted_average = gsub(",", "", weighted_average),
    weighted_average = trimws(weighted_average),
    weighted_average = na_if(weighted_average, ""),
    weighted_average = na_if(weighted_average, ".."),
    weighted_average = na_if(weighted_average, "-"),
    weighted_average = na_if(weighted_average, "n/a"),
    weighted_average = as.numeric(weighted_average)
  )

# ==== 5. Clean Country-Level PV ====
pv_country_long <- pv_country %>%
  rename_with(~ c("Country", names(pv_country)[-1]), .cols = 1:ncol(pv_country)) %>%
  pivot_longer(cols = -Country, names_to = "Year", values_to = "Installed_Cost") %>%
  mutate(
    Year = as.numeric(Year),
    Installed_Cost = as.numeric(Installed_Cost)
  ) %>%
  filter(!is.na(Installed_Cost), Installed_Cost < 15000)

# ==== 6. Color-blind safe palette (15-color version) ====
cb_safe_colors <- c(
  "#E69F00", "#56B4E9", "#009E73", "#F0E442",
  "#0072B2", "#D55E00", "#CC79A7", "#999999",
  "#004949", "#009292", "#FF6DB6", "#FFB6DB",
  "#490092", "#006DDB", "#B66DFF"
)

n_countries <- length(unique(pv_country_long$Country))
palette_use <- cb_safe_colors[1:n_countries]

# ==== 7. Plot ====

ggplot() +
  geom_point(
    data = pv_country_long,
    aes(x = Year, y = Installed_Cost, color = Country),
    size = 3.8, alpha = 0.85
  ) +
  geom_line(
    data = pv_world_t,
    aes(x = Year, y = weighted_average),
    color = "black", linewidth = 1.8
  ) +
  scale_color_manual(values = palette_use) +
  scale_x_continuous(
    limits = c(2009.5, 2024.5),
    breaks = seq(2010, 2024, by = 2),
    expand = c(0, 0)
  ) +
  labs(
    title = NULL,
    x = "Year",
    y = "Installed Cost (USD/kW)",
    color = NULL   
  ) +
  theme_minimal(base_size = 18) +
  theme(
    axis.title = element_text(size = 20),
    axis.text.x  = element_text(size = 17, color = "black"),
    axis.text.y  = element_text(size = 17, color = "black"),
    legend.position = "bottom",
    legend.title = element_text(size = 18),
    legend.text  = element_text(size = 16, color = "black"),
    panel.grid.minor = element_blank(),
    legend.key.width = unit(1.5, "cm"),
    legend.key.height = unit(1.0, "cm"),
    legend.box = "horizontal",
    plot.margin = margin(15, 20, 15, 20)
  ) +
  guides(color = guide_legend(nrow = 2, byrow = TRUE))





# ---- Save ----

file_base <- "Chapter5_Figure2a_Unit Cost of Selected Renewable Technologies(solar PV)"

# PNG 
ggsave(
  filename = file.path(Outputpath, paste0(file_base, ".png")),
  units = "in",
  width = 20,
  height = 15,
  dpi = 300
)

# SVG 
ggsave(
  filename = file.path(Outputpath, paste0(file_base, ".svg")),
  units = "in",
  width = 20,
  height = 15,
  device = "svg"
)







#############################################################################################################
## 💠💠 Figure 5.2.Unit Cost of Selected Renewable Technologies (Million USD per MW, constant 2023 value) 💠💠
####### b.Wind Power Installed Cost Trends (Onshore & Offshore) ##################
############################################################################################################

# ====================================================
# 1. Load required libraries
# ====================================================
library(readxl)
library(tidyverse)

# ====================================================
# 2. Load input data
# ====================================================


file_path <- file.path(
  base_raw,
  "1112_IRENA_Total_Installed_Cost.xlsx"
)

onshore_world   <- read_excel(file_path, sheet = "WindOnshore_World")
onshore_country <- read_excel(file_path, sheet = "WindOnshore_Country")
offshore_world  <- read_excel(file_path, sheet = "WindOffshore_World")

# ====================================================
# 3. Region mapping (World Bank official regions)
# ====================================================
region_map <- tribble(
  ~Country, ~Region,
  "Argentina","Latin America & Caribbean","Australia","East Asia & Pacific",
  "Austria","Europe & Central Asia","Brazil","Latin America & Caribbean",
  "Canada","North America","Chile","Latin America & Caribbean",
  "China","East Asia & Pacific","Costa Rica","Latin America & Caribbean",
  "Croatia","Europe & Central Asia","Cyprus","Europe & Central Asia",
  "Denmark","Europe & Central Asia","Dominican Republic","Latin America & Caribbean",
  "Egypt","Middle East, North Africa, Afghanistan & Pakistan","Ethiopia","Sub-Saharan Africa",
  "Finland","Europe & Central Asia","France","Europe & Central Asia",
  "Germany","Europe & Central Asia","Greece","Europe & Central Asia",
  "India","South Asia","Indonesia","East Asia & Pacific",
  "Ireland","Europe & Central Asia","Italy","Europe & Central Asia",
  "Japan","East Asia & Pacific","Mexico","Latin America & Caribbean",
  "Morocco","Middle East, North Africa, Afghanistan & Pakistan","Netherlands","Europe & Central Asia",
  "New Zealand","East Asia & Pacific","Norway","Europe & Central Asia",
  "Afghanistan","Middle East, North Africa, Afghanistan & Pakistan",
  "Pakistan","Middle East, North Africa, Afghanistan & Pakistan",
  "Panama","Latin America & Caribbean",
  "Peru","Latin America & Caribbean","Philippines","East Asia & Pacific",
  "Poland","Europe & Central Asia","Portugal","Europe & Central Asia",
  "Republic of Korea","East Asia & Pacific","Russian Federation","Europe & Central Asia",
  "South Africa","Sub-Saharan Africa","Spain","Europe & Central Asia",
  "Sweden","Europe & Central Asia","Turkey","Europe & Central Asia",
  "Ukraine","Europe & Central Asia","United Kingdom","Europe & Central Asia",
  "United States","North America","Uruguay","Latin America & Caribbean",
  "Viet Nam","East Asia & Pacific"
)

# ====================================================
# 4. Clean and reshape data
# ====================================================
onshore_world <- onshore_world %>% mutate(Year = as.numeric(Year))

offshore_world <- offshore_world %>%
  mutate(Year = as.numeric(Year)) %>%
  filter(Year >= 2008)

country_long <- onshore_country %>%
  pivot_longer(cols = -Country, names_to = "Year", values_to = "Installed_Cost") %>%
  mutate(Year = as.numeric(Year), Installed_Cost = as.numeric(Installed_Cost)) %>%
  left_join(region_map, by = "Country") %>%
  filter(!is.na(Region), Installed_Cost < 8000)

# ====================================================
# 5. World Bank Region Color Palette
# ====================================================
wb_colors <- c(
  "East Asia & Pacific"        = "#1f77b4",
  "Europe & Central Asia"      = "#ff7f0e",
  "Latin America & Caribbean"  = "#2ca02c",
  "Middle East, North Africa, Afghanistan & Pakistan" = "#d62728",
  "North America"              = "#9467bd",
  "South Asia"                 = "#8c564b",
  "Sub-Saharan Africa"         = "#e377c2"
)

# ====================================================
# 6. Plot (No titles, no legend subtitles)
# ====================================================
p3 <- ggplot() +
  geom_point(
    data = country_long,
    aes(x = Year, y = Installed_Cost, color = Region),
    size = 2, alpha = 0.85
  ) +
  geom_line(
    data = onshore_world,
    aes(x = Year, y = `Weighted average`, linetype = "Onshore World Average"),
    color = "black", linewidth = 1.2
  ) +
  geom_line(
    data = offshore_world,
    aes(x = Year, y = `Weighted average`, linetype = "Offshore World Average"),
    color = "#B22222", linewidth = 1.2
  ) +
  geom_vline(xintercept = 2008, linetype = "dashed", color = "gray40", linewidth = 0.7) +
  scale_color_manual(values = wb_colors, name = NULL) +
  scale_linetype_manual(values = c("Onshore World Average" = "solid", "Offshore World Average" = "longdash"), name = NULL) +
  scale_x_continuous(
    breaks = c(1984, 1990, 1995, 2000, 2005, 2008, 2010, 2015, 2020, 2023),
    expand = expansion(mult = c(0.03, 0.03))
  ) +
  labs(
    title = NULL,
    subtitle = NULL,
    x = "Year",
    y = "Installed Cost (2023 USD/kW)",
    color = NULL,
    linetype = NULL
  ) +
  theme_minimal(base_size = 20) +
  theme_minimal(base_size = 20) +
  theme(
    legend.position = "bottom",
    legend.text = element_text(color = "black"),   
    legend.title = element_text(color = "black"), 
    axis.text.x = element_text(color = "black"), 
    axis.text.y = element_text(color = "black"), 
    plot.title = element_text(face = "bold", hjust = 0.5),
    plot.subtitle = element_text(hjust = 0.5),
    panel.grid.minor = element_blank()
  )


p3


# ---- Save ----

file_base <- "Chapter5_Figure2b_Unit Cost of Selected Renewable Technologies (Wind Power)"

# PNG 
ggsave(
  filename = file.path(Outputpath, paste0(file_base, ".png")),
  plot = p3,
  units = "in",
  width = 20,
  height = 10,
  dpi = 300
)

# SVG 
ggsave(
  filename = file.path(Outputpath, paste0(file_base, ".svg")),
  plot = p3,
  units = "in",
  width = 20,
  height = 10,
  device = "svg"
)








###################################################################################################
# 💠💠 Figure 5.3 .Installed Cost of Hydro Power 2016-2023 💠💠
###################################################################################################



# --------------------------------------------------------------------
# 1. Load data
# --------------------------------------------------------------------

file_path <- file.path(
  base_raw,
  "1112_IRENA_Total_Installed_Cost.xlsx"
)

print(file_path)
print(file.exists(file_path))

large_raw <- read_excel(file_path, sheet = "Hydro_Region_Large")
small_raw <- read_excel(file_path, sheet = "Hydro_Region_Small")

# --------------------------------------------------------------------
# 2. Clean — select 2016–2023 + Weighted average only
# --------------------------------------------------------------------
large <- large_raw %>%
  as.data.frame() %>%
  dplyr::filter(Period == "2016-2023") %>%
  dplyr::rename(Weighted_average = `Weighted average`) %>%
  dplyr::select(Region, Weighted_average) %>%
  dplyr::filter(!is.na(Region) & !is.na(Weighted_average)) %>%   
  dplyr::mutate(Type = "Large Hydro (>10 MW)")

small <- small_raw %>%
  as.data.frame() %>%
  dplyr::filter(Period == "2016-2023") %>%
  dplyr::rename(Weighted_average = `Weighted average`) %>%
  dplyr::select(Region, Weighted_average) %>%
  dplyr::filter(!is.na(Region) & !is.na(Weighted_average)) %>%   
  dplyr::mutate(Type = "Small Hydro (≤ 10 MW)")

# --------------------------------------------------------------------
# 3. Bind data, # 4. Exact Region order
# --------------------------------------------------------------------
region_order <- c(
  "Africa","Brazil","China","Eurasia","Europe","India","Other Asia",
  "Middle East","North America","Oceania","Other South America"
)

df <- bind_rows(large, small) %>% 
  filter(!is.na(Region) & !is.na(Weighted_average)) %>%
  mutate(
    Region = str_trim(as.character(Region))   
  ) %>%
  filter(Region %in% region_order)            


df$Region <- factor(df$Region, levels = region_order)


# --------------------------------------------------------------------

# --------------------------------------------------------------------


df$Region <- factor(df$Region, levels = region_order)

# --------------------------------------------------------------------
# 5. Colors (Excel-style)
# --------------------------------------------------------------------
type_colors <- c(
  "Large Hydro (>10 MW)" = "#004c6d",   # dark blue
  "Small Hydro (≤ 10 MW)" = "#b23ac7"   # magenta
)

# --------------------------------------------------------------------
# 6. Plot 
# --------------------------------------------------------------------
p <- ggplot(df, aes(x = Region, y = Weighted_average, fill = Type)) +
  geom_col(
    position = position_dodge2(width = 0.8, preserve = "single"),
    width = 0.7
  ) +
  scale_fill_manual(values = type_colors) +
  labs(
    x = NULL,
    y = "Installed Cost (2023 USD/kW)", 
    fill = NULL
  ) +
  theme_minimal(base_size = 16) +
  theme(
    axis.text.x = element_text(angle = 45, hjust = 1, color = "black"),
    axis.title.x = element_text(color = "black"),
    panel.grid.minor = element_blank(),
    legend.position = "bottom"
  )

print(p)



# ---- Save ----

file_base <- "Chapter5_Figure3_Installed Cost of Hydro Power 2016-2023"

# PNG 
ggsave(
  filename = file.path(Outputpath, paste0(file_base, ".png")),
  width = 12,
  height = 6,
  dpi = 300
)

# SVG 
ggsave(
  filename = file.path(Outputpath, paste0(file_base, ".svg")),
  width = 12,
  height = 6,
  device = "svg"
)







###################################################################################################
# 💠💠 Figure 5.4.Unit Cost for Transmission Lines Million USD per km (constant 2023 value) 💠💠
###################################################################################################

# ----------------------------------------------------
# 0. Load Packages
# ----------------------------------------------------
library(readxl)
library(ggplot2)
library(tidyr)
library(dplyr)

# ----------------------------------------------------
# 1. File Path and Data Loading
# ----------------------------------------------------

file_path <- file.path(
  base_raw,
  "1112_CPI_Table 3.1.xlsx"
)

raw_data <- read_excel(
  path = file_path,
  sheet = "Sheet1",
  col_names = TRUE
)

# ----------------------------------------------------
# 2. Data Cleaning and Long Format Conversion
# ----------------------------------------------------
data_2023 <- raw_data %>%
  rename(Region = 1) %>%
  rename_with(~ gsub("[^A-Za-z0-9.]", ".", .x, perl = TRUE), .cols = 2:ncol(raw_data)) %>%
  rename_with(~ gsub("\\.{2,}", ".", .x, perl = TRUE), .cols = 2:ncol(raw_data)) %>%
  rename_with(~ gsub("\\.$", "", .x), .cols = 2:ncol(raw_data))

regional_data <- data_2023 %>% filter(Region != "World")
world_data <- data_2023 %>% filter(Region == "World")

cost_cols <- c(".100.kv", ".200.kv", ".300.kv", ".350.kv", ".400.kv.500.kv", "Above.500kv")

regional_data <- regional_data %>%
  mutate(
    across(all_of(cost_cols), ~ trimws(.x)),
    across(all_of(cost_cols), ~ gsub(",", "", .x)),
    across(all_of(cost_cols), ~ gsub("[^0-9.-]", "", .x)),
    across(all_of(cost_cols), ~ na_if(.x, "")),
    across(all_of(cost_cols), as.numeric)
  )

cost_cols <- names(data_2023)[-1]

world_data_cleaned <- world_data %>%
  mutate(across(all_of(cost_cols), as.numeric))

world_long <- world_data_cleaned %>%
  pivot_longer(cols = all_of(cost_cols), names_to = "Voltage_Range", values_to = "Cost")

regional_data_cleaned <- regional_data %>%
  mutate(across(all_of(cost_cols), as.numeric))

regional_long <- regional_data_cleaned %>%
  pivot_longer(cols = all_of(cost_cols), names_to = "Voltage_Range", values_to = "Cost") %>%
  filter(!is.na(Cost))

# ----------------------------------------------------
# 3. Visualization with Fixed Y-Axis Breaks & New Shape
# ----------------------------------------------------
voltage_order <- unique(world_long$Voltage_Range)
voltage_labels <- c("100-200 kV", "200-300 kV", "300-350 kV",
                    "350-400 kV", "400-500 kV", "Above 500 kV")

# WB color palette
wb_palette <- c(
  "East Asia and Pacific"        = "#4E79A7",  
  "Eastern and Southern Africa"  = "#F28E2B",  
  "Europe and Central Asia"      = "#59A14F",  
  "Middle East and North Africa" = "#E15759",  
  "South Asia"                   = "#B07AA1",  
  "Western and Central Africa"   = "#9C755F"   
)


# Solid filled shapes
wb_shapes <- c(
  "East Asia and Pacific"        = 16, # circle
  "Eastern and Southern Africa"  = 17, # triangle
  "Europe and Central Asia"      = 15, # square
  "Middle East and North Africa" = 18, # diamond
  "South Asia"                   = 19, # solid circle
  "Western and Central Africa"   = 23, # diamond-square
  "North America"                = 25, # filled triangle-down
  "Latin America & Caribbean"    = 24  # filled square
)


# Slightly lighter gray for world bar
world_bar_fill <- "#e5e5e5"

p5 <- ggplot() +
  # A. World Average Bar
  geom_col(
    data = world_long,
    aes(x = factor(Voltage_Range, levels = voltage_order, labels = voltage_labels),
        y = Cost),
    fill = world_bar_fill,
    alpha = 0.7,
    width = 0.6
  ) +
  # B. Regional Points
  geom_point(
    data = regional_long,
    aes(
      x = factor(Voltage_Range, levels = voltage_order, labels = voltage_labels),
      y = Cost,
      color = Region,
      shape = Region,
      fill = Region
    ),
    size = 10,
    alpha = 0.9,
    stroke = 0.6,
    position = position_jitter(width = 0.12, seed=42)
  ) +
  scale_color_manual(values = wb_palette) +
  scale_shape_manual(values = wb_shapes) +
  scale_fill_manual(values = wb_palette, guide = "none") +
  labs(
    title = NULL,
    subtitle = NULL,
    x = "Voltage Range (kV)",
    y = "Average Unit Cost (Million USD/km)",
    color = NULL,
    shape = NULL
  ) +
  # Fixed Y-axis interval of 0.5
  scale_y_continuous(
    expand = expansion(mult = c(0, 0.1)),
    breaks = seq(0, ceiling(max(regional_long$Cost, na.rm = TRUE)), by = 0.5)
  ) +
  # Clean theme, no grid
  theme_minimal(base_size = 14) +
  theme(
    axis.title = element_text(size = 20),
    axis.text.x = element_text(angle = 45, hjust = 1, size = 15, color = "gray30"),
    axis.text.y = element_text(size = 17, color = "gray30"),
    panel.grid = element_blank(),
    panel.border = element_blank(),
    legend.position = "bottom",
    legend.direction = "horizontal",
    legend.text = element_text(size = 16),
    plot.margin = margin(15, 20, 15, 20)
  ) +
  guides(
    color = guide_legend(
      nrow = 1, byrow = TRUE,
      override.aes = list(fill = wb_palette)  
    ),
    shape = guide_legend(nrow = 1, byrow = TRUE)
  )
unique(regional_long$Region)



print(p5)




# ---- Save ----

file_base <- "Chapter5_Figure4_Unit Cost for Transmission Lines Million USD per km"

# PNG 
ggsave(
  filename = file.path(Outputpath, paste0(file_base, ".png")),
  plot = p5,
  units = "in",
  width = 20,
  height = 10,
  dpi = 300
)

# SVG 
ggsave(
  filename = file.path(Outputpath, paste0(file_base, ".svg")),
  plot = p5,
  units = "in",
  width = 20,
  height = 10,
  device = "svg"
)