library(targets)
library(ggplot2)
library(tidyverse)
library(tidybayes)
# source("posts/2022-11-29-selection-on-plasticity/functions.R")
## functions for measuring selection on plasticity
<- function(pop_average_dponte = 138,
simulate_many_moms mom_quality_max = 4,
quality_on_dponte = 2,
quality_on_csize = .2,
n_females = 42,
lifespan = 5,
temp_range = c(2, 12)) {
<- runif(lifespan, temp_range[1], max = temp_range[2])
general_temp
<- general_temp - mean(general_temp)
general_temp_c
<- runif(n_females, min = 0, max = 4)
mom_qualities
<- expand_grid(year = 1:lifespan,
many_moms_temperature idF1 = 1:n_females) |>
mutate(mom_quality = mom_qualities[idF1],
general_temp = general_temp[year],
general_temp_c = general_temp_c[year],
## adding the biology
## Effect of temperature -- does it depend on quality? let's say that it DOES (for now)
effet_temp_dponte_qual = -.7*mom_quality,
effet_temp_csize_qual = .1*log(mom_quality),
# csize
mom_avg_csize = log(pop_average_csize) + quality_on_csize*log(mom_quality),
temp_avg_csize = exp(mom_avg_csize + effet_temp_csize_qual*general_temp_c),
# dponte
mom_avg_dponte = pop_average_dponte + quality_on_dponte*mom_quality,
temp_avg_dponte = mom_avg_dponte + effet_temp_dponte_qual*general_temp_c,
## observations
obs_csize = rpois(n = length(year), lambda = temp_avg_csize),
obs_dponte = rnorm(n = length(year), mean = temp_avg_dponte, sd = 3) |> round()
)return(many_moms_temperature)
}
Model for measuring selection directly:
<- .7
true_corr_plasticity_avg <- .9
sd_avg <- .3
sd_plasticity <- 47
n_females
<- matrix(c(1, true_corr_plasticity_avg, true_corr_plasticity_avg, 1),
corrmat byrow = TRUE, ncol = 2)
<- diag(c(sd_avg, sd_plasticity)) %*% corrmat %*% diag(c(sd_avg, sd_plasticity))
var_covar
<- MASS::mvrnorm(
female_avg_and_plasticity n = n_females,
mu = c(0,0),
Sigma = var_covar)
We have the average and the slope for each female.
For a bit of extra realism, lets simulate several years and let the females belong to different cohorts. for simplicity, lets say each female lives for
<- runif(20, min = -3, max = 3)
twenty_years_environment
<- sample(1:16, size = n_females, replace = TRUE)
female_start_years library(tidyverse)
<- tibble(
df female_id = rep(1:n_females, each = 4),
year_id = rep(female_start_years, each = 4) + 0:3,
env = twenty_years_environment[year_id]
)
$env |> mean() df