Process landscape snapshots to get item and agent abundance

library(data.table)
library(glue)
library(ggplot2)
library(stringr)

# load local functions
devtools::load_all()

Get agent abundances

Prepare paths.

# read paths
paths <- list.dirs("data/", recursive = F)
paths <- paths[grep("rep_", paths)]

# select gens
gens_for_figure <- stringr::str_pad(
  unique(
    c(
      seq(1, 10),
      seq(10, 50, 10),
      seq(50, 950, by = 50)
    )
  ), 
  width = 5, pad = "0"
)

# make df
data = CJ(
  path = paths,
  gen = gens_for_figure
)

# get replicate
data[, rep := as.numeric(
  stringr::str_extract_all(path, "rep_(\\d{3})") |> 
    stringr::str_extract_all("\\d{3}")
)]

# get sim type
data[, sim_type := stringr::str_extract(
  path, "obligate|facultative|foragers|random"
 ) 
]

data[, regrowth := as.numeric(str_extract(path, "(0\\.\\d+)"))]

# get paths
data$image <- glue_data(data, "{path}/{gen}.png")

Process agent counts for all scenarios

From the exported image data, count the number of individuals in each landscape cell. This uses the function read_landscape, which is defined in R/fun_read_land.R.

# get data for scenarios 1 and 3
agent_data <- lapply(
  X = data$image,

  # apply this function over the landscape simulation data
  FUN = read_landscape,

  # arguments to the function
  layer = c(1, 2, 3), # read all individuals
  crop_dim = 60,
  type = "items"
)

Remove unoccupied cells

# remove where agents are 0
agent_data <- lapply(
  agent_data, function(df) {
    df <- df[items > 0, ]
    setnames(df, "items", "agents")
    # df[, agents := round(agents / 0.02)]
  }
)

Process productivity layer

# load the productivity layer
quality_data <- read_landscape(
  "data/data_parameters/kernels32.png",
  layer = 1, crop_dim = 60, type = "items"
)

setnames(quality_data, old = "items", new = "quality")

# combine agent presence data with the productivity layer data
agent_data <- lapply(agent_data, function(df) {
  merge(
    df, quality_data, 
    by = intersect(names(df), names(quality_data)), 
    all = F
  )
})

Prepare data for export

# unlist and merge with simulation parameters
data$layer_data <- agent_data

# remove cols
data = data[, !c("path", "image")]

# unlist
data <- data[, unlist(layer_data, recursive = F),
  by = c("sim_type", "gen", "rep", "regrowth")
]

# assign strategy -- keep this step tho not necessary any more
data$strategy =  "consumers"

# select data
data[, gen := as.numeric(gen)]
data <- data[, list(sim_type, gen, rep, regrowth, 
                    x, y, agents, quality, strategy)]

# save data
fwrite(data, file = "data/results/data_input_matching.csv")


pratikunterwegs/kleptomove-ms documentation built on March 17, 2023, 1:39 a.m.