# Maternal effects inflate heritability
# https://tidyecology.com/posts/maternal-effects-and-shared-environment/
#
# The R code of this Tidy Ecology tutorial, chunk by chunk, in the order of the post.
# Run it top to bottom in a fresh R session. Code the post shows but does not run
# is commented out. The prose, and the numbers it quotes, are in the post itself.
# Post last modified: 2026-10-07

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

te_pal <- list(forest = "#275139", green = "#2f8f63", sage = "#93a87f",
               clay = "#b5534e", gold = "#cda23f", line = "#dad9ca",
               ink = "#16241d", paper = "#f5f4ee")

theme_te <- function() {
  theme_minimal(base_size = 12) +
    theme(panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#e7e6dc"),
          plot.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          plot.title = element_text(face = "bold", colour = te_pal$ink),
          axis.title = element_text(colour = "#2c3a31"),
          legend.position = "bottom")
}

## ---- pedigree-tools ----
amat <- function(sire, dam) {
  n <- length(sire)
  A <- matrix(0, n, n)
  for (i in seq_len(n)) {
    s <- sire[i]; d <- dam[i]
    if (i > 1L) {
      j <- seq_len(i - 1L)
      v <- 0.5 * ((if (s > 0L) A[j, s] else 0) + (if (d > 0L) A[j, d] else 0))
      A[i, j] <- v; A[j, i] <- v
    }
    A[i, i] <- 1 + if (s > 0L && d > 0L) 0.5 * A[s, d] else 0
  }
  A
}

## one sire, one dam, two full sib offspring
print(amat(c(0, 0, 1, 1), c(0, 0, 2, 2)))

## ---- reml ----
reml_ll <- function(y, Ao, Zn, s) {
  n <- length(y)
  V <- s[1] * Ao + s[3] * diag(n)
  if (!is.null(Zn)) V <- V + s[2] * Zn
  ch <- chol(V)
  Viy <- backsolve(ch, backsolve(ch, y, transpose = TRUE))
  Vi1 <- backsolve(ch, backsolve(ch, rep(1, n), transpose = TRUE))
  s11 <- sum(Vi1)
  yPy <- sum(y * Viy) - sum(y * Vi1)^2 / s11
  -0.5 * (2 * sum(log(diag(ch))) + log(s11) + yPy)
}

reml_prof <- function(y, Ao, Zn, r) {
  n <- length(y)
  H <- diag(n) + r[1] * Ao
  if (!is.null(Zn)) H <- H + r[2] * Zn
  ch <- chol(H)
  Hiy <- backsolve(ch, backsolve(ch, y, transpose = TRUE))
  Hi1 <- backsolve(ch, backsolve(ch, rep(1, n), transpose = TRUE))
  s11 <- sum(Hi1)
  yPy <- sum(y * Hiy) - sum(y * Hi1)^2 / s11
  list(ll = -0.5 * ((n - 1) * log(yPy / (n - 1)) + 2 * sum(log(diag(ch))) +
                      log(s11) + (n - 1)),
       se2 = yPy / (n - 1))
}

fit_a <- function(y, Ao) {
  o <- optimize(function(lr) -reml_prof(y, Ao, NULL, c(exp(lr), 0))$ll,
                c(-10, 4), tol = 1e-4)
  ra <- exp(o$minimum); p <- reml_prof(y, Ao, NULL, c(ra, 0))
  c(sa2 = ra * p$se2, sn2 = 0, se2 = p$se2, h2 = ra / (1 + ra), ll = p$ll)
}

fit_an <- function(y, Ao, Zn, start = c(-1.2, -1.2)) {
  o <- optim(start, function(lr) -reml_prof(y, Ao, Zn, exp(pmax(pmin(lr, 4), -10)))$ll,
             method = "Nelder-Mead", control = list(reltol = 1e-6))
  r <- exp(pmax(pmin(o$par, 4), -10)); p <- reml_prof(y, Ao, Zn, r)
  tot <- (r[1] + r[2] + 1) * p$se2
  c(sa2 = r[1] * p$se2, sn2 = r[2] * p$se2, se2 = p$se2,
    h2 = r[1] * p$se2 / tot, c2 = r[2] * p$se2 / tot, ll = p$ll)
}

## the same fit on the variance ratios, bounded below at exactly zero: the clamped log
## scale of fit_an is flat below its floor, and its search can stop there, short of the
## maximum; the demonstrations on the flat ridge below keep fit_an to show where it lands
fit_anb <- function(y, Ao, Zn, start = exp(c(-1.2, -1.2))) {
  o <- optim(start, function(r) -reml_prof(y, Ao, Zn, r)$ll, method = "L-BFGS-B",
             lower = c(0, 0), upper = exp(c(4, 4)))
  r <- o$par; p <- reml_prof(y, Ao, Zn, r)
  tot <- (r[1] + r[2] + 1) * p$se2
  c(sa2 = r[1] * p$se2, sn2 = r[2] * p$se2, se2 = p$se2,
    h2 = r[1] * p$se2 / tot, c2 = r[2] * p$se2 / tot, ll = p$ll)
}

## ---- designs ----
make_design <- function(n_sire, dams_per_sire, k) {
  n_dam <- n_sire * dams_per_sire
  n_off <- n_dam * k
  n_ped <- n_sire + n_dam + n_off
  sire <- integer(n_ped); dam <- integer(n_ped)
  off <- n_sire + n_dam + seq_len(n_off)
  sire[off] <- rep(rep(seq_len(n_sire), each = dams_per_sire), each = k)
  dam[off] <- rep(n_sire + seq_len(n_dam), each = k)
  A <- amat(sire, dam)
  list(A = A, L = t(chol(A)), Ao = A[off, off], off = off, n_ped = n_ped,
       nest = rep(seq_len(n_dam), each = k), n_off = n_off, n_nest = n_dam)
}

zz_of <- function(nest) outer(nest, nest, "==") * 1

sim_y <- function(d, sa2, sn2, se2, nest = d$nest) {
  a <- as.vector(d$L %*% rnorm(d$n_ped)) * sqrt(sa2)
  a[d$off] + rnorm(max(nest), 0, sqrt(sn2))[nest] + rnorm(d$n_off, 0, sqrt(se2))
}

k_off <- 4L
sib <- make_design(25L, 1L, k_off)
hs <- make_design(5L, 5L, k_off)
Zs <- zz_of(sib$nest); Zh <- zz_of(hs$nest)
sa2_true <- 0.3; h2_true <- 0.3
print(c(offspring = sib$n_off, nests = sib$n_nest, brood_size = k_off,
        sires_sib_design = 25L, sires_halfsib_design = 5L, dams_per_sire = 5L))
print(round(c(sa2_true = sa2_true, total_variance = 1, h2_true = h2_true), 3))
cat("relatedness classes, full sib design\n")
print(table(round(sib$Ao[upper.tri(sib$Ao)], 4)))
cat("relatedness classes, half sib design\n")
print(table(round(hs$Ao[upper.tri(hs$Ao)], 4)))

## ---- bias-grid ----
set.seed(41010727)
reps <- 100L; vgrid <- c(0, 0.1, 0.2, 0.3, 0.4)
E1 <- NULL; cell0 <- NULL
for (v in vgrid) {
  se2 <- 1 - sa2_true - v
  m <- matrix(NA_real_, reps, 5)
  for (i in seq_len(reps)) {
    ys <- sim_y(sib, sa2_true, v, se2)
    yh <- sim_y(hs, sa2_true, v, se2)
    m[i, 1] <- fit_a(ys, sib$Ao)["h2"]
    m[i, 2] <- fit_a(yh, hs$Ao)["h2"]
    m[i, 3:5] <- fit_anb(yh, hs$Ao, Zh)[c("h2", "c2", "sn2")]
  }
  if (v == 0) cell0 <- m
  E1 <- rbind(E1, data.frame(nest_var = v, sibs_no_nest = mean(m[, 1]),
    hs_no_nest = mean(m[, 2]), hs_with_nest = mean(m[, 3]),
    hs_nest_share = mean(m[, 4]), sd_sibs_no_nest = sd(m[, 1]),
    sd_hs_no_nest = sd(m[, 2]), sd_hs_with_nest = sd(m[, 3])))
}
print(round(E1, 3))
print(c(replicates_per_cell = reps))
print(round(c(
  slope_sibs = unname(coef(lm(sibs_no_nest ~ nest_var, E1[1:4, ]))[2]),
  slope_halfsib = unname(coef(lm(hs_no_nest ~ nest_var, E1[1:4, ]))[2])), 3))

## ---- fig-bias ----
lab_mod <- c("full sibs, no nest term", "half sibs, no nest term",
             "half sibs, nest term")
fa <- data.frame(nest_var = rep(E1$nest_var, 3),
                 h2 = c(E1$sibs_no_nest, E1$hs_no_nest, E1$hs_with_nest),
                 model = factor(rep(lab_mod, each = nrow(E1)), levels = lab_mod))
ggplot(fa, aes(nest_var, h2, colour = model, shape = model)) +
  geom_hline(yintercept = h2_true, linetype = "dashed",
             colour = te_pal$sage, linewidth = 0.7) +
  geom_line(linewidth = 0.8) +
  geom_point(size = 2.6) +
  scale_colour_manual(values = c(te_pal$clay, te_pal$gold, te_pal$forest)) +
  scale_shape_manual(values = c(16, 17, 15)) +
  scale_y_continuous(limits = c(0, 1)) +
  labs(x = "true nest variance", y = "mean estimated heritability",
       colour = NULL, shape = NULL) + theme_te()

## ---- flat-ridge ----
set.seed(20260727)
truth_demo <- data.frame(additive = sa2_true, nest = 0.2, residual = 0.5)
print(truth_demo)
y_sib <- sim_y(sib, truth_demo$additive, truth_demo$nest, truth_demo$residual)
y_hs <- sim_y(hs, truth_demo$additive, truth_demo$nest, truth_demo$residual)

t1 <- c(0.20, 0.15, 0.60)
t2 <- c(0.50, 0.00, 0.45)
print(data.frame(triple = c("first", "second"),
                 additive = c(t1[1], t2[1]), nest = c(t1[2], t2[2]),
                 residual = c(t1[3], t2[3]),
                 ll = round(c(reml_ll(y_sib, sib$Ao, Zs, t1),
                              reml_ll(y_sib, sib$Ao, Zs, t2)), 5)))

starts <- rbind(c(-3, 0.5), c(-1.2, -1.2), c(0.5, -3))
ms_sib <- t(apply(starts, 1, function(s) fit_an(y_sib, sib$Ao, Zs, s)))
ms_hs <- t(apply(starts, 1, function(s) fit_an(y_hs, hs$Ao, Zh, s)))
cat("three starting values, full sib data\n")
print(round(ms_sib, 4))
cat("three starting values, half sib data\n")
print(round(ms_hs, 4))

## ---- surface ----
vp_sib <- sum(ms_sib[2, 1:3]); vp_hs <- sum(ms_hs[2, 1:3])

## profile the nest variance out, one additive variance at a time
prof_sa2 <- function(y, Ao, Zn, vp, a) {
  -optimize(function(nn) -reml_ll(y, Ao, Zn, c(a, nn, vp - a - nn)),
            c(1e-4, vp - a - 0.02), tol = 1e-4)$objective
}
ag <- seq(0.02, 0.84, by = 0.02)
P1 <- sapply(ag, function(a) prof_sa2(y_sib, sib$Ao, Zs, vp_sib, a))
P2 <- sapply(ag, function(a) prof_sa2(y_hs, hs$Ao, Zh, vp_hs, a))
flat <- function(p) range(ag[p > max(p) - 0.1])
print(data.frame(design = c("full sibs", "half sibs"),
                 total_variance = round(c(vp_sib, vp_hs), 3),
                 flat_from = c(flat(P1)[1], flat(P2)[1]),
                 flat_to = c(flat(P1)[2], flat(P2)[2]),
                 searched = paste(min(ag), "to", max(ag))))

## the surface itself, on the slice through the fitted total variance
gsa <- seq(0.01, 0.7, length.out = 51)
gsn <- seq(0.01, 0.5, length.out = 51)
surf <- function(y, Ao, Zn, vp) {
  z <- outer(gsa, gsn, Vectorize(function(a, nn) {
    e <- vp - a - nn
    if (e <= 0.02) return(-500)
    reml_ll(y, Ao, Zn, c(a, nn, e))
  }))
  z - max(z)
}
S1 <- surf(y_sib, sib$Ao, Zs, vp_sib); S2 <- surf(y_hs, hs$Ao, Zh, vp_hs)

## ---- fig-surface ----
gr <- expand.grid(sa2 = gsa, sn2 = gsn)
sur <- rbind(data.frame(gr, ll = as.vector(S1), design = "full sibs only"),
             data.frame(gr, ll = as.vector(S2), design = "with paternal half sibs"))
sur$ll <- pmax(sur$ll, -3)
sur$vp <- rep(c(vp_sib, vp_hs), each = nrow(gr))
no_room <- sur[sur$vp - sur$sa2 - sur$sn2 <= 0.02, ]
ggplot(sur, aes(sa2, sn2)) +
  geom_raster(aes(fill = ll)) +
  geom_contour(aes(z = ll), breaks = c(-0.1, -0.5, -1, -2),
               colour = "#f5f4ee", linewidth = 0.3) +
  geom_raster(data = no_room, fill = "#b9b7a8") +
  annotate("point", x = sa2_true, y = 0.2, colour = te_pal$paper,
           shape = 4, size = 4.2, stroke = 3) +
  annotate("point", x = sa2_true, y = 0.2, colour = te_pal$clay,
           shape = 4, size = 3.4, stroke = 1.6) +
  facet_wrap(~ design) +
  scale_fill_gradient(low = "#12291d", high = te_pal$gold,
                      name = "log likelihood from maximum") +
  labs(x = "additive variance", y = "nest variance") + theme_te() +
  theme(panel.grid.major = element_blank(),
        legend.key.width = unit(1.6, "cm"))

## ---- multi-start ----
set.seed(60060727)
n_start <- 60L
st <- cbind(runif(n_start, -4, 1), runif(n_start, -4, 1))
multi <- function(y, Ao, Zn) t(apply(st, 1, function(s) fit_an(y, Ao, Zn, s)))
Q1 <- multi(y_sib, sib$Ao, Zs)
Q2 <- multi(y_hs, hs$Ao, Zh)

print(c(starting_values = n_start))
print(data.frame(
  design = c("full sibs", "half sibs"),
  h2_min = round(c(min(Q1[, "h2"]), min(Q2[, "h2"])), 4),
  h2_max = round(c(max(Q1[, "h2"]), max(Q2[, "h2"])), 4),
  sa2_min = round(c(min(Q1[, "sa2"]), min(Q2[, "sa2"])), 4),
  sa2_max = round(c(max(Q1[, "sa2"]), max(Q2[, "sa2"])), 4),
  ll_range = round(c(diff(range(Q1[, "ll"])), diff(range(Q2[, "ll"]))), 4),
  slope = round(c(unname(coef(lm(Q1[, "sn2"] ~ Q1[, "sa2"]))[2]),
                  unname(coef(lm(Q2[, "sn2"] ~ Q2[, "sa2"]))[2])), 4)))

## ---- fig-starts ----
fc <- rbind(data.frame(sa2 = Q1[, "sa2"], sn2 = Q1[, "sn2"],
                       design = "full sibs only"),
            data.frame(sa2 = Q2[, "sa2"], sn2 = Q2[, "sn2"],
                       design = "with paternal half sibs"))
ggplot(fc, aes(sa2, sn2)) +
  geom_point(colour = te_pal$forest, size = 2.1, alpha = 0.75) +
  annotate("point", x = sa2_true, y = 0.2, colour = te_pal$clay,
           shape = 4, size = 3.4, stroke = 1.2) +
  facet_wrap(~ design) +
  labs(x = "estimated additive variance", y = "estimated nest variance") +
  theme_te()

## ---- replicate-correlation ----
set.seed(20260728)
reps2 <- 120L
R1 <- matrix(NA_real_, reps2, 3); R2 <- matrix(NA_real_, reps2, 3)
fixed_h2 <- numeric(reps2); dll <- numeric(reps2)
for (i in seq_len(reps2)) {
  ys <- sim_y(sib, sa2_true, 0.2, 0.5)
  yh <- sim_y(hs, sa2_true, 0.2, 0.5)
  a1 <- fit_an(ys, sib$Ao, Zs, runif(2, -3, 0))
  a0 <- fit_an(ys, sib$Ao, Zs)
  a2 <- fit_anb(yh, hs$Ao, Zh, exp(runif(2, -3, 0)))
  b1 <- fit_a(ys, sib$Ao)
  R1[i, ] <- a1[c("sa2", "sn2", "h2")]; R2[i, ] <- a2[c("sa2", "sn2", "h2")]
  fixed_h2[i] <- a0["h2"]; dll[i] <- a0["ll"] - b1["ll"]
}
print(c(replicates = reps2))
print(round(c(mean_h2_sibs_fixed_start = mean(fixed_h2),
              sd_h2_sibs_fixed_start = sd(fixed_h2),
              h2_implied_by_the_start = exp(-1.2) / (1 + 2 * exp(-1.2)),
              mean_h2_halfsib = mean(R2[, 3]), sd_h2_halfsib = sd(R2[, 3]),
              corr_sibs = cor(R1[, 1], R1[, 2]),
              corr_halfsib = cor(R2[, 1], R2[, 2])), 3))
print(round(c(mean_ll_gain = mean(dll), max_ll_gain = max(dll),
              frac_gain_above_001 = mean(dll > 0.001),
              frac_lrt_significant = mean(2 * dll > 2.706)), 4))

## ---- strong-nest ----
set.seed(20260729)
reps3 <- 100L
big <- data.frame(additive = sa2_true, nest = 0.45, residual = 0.25)
d2 <- numeric(reps3)
for (i in seq_len(reps3)) {
  ys <- sim_y(sib, big$additive, big$nest, big$residual)
  d2[i] <- fit_an(ys, sib$Ao, Zs)["ll"] - fit_a(ys, sib$Ao)["ll"]
}
print(c(replicates = reps3))
print(data.frame(big,
                 full_sib_correlation = 0.5 * big$additive + big$nest,
                 mean_ll_gain = round(mean(d2), 3),
                 frac_lrt_significant = mean(2 * d2 > 2.706)))

## ---- fostering ----
foster <- function(nest, f) {
  n <- length(nest); m <- round(f * n)
  if (m < 2) return(nest)
  idx <- sample.int(n, m)
  nest[idx] <- nest[sample(idx)]
  nest
}

## nothing fostered is the flat ridge, kept on fit_an; a fostered design gets the bounded
## fit from the three starting values used earlier, best kept (a tenth fostered can
## leave more than one peak)
fit_fost <- function(y, Zn) {
  fs <- apply(starts, 1, function(s) fit_anb(y, sib$Ao, Zn, exp(s)))
  fs[, which.max(fs["ll", ])]
}

set.seed(30070727)
fr <- c(0, 0.1, 0.25, 0.5, 0.75, 1); repsf <- 120L
E3 <- NULL
for (f in fr) {
  m <- matrix(NA_real_, repsf, 2)
  for (i in seq_len(repsf)) {
    nn <- foster(sib$nest, f)
    ys <- sim_y(sib, sa2_true, 0.2, 0.5, nest = nn)
    fit <- if (f == 0) fit_an(ys, sib$Ao, zz_of(nn)) else fit_fost(ys, zz_of(nn))
    m[i, ] <- fit[c("h2", "c2")]
  }
  E3 <- rbind(E3, data.frame(fostered = f, mean_h2 = mean(m[, 1]),
    sd_h2 = sd(m[, 1]), sd_nest_share = sd(m[, 2]), corr = cor(m[, 1], m[, 2])))
}
print(round(E3, 3))
print(c(replicates_per_fraction = repsf))
print(round(c(gain_realised_at_half =
  (E3$sd_h2[2] - E3$sd_h2[4]) / (E3$sd_h2[2] - E3$sd_h2[5])), 3))

## ---- fig-fostering ----
fd <- rbind(data.frame(f = E3$fostered, s = E3$sd_h2, quantity = "heritability"),
            data.frame(f = E3$fostered, s = E3$sd_nest_share,
                       quantity = "nest share of variance"))
ggplot(fd, aes(f, s, colour = quantity, shape = quantity)) +
  geom_line(data = fd[fd$f > 0, ], linewidth = 0.8) +
  geom_point(size = 2.6) +
  annotate("text", x = 0.02, y = 0.055, hjust = 0, size = 3.4,
           colour = te_pal$ink, label = "no fostering: not identified") +
  scale_colour_manual(values = c(te_pal$forest, te_pal$gold)) +
  scale_shape_manual(values = c(16, 17)) +
  scale_y_continuous(limits = c(0, 0.34)) +
  labs(x = "fraction of chicks fostered", colour = NULL, shape = NULL,
       y = "standard deviation across replicates") + theme_te()

## ---- maternal-pedigree ----
n_gsire <- 5L; dams_per_gsire <- 5L; n_msire <- 5L
n_mdam <- n_gsire * dams_per_gsire; n_moff <- n_mdam * k_off
gsire <- seq_len(n_gsire); msire <- n_gsire + seq_len(n_msire)
mdam <- n_gsire + n_msire + seq_len(n_mdam)
moff <- n_gsire + n_msire + n_mdam + seq_len(n_moff)
n_mped <- n_gsire + n_msire + n_mdam + n_moff
sire_m <- integer(n_mped); dam_m <- integer(n_mped)
sire_m[mdam] <- rep(gsire, each = dams_per_gsire)
dam_of_off <- rep(as.vector(sapply(seq_len(n_msire), function(s)
  mdam[(seq_len(n_gsire) - 1L) * dams_per_gsire + s])), each = k_off)
sire_m[moff] <- rep(msire, each = n_gsire * k_off); dam_m[moff] <- dam_of_off

Am <- amat(sire_m, dam_m); Lm <- t(chol(Am))
Amo <- Am[moff, moff]
Zm <- zz_of(rep(seq_len(n_mdam), each = k_off))
print(c(offspring = n_moff, nests = n_mdam, grandsires = n_gsire,
        sires = n_msire))
cat("relatedness classes among offspring\n")
print(table(round(Amo[upper.tri(Amo)], 4)))

## ---- maternal-fit ----
se2_m <- 0.7
Aod <- Am[moff, dam_of_off]; same_dam <- outer(dam_of_off, dam_of_off, "==") * 1
cov_pred <- function(m) sa2_true * Amo + m * sa2_true * (Aod + t(Aod)) +
  m^2 * (sa2_true * Am[dam_of_off, dam_of_off] + se2_m * same_dam)

sim_mat <- function(m) {
  a <- as.vector(Lm %*% rnorm(n_mped)) * sqrt(sa2_true)
  zd <- a[mdam] + rnorm(n_mdam, 0, sqrt(se2_m))
  a[moff] + m * zd[match(dam_of_off, mdam)] + rnorm(n_moff, 0, sqrt(se2_m))
}

cls <- round(Amo, 4); ut <- upper.tri(cls)
lv <- sort(unique(cls[ut]))
msk <- lapply(lv, function(l) which(ut & cls == l))
set.seed(40040727)
reps_cov <- 600L; repsm <- 100L
MAT <- NULL; COV <- NULL; SPLIT <- NULL
for (mm in c(0.4, -0.25)) {
  cv <- matrix(NA_real_, reps_cov, length(lv))
  for (i in seq_len(reps_cov)) {
    y <- sim_mat(mm); cp <- outer(y, y)
    for (j in seq_along(lv)) cv[i, j] <- mean(cp[msk[[j]]])
  }
  cpm <- cov_pred(mm)
  COV <- rbind(COV, data.frame(m = mm, relatedness = lv,
    additive_only = lv * sa2_true,
    with_maternal = sapply(msk, function(w) mean(cpm[w])),
    observed = colMeans(cv)))
  res <- matrix(NA_real_, repsm, 6)
  for (i in seq_len(repsm)) {
    y <- sim_mat(mm)
    res[i, ] <- c(fit_anb(y, Amo, Zm)[c("sa2", "sn2", "h2", "c2")],
                  fit_a(y, Amo)["h2"], mean(y^2))
  }
  pin <- res[, 2] < 0.001
  SPLIT <- rbind(SPLIT, data.frame(m = mm, nest_at_zero = c(TRUE, FALSE),
    replicates = c(sum(pin), sum(!pin)),
    h2_with_nest = c(mean(res[pin, 3]), mean(res[!pin, 3])),
    h2_no_nest = c(mean(res[pin, 5]), mean(res[!pin, 5]))))
  vp <- sa2_true + mm^2 * (sa2_true + se2_m) + mm * sa2_true + se2_m
  MAT <- rbind(MAT, data.frame(m = mm, phenotypic_var = vp,
    mean_square = mean(res[, 6]), true_h2 = sa2_true / vp,
    sa2_hat = mean(res[, 1]), sn2_hat = mean(res[, 2]),
    h2_with_nest = mean(res[, 3]), h2_no_nest = mean(res[, 5]),
    frac_nest_at_zero = mean(res[, 2] < 0.001)))
}
print(round(COV, 4))
print(round(MAT, 3))
print(data.frame(SPLIT[1:3], round(SPLIT[4:5], 3)))
print(c(replicates_for_covariances = reps_cov, replicates_for_fits = repsm))

## ---- insurance ----
print(round(c(mean_no_nest = mean(cell0[, 2]), mean_with_nest = mean(cell0[, 3]),
              sd_no_nest = sd(cell0[, 2]), sd_with_nest = sd(cell0[, 3]),
              rmse_no_nest = sqrt(mean((cell0[, 2] - h2_true)^2)),
              rmse_with_nest = sqrt(mean((cell0[, 3] - h2_true)^2)),
              frac_nest_at_zero = mean(cell0[, 5] < 0.001)), 3))
