# ============================================================================= # Shiny GUI – Konfiguration einer Fotofallen-Simulationsstudie # Rehwild, Rotwild und Gamswild # # Start: # install.packages(c("shiny","sf","data.table","ggplot2","DT")) # shiny::runApp("app.R") # # Output: # Download einer .RData-Datei mit den Objekten: # CFG, AREA, SPECIES, HABITAT # # Diese Datei kann später im Poweranalyse-Skript geladen werden: # load("simulations_setup.RData") # ============================================================================= required <- c("shiny", "sf", "data.table", "ggplot2", "DT") missing <- required[!vapply(required, requireNamespace, logical(1), quietly = TRUE)] if (length(missing)) { stop( "Bitte zuerst installieren: install.packages(c(", paste(sprintf('"%s"', missing), collapse = ", "), "))" ) } library(shiny) library(sf) library(data.table) library(ggplot2) library(DT) # --------------------------------------------------------------------------- # Standardwerte # --------------------------------------------------------------------------- default_CFG <- list( crs = 32632, years = 1:5, survey_days = 30, fixes_per_day = 288, n_replicates = 500, alpha = 0.05, target_power = 0.80, 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 = 250, grid_spacings_m = c(250, 350, 500, 700), grid_random_rotation = TRUE, grid_clip_to = "outer", 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, focus_use_multiplier_end = 0.60, annual_population_change = 0.00, permanent_cameras = TRUE ) default_SPECIES <- list( Rehwild = list( n_animals = 80, 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 = 45, home_range_ha = 900, 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 = 55, home_range_ha = 260, step_scale_m = 70, n_attraction_points = 8, attraction_strength = 0.075, resting_probability = 0.18, speed_km_day = 5.0, group_size_mean = 2.2 ) ) # Parameter der synthetischen Habitatgewichtung. # Diese Parameter werden ebenfalls gespeichert und können später durch # Raster-/RSF-/SSF-basierte Habitatmodelle ersetzt werden. default_HABITAT <- list( enabled = TRUE, apply_to = "Gamswild", ridge_intercept_m = 500, ridge_slope = 0.35, ridge_sd_m = 850, rugged_x_scale_m = 230, rugged_y_scale_m = 270, rugged_min = 0.55, minimum_weight = 0.05 ) # --------------------------------------------------------------------------- # Hilfsfunktionen # --------------------------------------------------------------------------- parse_num_vector <- function(x, integer = FALSE, min_value = -Inf, max_value = Inf) { x <- trimws(x) if (!nzchar(x)) return(numeric(0)) z <- suppressWarnings(as.numeric(unlist(strsplit(gsub(";", ",", x), ",")))) z <- z[is.finite(z)] z <- z[z >= min_value & z <= max_value] if (integer) z <- as.integer(round(z)) unique(z) } make_area_from_cfg <- function(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( source = "generated", center = center, focus = focus, buffer = buffer, outer = outer, landscape = landscape, zones = zones ) } read_uploaded_shape <- function(fileinfo, target_crs, layer_mode = "first") { if (is.null(fileinfo) || nrow(fileinfo) == 0) { stop("Keine Geodatei ausgewählt.") } tmpdir <- tempfile("shape_upload_") dir.create(tmpdir, recursive = TRUE) for (i in seq_len(nrow(fileinfo))) { file.copy(fileinfo$datapath[i], file.path(tmpdir, fileinfo$name[i]), overwrite = TRUE) } files <- list.files(tmpdir, full.names = TRUE) shp <- files[grepl("\\.shp$", files, ignore.case = TRUE)] gpkg <- files[grepl("\\.gpkg$", files, ignore.case = TRUE)] geojson <- files[grepl("\\.(geojson|json)$", files, ignore.case = TRUE)] if (length(gpkg)) { layers <- st_layers(gpkg[1])$name layer <- if (layer_mode == "first") layers[1] else layer_mode x <- st_read(gpkg[1], layer = layer, quiet = TRUE) } else if (length(shp)) { x <- st_read(shp[1], quiet = TRUE) } else if (length(geojson)) { x <- st_read(geojson[1], quiet = TRUE) } else { stop( "Keine unterstützte Vektordatei gefunden. ", "Für Shapefiles bitte .shp, .shx, .dbf und ggf. .prj gemeinsam hochladen; ", "alternativ GeoPackage (.gpkg) oder GeoJSON." ) } if (nrow(x) < 1) stop("Die Geodatei enthält keine Features.") x <- st_make_valid(x) x <- x[!st_is_empty(x), , drop = FALSE] if (is.na(st_crs(x))) { stop("Die hochgeladene Geodatei besitzt kein definiertes CRS.") } x <- st_transform(x, target_crs) geom <- st_union(st_geometry(x)) focus <- st_sf(geometry = geom) focus <- st_make_valid(focus) focus } make_area_from_focus <- function(focus, cfg) { focus <- st_transform(focus, cfg$crs) focus <- st_sf(geometry = st_union(st_geometry(st_make_valid(focus)))) outer <- st_buffer(focus, cfg$buffer_width_m) buffer <- st_difference(outer, focus) landscape <- st_buffer(outer, cfg$landscape_margin_m) center <- st_centroid(focus) zones <- rbind( st_sf(zone = "Fokus", geometry = st_geometry(focus)), st_sf(zone = "Buffer", geometry = st_geometry(buffer)) ) list( source = "uploaded", center = center, focus = focus, buffer = buffer, outer = outer, landscape = landscape, zones = zones ) } home_range_sd <- function(home_range_ha) { radius <- sqrt(home_range_ha * 10000 / pi) radius / 2.45 } habitat_weight <- function(x, y, species, habitat) { if (!isTRUE(habitat$enabled) || species != habitat$apply_to) { return(rep(1, length(x))) } ridge_center <- habitat$ridge_slope * x + habitat$ridge_intercept_m ridge <- exp(-((y - ridge_center)^2) / (2 * habitat$ridge_sd_m^2)) rugged <- habitat$rugged_min + (1 - habitat$rugged_min) * (sin(x / habitat$rugged_x_scale_m) * cos(y / habitat$rugged_y_scale_m) + 1) / 2 pmin(1, pmax(habitat$minimum_weight, ridge * rugged)) } sample_point_in_polygon <- function(poly) { p <- st_sample(poly, 1, type = "random") if (!length(p)) stop("Kein Punkt in der Fläche erzeugt.") st_coordinates(p)[1, ] } sample_centers_gui <- function(n, species, year, area, cfg, habitat) { pts <- vector("list", n) n_years <- length(cfg$years) denom <- max(1, n_years - 1) focus_mult <- cfg$focus_use_multiplier_end ^ ((year - min(cfg$years)) / denom) i <- 1L tries <- 0L while (i <= n && tries < 100000L) { tries <- tries + 1L cand <- st_sample(area$outer, 1) xy <- st_coordinates(cand)[1, ] inside_focus <- lengths(st_intersects(cand, area$focus)) > 0 w_zone <- if (inside_focus) focus_mult else 1 w_hab <- habitat_weight(xy[1], xy[2], species, habitat) if (runif(1) < w_zone * w_hab) { pts[[i]] <- cand[[1]] i <- i + 1L } } 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_one_track <- function(species, pars, area, cfg, habitat, days = 3, fixes_per_day = NULL) { if (is.null(fixes_per_day)) { fixes_per_day <- min(cfg$fixes_per_day, 288) } center <- sample_centers_gui( n = 1, species = species, year = min(cfg$years), area = area, cfg = cfg, habitat = habitat ) center_xy <- st_coordinates(center)[1, ] hr_sd <- home_range_sd(pars$home_range_ha) att <- cbind( rnorm(pars$n_attraction_points, center_xy[1], hr_sd), rnorm(pars$n_attraction_points, center_xy[2], hr_sd) ) n_steps <- max(2L, as.integer(days * fixes_per_day)) dt_hours <- 24 / fixes_per_day pos <- matrix(NA_real_, n_steps, 2) pos[1, ] <- center_xy 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 - pos[t - 1, ]) eps <- rnorm(2, 0, pars$step_scale_m) proposed <- pos[t - 1, ] + pull_att + pull_ctr + eps hw <- habitat_weight(proposed[1], proposed[2], species, habitat) if (runif(1) > hw) { proposed <- pos[t - 1, ] + 0.35 * eps + pull_ctr } pos[t, ] <- proposed } } data.table( species = species, animal_id = paste0(species, "_sample"), step = seq_len(n_steps), time_hours = (seq_len(n_steps) - 1) * dt_hours, x = pos[, 1], y = pos[, 2], active = active ) } make_randomized_grid <- function(area, spacing_m, cfg) { target <- switch( cfg$grid_clip_to, outer = area$outer, focus = area$focus, buffer = area$buffer, stop("grid_clip_to muss 'outer', 'focus' oder 'buffer' sein.") ) bb <- st_bbox(target) 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 ) off_x <- runif(1, 0, spacing_m) off_y <- runif(1, 0, spacing_m) lim <- as.numeric(diagonal / 2 + 2 * spacing_m) xs <- seq(cx - lim + off_x, cx + lim, by = spacing_m) ys <- seq(cy - lim + off_y, cy + lim, by = 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)) stop("Das Raster erzeugt keine Kamerastandorte.") pts$zone <- ifelse( lengths(st_within(pts, area$focus)) > 0, "Fokus", "Buffer" ) pts$camera_id <- sprintf("K%03d", seq_len(nrow(pts))) pts$grid_spacing_m <- spacing_m pts$grid_angle_deg <- angle * 180 / pi pts$grid_offset_x_m <- off_x pts$grid_offset_y_m <- off_y pts } random_points_min_distance <- function(polygon, n, min_dist, max_tries = 10000) { if (n <= 0) { return(st_sf(geometry = st_sfc(crs = st_crs(polygon)))) } accepted <- NULL tries <- 0L while ((is.null(accepted) || nrow(accepted) < n) && tries < max_tries) { tries <- tries + 1L cand <- st_sf(geometry = st_sample(polygon, size = max(10, n))) if (!nrow(cand)) next for (i in seq_len(nrow(cand))) { p <- cand[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 und Mindestabstand sind für die Fläche nicht realisierbar." ) } accepted[seq_len(n), ] } make_camera_design_gui <- function(area, cfg) { if (cfg$camera_design_mode == "grid") { spacing <- cfg$grid_spacings_m[1] return(make_randomized_grid(area, spacing, cfg)) } n_cameras <- cfg$camera_numbers[1] prop_focus <- cfg$allocations_focus[1] 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$camera_id <- sprintf("K%03d", seq_len(nrow(cams))) cams } area_summary_table <- function(area) { data.frame( zone = c("Fokus", "Buffer", "Fokus + Buffer", "Landschaft"), area_ha = round( c( as.numeric(st_area(area$focus)), as.numeric(st_area(area$buffer)), as.numeric(st_area(area$outer)), as.numeric(st_area(area$landscape)) ) / 10000, 2 ) ) } species_to_df <- function(species) { rbindlist( lapply(names(species), function(s) { as.data.table(c(list(species = s), species[[s]])) }), fill = TRUE ) } # --------------------------------------------------------------------------- # Benutzeroberfläche # --------------------------------------------------------------------------- ui <- navbarPage( title = "Fotofallen-Simulationsstudie", id = "main_tabs", tabPanel( "CFG", sidebarLayout( sidebarPanel( width = 4, h4("Zeit und Wiederholungen"), numericInput("crs", "Projektions-CRS (EPSG)", default_CFG$crs, min = 1, step = 1), textInput("years", "Jahre (z.B. 1,2,3,4,5)", "1,2,3,4,5"), numericInput("survey_days", "Erhebungsdauer je Jahr [Tage]", default_CFG$survey_days, min = 1, step = 1), numericInput("fixes_per_day", "Simulierte Positionen pro Tag", default_CFG$fixes_per_day, min = 1, step = 1), numericInput("n_replicates", "Monte-Carlo-Wiederholungen", default_CFG$n_replicates, min = 1, step = 50), numericInput("alpha", "Signifikanzniveau α", default_CFG$alpha, min = 0.001, max = 0.5, step = 0.005), numericInput("target_power", "Ziel-Power", default_CFG$target_power, min = 0.1, max = 0.999, step = 0.01), hr(), h4("Kameradesign"), radioButtons( "camera_design_mode", "Design", choices = c("Zufälliges Grid" = "grid", "Zufällige Punkte" = "random"), selected = default_CFG$camera_design_mode ), conditionalPanel( "input.camera_design_mode == 'grid'", textInput("grid_spacings_m", "Grid-Abstände [m], kommasepariert", paste(default_CFG$grid_spacings_m, collapse = ",")), checkboxInput("grid_random_rotation", "Grid zufällig drehen", default_CFG$grid_random_rotation), selectInput( "grid_clip_to", "Grid begrenzen auf", choices = c( "Fokus + Buffer" = "outer", "nur Fokus" = "focus", "nur Buffer" = "buffer" ), selected = default_CFG$grid_clip_to ) ), conditionalPanel( "input.camera_design_mode == 'random'", textInput("camera_numbers", "Kamerazahlen, kommasepariert", paste(default_CFG$camera_numbers, collapse = ",")), textInput("allocations_focus", "Anteile Fokus (0–1), kommasepariert", paste(default_CFG$allocations_focus, collapse = ",")), numericInput("min_camera_spacing_m", "Mindestabstand Kameras [m]", default_CFG$min_camera_spacing_m, min = 0, step = 10) ) ), mainPanel( width = 8, fluidRow( column( 6, h4("Detektion"), numericInput("detection_radius_m", "Detektionsradius [m]", default_CFG$detection_radius_m, min = 0.1, step = 1), numericInput("p_detect_5m", "P(Detektion) bei 5 m", default_CFG$p_detect_5m, min = 0.001, max = 0.999, step = 0.01), numericInput("p_detect_18m", "P(Detektion) bei 18 m", default_CFG$p_detect_18m, min = 0.001, max = 0.999, step = 0.01), numericInput("independence_minutes", "Unabhängigkeitsintervall [min]", default_CFG$independence_minutes, min = 0, step = 5) ), column( 6, h4("Trend / Szenario"), numericInput( "focus_use_multiplier_end", "Nutzung Fokus im letzten Jahr (relativ zu Jahr 1)", default_CFG$focus_use_multiplier_end, min = 0.01, max = 2, step = 0.05 ), numericInput( "annual_population_change", "Jährliche Populationsänderung", default_CFG$annual_population_change, min = -0.99, max = 1, step = 0.01 ), checkboxInput( "permanent_cameras", "Kamerastandorte über Jahre konstant", default_CFG$permanent_cameras ) ) ), hr(), h4("Aktuelle CFG-Vorschau"), verbatimTextOutput("cfg_preview") ) ) ), tabPanel( "Artprofile", fluidRow( column( 4, selectInput( "species_edit", "Wildart", choices = names(default_SPECIES), selected = "Rehwild" ), numericInput("sp_n_animals", "Anzahl Tiere", 80, min = 1, step = 1), numericInput("sp_home_range_ha", "Streifgebiet [ha]", 70, min = 0.1, step = 10), numericInput("sp_step_scale_m", "Schritt-Skala [m]", 38, min = 0.1, step = 1), numericInput("sp_n_attraction_points", "Attraktionspunkte", 7, min = 1, step = 1) ), column( 4, numericInput("sp_attraction_strength", "Attraktionsstärke", 0.10, min = 0, max = 1, step = 0.005), numericInput("sp_resting_probability", "Ruhewahrscheinlichkeit", 0.22, min = 0, max = 0.99, step = 0.01), numericInput("sp_speed_km_day", "Bewegungsstrecke [km/Tag]", 3.5, min = 0.01, step = 0.1), numericInput("sp_group_size_mean", "Mittlere Gruppengröße", 1.3, min = 1, step = 0.1), actionButton("save_species", "Artprofil übernehmen", class = "btn-primary") ), column( 4, h4("Gespeicherte Artprofile"), DTOutput("species_table") ) ) ), tabPanel( "Study Area", sidebarLayout( sidebarPanel( width = 4, radioButtons( "area_mode", "Fokusfläche", choices = c( "Künstliche Kreisfläche" = "generated", "Eigene Vektordatei" = "uploaded" ), selected = "generated" ), conditionalPanel( "input.area_mode == 'generated'", numericInput("focus_radius_m", "Radius Fokusfläche [m]", default_CFG$focus_radius_m, min = 10, step = 100) ), conditionalPanel( "input.area_mode == 'uploaded'", fileInput( "focus_shape", "Fokusfläche hochladen", multiple = TRUE, accept = c(".shp", ".shx", ".dbf", ".prj", ".gpkg", ".geojson", ".json") ), helpText( "Shapefile: .shp, .shx, .dbf und .prj gemeinsam auswählen. ", "GeoPackage oder GeoJSON kann einzeln geladen werden." ) ), numericInput("buffer_width_m", "Bufferbreite [m]", default_CFG$buffer_width_m, min = 0, step = 100), numericInput("landscape_margin_m", "Zusätzlicher Landschaftspuffer [m]", default_CFG$landscape_margin_m, min = 0, step = 100), actionButton("build_area", "Fläche erstellen / aktualisieren", class = "btn-primary") ), mainPanel( width = 8, plotOutput("area_plot", height = 550), DTOutput("area_table") ) ) ), tabPanel( "Habitat", sidebarLayout( sidebarPanel( width = 4, checkboxInput("habitat_enabled", "Habitatgewichtung aktivieren", default_HABITAT$enabled), selectInput( "habitat_apply_to", "Habitatgewichtung anwenden auf", choices = names(default_SPECIES), selected = default_HABITAT$apply_to ), numericInput("ridge_intercept_m", "Ridge: Achsenabschnitt [m]", default_HABITAT$ridge_intercept_m, step = 50), numericInput("ridge_slope", "Ridge: Steigung", default_HABITAT$ridge_slope, step = 0.05), numericInput("ridge_sd_m", "Ridge: Breite / SD [m]", default_HABITAT$ridge_sd_m, min = 1, step = 50), numericInput("rugged_x_scale_m", "Ruggedness: X-Skala [m]", default_HABITAT$rugged_x_scale_m, min = 1, step = 10), numericInput("rugged_y_scale_m", "Ruggedness: Y-Skala [m]", default_HABITAT$rugged_y_scale_m, min = 1, step = 10), numericInput("rugged_min", "Ruggedness: Mindestfaktor", default_HABITAT$rugged_min, min = 0, max = 1, step = 0.05), numericInput("minimum_weight", "Minimales Habitatgewicht", default_HABITAT$minimum_weight, min = 0.001, max = 1, step = 0.01) ), mainPanel( width = 8, h4("Synthetische Habitatgewichtung"), p( "Diese Ansicht dient zur Parametrisierung des Habitatanteils der ", "Bewegungssimulation. Für reale Anwendungen kann die Funktion später ", "durch Rasterwerte oder ein RSF/SSF-Modell ersetzt werden." ), plotOutput("habitat_plot", height = 550) ) ) ), tabPanel( "Sample Tracks", fluidRow( column( 3, numericInput("track_days", "Simulierte Tage", 3, min = 1, max = 30), numericInput("track_fixes_day", "Positionen pro Tag", 96, min = 4, max = 1440, step = 4), actionButton("simulate_tracks_btn", "Sample Tracks für alle Arten simulieren", class = "btn-primary") ), column( 9, plotOutput("tracks_plot", height = 650) ) ) ), tabPanel( "Study Design", sidebarLayout( sidebarPanel( width = 3, p( "Für die Beispielkarte wird im Grid-Modus der erste angegebene ", "Rasterabstand verwendet. Im Random-Modus werden die erste ", "Kamerazahl und der erste Fokusanteil verwendet." ), actionButton("design_btn", "Beispiel-Design neu ziehen", class = "btn-primary") ), mainPanel( width = 9, plotOutput("design_plot", height = 650), verbatimTextOutput("design_summary") ) ) ), tabPanel( "Speichern", fluidRow( column( 7, h3("Setup für die Poweranalyse speichern"), p( "Die RData-Datei enthält die vier Objekte ", code("CFG"), ", ", code("AREA"), ", ", code("SPECIES"), " und ", code("HABITAT"), "." ), downloadButton("download_rdata", "simulations_setup.RData speichern", class = "btn-primary"), br(), br(), h4("Später im Poweranalyse-Skript"), tags$pre( 'load("simulations_setup.RData")\n\n', '# Danach stehen zur Verfügung:\n', 'str(CFG)\n', 'names(AREA)\n', 'SPECIES$Rehwild\n', 'HABITAT\n\n', '# Beispiel:\n', 'ans <- run_power_analysis(species_names = names(SPECIES), cfg = CFG)' ) ), column( 5, h4("Validierung"), verbatimTextOutput("validation") ) ) ) ) # --------------------------------------------------------------------------- # Server # --------------------------------------------------------------------------- server <- function(input, output, session) { species_rv <- reactiveVal(default_SPECIES) area_rv <- reactiveVal(make_area_from_cfg(default_CFG)) tracks_rv <- reactiveVal(NULL) design_rv <- reactiveVal(NULL) cfg_current <- reactive({ years <- parse_num_vector(input$years, integer = TRUE) if (!length(years)) years <- 1:5 camera_numbers <- parse_num_vector( input$camera_numbers, integer = TRUE, min_value = 1 ) if (!length(camera_numbers)) camera_numbers <- default_CFG$camera_numbers allocations_focus <- parse_num_vector( input$allocations_focus, min_value = 0, max_value = 1 ) if (!length(allocations_focus)) { allocations_focus <- default_CFG$allocations_focus } grid_spacings <- parse_num_vector( input$grid_spacings_m, min_value = 0.1 ) if (!length(grid_spacings)) grid_spacings <- default_CFG$grid_spacings_m list( crs = as.integer(input$crs), years = sort(unique(years)), survey_days = as.integer(input$survey_days), fixes_per_day = as.integer(input$fixes_per_day), n_replicates = as.integer(input$n_replicates), alpha = input$alpha, target_power = input$target_power, camera_design_mode = input$camera_design_mode, camera_numbers = camera_numbers, allocations_focus = allocations_focus, min_camera_spacing_m = input$min_camera_spacing_m, grid_spacings_m = grid_spacings, grid_random_rotation = isTRUE(input$grid_random_rotation), grid_clip_to = input$grid_clip_to, focus_radius_m = input$focus_radius_m, buffer_width_m = input$buffer_width_m, landscape_margin_m = input$landscape_margin_m, detection_radius_m = input$detection_radius_m, p_detect_5m = input$p_detect_5m, p_detect_18m = input$p_detect_18m, independence_minutes = input$independence_minutes, focus_use_multiplier_end = input$focus_use_multiplier_end, annual_population_change = input$annual_population_change, permanent_cameras = isTRUE(input$permanent_cameras) ) }) habitat_current <- reactive({ list( enabled = isTRUE(input$habitat_enabled), apply_to = input$habitat_apply_to, ridge_intercept_m = input$ridge_intercept_m, ridge_slope = input$ridge_slope, ridge_sd_m = input$ridge_sd_m, rugged_x_scale_m = input$rugged_x_scale_m, rugged_y_scale_m = input$rugged_y_scale_m, rugged_min = input$rugged_min, minimum_weight = input$minimum_weight ) }) # Artprofil-Felder beim Wechsel aktualisieren observeEvent(input$species_edit, { sp <- species_rv()[[input$species_edit]] updateNumericInput(session, "sp_n_animals", value = sp$n_animals) updateNumericInput(session, "sp_home_range_ha", value = sp$home_range_ha) updateNumericInput(session, "sp_step_scale_m", value = sp$step_scale_m) updateNumericInput(session, "sp_n_attraction_points", value = sp$n_attraction_points) updateNumericInput(session, "sp_attraction_strength", value = sp$attraction_strength) updateNumericInput(session, "sp_resting_probability", value = sp$resting_probability) updateNumericInput(session, "sp_speed_km_day", value = sp$speed_km_day) updateNumericInput(session, "sp_group_size_mean", value = sp$group_size_mean) }, ignoreInit = FALSE) observeEvent(input$save_species, { req(input$species_edit) sp <- species_rv() sp[[input$species_edit]] <- list( n_animals = as.integer(input$sp_n_animals), home_range_ha = input$sp_home_range_ha, step_scale_m = input$sp_step_scale_m, n_attraction_points = as.integer(input$sp_n_attraction_points), attraction_strength = input$sp_attraction_strength, resting_probability = input$sp_resting_probability, speed_km_day = input$sp_speed_km_day, group_size_mean = input$sp_group_size_mean ) species_rv(sp) showNotification( paste("Artprofil", input$species_edit, "übernommen."), type = "message" ) }) output$species_table <- renderDT({ datatable( species_to_df(species_rv()), rownames = FALSE, options = list(scrollX = TRUE, pageLength = 3, dom = "t") ) }) # Study Area explizit neu aufbauen observeEvent(input$build_area, { cfg <- cfg_current() tryCatch({ if (input$area_mode == "uploaded") { req(input$focus_shape) focus <- read_uploaded_shape(input$focus_shape, cfg$crs) area <- make_area_from_focus(focus, cfg) } else { area <- make_area_from_cfg(cfg) } area_rv(area) design_rv(NULL) tracks_rv(NULL) showNotification( "Study Area wurde aktualisiert.", type = "message" ) }, error = function(e) { showNotification(e$message, type = "error", duration = NULL) }) }) output$area_plot <- renderPlot({ area <- area_rv() ggplot() + geom_sf( data = area$landscape, fill = "grey96", colour = "grey70", linewidth = 0.4 ) + geom_sf( data = area$buffer, fill = "#9ecae1", alpha = 0.45, colour = "#3182bd" ) + geom_sf( data = area$focus, fill = "#fdae6b", alpha = 0.65, colour = "#e6550d" ) + coord_sf() + labs( title = "Aktuelle Study Area", subtitle = paste( "Quelle:", ifelse(area$source == "uploaded", "hochgeladene Fokusfläche", "generierte Kreisfläche") ), x = NULL, y = NULL ) + theme_bw() }) output$area_table <- renderDT({ datatable( area_summary_table(area_rv()), rownames = FALSE, options = list(dom = "t") ) }) # Habitatkarte: rasterisiert nur für die Vorschau output$habitat_plot <- renderPlot({ area <- area_rv() hab <- habitat_current() bb <- st_bbox(area$landscape) nx <- 100 ny <- 100 grid <- expand.grid( x = seq(bb["xmin"], bb["xmax"], length.out = nx), y = seq(bb["ymin"], bb["ymax"], length.out = ny) ) pts <- st_as_sf(grid, coords = c("x", "y"), crs = st_crs(area$landscape)) inside <- lengths(st_within(pts, area$landscape)) > 0 grid <- grid[inside, , drop = FALSE] grid$weight <- habitat_weight( grid$x, grid$y, hab$apply_to, hab ) ggplot(grid, aes(x = x, y = y, fill = weight)) + geom_raster() + geom_sf( data = area$focus, inherit.aes = FALSE, fill = NA, colour = "white", linewidth = 0.8 ) + geom_sf( data = area$outer, inherit.aes = FALSE, fill = NA, colour = "black", linewidth = 0.5 ) + coord_sf(crs = st_crs(area$landscape)) + scale_fill_viridis_c(limits = c(0, 1)) + labs( title = paste("Habitatgewichtung:", hab$apply_to), fill = "Gewicht", x = NULL, y = NULL ) + theme_bw() }) # Sample Tracks observeEvent(input$simulate_tracks_btn, { cfg <- cfg_current() area <- area_rv() spp <- species_rv() hab <- habitat_current() withProgress(message = "Sample Tracks werden simuliert ...", value = 0, { out <- lapply(seq_along(spp), function(i) { incProgress(1 / length(spp), detail = names(spp)[i]) simulate_one_track( species = names(spp)[i], pars = spp[[i]], area = area, cfg = cfg, habitat = hab, days = input$track_days, fixes_per_day = input$track_fixes_day ) }) tracks_rv(rbindlist(out)) }) }) output$tracks_plot <- renderPlot({ tr <- tracks_rv() area <- area_rv() validate( need(!is.null(tr), "Auf „Sample Tracks für alle Arten simulieren“ klicken.") ) ggplot() + geom_sf( data = area$outer, fill = "grey96", colour = "grey70" ) + geom_sf( data = area$focus, fill = "#fdae6b", alpha = 0.30, colour = "#e6550d" ) + geom_path( data = tr, aes(x = x, y = y, colour = species), linewidth = 0.45, alpha = 0.85 ) + geom_point( data = tr[, .SD[1], by = species], aes(x = x, y = y, colour = species), size = 2.5 ) + coord_sf(crs = st_crs(area$outer)) + facet_wrap(~species) + labs( title = "Exemplarischer Sample Track je Wildart", subtitle = "Ein simuliertes Individuum je Art", colour = "Wildart", x = NULL, y = NULL ) + theme_bw() }) # Beispiel-Study-Design make_design <- function() { cfg <- cfg_current() area <- area_rv() tryCatch( make_camera_design_gui(area, cfg), error = function(e) { showNotification(e$message, type = "error", duration = NULL) NULL } ) } observeEvent(input$design_btn, { design_rv(make_design()) }) output$design_plot <- renderPlot({ cams <- design_rv() area <- area_rv() if (is.null(cams)) { cams <- make_design() validate(need(!is.null(cams), "Kein Design erzeugt.")) } ggplot() + geom_sf( data = area$buffer, fill = "#9ecae1", alpha = 0.35, colour = "#3182bd" ) + geom_sf( data = area$focus, fill = "#fdae6b", alpha = 0.50, colour = "#e6550d" ) + geom_sf( data = cams, aes(colour = zone), size = 2.1 ) + coord_sf() + labs( title = "Exemplarisches Kameradesign", subtitle = paste(nrow(cams), "Kamerastandorte"), colour = "Zone", x = NULL, y = NULL ) + theme_bw() }) output$design_summary <- renderPrint({ cams <- design_rv() if (is.null(cams)) { cat("Noch kein explizit neu gezogenes Design.\n") return() } cat("Anzahl Kameras:", nrow(cams), "\n") cat("Fokus:", sum(cams$zone == "Fokus"), "\n") cat("Buffer:", sum(cams$zone == "Buffer"), "\n") if ("grid_spacing_m" %in% names(cams)) { cat("Grid-Abstand:", unique(cams$grid_spacing_m), "m\n") cat("Grid-Winkel:", round(unique(cams$grid_angle_deg), 1), "Grad\n") } }) output$cfg_preview <- renderPrint({ str(cfg_current(), max.level = 1) }) output$validation <- renderPrint({ cfg <- cfg_current() area <- area_rv() spp <- species_rv() hab <- habitat_current() issues <- character() if (cfg$p_detect_18m >= cfg$p_detect_5m) { issues <- c( issues, "WARNUNG: P(Detektion bei 18 m) ist nicht kleiner als bei 5 m." ) } if (cfg$detection_radius_m < 18) { issues <- c( issues, "Hinweis: Detektionsradius ist kleiner als der Kalibrierpunkt 18 m." ) } if (cfg$fixes_per_day < 96) { issues <- c( issues, "Hinweis: Wenige Positionen/Tag können kurze Kamerapassagen verpassen." ) } if (!length(cfg$grid_spacings_m)) { issues <- c(issues, "FEHLER: Kein Grid-Abstand angegeben.") } if (any(vapply(spp, function(x) x$home_range_ha <= 0, logical(1)))) { issues <- c(issues, "FEHLER: Streifgebietsgrößen müssen > 0 sein.") } if (isTRUE(hab$enabled) && hab$ridge_sd_m <= 0) { issues <- c(issues, "FEHLER: Habitat ridge_sd_m muss > 0 sein.") } cat("CRS:", cfg$crs, "\n") cat("Study-Area-Quelle:", area$source, "\n") cat("Wildarten:", paste(names(spp), collapse = ", "), "\n") cat("Design:", cfg$camera_design_mode, "\n") if (!length(issues)) { cat("\nOK: Keine offensichtlichen Parameterkonflikte erkannt.\n") } else { cat("\n", paste(issues, collapse = "\n"), "\n", sep = "") } }) output$download_rdata <- downloadHandler( filename = function() { paste0("simulations_setup_", format(Sys.Date(), "%Y%m%d"), ".RData") }, content = function(file) { CFG <- cfg_current() AREA <- area_rv() SPECIES <- species_rv() HABITAT <- habitat_current() save(CFG, AREA, SPECIES, HABITAT, file = file, compress = "xz") } ) } shinyApp(ui, server)