Files
ffdaten_simulation_R/fotofallen_power_simulation_schalenwild_grid.R
2026-08-18 22:48:02 +00:00

1364 lines
42 KiB
R

# ============================================================================
# Fotofallen-Poweranalyse fuer Reh-, Rot- und Gamswild
# ----------------------------------------------------------------------------
# Ziel:
# Ermitteln, mit welcher Anzahl und raeumlichen Verteilung von Kameras eine
# zeitliche Abnahme der Nutzung einer Fokusflaeche gegenueber einem Buffer
# verlaesslich erkannt werden kann.
#
# Methodische Idee (nach Calenge et al. 2026, Appendix S1):
# 1) Bewegungen einzelner Tiere mit raeumlicher Bindung an Streifgebiete
# und Attraktionspunkte simulieren.
# 2) Kameras mit entfernungsabhaengiger Detektion simulieren.
# 3) wiederholte Stichproben-Designs vergleichen.
# 4) Power fuer eine Zeit x Zone-Interaktion bestimmen.
#
# WICHTIG:
# - Die voreingestellten Artparameter sind plausible STARTWERTE, keine
# belastbaren lokalen Schaetzungen. Bitte mit GPS-/Literaturdaten kalibrieren.
# - "Dichte" ist bei nicht individuell erkennbaren Tieren nur unter weiteren
# Annahmen schaetzbar. Das Skript berichtet daher primaer relative
# Detektionsrate (RAI) und optional eine REM-artige Dichtekennzahl.
# ============================================================================
# ---- 0. Pakete --------------------------------------------------------------
required <- c("sf", "data.table", "ggplot2", "MASS", "future", "future.apply")
missing <- required[!vapply(required, requireNamespace, logical(1), quietly = TRUE)]
if (length(missing) > 0) {
stop("Bitte zuerst installieren: install.packages(c(",
paste(sprintf('"%s"', missing), collapse = ", "), "))")
}
library(sf)
library(data.table)
library(ggplot2)
library(MASS)
library(future)
library(future.apply)
# Optional fuer robuste Negativ-Binomial-Modelle:
has_glmmTMB <- requireNamespace("glmmTMB", quietly = TRUE)
set.seed(20260730)
# ---- 1. Globale Einstellungen ----------------------------------------------
# CFG <- list(
# crs = 32632, # Beispiel: UTM 32N; an Projektgebiet anpassen
# years = 1:5,
# survey_days = 30,
# fixes_per_day = 48, # 30-min Schritte; fuer feinere Detektion erhoehen
# n_replicates = 200, # fuer finale Analyse eher 500-1000
# alpha = 0.05,
# target_power = 0.80,
# # Kameradesign: "random" = vorgegebene Anzahl zufaelliger Standorte;
# # "grid" = zufaellig verschobenes/gedrehtes Raster.
# camera_design_mode = "grid",
# camera_numbers = c(12, 20, 30, 40, 60),
# allocations_focus = c(0.35, 0.50, 0.65, 0.80),
# min_camera_spacing_m = 300,
# # Bei Grid-Design bestimmt der Rasterabstand direkt die Kamerazahl.
# # Mehrere Werte koennen in der Poweranalyse verglichen werden.
# grid_spacings_m = c(300, 400, 500, 700),
# grid_random_rotation = TRUE,
# grid_clip_to = "outer", # "outer", "focus" oder "buffer"
#
# focus_radius_m = 1000,
# buffer_width_m = 1500,
# landscape_margin_m = 1800,
# detection_radius_m = 20,
# p_detect_5m = 0.95,
# p_detect_18m = 0.05,
# independence_minutes = 30,
# # relative Aenderung der Nutzung der Fokusflaeche von Jahr 1 bis Jahr 5:
# focus_use_multiplier_end = 0.60,
# # Gesamtpopulation konstant (=0) oder jaehrliche proportionale Aenderung:
# annual_population_change = 0.00,
# # gleiche Kamerastandorte ueber die Jahre erhoehen Vergleichbarkeit:
# permanent_cameras = TRUE
# )
#
# # ---- 2. Artprofile ----------------------------------------------------------
# # home_range_ha beeinflusst die Streuung um das Streifgebietszentrum.
# # step_scale_m beeinflusst kurzfristige Bewegung; attraction_strength die
# # Rueckkehr zu Attraktionspunkten. Gamswild kann zusaetzlich durch ein
# # Habitat-/Topographie-Raster gewichtet werden (siehe habitat_weight_function).
# SPECIES <- list(
# Rehwild = list(
# n_animals = 20,
# home_range_ha = 70,
# step_scale_m = 38,
# n_attraction_points = 7,
# attraction_strength = 0.10,
# resting_probability = 0.22,
# speed_km_day = 3.5,
# group_size_mean = 1.3
# ),
# Rotwild = list(
# n_animals = 40,
# home_range_ha = 300,
# step_scale_m = 105,
# n_attraction_points = 10,
# attraction_strength = 0.055,
# resting_probability = 0.16,
# speed_km_day = 7.0,
# group_size_mean = 3.5
# ),
# Gamswild = list(
# n_animals = 50,
# home_range_ha = 150,
# step_scale_m = 70,
# n_attraction_points = 8,
# attraction_strength = 0.075,
# resting_probability = 0.18,
# speed_km_day = 5.0,
# group_size_mean = 4.2
# )
# )
# ---- 3. Untersuchungsraum: Fokusflaeche, Buffer, Landschaft ----------------
make_study_area <- function(cfg = CFG) {
center <- st_sfc(st_point(c(0, 0)), crs = cfg$crs)
focus <- st_buffer(center, cfg$focus_radius_m)
outer <- st_buffer(focus, cfg$buffer_width_m)
buffer <- st_difference(outer, focus)
landscape <- st_buffer(outer, cfg$landscape_margin_m)
zones <- st_sf(
zone = c("Fokus", "Buffer"),
geometry = st_sfc(st_geometry(focus)[[1]], st_geometry(buffer)[[1]]),
crs = cfg$crs
)
list(center = center, focus = focus, buffer = buffer,
outer = outer, landscape = landscape, zones = zones)
}
#AREA <- make_study_area()
# ---- 4. Hilfsfunktionen -----------------------------------------------------
random_points_min_distance <- function(polygon, n, min_dist, max_tries = 5000) {
if (n == 0) return(st_sf(geometry = st_sfc(crs = st_crs(polygon))))
accepted <- NULL
tries <- 0
while ((is.null(accepted) || nrow(accepted) < n) && tries < max_tries) {
tries <- tries + 1
cand <- st_sample(polygon, size = max(5, n), type = "random")
if (length(cand) == 0) next
cand_sf <- st_sf(geometry = cand)
for (i in seq_len(nrow(cand_sf))) {
p <- cand_sf[i, ]
if (is.null(accepted)) {
accepted <- p
} else {
d <- as.numeric(st_distance(p, accepted))
if (all(d >= min_dist)) accepted <- rbind(accepted, p)
}
if (nrow(accepted) >= n) break
}
}
if (is.null(accepted) || nrow(accepted) < n) {
stop("Kamerazahl/Minimalabstand fuer die Flaeche nicht realisierbar. ",
"Minimalabstand reduzieren oder Flaeche vergroessern.")
}
accepted[seq_len(n), ]
}
# Regelmaessiges Raster mit zufaelligem Versatz und optional zufaelliger Drehung.
# Der Abstand grid_spacing_m bestimmt die Zahl der Kameras; n_cameras und
# prop_focus werden im Grid-Modus nicht zur Standortwahl verwendet.
make_randomized_grid <- function(area = AREA, grid_spacing_m, cfg = CFG) {
stopifnot(is.numeric(grid_spacing_m), length(grid_spacing_m) == 1,
is.finite(grid_spacing_m), grid_spacing_m > 0)
target <- switch(cfg$grid_clip_to,
outer = area$outer,
focus = area$focus,
buffer = area$buffer,
stop("cfg$grid_clip_to muss 'outer', 'focus' oder 'buffer' sein."))
bb <- st_bbox(target)
# Grosszuegige Ausgangsausdehnung, damit nach Drehung die Zielflaeche abgedeckt ist.
cx <- mean(c(bb["xmin"], bb["xmax"]))
cy <- mean(c(bb["ymin"], bb["ymax"]))
diagonal <- sqrt((bb["xmax"] - bb["xmin"])^2 +
(bb["ymax"] - bb["ymin"])^2)
# Zufaelliger Rasterursprung innerhalb einer Rasterzelle.
off_x <- runif(1, 0, grid_spacing_m)
off_y <- runif(1, 0, grid_spacing_m)
lim <- as.numeric(diagonal / 2 + 2 * grid_spacing_m)
xs <- seq(cx - lim + off_x, cx + lim, by = grid_spacing_m)
ys <- seq(cy - lim + off_y, cy + lim, by = grid_spacing_m)
xy <- as.matrix(expand.grid(x = xs, y = ys))
angle <- if (isTRUE(cfg$grid_random_rotation)) runif(1, 0, pi / 2) else 0
if (angle != 0) {
centered <- sweep(xy, 2, c(cx, cy), "-")
rot <- matrix(c(cos(angle), -sin(angle),
sin(angle), cos(angle)), nrow = 2, byrow = TRUE)
xy <- centered %*% t(rot)
xy <- sweep(xy, 2, c(cx, cy), "+")
}
pts <- st_as_sf(data.frame(x = xy[,1], y = xy[,2]),
coords = c("x", "y"), crs = cfg$crs)
pts <- pts[lengths(st_within(pts, target)) > 0, , drop = FALSE]
if (nrow(pts) == 0) stop("Das Raster erzeugt keine Kamerastandorte in der Zielflaeche.")
pts$zone <- ifelse(lengths(st_within(pts, area$focus)) > 0,
"Fokus", "Buffer")
pts$grid_spacing_m <- grid_spacing_m
pts$grid_angle_deg <- angle * 180 / pi
pts$grid_offset_x_m <- off_x
pts$grid_offset_y_m <- off_y
pts
}
make_camera_design <- function(n_cameras = NULL, prop_focus = NULL, area = AREA,
cfg = CFG, grid_spacing_m = NULL) {
if (identical(cfg$camera_design_mode, "grid")) {
if (is.null(grid_spacing_m)) {
if (length(cfg$grid_spacings_m) != 1)
stop("Im Einzelaufruf grid_spacing_m angeben oder nur einen Wert in cfg$grid_spacings_m setzen.")
grid_spacing_m <- cfg$grid_spacings_m
}
cams <- make_randomized_grid(area, grid_spacing_m, cfg)
} else if (identical(cfg$camera_design_mode, "random")) {
if (is.null(n_cameras) || is.null(prop_focus))
stop("Im Random-Modus muessen n_cameras und prop_focus angegeben werden.")
n_focus <- round(n_cameras * prop_focus)
n_buffer <- n_cameras - n_focus
cf <- random_points_min_distance(area$focus, n_focus, cfg$min_camera_spacing_m)
cb <- random_points_min_distance(area$buffer, n_buffer, cfg$min_camera_spacing_m)
cf$zone <- "Fokus"; cb$zone <- "Buffer"
cams <- rbind(cf, cb)
cams$grid_spacing_m <- NA_real_
cams$grid_angle_deg <- NA_real_
cams$grid_offset_x_m <- NA_real_
cams$grid_offset_y_m <- NA_real_
} else {
stop("cfg$camera_design_mode muss 'random' oder 'grid' sein.")
}
cams$camera_id <- sprintf("K%03d", seq_len(nrow(cams)))
cams[, c("camera_id", "zone", "grid_spacing_m", "grid_angle_deg",
"grid_offset_x_m", "grid_offset_y_m", "geometry")]
}
home_range_sd <- function(home_range_ha) {
# Kreisflaeche A = pi*r^2; ca. 95%-Radius ~ 2.45*SD bei isotroper Normalverteilung
radius <- sqrt(home_range_ha * 10000 / pi)
radius / 2.45
}
focus_multiplier_by_year <- function(year, cfg = CFG) {
# geometrische Interpolation; Jahr 1 = 1, letztes Jahr = Endmultiplikator
n <- length(cfg$years)
cfg$focus_use_multiplier_end ^ ((year - min(cfg$years)) / max(1, n - 1))
}
population_multiplier_by_year <- function(year, cfg = CFG) {
(1 + cfg$annual_population_change) ^ (year - min(cfg$years))
}
# Gamswild-Anpassung: hier koennen Hangneigung, Hoehe, Exposition, Felsanteil etc.
# aus Rasterdaten eingebaut werden. Ohne externe Raster wird ein synthetischer
# alpiner Gradientenfaktor verwendet. Rueckgabewert muss zwischen 0 und 1 liegen.
habitat_weight_function <- function(x, y, species) {
if (species != "Gamswild") return(rep(1, length(x)))
ridge <- exp(-((y - 0.35 * x - 500)^2) / (2 * 850^2))
rugged <- 0.55 + 0.45 * (sin(x / 230) * cos(y / 270) + 1) / 2
pmin(1, pmax(0.05, ridge * rugged))
}
sample_centers <- function(n, species, year, area = AREA, cfg = CFG) {
# Ablehnungssampling: Nutzung der Fokusflaeche kann im Zeitverlauf sinken.
pts <- vector("list", n)
focus_mult <- focus_multiplier_by_year(year, cfg)
i <- 1; tries <- 0
while (i <= n && tries < 100000) {
tries <- tries + 1
cand <- st_sample(area$outer, 1)
xy <- st_coordinates(cand)
inside_focus <- lengths(st_intersects(cand, area$focus)) > 0
w_zone <- ifelse(inside_focus, focus_mult, 1)
w_hab <- habitat_weight_function(xy[,1], xy[,2], species)
if (runif(1) < w_zone * w_hab) {
pts[[i]] <- cand[[1]]
i <- i + 1
}
}
if (i <= n) stop("Zu wenige Streifgebietszentren akzeptiert.")
st_sf(animal_id = sprintf("A%04d", seq_len(n)),
geometry = st_sfc(pts, crs = cfg$crs))
}
simulate_tracks <- function(species, year, pars, area = AREA, cfg = CFG) {
n <- max(1, round(pars$n_animals * population_multiplier_by_year(year, cfg)))
centers <- sample_centers(n, species, year, area, cfg)
center_xy <- st_coordinates(centers)
hr_sd <- home_range_sd(pars$home_range_ha)
n_steps <- cfg$survey_days * cfg$fixes_per_day
dt_hours <- 24 / cfg$fixes_per_day
out <- vector("list", n)
for (a in seq_len(n)) {
# Attraktionspunkte innerhalb des Streifgebietes
att <- cbind(
rnorm(pars$n_attraction_points, center_xy[a,1], hr_sd),
rnorm(pars$n_attraction_points, center_xy[a,2], hr_sd)
)
pos <- matrix(NA_real_, n_steps, 2)
pos[1, ] <- center_xy[a, ]
target <- sample.int(nrow(att), 1)
active <- rep(TRUE, n_steps)
for (t in 2:n_steps) {
if (runif(1) < 0.025) target <- sample.int(nrow(att), 1)
active[t] <- runif(1) > pars$resting_probability
if (!active[t]) {
pos[t, ] <- pos[t-1, ]
} else {
pull_att <- pars$attraction_strength * (att[target, ] - pos[t-1, ])
pull_ctr <- 0.012 * (center_xy[a, ] - pos[t-1, ])
eps <- rnorm(2, 0, pars$step_scale_m)
proposed <- pos[t-1, ] + pull_att + pull_ctr + eps
# Bei Gamswild: ungeeignete Punkte werden haeufig verworfen.
hw <- habitat_weight_function(proposed[1], proposed[2], species)
if (runif(1) > hw) proposed <- pos[t-1, ] + 0.35 * eps + pull_ctr
pos[t, ] <- proposed
}
}
out[[a]] <- data.table(
species = species, year = year,
animal_id = centers$animal_id[a],
step = seq_len(n_steps),
time_hours = (seq_len(n_steps) - 1) * dt_hours,
x = pos[,1], y = pos[,2], active = active
)
}
rbindlist(out)
}
# Kalibrierung der Distanz-Detektionsfunktion analog zum Tutorial:
detection_coefficients <- function(p1, d1, p2, d2) {
beta_d <- (log(-log(1-p1)) - log(-log(1-p2))) / (d1-d2)
beta_0 <- log(-log(1-p2)) - beta_d*d2
c(beta0 = beta_0, beta_d = beta_d)
}
# simulate_detections <- function(tracks, cameras, cfg = CFG) {
# cam_xy <- st_coordinates(cameras)
# beta <- detection_coefficients(cfg$p_detect_5m, 5,
# cfg$p_detect_18m, 18)
# tr <- copy(tracks)
# # Pro Kamerapunkt nur Positionen innerhalb des Maximalradius pruefen.
# detections <- vector("list", nrow(cameras))
# for (k in seq_len(nrow(cameras))) {
# dx <- tr$x - cam_xy[k,1]
# dy <- tr$y - cam_xy[k,2]
# d <- sqrt(dx^2 + dy^2)
# idx <- which(d <= cfg$detection_radius_m & tr$active)
# if (length(idx) == 0) next
# hazard <- exp(beta["beta0"] + beta["beta_d"] * d[idx])
# p <- 1 - exp(-hazard)
# hit <- runif(length(idx)) < p
# idx <- idx[hit]
# if (length(idx) == 0) next
# detections[[k]] <- tr[idx, .(
# species, year, animal_id, step, time_hours
# )][, `:=`(
# camera_id = cameras$camera_id[k],
# zone = cameras$zone[k]
# )]
# }
# det <- rbindlist(detections, fill = TRUE)
# if (nrow(det) == 0) return(det)
#
# # Unabhaengige Ereignisse je Tier x Kamera mit Mindestabstand
# gap_steps <- max(1, ceiling(cfg$independence_minutes / 60 * cfg$fixes_per_day / 24))
# setorder(det, camera_id, animal_id, step)
# det[, new_event := is.na(shift(step)) | (step - shift(step) > gap_steps),
# by = .(camera_id, animal_id, year)]
# det <- det[new_event == TRUE]
#
# det[, new_event := NULL]
#
# }
simulate_detections <- function(tracks, cameras, cfg = CFG, verbose = TRUE) {
stopifnot(
all(c("x", "y", "active", "species", "year",
"animal_id", "step", "time_hours") %in% names(tracks)),
inherits(cameras, "sf"),
nrow(cameras) > 0
)
cam_xy <- sf::st_coordinates(cameras)
beta <- detection_coefficients(
p1 = cfg$p_detect_5m,
d1 = 5,
p2 = cfg$p_detect_18m,
d2 = 18
)
tr <- data.table::as.data.table(data.table::copy(tracks))
# Immer einen definierten Datentyp zurückgeben
empty_result <- data.table::data.table(
species = character(),
year = integer(),
animal_id = character(),
step = integer(),
time_hours = numeric(),
camera_id = character(),
zone = character(),
distance_m = numeric(),
p_detect = numeric()
)
if (nrow(tr) == 0) {
if (verbose) message("Keine Bewegungspositionen vorhanden.")
return(empty_result)
}
detections <- vector("list", nrow(cameras))
n_positions_in_radius <- 0L
n_stochastic_hits <- 0L
for (k in seq_len(nrow(cameras))) {
dx <- tr$x - cam_xy[k, 1]
dy <- tr$y - cam_xy[k, 2]
distance_m <- sqrt(dx^2 + dy^2)
# isTRUE funktioniert hier nicht, da active ein Vektor ist
active_idx <- !is.na(tr$active) & tr$active == TRUE
idx <- which(
distance_m <= cfg$detection_radius_m &
active_idx
)
if (length(idx) == 0L) {
next
}
n_positions_in_radius <- n_positions_in_radius + length(idx)
hazard <- exp(
beta["beta0"] +
beta["beta_d"] * distance_m[idx]
)
p_detect <- 1 - exp(-hazard)
p_detect <- pmin(pmax(p_detect, 0), 1)
detected <- stats::runif(length(idx)) < p_detect
idx_detected <- idx[detected]
if (length(idx_detected) == 0L) {
next
}
n_stochastic_hits <- n_stochastic_hits + length(idx_detected)
detections[[k]] <- tr[idx_detected, .(
species,
year,
animal_id,
step,
time_hours,
distance_m = distance_m[idx_detected],
p_detect = p_detect[detected]
)][, `:=`(
camera_id = as.character(cameras$camera_id[k]),
zone = as.character(cameras$zone[k])
)]
}
detections <- Filter(Negate(is.null), detections)
if (length(detections) == 0L) {
if (verbose) {
message(
"Keine Detektionen erzeugt. ",
"Aktive Positionen im Detektionsradius: ",
n_positions_in_radius,
"; stochastische Treffer: 0."
)
}
return(empty_result)
}
det <- data.table::rbindlist(
detections,
use.names = TRUE,
fill = TRUE
)
# Zeitabstand der simulierten Positionen in Minuten
fix_interval_minutes <- 24 * 60 / cfg$fixes_per_day
gap_steps <- max(
1L,
ceiling(
cfg$independence_minutes /
fix_interval_minutes
)
)
data.table::setorder(
det,
camera_id,
animal_id,
year,
step
)
det[, previous_step := data.table::shift(step),
by = .(camera_id, animal_id, year)]
det[, new_event :=
is.na(previous_step) |
step - previous_step > gap_steps]
det <- det[new_event == TRUE]
det[, c("previous_step", "new_event") := NULL]
if (verbose) {
message(
"Detektionssimulation abgeschlossen: ",
n_positions_in_radius,
" aktive Positionen im Radius, ",
n_stochastic_hits,
" einzelne Treffer und ",
nrow(det),
" unabhängige Ereignisse."
)
}
det[]
}
# summarise_camera_counts <- function(det, cameras, year, species, cfg = CFG) {
# base <- data.table(
# camera_id = cameras$camera_id,
# zone = cameras$zone,
# year = year,
# species = species,
# effort_days = cfg$survey_days
# )
# if (nrow(det) == 0) {
# base[, events := 0L]
# } else {
# cnt <- det[, .(events = .N), by = .(camera_id, zone, year, species)]
# base <- merge(base, cnt, by = c("camera_id", "zone", "year", "species"),
# all.x = TRUE)
# base[is.na(events), events := 0L]
# }
# base[, RAI_100_days := 100 * events / effort_days]
# base
# }
summarise_camera_counts <- function(
det,
cameras,
year,
species,
cfg = CFG,
verbose = TRUE
) {
# Eingaben prüfen
if (!inherits(cameras, "sf")) {
stop("'cameras' muss ein sf-Objekt sein.")
}
if (nrow(cameras) == 0L) {
stop("'cameras' enthält keine Kamerastandorte.")
}
required_camera_columns <- c("camera_id", "zone")
missing_camera_columns <- setdiff(
required_camera_columns,
names(cameras)
)
if (length(missing_camera_columns) > 0L) {
stop(
"In 'cameras' fehlen folgende Spalten: ",
paste(missing_camera_columns, collapse = ", ")
)
}
# Geometrie entfernen und Datentypen vereinheitlichen
camera_data <- data.table::as.data.table(
sf::st_drop_geometry(cameras)
)
base <- camera_data[, .(
camera_id = as.character(camera_id),
zone = as.character(zone)
)]
# Doppelte Kamera-IDs verhindern
if (anyDuplicated(base$camera_id)) {
stop("Die Spalte 'camera_id' enthält doppelte Werte.")
}
base[, `:=`(
year = as.integer(year),
species = as.character(species),
effort_days = as.numeric(cfg$survey_days),
events = 0L
)]
# NULL oder vollständig leere Detektionstabelle behandeln
if (!is.null(det) && NROW(det) > 0L) {
det_dt <- data.table::as.data.table(
data.table::copy(det)
)
required_detection_columns <- c(
"camera_id",
"zone",
"year",
"species"
)
missing_detection_columns <- setdiff(
required_detection_columns,
names(det_dt)
)
if (length(missing_detection_columns) > 0L) {
stop(
"In 'det' fehlen folgende Spalten: ",
paste(missing_detection_columns, collapse = ", ")
)
}
# Einheitliche Datentypen sind wichtig für den Join
det_dt[, `:=`(
camera_id = as.character(camera_id),
zone = as.character(zone),
year = as.integer(year),
species = as.character(species)
)]
counts <- det_dt[
,
.(events = .N),
by = .(camera_id, zone, year, species)
]
# Update-Join: vorhandene Nullen werden durch Ereigniszahlen ersetzt
base[
counts,
on = .(camera_id, zone, year, species),
events := i.events
]
}
base[, RAI_100_days := data.table::fifelse(
effort_days > 0,
100 * events / effort_days,
NA_real_
)]
data.table::setorder(base, zone, camera_id)
if (verbose) {
message(
"Zusammenfassung erstellt: ",
nrow(base), " Kameras, ",
sum(base$events), " Ereignisse, Jahr ",
year, ", Art ", species, "."
)
}
return(base[])
}
# ---- 5. Statistischer Test: nimmt Fokus relativ zum Buffer ab? --------------
fit_change_test <- function(camera_counts) {
dat <- copy(camera_counts)
dat[, year_c := year - min(year)]
dat[, zone := factor(zone, levels = c("Buffer", "Fokus"))]
# Zielparameter: year_c:zoneFokus < 0
if (has_glmmTMB) {
fit <- try(glmmTMB::glmmTMB(
events ~ year_c * zone + offset(log(effort_days)) + (1 | camera_id),
family = glmmTMB::nbinom2(), data = dat
), silent = TRUE)
if (!inherits(fit, "try-error")) {
sm <- summary(fit)$coefficients$cond
term <- "year_c:zoneFokus"
if (term %in% rownames(sm)) {
est <- sm[term, "Estimate"]
p_two <- sm[term, "Pr(>|z|)"]
p_one <- if (est < 0) p_two / 2 else 1 - p_two / 2
return(list(estimate = est, p_one_sided = p_one,
detected = is.finite(p_one) && p_one < CFG$alpha && est < 0,
method = "NB-GLMM"))
}
}
}
# Robuster Fallback: NB-GLM mit Kamera als fixer Effekt
fit <- try(MASS::glm.nb(
events ~ year_c * zone + factor(camera_id) + offset(log(effort_days)),
data = dat
), silent = TRUE)
if (inherits(fit, "try-error")) {
return(list(estimate = NA_real_, p_one_sided = NA_real_,
detected = FALSE, method = "failed"))
}
sm <- coef(summary(fit)); term <- "year_c:zoneFokus"
if (!term %in% rownames(sm)) {
return(list(estimate = NA_real_, p_one_sided = NA_real_,
detected = FALSE, method = "term missing"))
}
est <- sm[term, "Estimate"]
p_two <- sm[term, "Pr(>|z|)"]
p_one <- if (est < 0) p_two / 2 else 1 - p_two / 2
list(estimate = est, p_one_sided = p_one,
detected = is.finite(p_one) && p_one < CFG$alpha && est < 0,
method = "NB-GLM")
}
# Einfache REM-artige Kennzahl; nur als Sensitivitaetsanalyse verwenden.
# D proportional zu Ereignisrate / (Geschwindigkeit * Detektionsbreite).
rem_density_index <- function(camera_counts, species_pars, cfg = CFG) {
effective_width_km <- 2 * cfg$detection_radius_m / 1000
camera_counts[, density_index :=
(events / effort_days) /
pmax(1e-9, species_pars$speed_km_day * effective_width_km)]
camera_counts
}
# `%||%` <- function(x, y) {
# if (!is.null(x)) x else y
# }
`%||%` <- function(x, y) {
if (is.null(x) || length(x) == 0L) y else x
}
# ---- 6. Eine Simulationswiederholung ---------------------------------------
run_one_replicate <- function(species, pars, n_cameras = NA_integer_,
prop_focus = NA_real_, grid_spacing_m = NA_real_,
replicate_id, cfg = CFG) {
make_cams <- function() make_camera_design(
n_cameras = n_cameras, prop_focus = prop_focus, area = AREA, cfg = cfg,
grid_spacing_m = if (is.finite(grid_spacing_m)) grid_spacing_m else NULL
)
cams_fixed <- if (cfg$permanent_cameras) make_cams() else NULL
yearly <- vector("list", length(cfg$years))
for (j in seq_along(cfg$years)) {
yr <- cfg$years[j]
cams <- if (cfg$permanent_cameras) cams_fixed else make_cams()
tracks <- simulate_tracks(species, yr, pars, AREA, cfg)
det <- simulate_detections(tracks, cams, cfg)
yearly[[j]] <- summarise_camera_counts(det, cams, yr, species, cfg)
}
counts <- rbindlist(yearly)
counts <- rem_density_index(counts, pars, cfg)
tst <- fit_change_test(counts)
data.table(
species = species,
replicate = replicate_id,
n_cameras = nrow(cams_fixed %||% cams),
prop_focus = mean((cams_fixed %||% cams)$zone == "Fokus"),
grid_spacing_m = if (identical(cfg$camera_design_mode, "grid")) grid_spacing_m else NA_real_,
estimate_interaction = tst$estimate,
p_one_sided = tst$p_one_sided,
detected_decline = tst$detected,
method = tst$method,
mean_events = mean(counts$events),
zero_fraction = mean(counts$events == 0)
)
}
# ---- 7. Vollstaendige Poweranalyse -----------------------------------------
run_power_analysis <- function(species_names = names(SPECIES), cfg = CFG) {
if (identical(cfg$camera_design_mode, "grid")) {
design <- CJ(
species = species_names,
grid_spacing_m = cfg$grid_spacings_m,
replicate = seq_len(cfg$n_replicates),
unique = TRUE
)
design[, `:=`(n_cameras = NA_integer_, prop_focus = NA_real_)]
} else {
design <- CJ(
species = species_names,
n_cameras = cfg$camera_numbers,
prop_focus = cfg$allocations_focus,
replicate = seq_len(cfg$n_replicates),
unique = TRUE
)
design[, grid_spacing_m := NA_real_]
}
results <- vector("list", nrow(design))
for (i in seq_len(nrow(design))) {
d <- design[i]
if (identical(cfg$camera_design_mode, "grid")) {
message(sprintf("%d/%d: %s, Grid %.0f m, Rep %d",
i, nrow(design), d$species, d$grid_spacing_m, d$replicate))
} else {
message(sprintf("%d/%d: %s, %d Kameras, %.0f%% Fokus, Rep %d",
i, nrow(design), d$species, d$n_cameras,
100*d$prop_focus, d$replicate))
}
results[[i]] <- tryCatch(
run_one_replicate(d$species, SPECIES[[d$species]],
n_cameras = d$n_cameras, prop_focus = d$prop_focus,
grid_spacing_m = d$grid_spacing_m,
replicate_id = d$replicate, cfg = cfg),
error = function(e) data.table(
species=d$species, replicate=d$replicate,
n_cameras=d$n_cameras, prop_focus=d$prop_focus,
grid_spacing_m=d$grid_spacing_m,
estimate_interaction=NA_real_, p_one_sided=NA_real_,
detected_decline=FALSE, method=paste("ERROR:", e$message),
mean_events=NA_real_, zero_fraction=NA_real_
)
)
}
raw <- rbindlist(results, fill = TRUE)
if (identical(cfg$camera_design_mode, "grid")) {
summary <- raw[, .(
power = mean(detected_decline, na.rm = TRUE),
valid_runs = sum(is.finite(p_one_sided)),
mean_effect = mean(estimate_interaction, na.rm = TRUE),
n_cameras = mean(n_cameras, na.rm = TRUE),
n_cameras_min = min(n_cameras, na.rm = TRUE),
n_cameras_max = max(n_cameras, na.rm = TRUE),
prop_focus = mean(prop_focus, na.rm = TRUE),
median_events_per_camera_year = median(mean_events, na.rm = TRUE),
mean_zero_fraction = mean(zero_fraction, na.rm = TRUE)
), by = .(species, grid_spacing_m)]
} else {
summary <- raw[, .(
power = mean(detected_decline, na.rm = TRUE),
valid_runs = sum(is.finite(p_one_sided)),
mean_effect = mean(estimate_interaction, na.rm = TRUE),
median_events_per_camera_year = median(mean_events, na.rm = TRUE),
mean_zero_fraction = mean(zero_fraction, na.rm = TRUE)
), by = .(species, n_cameras, prop_focus)]
summary[, grid_spacing_m := NA_real_]
}
summary[, reaches_target := power >= cfg$target_power]
list(raw = raw, summary = summary)
}
# Run Power Analysis in Parallel ------------------------------------------
run_power_analysis_parallel <- function(
species_names = names(SPECIES),
cfg = CFG,
species_profiles = SPECIES,
n_cores = max(1, parallel::detectCores() - 1),
seed = 777
) {
requireNamespace("future", quietly = TRUE)
requireNamespace("future.apply", quietly = TRUE)
requireNamespace("data.table", quietly = TRUE)
future::plan(
future::multisession,
workers = n_cores
)
on.exit(
future::plan(future::sequential),
add = TRUE
)
# ------------------------------------------------------------
# Szenarien definieren
# ------------------------------------------------------------
if (cfg$camera_design_mode == "grid") {
scenarios <- expand.grid(
species = species_names,
grid_spacing_m = cfg$grid_spacings_m,
stringsAsFactors = FALSE
)
} else {
scenarios <- expand.grid(
species = species_names,
n_cameras = cfg$camera_numbers,
prop_focus = cfg$allocations_focus,
stringsAsFactors = FALSE
)
}
all_results <- vector(
"list",
nrow(scenarios)
)
# ------------------------------------------------------------
# Szenarien
# ------------------------------------------------------------
for (s in seq_len(nrow(scenarios))) {
species <- scenarios$species[s]
if (cfg$camera_design_mode == "grid") {
grid_spacing_m <- scenarios$grid_spacing_m[s]
message(
"Szenario ",
s, "/", nrow(scenarios),
": ",
species,
" | Grid ",
grid_spacing_m,
" m"
)
} else {
n_cameras <- scenarios$n_cameras[s]
prop_focus <- scenarios$prop_focus[s]
message(
"Szenario ",
s, "/", nrow(scenarios),
": ",
species,
" | ",
n_cameras,
" Kameras | Fokusanteil ",
prop_focus
)
}
# ----------------------------------------------------------
# Replikate parallel ausführen
# ----------------------------------------------------------
reps <- future.apply::future_lapply(
seq_len(cfg$n_replicates),
function(rep_id) {
tryCatch({
if (cfg$camera_design_mode == "grid") {
res <- run_one_replicate(
species = species,
pars = species_profiles[[species]],
grid_spacing_m = grid_spacing_m,
replicate_id = rep_id,
cfg = cfg
)
} else {
res <- run_one_replicate(
species = species,
pars = species_profiles[[species]],
n_cameras = n_cameras,
allocation_focus = prop_focus,
replicate_id = rep_id,
cfg = cfg
)
}
res <- data.table::as.data.table(res)
# Erfolgreicher Lauf
res[, `:=`(
error = FALSE,
error_message = NA_character_
)]
res
}, error = function(e) {
# Fehlgeschlagener Lauf erhält exakt dieselbe Struktur
data.table::data.table(
species = species,
replicate = rep_id,
n_cameras =
if (cfg$camera_design_mode == "random")
as.numeric(n_cameras)
else
NA_real_,
prop_focus =
if (cfg$camera_design_mode == "random")
as.numeric(prop_focus)
else
NA_real_,
grid_spacing_m =
if (cfg$camera_design_mode == "grid")
as.numeric(grid_spacing_m)
else
NA_real_,
estimate_interaction = NA_real_,
p_one_sided = NA_real_,
detected_decline = NA,
method = NA_character_,
mean_events = NA_real_,
zero_fraction = NA_real_,
error = TRUE,
error_message = conditionMessage(e)
)
})
},
future.seed = seed + s
)
all_results[[s]] <- data.table::rbindlist(
reps,
use.names = TRUE,
fill = TRUE
)
}
# ------------------------------------------------------------
# Alle Ergebnisse zusammenführen
# ------------------------------------------------------------
raw <- data.table::rbindlist(
all_results,
use.names = TRUE,
fill = TRUE
)
# Sicherheitsnetz
if (!"error" %in% names(raw)) {
raw[, error := FALSE]
}
if (!"error_message" %in% names(raw)) {
raw[, error_message := NA_character_]
}
# ------------------------------------------------------------
# POWER-ZUSAMMENFASSUNG
# ------------------------------------------------------------
if (cfg$camera_design_mode == "grid") {
summary <- raw[
,
.(
n_requested = .N,
n_valid = sum(
!error &
!is.na(detected_decline)
),
n_errors = sum(error),
error_rate = mean(error),
power = {
z <- detected_decline[
!error &
!is.na(detected_decline)
]
if (!length(z)) {
NA_real_
} else {
mean(z)
}
},
mean_n_cameras = {
z <- n_cameras[!error]
if (!length(z) || all(is.na(z))) {
NA_real_
} else {
mean(z, na.rm = TRUE)
}
},
min_n_cameras = {
z <- n_cameras[!error]
if (!length(z) || all(is.na(z))) {
NA_real_
} else {
min(z, na.rm = TRUE)
}
},
max_n_cameras = {
z <- n_cameras[!error]
if (!length(z) || all(is.na(z))) {
NA_real_
} else {
max(z, na.rm = TRUE)
}
},
mean_prop_focus = {
z <- prop_focus[!error]
if (!length(z) || all(is.na(z))) {
NA_real_
} else {
mean(z, na.rm = TRUE)
}
},
mean_interaction = {
z <- estimate_interaction[!error]
if (!length(z) || all(is.na(z))) {
NA_real_
} else {
mean(z, na.rm = TRUE)
}
},
mean_p_one_sided = {
z <- p_one_sided[!error]
if (!length(z) || all(is.na(z))) {
NA_real_
} else {
mean(z, na.rm = TRUE)
}
},
mean_events = {
z <- mean_events[!error]
if (!length(z) || all(is.na(z))) {
NA_real_
} else {
mean(z, na.rm = TRUE)
}
},
mean_zero_fraction = {
z <- zero_fraction[!error]
if (!length(z) || all(is.na(z))) {
NA_real_
} else {
mean(z, na.rm = TRUE)
}
}
),
by = .(
species,
grid_spacing_m
)
]
} else {
summary <- raw[
,
.(
n_requested = .N,
n_valid = sum(
!error &
!is.na(detected_decline)
),
n_errors = sum(error),
error_rate = mean(error),
power = {
z <- detected_decline[
!error &
!is.na(detected_decline)
]
if (!length(z)) NA_real_ else mean(z)
},
mean_interaction = {
z <- estimate_interaction[!error]
if (!length(z) || all(is.na(z))) {
NA_real_
} else {
mean(z, na.rm = TRUE)
}
},
mean_events = {
z <- mean_events[!error]
if (!length(z) || all(is.na(z))) {
NA_real_
} else {
mean(z, na.rm = TRUE)
}
},
mean_zero_fraction = {
z <- zero_fraction[!error]
if (!length(z) || all(is.na(z))) {
NA_real_
} else {
mean(z, na.rm = TRUE)
}
}
),
by = .(
species,
n_cameras,
prop_focus
)
]
}
# ------------------------------------------------------------
# Fehlertabelle
# ------------------------------------------------------------
errors <- raw[
error == TRUE,
.(
N = .N
),
by = .(
species,
grid_spacing_m,
error_message
)
][order(-N)]
# ------------------------------------------------------------
# Rückgabe
# ------------------------------------------------------------
list(
raw = raw,
summary = summary,
errors = errors
)
}
# ---- 8. Beispiel / Hauptlauf -----------------------------------------------
# Zuerst einen kleinen Testlauf starten. Danach n_replicates in CFG erhoehen.
RUN_FULL_ANALYSIS <- FALSE
if (RUN_FULL_ANALYSIS) {
ans <- run_power_analysis()
fwrite(ans$raw, "power_raw.csv")
fwrite(ans$summary, "power_summary.csv")
# Auch im Grid-Modus wird gegen die tatsaechlich resultierende Kamerazahl geplottet.
p <- ggplot(ans$summary,
aes(x = n_cameras, y = power,
group = if (identical(CFG$camera_design_mode, "grid"))
factor(grid_spacing_m) else factor(prop_focus),
linetype = if (identical(CFG$camera_design_mode, "grid"))
factor(grid_spacing_m) else factor(prop_focus))) +
geom_line() + geom_point() +
geom_hline(yintercept = CFG$target_power, linetype = 2) +
facet_wrap(~ species) +
scale_y_continuous(limits = c(0,1)) +
labs(x = "Gesamtzahl Kameras", y = "Power",
linetype = if (identical(CFG$camera_design_mode, "grid"))
"Grid-Abstand (m)" else "Anteil Fokus",
title = "Power zur Erkennung einer Abnahme der Fokusflaechennutzung") +
theme_bw()
ggsave("power_sampling_design.png", p, width = 10, height = 6, dpi = 300)
# Kleinstes Design je Art mit Ziel-Power:
recommendation <- ans$summary[reaches_target == TRUE][
order(n_cameras, -power), .SD[1], by = species]
print(recommendation)
}
# ---- 9. Schneller Funktionscheck -------------------------------------------
# Dieser Block ist absichtlich klein und kann direkt ausgefuehrt werden.
RUN_SMOKE_TEST <- FALSE
if (RUN_SMOKE_TEST) {
cfg_test <- CFG
cfg_test$years <- 1:3
cfg_test$survey_days <- 5
cfg_test$fixes_per_day <- 24
cfg_test$n_replicates <- 2
cfg_test$camera_design_mode <- "grid"
cfg_test$grid_spacings_m <- 700
smoke <- run_one_replicate(
species = "Rehwild", pars = SPECIES$Rehwild,
grid_spacing_m = 700, replicate_id = 1, cfg = cfg_test
)
print(smoke)
}
# ---- 10. Empfohlene Kalibrierung mit realen Daten --------------------------
# A) Streifgebietsgroessen:
# SPECIES[[Art]]$home_range_ha aus GPS-Daten (z.B. AKDE/MCP) setzen.
# B) Bewegung:
# step_scale_m und resting_probability anhand Schrittlaengen/Aktivitaet.
# C) Gamswild:
# habitat_weight_function durch Vorhersagen eines RSF/SSF-Modells mit
# Hoehe, Hangneigung, Exposition, Fels/Wald und Schneelage ersetzen.
# D) Kameras:
# camera_design_mode = "grid" und grid_spacings_m anpassen; jeder Lauf
# verwendet einen zufaelligen Rasterversatz und optional eine Drehung.
# Fuer feste reale Standorte vorhandene/erlaubte Punkte als sf einlesen.
# E) Effektszenarien:
# focus_use_multiplier_end = 0.9, 0.8, 0.7, ... fuer minimale erkennbare
# Abnahme testen; annual_population_change separat variieren.
# F) Interpretation:
# Eine sinkende Detektionsrate kann durch geringere Dichte, geringere
# Nutzung, veraenderte Aktivitaet oder Detektierbarkeit entstehen. Das
# Fokus-vs-Buffer-BACI-aehnliche Design hilft, trennt diese Prozesse aber
# nicht ohne Zusatzdaten vollstaendig.