# Install required packages
install.packages("devtools")
install.packages("circacompare")
install.packages("ggplot2")
install.packages("svglite")

# Install the development version of circacompare
devtools::install_github("RWParsons/circacompare")

# Load libraries
library(circacompare)
library(ggplot2)

##Import the dataset. The input file must be a CSV file with three columns: Time (circadian time points), Group (experimental conditions), and Outcome (measured variable).
# Import data (replace "XXX.csv" with your file name)
data <- read.csv("XXX.csv", sep = ";")

# Verify that the data loaded correctly
View(data)

##Run the circacompare analysis. This function performs statistical comparison between two rhythmic groups by testing for rhythmicity and fitting a nonlinear model with a 24-hour period.
fit <- circacompare(
  data,
  col_time = "Time",
  col_group = "Group",
  col_outcome = "Outcome",
  period = 24,
  alpha_threshold = 1,
  timeout_n = 100000,
  control = list(),
  weights = NULL,
  suppress_all = FALSE
)

##Export the statistical results table containing mesor, amplitude, and phase estimates for each group.
# Save summary results (replace "YYY.csv" with desired output name)
write.csv(fit$summary, "YYY.csv", row.names = FALSE)

##Adjust the plot axes to match the scale of the measured outcome variable.
# Customize plot axes (modify limits as appropriate for your data)
fit$plot <- fit$plot +
  ylim(-2, 2) +
  scale_x_continuous(
    limits = c(0, 24),
    breaks = seq(0, 24, by = 4)
  )

##Save the resulting plot as a high-resolution SVG file suitable for publication.
# Save plot (replace "ZZZ.svg" with desired file name)
ggsave(
  filename = "ZZZ.svg",
  plot = fit$plot,
  device = "svg",
  width = 7,
  height = 5,
  units = "in"
)