# sepsis-figures.R
# Rebuilds the figures from part 4 for the export examples in part 5.
# Creates the plots figure, trajectory, paths, pattern_heatmap, and six_panels,
# plus the data and settings they use: samples, heat, patients, mean_paths,
# outcome_colours, line_colours, and source_note.
# Run it from the lesson folder, with the Ghana sepsis CSVs in data/.

library(ggplot2)
library(patchwork)

samples <- read.csv("data/ghana_sepsis_samples.csv", na.strings = c("", "NA"))
heat <- read.csv("data/ghana_sepsis_heatmaps.csv", na.strings = c("", "NA"))

samples$outcome <- factor(samples$outcome,
                          levels = c("Healthy", "Survived", "Died"))
samples$visit <- factor(samples$visit,
                        levels = c("H", "0h", "6h", "24h", "48h", "72h",
                                   "28d", "6m", "12m"))

outcome_colours <- c(Healthy = "#E3B505", Survived = "#CDBB98", Died = "#C8102E")
line_colours <- c(Survived = "#6B5530", Died = "#7A0019")
source_note <- "Source: Chenoweth et al. (2024), Nat Commun; source data on Zenodo (CC BY 4.0)."

# Boxplots over time: the finished figure from part 4, Steps 1 to 4 ----------

figure <- ggplot(samples, aes(x = visit, y = PC1, fill = outcome)) +
  geom_boxplot(coef = Inf, width = 0.7,
               position = position_dodge2(preserve = "single")) +
  scale_fill_manual(
    values = outcome_colours,
    breaks = c("Healthy", "Survived", "Died"),
    labels = c("Healthy donor", "Survived 28 days", "Died by 28 days")
  ) +
  labs(
    title = "Later samples from survivors resemble healthy donors",
    subtitle = "Ghana sepsis cohort | Principal component 1 by visit and 28-day outcome",
    x = "Visit (H = healthy donor; hours, days, or months after enrolment)",
    y = "PC1 score", fill = NULL,
    caption = paste(
      source_note,
      "Whiskers show the minimum and maximum. Each visit includes only the samples available.",
      sep = "\n"
    )
  ) +
  theme_classic(base_size = 12) +
  theme(
    legend.position = "bottom",
    plot.title = element_text(face = "bold"),
    plot.caption = element_text(hjust = 0, colour = "#52616B")
  )

# Trajectory plot: average paths of patterns 23 and 4 -------------------------

patients <- subset(samples, outcome != "Healthy")
patients <- patients[order(patients$patient_id, patients$visit), ]

mean_paths <- aggregate(cbind(P23, P4) ~ outcome + visit,
                        data = patients, FUN = mean)
mean_paths <- mean_paths[order(mean_paths$outcome, mean_paths$visit), ]

visit_sizes <- c("H" = 2.6, "0h" = 2.8, "6h" = 2.5, "24h" = 2.2, "48h" = 1.9,
                 "72h" = 1.6, "28d" = 1.3, "6m" = 1.0, "12m" = 0.8)

trajectory <- ggplot(samples, aes(x = P23, y = P4)) +
  geom_point(aes(fill = outcome, size = visit), shape = 21,
             colour = "grey25", stroke = 0.2, alpha = 0.8) +
  geom_path(data = mean_paths, aes(colour = outcome), linewidth = 1.3,
            arrow = arrow(length = unit(0.3, "cm"), type = "closed")) +
  scale_fill_manual(values = outcome_colours) +
  scale_colour_manual(values = line_colours, guide = "none") +
  scale_size_manual(values = visit_sizes) +
  labs(
    x = "Pattern 23 value (linked to septic shock)",
    y = "Pattern 4 value (linked to health)",
    fill = "28-day outcome", size = "Visit",
    caption = "Lines join each group's mean at each visit; arrows point to the last visit."
  ) +
  theme_classic(base_size = 12)

# Individual patient paths ----------------------------------------------------

paths <- ggplot(patients, aes(x = P23, y = P4, group = patient_id,
                              colour = outcome)) +
  geom_path(alpha = 0.4) +
  geom_point(size = 0.8) +
  facet_wrap(~ outcome) +
  scale_colour_manual(values = line_colours, guide = "none") +
  labs(x = "Pattern 23 value", y = "Pattern 4 value") +
  theme_classic(base_size = 12)

# Heatmap of the 30 pattern z-scores ------------------------------------------

pattern_order <- c(3, 17, 4, 12, 27, 25, 10, 29, 21, 19, 6, 18, 11, 2, 22,
                   20, 14, 26, 8, 13, 16, 7, 1, 23, 15, 5, 9, 30, 28, 24)
heat$pattern <- factor(heat$pattern, levels = rev(pattern_order))

zscores <- subset(heat, panel == "CoGAPS z-score")
zscores$group <- factor(zscores$group, levels = c("Healthy", "Survived", "Died"))
zscores$column <- factor(zscores$column, levels = levels(samples$visit))

pattern_heatmap <- ggplot(zscores, aes(x = column, y = pattern, fill = value)) +
  geom_tile(colour = "white", linewidth = 0.3) +
  facet_grid(. ~ group, scales = "free_x", space = "free_x") +
  scale_fill_gradientn(colours = c("#FFFFCC", "#FEB24C", "#F03B20", "#800026")) +
  labs(x = NULL, y = "Pattern", fill = "z-score") +
  theme_minimal(base_size = 11) +
  theme(panel.grid = element_blank())

# Six heatmaps side by side ---------------------------------------------------

heat_panel <- function(panel_name, high_colour, fill_label) {
  panel_data <- subset(heat, panel == panel_name)
  panel_data$column <- factor(panel_data$column,
                              levels = unique(panel_data$column))
  ggplot(panel_data, aes(x = column, y = pattern, fill = value)) +
    geom_tile(colour = "white", linewidth = 0.3) +
    scale_fill_gradient(low = "white", high = high_colour) +
    labs(title = panel_name, x = NULL, y = NULL, fill = fill_label) +
    theme_minimal(base_size = 9) +
    theme(
      panel.grid = element_blank(),
      axis.text.y = element_blank(),
      axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5),
      legend.position = "bottom"
    )
}

six_panels <- pattern_heatmap +
  labs(title = "CoGAPS z-score") +
  theme(legend.position = "bottom") +
  heat_panel("AUROC", "#08306B", "AUROC") +
  heat_panel("CIBERSORT", "#00441B", "r") +
  heat_panel("Hematology", "#00441B", "r") +
  heat_panel("Chemistry and vitals", "#7F2704", "r") +
  heat_panel("Proteins", "#67000D", "r") +
  plot_layout(widths = c(14, 5, 6, 7, 7, 12)) +
  plot_annotation(caption = source_note)
