# Rainclouds with ggrain: run with Rscript from an empty working directory.
# The plotting blocks adapt the ggrain 0.1.2 vignette.
# https://github.com/cran/ggrain/blob/0.1.2/vignettes/ggrain.Rmd
# # MIT License
# 
# Copyright (c) 2022 Nicholas Judd
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

library(ggplot2)
library(ggrain)
library(palmerpenguins)

dir.create("outputs", showWarnings = FALSE)
options(width = 80)

for (package in c("ggplot2", "ggrain", "palmerpenguins", "svglite")) {
  cat(package, as.character(packageVersion(package)), "\n")
}

penguin_mass <- as.data.frame(penguins[c("species", "body_mass_g")])
keep <- complete.cases(penguin_mass)
cat("Rows without species or body mass:", sum(!keep), "\n")
penguin_mass <- penguin_mass[keep, ]
penguin_mass$species <- droplevels(penguin_mass$species)

species_counts <- table(penguin_mass$species)
print(species_counts)
species_labels <- paste0(
  names(species_counts), "\nn = ", as.integer(species_counts)
)
names(species_labels) <- names(species_counts)
write.csv(penguin_mass, "outputs/penguin_mass.csv", row.names = FALSE)

species_colors <- c(
  Adelie = "#0072B2", Chinstrap = "#D55E00", Gentoo = "#009E73"
)

penguin_plot <- ggplot(
  penguin_mass, aes(x = species, y = body_mass_g, fill = species)
) +
  geom_rain(
    seed = 42,
    point.args = list(size = 1.2, alpha = 0.45, colour = "grey25"),
    boxplot.args = list(outlier.shape = NA, alpha = 0.85),
    violin.args = list(
      alpha = 0.55, colour = NA, trim = TRUE, scale = "area", adjust = 1
    )
  ) +
  scale_fill_manual(values = species_colors) +
  scale_x_discrete(labels = species_labels) +
  labs(
    title = "Penguin body mass by species",
    subtitle = "Each point is one penguin; clouds show estimated densities.",
    x = NULL, y = "Body mass (g)",
    caption = "Data come from palmerpenguins; missing body masses are omitted."
  ) +
  theme_classic(base_size = 12) +
  theme(
    legend.position = "none",
    plot.title.position = "plot",
    plot.caption = element_text(hjust = 0, colour = "grey35")
  )

ggsave(
  "outputs/ggrain_penguins.png", penguin_plot,
  width = 7.2, height = 4.8, units = "in", dpi = 300, bg = "white"
)

set.seed(20261116)
participant_count <- 24L
baseline <- round(rnorm(participant_count, mean = 50, sd = 8), 1)
follow_up <- round(baseline + rnorm(participant_count, mean = 4, sd = 5), 1)

paired_data <- data.frame(
  participant_id = rep(sprintf("P%02d", seq_len(participant_count)), each = 2),
  visit = factor(
    rep(c("Baseline", "Follow up"), times = participant_count),
    levels = c("Baseline", "Follow up")
  ),
  response = as.vector(rbind(baseline, follow_up))
)
print(head(paired_data))

#' Validate complete pairs for a two-visit raincloud plot.
#'
#' @param data A data frame with participant_id, visit, and response columns.
#' @return The input data, sorted by participant and visit.
#' @export
ValidatePairs <- function(data) {
  required <- c("participant_id", "visit", "response")
  if (!all(required %in% names(data)) || nrow(data) == 0L) {
    stop("Supply nonempty data with participant_id, visit, and response.")
  }
  visits <- c("Baseline", "Follow up")
  if (anyNA(data[required]) || any(trimws(data$participant_id) == "")) {
    stop("Participant IDs, visits, and responses must be present.")
  }
  if (!is.numeric(data$response) || any(!is.finite(data$response))) {
    stop("Responses must be finite numbers.")
  }
  if (!all(data$visit %in% visits)) {
    stop("Visit must be Baseline or Follow up.")
  }
  if (anyDuplicated(data[c("participant_id", "visit")]) > 0L) {
    stop("Each participant must have only one row per visit.")
  }
  data$visit <- factor(data$visit, levels = visits)
  counts <- table(data$participant_id, data$visit)
  if (any(counts != 1L)) {
    stop("Each participant must have both visits.")
  }
  data[order(data$participant_id, data$visit), ]
}

paired_data <- ValidatePairs(paired_data)
cat("Complete participants:", length(unique(paired_data$participant_id)), "\n")
cat("Observations:", nrow(paired_data), "\n")
write.csv(paired_data, "outputs/paired_measurements.csv", row.names = FALSE)

visit_counts <- table(paired_data$visit)
visit_labels <- paste0(
  names(visit_counts), "\nn = ", as.integer(visit_counts)
)
names(visit_labels) <- names(visit_counts)

paired_plot <- ggplot(
  paired_data, aes(x = visit, y = response, fill = visit)
) +
  geom_rain(
    id.long.var = "participant_id", rain.side = "f1x1", seed = 42,
    point.args = list(size = 1.8, alpha = 0.85, colour = "grey20"),
    line.args = list(alpha = 0.35, linewidth = 0.4, colour = "grey40"),
    boxplot.args = list(outlier.shape = NA, alpha = 0.85),
    violin.args = list(
      alpha = 0.55, colour = NA, trim = TRUE, scale = "area", adjust = 1
    )
  ) +
  scale_fill_manual(values = c(Baseline = "#0072B2", "Follow up" = "#D55E00")) +
  scale_x_discrete(labels = visit_labels, expand = expansion(add = 0.65)) +
  labs(
    title = "Paired assay measurements",
    subtitle = "Simulated data; each line connects the same participant.",
    x = NULL, y = "Assay response (arbitrary units)",
    caption = "Clouds summarize visits; lines show individual changes."
  ) +
  theme_classic(base_size = 12) +
  theme(
    legend.position = "none",
    plot.title.position = "plot",
    plot.caption = element_text(hjust = 0, colour = "grey35")
  )

ggsave(
  "outputs/ggrain_paired.png", paired_plot,
  width = 7.2, height = 4.8, units = "in", dpi = 300, bg = "white"
)

ggsave(
  "outputs/ggrain_penguins.svg", penguin_plot, device = svglite::svglite,
  width = 7.2, height = 4.8, units = "in", bg = "white"
)
ggsave(
  "outputs/ggrain_paired.svg", paired_plot, device = svglite::svglite,
  width = 7.2, height = 4.8, units = "in", bg = "white"
)
print(sort(list.files("outputs", pattern = "\\.(png|svg|csv)$")))
