## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(
  echo = TRUE,
  message = FALSE,
  warning = FALSE,
  fig.width = 8,
  fig.height = 5,
  out.width = "100%"
)

library(cdmetapopR)
library(tidyverse)

## ----example-paths------------------------------------------------------------
ex_dir <- system.file("extdata", "Example_dat", package = "cdmetapopR")

pop_file <- file.path(ex_dir, "run0batch0mc0species0", "summary_popAllTime.csv")
class_file <- file.path(ex_dir, "run0batch0mc0species0", "summary_classAllTime.csv")
ind_file <- file.path(ex_dir, "run0batch0mc0species0", "ind9.csv")

ex_dir
list.files(ex_dir)

## ----filter-examples----------------------------------------------------------
one_mc <- summary_dataframe(ex_dir, type = "ind", years = 9, mc = 0)
both_mcs <- summary_dataframe(ex_dir, type = "ind", years = 9, mc = "all")
all_batches_mcs <- summary_dataframe(ex_dir, type = "pop", batch = "all", mc = "all")

c(
  one_mc_rows = nrow(one_mc),
  both_mcs_rows = nrow(both_mcs),
  all_batches_mcs_rows = nrow(all_batches_mcs)
)

## ----create-cdmat-------------------------------------------------------------
coords <- data.frame(
  x = c(0, 1, 3, 6),
  y = c(0, 2, 2, 5)
)

create_cdmat(coords, method = "euclidean")
create_cdmat(coords, method = "equal")

## ----cdmetapop-to-gene--------------------------------------------------------
old_wd <- getwd()
setwd(tempdir())

cdmetapop_to_gene(ind_file, format = "genepop")
list.files(pattern = "^my_genepop")

setwd(old_wd)

## ----summary-dataframe-pop----------------------------------------------------
pop_df <- summary_dataframe(ex_dir, type = "pop", batch = 0, mc = 0)
head(pop_df[, c("Year", ".batch", ".mc", "PatchID", "GrowthRate", "K", "N_Initial")])

## ----summary-dataframe-pop-total-plot-----------------------------------------
pop_totals <- pop_df %>%
  filter(PatchID == 1)

ggplot(pop_totals, aes(x = Year, y = N_Initial)) +
  geom_line(linewidth = 0.8, color = "steelblue") +
  labs(
    title = "Initial Population Size from summary_dataframe()",
    x = "Year",
    y = "N initial"
  ) +
  theme_minimal()

## ----summary-dataframe-pop-patch-plot-----------------------------------------
patch_subset <- pop_df %>%
  filter(PatchID %in% 2:9)

ggplot(patch_subset, aes(x = Year, y = K, color = factor(PatchID))) +
  geom_line(linewidth = 0.7) +
  labs(
    title = "Patch Carrying Capacity for Selected Patches",
    x = "Year",
    y = "K",
    color = "PatchID"
  ) +
  theme_minimal()

## ----summary-dataframe-pop-multi-mc-------------------------------------------
pop_mc <- summary_dataframe(ex_dir, type = "pop", batch = 0, mc = "all") %>%
  filter(PatchID == 1)

ggplot(pop_mc, aes(x = Year, y = Births, color = factor(.mc), group = .mc)) +
  geom_line(linewidth = 0.8) +
  labs(
    title = "Births by Monte Carlo Replicate",
    x = "Year",
    y = "Births",
    color = "MC"
  ) +
  theme_minimal()

## ----summary-dataframe-pop-wide-----------------------------------------------
pop_wide_df <- summary_dataframe(ex_dir, type = "pop", batch = 0, mc = 0, summary_format = "wide")
head(pop_wide_df[, c("Year", "GrowthRate", "N_Initial")])

## ----summary-dataframe-class--------------------------------------------------
class_df <- summary_dataframe(ex_dir, type = "class", batch = 0, mc = 0)
head(class_df[, c("Year", ".batch", ".mc", "ClassID", "Ages", "N_Initial_Age")])

## ----summary-dataframe-class-age-plot-----------------------------------------
class_selected_years <- class_df %>%
  filter(Year %in% c(0, 5, 9))

ggplot(class_selected_years, aes(x = Ages, y = N_Initial_Age, fill = factor(Year))) +
  geom_col(position = "dodge") +
  labs(
    title = "Age Structure Across Selected Years",
    x = "Age",
    y = "Individuals",
    fill = "Year"
  ) +
  theme_minimal()

## ----summary-dataframe-disease------------------------------------------------
disease_df <- summary_dataframe(
  ex_dir,
  type = "disease",
  state_names = c("Susceptible", "Infected", "Recovered")
)
head(disease_df)

## ----summary-dataframe-disease-plot-------------------------------------------
disease_mc <- summary_dataframe(
  ex_dir,
  type = "disease",
  state_names = c("Susceptible", "Infected", "Recovered"),
  mc = "all"
)

ggplot(disease_mc, aes(x = Year, y = Count, color = factor(.mc), group = .mc)) +
  geom_line(linewidth = 0.8) +
  facet_wrap(~ State, scales = "free_y") +
  labs(
    title = "Disease State Counts by Monte Carlo Replicate",
    x = "Year",
    y = "Count",
    color = "MC"
  ) +
  theme_minimal()

## ----summary-dataframe-ind----------------------------------------------------
ind_df <- summary_dataframe(ex_dir, type = "ind", years = 9, patches = c(1, 3))
head(ind_df)

## ----summary-dataframe-ind-custom-age-----------------------------------------
ind_year9 <- summary_dataframe(ex_dir, type = "ind", years = 9, mc = "all")

ggplot(ind_year9, aes(x = age, fill = factor(.mc))) +
  geom_histogram(binwidth = 1, position = "identity", alpha = 0.45) +
  labs(
    title = "Individual Age Distribution by Monte Carlo Replicate",
    x = "Age",
    y = "Individuals",
    fill = "MC"
  ) +
  theme_minimal()

## ----summary-dataframe-ind-custom-patch-boxplot-------------------------------
top_patches <- ind_year9 %>%
  count(PatchID, sort = TRUE) %>%
  slice_head(n = 8) %>%
  pull(PatchID)

ind_top_patches <- ind_year9 %>%
  filter(PatchID %in% top_patches)

ggplot(ind_top_patches, aes(x = factor(PatchID), y = size, fill = factor(.mc))) +
  geom_boxplot(outlier.alpha = 0.3) +
  labs(
    title = "Individual Size in the Most Populated Patches",
    x = "Patch",
    y = "Size",
    fill = "MC"
  ) +
  theme_minimal()


## ----summary-dataframe-ind-custom-spatial-------------------------------------
patch_counts <- ind_year9 %>%
  group_by(.mc, PatchID, XCOORD, YCOORD) %>%
  summarise(n = n(), .groups = "drop")

ggplot(patch_counts, aes(x = XCOORD, y = YCOORD, size = n, color = factor(.mc))) +
  geom_point(alpha = 0.7) +
  coord_equal() +
  labs(
    title = "Patch Abundance",
    x = "X coordinate",
    y = "Y coordinate",
    size = "Individuals",
    color = "MC"
  ) +
  theme_minimal()

## ----summary-pop-n-initial----------------------------------------------------
summary_pop(ex_dir, type = "N_initial")

## ----summary-pop-n-initial-all-mc---------------------------------------------
summary_pop(ex_dir, type = "N_initial", mc = "all")

## ----summary-pop-n-initial-ci-only--------------------------------------------
summary_pop(ex_dir, type = "N_initial", mc = "all", show_mc = FALSE)

## ----summary-pop-sex----------------------------------------------------------
summary_pop(ex_dir, type = "sex")

## ----summary-pop-sex-yys------------------------------------------------------
summary_pop(ex_dir, type = "sex", include_yys = TRUE)

## ----summary-pop-sex-all-batches----------------------------------------------
summary_pop(
  ex_dir,
  type = "sex",
  batch = "all",
  mc = "all",
  include_yys = TRUE,
  show_mc = FALSE
)

## ----summary-pop-mature-------------------------------------------------------
summary_pop(ex_dir, type = "mature")

## ----summary-pop-mature-yys---------------------------------------------------
summary_pop(ex_dir, type = "mature", include_yys = TRUE)

## ----summary-pop-births-------------------------------------------------------
summary_pop(ex_dir, type = "births")

## ----summary-pop-births-all-mc------------------------------------------------
summary_pop(ex_dir, type = "births", mc = "all")

## ----summary-pop-myy-ratio----------------------------------------------------
summary_pop(ex_dir, type = "myy_ratio")

## ----summary-pop-patch--------------------------------------------------------
summary_pop(ex_dir, type = "patch", years = c(0, 5, 9))

## ----summary-pop-allelic-richness---------------------------------------------
summary_pop(ex_dir, type = "allelic_richness", mc = "all")

## ----summary-pop-het----------------------------------------------------------
summary_pop(ex_dir, type = "het", mc = "all")

## ----summary-class-age-class--------------------------------------------------
summary_class(ex_dir, type = "age_class", n = 10)

## ----summary-class-age-class-n5-----------------------------------------------
summary_class(ex_dir, type = "age_class", n = 5)

## ----summary-class-age-plus-one-----------------------------------------------
summary_class(ex_dir, type = "age_plus_one")

## ----summary-class-age-plus-one-all-mc----------------------------------------
summary_class(ex_dir, type = "age_plus_one", mc = "all")

## ----summarize-states-default-------------------------------------------------
summary_disease(ex_dir)

## ----summarize-states-custom--------------------------------------------------
summary_disease(
  ex_dir,
  state_names = c("State 1", "State 2", "State 3"),
  scenario_names = c("Batch 0", "Batch 1")
)

## ----summarize-states-cumulative----------------------------------------------
summary_disease(
  ex_dir,
  state_names = c("State 1", "State 2", "State 3"),
  scenario_names = c("Batch 0", "Batch 1"),
  cumulative_states = "State 3"
)

## ----summary-ind-age----------------------------------------------------------
summary_ind(ex_dir, type = "age", year = 9, batch = 0, mc = 0)

## ----summary-ind-age-all-mc---------------------------------------------------
summary_ind(ex_dir, type = "age", year = 9, batch = 0, mc = "all")

## ----summary-ind-size---------------------------------------------------------
summary_ind(ex_dir, type = "size", year = 9, batch = 0, mc = 0)

## ----summary-ind-age-size-----------------------------------------------------
summary_ind(ex_dir, type = "age_size", year = 9, batch = 0, mc = 0)

## ----summary-ind-age-size-patches---------------------------------------------
summary_ind(ex_dir, type = "age_size", year = 9, batch = 0, mc = 0, patches = c(1, 3, 4, 5))

## ----summary-ind-hindex-------------------------------------------------------
summary_ind(ex_dir, type = "hindex", year = 9, batch = 0, mc = 0)

## ----summary-ind-cdist--------------------------------------------------------
summary_ind(ex_dir, type = "cdist", year = 9, batch = 0, mc = 0)

## ----summary-ind-movement-----------------------------------------------------
summary_ind(ex_dir, type = "movement", years = 0:9, batch = 0, mc = 0)

## ----summary-ind-movement-all-mc----------------------------------------------
summary_ind(ex_dir, type = "movement", years = 0:9, batch = 0, mc = "all")

## ----summary-ind-sample-example, eval=FALSE-----------------------------------
# summary_ind(ex_dir, type = "age", year = 9, file_type = "ind_Sample")

## ----allele-frequencies-by-patch----------------------------------------------
allele_frequencies_ind(ex_dir, year = 9, batch = 0, mc = 0)

## ----allele-frequencies-locus-------------------------------------------------
allele_frequencies_ind(ex_dir, year = 9, batch = 0, mc = 0, loci = "L0")

## ----allele-frequencies-patches-----------------------------------------------
allele_frequencies_ind(
  ex_dir,
  year = 9,
  batch = 0,
  mc = 0,
  loci = "L0",
  patches = c(1, 3, 4, 5, 7, 9)#, 
  #jitter = FALSE
)

## ----heterozygosity-by-patch--------------------------------------------------
heterozygosity_ind(ex_dir, year = 9, batch = 0, mc = 0)

## ----heterozygosity-locus-patches---------------------------------------------
heterozygosity_ind(
  ex_dir,
  year = 9,
  batch = 0,
  mc = 0,
  loci = "L0",
  patches = c(1, 3, 4, 5, 7, 9)
)

## ----pairwise-fst-------------------------------------------------------------
pairwise_fst_ind(ex_dir, year = 9, batch = 0, mc = 0)

## ----pairwise-fst-locus-------------------------------------------------------
pairwise_fst_ind(ex_dir, year = 9, batch = 0, mc = 0, loci = "L0")

## ----summary-patch-map-all----------------------------------------------------
summary_patch_map(
  ex_dir,
  years = c(0, 5, 9),
  batch = 0,
  mc = 0,
  crs = 5070
)

## ----summary-patch-map-log----------------------------------------------------
summary_patch_map(
  ex_dir,
  years = c(0, 5, 9),
  batch = 0,
  mc = 0,
  log_scale = TRUE,
  crs = 5070
)

## ----summary-patch-map-state--------------------------------------------------
summary_patch_map(
  ex_dir,
  years = c(0, 5, 9),
  batch = 0,
  mc = 0,
  states = 1,
  crs = 5070
)

## ----summary-patch-map-state-facet, fig.height=7------------------------------
summary_patch_map(
  ex_dir,
  years = c(0, 9),
  batch = 0,
  mc = 0,
  states = c(0, 1),
  facet_by_state = TRUE,
  crs = 5070
)

## ----summary-patch-map-allele-frequency---------------------------------------
summary_patch_map(
  ex_dir,
  type = "allele_frequency",
  years = 9,
  batch = 0,
  mc = 0,
  locus = "L0",
  allele = "A1",
  crs = 5070
)

## ----summary-patch-map-heterozygosity-----------------------------------------
summary_patch_map(
  ex_dir,
  type = "heterozygosity",
  years = 9,
  batch = 0,
  mc = 0,
  locus = "L0",
  metric = "Ho",
  crs = 5070
)

## ----age-structure-proportions------------------------------------------------
age_structure_proportions(
  path = paste0(ex_dir, "/"),
  runs = 1,
  gen = 9,
  species = 0
)

## ----launch-cdmetapop, eval=FALSE---------------------------------------------
# launch_cdmetapop(
#   pythonFilepath = "C:/path/to/python.exe",
#   CDMetaPOPFilepath = "C:/path/to/CDMetaPOP.py",
#   runvarsDirectory = "C:/path/to/example_files/",
#   runvarsFilename = "RunVars.csv",
#   outputDirectory = "test_output"
# )

## ----write-template-functions, eval=FALSE-------------------------------------
# write_runvars(output_file = "my_new_runvars.csv")
# write_popvars(output_file = "my_new_popvars.csv")
# write_patchvars(output_file = "my_new_patchvars.csv")
# write_classvars(output_file = "my_new_classvars.csv")

