## -----------------------------------------------------------------------------
#| label: Setup
#| eval: false
#| include: false

# library(logolink)
# 
# library(cli)
# library(dplyr)
# library(ggplot2)
# library(ggimage)
# library(ggtext)
# library(here)
# library(magick)
# library(magrittr)
# library(ragg)
# library(stringr)
# library(tidyr)
# 
# source(here("R", ".setup.R"))


## -----------------------------------------------------------------------------
library(logolink)


## -----------------------------------------------------------------------------
model_path <-
  find_netlogo_home() |>
  file.path(
    "models",
    "IABM Textbook",
    "chapter 6",
    "Spread of Disease.nlogox"
  )


## -----------------------------------------------------------------------------
setup_file <- create_experiment(
  name = "Population Density (Runtime)",
  repetitions = 10,
  sequential_run_order = TRUE,
  run_metrics_every_step = TRUE,
  time_limit = 1000,
  setup = 'setup',
  go = 'go',
  metrics = 'count turtles with [infected?]',
  constants = list(
    "variant" = "mobile",
    "num-people" = list(
      first = 50,
      step = 50,
      last = 200
    ),
    "connections-per-node" = 4.1,
    "num-infected" = 1,
    "disease-decay" = 0
  )
)


## -----------------------------------------------------------------------------
setup_file |> inspect_experiment()
#> <experiments>
#>   <experiment name="Population Density (Runtime)" repetitions="10"
#>   sequentialRunOrder="true" runMetricsEveryStep="true" timeLimit="1000">
#>     <setup>setup</setup>
#>     <go>go</go>
#>     <metrics>
#>       <metric>count turtles with [infected?]</metric>
#>     </metrics>
#>     <constants>
#>       <enumeratedValueSet variable="variant">
#>         <value value="&quot;mobile&quot;"></value>
#>       </enumeratedValueSet>
#>       <steppedValueSet variable="num-people" first="50" step="50" last="200">
#>       </steppedValueSet>
#>       <enumeratedValueSet variable="connections-per-node">
#>         <value value="4.1"></value>
#>       </enumeratedValueSet>
#>       <enumeratedValueSet variable="num-infected">
#>         <value value="1"></value>
#>       </enumeratedValueSet>
#>       <enumeratedValueSet variable="disease-decay">
#>         <value value="0"></value>
#>       </enumeratedValueSet>
#>     </constants>
#>   </experiment>
#> </experiments>


## -----------------------------------------------------------------------------
#| output: false

results <-
  model_path |>
  run_experiment(
    setup_file = setup_file
  )
#> ✔ Running model [4.2s]
#> ✔ Gathering metadata [21ms]
#> ✔ Processing table output [7ms]


## -----------------------------------------------------------------------------
library(dplyr)

results |> glimpse()
#> List of 2
#>  $ metadata:List of 6
#>   ..$ timestamp       : POSIXct[1:1], format: "2026-01-08 03:51:43"
#>   ..$ netlogo_version : chr "7.0.3"
#>   ..$ output_version  : chr "2.0"
#>   ..$ model_file      : chr "Spread of Disease.nlogox"
#>   ..$ experiment_name : chr "Population Density (Runtime)"
#>   ..$ world_dimensions: Named int [1:4] -20 20 -20 20
#>   .. ..- attr(*, "names")= chr [1:4] "min-pxcor" "max-pxcor" ...
#>  $ table   : tibble [8,006 × 8] (S3: tbl_df/tbl/data.frame)
#>   ..$ run_number                 : num [1:8006] 1 1 1 1 1 1 1 1 1 1 ...
#>   ..$ variant                    : chr [1:8006] "mobile" "mobile" ...
#>   ..$ num_people                 : num [1:8006] 50 50 50 50 50 50 ...
#>   ..$ connections_per_node       : num [1:8006] 4.1 4.1 4.1 4.1 ...
#>   ..$ num_infected               : num [1:8006] 1 1 1 1 1 1 1 1 1 1 ...
#>   ..$ disease_decay              : num [1:8006] 0 0 0 0 0 0 0 0 0 0 ...
#>   ..$ step                       : num [1:8006] 0 1 2 3 4 5 6 7 8 9 ...
#>   ..$ count_turtles_with_infected: num [1:8006] 1 1 1 1 1 2 2 2 ...


## -----------------------------------------------------------------------------
#| eval: false

# library(dplyr)
# library(magrittr)
# 
# data <-
#   results |>
#   extract2("table") |>
#   rename(infected = count_turtles_with_infected) |>
#   mutate(
#     variant = as.factor(variant),
#     frac_infected = infected / num_people
#   ) |>
#   summarize(
#     mean = mean(frac_infected, na.rm = TRUE),
#     sd = sd(frac_infected, na.rm = TRUE),
#     .by = c(num_people, step)
#   ) |>
#   arrange(num_people, step)


## -----------------------------------------------------------------------------
data |> glimpse()


## -----------------------------------------------------------------------------
library(ggplot2)

data |>
  filter(step %% 10 == 0) |>
  mutate(se = sd / sqrt(10)) |>
  ggplot(aes(
    x = step,
    y = mean,
    color = as.factor(num_people)
  )) +
  geom_point(
    aes(shape = as.factor(num_people)),
    size = 1,
    alpha = 0.75
  ) +
  geom_errorbar(
    aes(
      ymin = mean + se,
      ymax = mean - se
    ),
    width = 5
  ) +
  geom_line() +
  scale_x_continuous(
    breaks = seq(0, max(data$step), 100)
  ) +
  labs(
    title = "Infected Over Time",
    x = "Steps",
    y = "Fraction of Infected",
    color = "People",
    shape = "People"
  )


## -----------------------------------------------------------------------------
#| eval: false
#| include: false

# ggsave(
#   filename = "vignette-spread-of-disease-model-plot-1.png",
#   plot = get_last_plot(),
#   device = agg_png,
#   path = here("man", "figures"),
#   width = 7,
#   height = 5,
#   units = "in",
#   dpi = 96
# )


## -----------------------------------------------------------------------------
#| eval: false
#| include: false

# person_shape <- get_netlogo_shape("person")


## -----------------------------------------------------------------------------
#| eval: false
#| include: false

# setup_file <- create_experiment(
#   name = "Wolf Sheep Simple Model Analysis",
#   repetitions = 1,
#   sequential_run_order = TRUE,
#   run_metrics_every_step = FALSE,
#   setup = c('random-seed 2026', 'setup'),
#   go = 'go',
#   time_limit = 300,
#   run_metrics_condition = 'ticks mod 50 = 0',
#   metrics = c(
#     '[xcor] of turtles',
#     '[ycor] of turtles',
#     '[color] of turtles',
#     '[infected?] of turtles',
#     '[pxcor] of patches',
#     '[pycor] of patches'
#   ),
#   constants = list(
#     "variant" = "mobile",
#     "num-people" = 50,
#     "connections-per-node" = 4.1,
#     "num-infected" = 1,
#     "disease-decay" = 0
#   )
# )


## -----------------------------------------------------------------------------
#| eval: false
#| include: false

# results <-
#   model_path |>
#   run_experiment(
#     setup_file = setup_file,
#     output = c("table", "lists")
#   )


## -----------------------------------------------------------------------------
#| eval: false
#| include: false

# plot_data <-
#   results |>
#   extract2("lists") |>
#   mutate(
#     pcolor_of_patches = parse_netlogo_color(0)
#   )


## -----------------------------------------------------------------------------
#| eval: false
#| include: false

# plot_data |> glimpse()


## -----------------------------------------------------------------------------
#| eval: false
#| include: false

# plot_netlogo_world <- function(
#   data,
#   run_number = 1,
#   step = 0,
#   step_label = TRUE
# ) {
#   showtext_auto(FALSE)
# 
#   data <-
#     data |>
#     filter(
#       run_number == .env$run_number,
#       step == .env$step
#     )
# 
#   person_size <- 0.03
# 
#   plot <-
#     data |>
#     ggplot(
#       aes(
#         x = pxcor_of_patches,
#         y = pycor_of_patches,
#         fill = pcolor_of_patches
#       )
#     ) +
#     geom_raster() +
#     coord_fixed(expand = FALSE) +
#     geom_image(
#       data = data |>
#         drop_na(xcor_of_turtles) |>
#         filter(infected_of_turtles == FALSE),
#       mapping = aes(
#         x = xcor_of_turtles,
#         y = ycor_of_turtles,
#         image = person_shape
#       ),
#       size = person_size,
#       color = parse_netlogo_color(5)
#     ) +
#     geom_image(
#       data = data |>
#         drop_na(xcor_of_turtles) |>
#         filter(infected_of_turtles == TRUE),
#       mapping = aes(
#         x = xcor_of_turtles,
#         y = ycor_of_turtles,
#         image = person_shape
#       ),
#       size = person_size,
#       color = parse_netlogo_color(15)
#     ) +
#     scale_fill_identity(na.value = parse_netlogo_color(0)) +
#     theme_void() +
#     theme(legend.position = "none")
# 
#   if (isTRUE(step_label)) {
#     plot +
#       labs(title = paste0("Step: **", step, "**")) +
#       theme(
#         plot.title.position = "plot",
#         plot.title = element_markdown(size = 20, margin = margin(b = 10)),
#         plot.background = element_rect(fill = "white", color = NA),
#         plot.margin = margin(1.5, 1.5, 1.5, 1.5, "line")
#       )
#   } else {
#     plot
#   }
# }


## -----------------------------------------------------------------------------
#| eval: false
#| include: false

# plot_netlogo_world(plot_data)


## -----------------------------------------------------------------------------
#| eval: false
#| include: false

# ggsave(
#   filename = "vignette-spread-of-disease-model-plot-2.png",
#   plot = get_last_plot(),
#   device = agg_png,
#   path = here("man", "figures"),
#   width = 7,
#   height = 7.4,
#   units = "in",
#   dpi = 96
# )


## -----------------------------------------------------------------------------
#| eval: false
#| include: false

# steps <-
#   plot_data |>
#   pull(step) |>
#   unique()


## -----------------------------------------------------------------------------
#| eval: false
#| include: false

# steps


## -----------------------------------------------------------------------------
#| eval: false
#| include: false

# files <- character()
# 
# cli_progress_bar("Generating frames", total = length(steps))
# 
# for (i in steps) {
#   i_plot <- plot_netlogo_world(plot_data, step = i, step_label = TRUE)
# 
#   i_file <- tempfile(pattern = paste0("step-", i, "-"), fileext = ".png")
# 
#   ggsave(
#     filename = i_file,
#     plot = i_plot,
#     device = agg_png,
#     width = 7,
#     height = 7.4,
#     units = "in",
#     dpi = 96
#   )
# 
#   files <- append(files, i_file)
#   cli_progress_update()
# }
# 
# cli_progress_done()


## -----------------------------------------------------------------------------
#| eval: false
#| include: false

# animation <-
#   files |>
#   lapply(image_read) |>
#   image_join() |>
#   image_animate(fps = 1)


## -----------------------------------------------------------------------------
#| eval: false
#| include: false

# animation |>
#   image_write(
#     here(
#       "man",
#       "figures",
#       "vignette-spread-of-disease-animation-1.gif"
#     )
#   )

