diff --git a/.Rbuildignore b/.Rbuildignore index 4202cc4..f408003 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -5,10 +5,11 @@ ^INPUT\.md$ ^CONTRIBUTING\.md$ ^scripts$ +^site$ +^_site$ ^study$ ^output$ ^references$ -^OpenPVA\.png$ ^\.github$ ^\.vscode$ ^.*\.Rcheck$ diff --git a/.github/workflows/site.yaml b/.github/workflows/site.yaml new file mode 100644 index 0000000..be87e55 --- /dev/null +++ b/.github/workflows/site.yaml @@ -0,0 +1,56 @@ +name: Build and deploy documentation site + +on: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + pages: write + id-token: write + +concurrency: + group: pages + cancel-in-progress: false + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: r-lib/actions/setup-r@v2 + with: + r-version: release + use-public-rspm: true + + - name: Install OpenPVA and litedown + shell: Rscript {0} + run: | + install.packages("litedown") + + - name: Build and install package with vignettes + run: | + R CMD build . + R CMD INSTALL --no-multiarch --with-keep.source OpenPVA_*.tar.gz + rm -f OpenPVA_*.tar.gz + + - name: Build static site with litedown::pkg_site() + run: Rscript --vanilla scripts/build_site.R _site + + - name: Upload Pages artifact + uses: actions/upload-pages-artifact@v3 + with: + path: _site + + deploy: + needs: build + runs-on: ubuntu-latest + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v4 diff --git a/.gitignore b/.gitignore index 8a021a7..0ac442c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ /output/ +/_site/ .DS_Store .Rhistory .RData diff --git a/AGENTS.md b/AGENTS.md index dd22fa4..f16c54c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,7 +12,7 @@ OpenPVA is a modern, open-R descendant of the GAPPS construction philosophy—bu so conservation biologists (and their AI agents) can compose transparent, inspectable, individual-based Population Viability Analyses in ordinary R. -## Core architecture (OpenPVA 2.2.0) +## Core architecture (OpenPVA 2.3.0) - **One unified, pure-base-R engine:** `NeedsCompilation: no`, `Depends: R (>= 4.1.0)`, and runtime `Imports` restricted to base/recommended packages (`codetools`, diff --git a/DESCRIPTION b/DESCRIPTION index aa89b25..4e2b32d 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,6 +1,6 @@ Package: OpenPVA Title: Composable Individual-Based Population Viability Analysis -Version: 2.2.0 +Version: 2.3.0 Authors@R: person("Barry W.", "Brook", email = "barry.brook@utas.edu.au", role = c("aut", "cre", "cph")) @@ -19,8 +19,8 @@ Description: An execution engine for individual-based population viability report heterozygosity, allelic retention and founder representation. Ensemble helpers separate structural and parametric designs from Monte Carlo replicates and report viability summaries with Monte Carlo - standard errors, and base-graphics plot methods display trajectories, - risk and accounting. + standard errors, and base-graphics plot methods display lifecycle flow + diagrams, trajectories, risk, accounting and ensemble contrasts. License: MIT + file LICENSE Encoding: UTF-8 Depends: R (>= 4.1.0) diff --git a/NAMESPACE b/NAMESPACE index 49af906..29b3e44 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,6 +1,11 @@ +S3method("[",pva_ensemble) +S3method("[",pva_lifecycle) S3method(plot,pva_ensemble) +S3method(plot,pva_lifecycle) S3method(plot,pva_run) +S3method(plot,pva_scenario) S3method(print,pva_ensemble) +S3method(print,pva_lifecycle) S3method(print,pva_process) S3method(print,pva_run) S3method(print,pva_scenario) @@ -15,11 +20,13 @@ export(catastrophe_process) export(ceiling_density_multiplier) export(ceiling_process) export(census_process) +export(describe_lifecycle) export(dispersal_process) export(env_ar1) export(env_trend) export(environment_process) export(execute_processes) +export(format_lifecycle) export(genetic_metrics) export(inbreeding_multiplier) export(inbreeding_proxy_process) diff --git a/NEWS.md b/NEWS.md index 140828d..0234a40 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,34 @@ # OpenPVA news +## OpenPVA 2.3.0 + +- Visual lifecycle translation and inspection: `describe_lifecycle()` audits any + `pva_scenario`, `pva_run`, or process list into an ordered `pva_lifecycle` + data frame classifying ecological roles and inter-process data flows + (`same_interval` and `carryover`). `plot()` on a `pva_scenario` or + `pva_lifecycle` draws a pure-base-R node-and-edge lifecycle flow diagram + (single row up to 5 steps, two-row clockwise loop for 6+ steps). + `format_lifecycle()` exports plain-text summaries, Mermaid flowcharts, and + Graphviz DOT specifications without perturbing the RNG. +- Presentation, documentation, and site infrastructure: added the OpenPVA hex + logo (`man/figures/logo.png` / `scripts/logo.svg`), reproducible 3-panel + README hero graphic (`scripts/make_readme_hero.R`), refreshed `README.md`, + Zenodo Concept DOI in `inst/CITATION`, updated `docs/vision_and_scope.md`, + an agent-first modelling guide (`docs/for-agents.md`), a new visual workflow + vignette (`vignette("workflow", package = "OpenPVA")`), and a self-contained + `litedown::pkg_site()` documentation site (`site/`, `scripts/build_site.R`, + GitHub Pages workflow). +- Ergonomic fixes: `shift_logit()` now accepts empty `logical(0)` from `ifelse()` + when an extinct replicate hits `N == 0` while keeping strict validation on + non-empty inputs; `[.pva_ensemble` preserves provenance attributes across + data-frame subsetting; and `plot.pva_ensemble()` honours scalar or per-member + `col`. +- *Development provenance:* Developed iteratively in-house by Barry W. Brook + and Google Gemini 4 Neon (presentation, visual inspection, documentation, + and UX polish on top of the frozen `2.2.0` simulation core), with an + independent read-only cross-lab challenge audit by OpenAI Codex + (`gpt-6.2-astra`). + ## OpenPVA 2.2.0 - Target removals, ceilings, translocations and individual treatments with diff --git a/R/ensemble.R b/R/ensemble.R index 57145e9..875d559 100644 --- a/R/ensemble.R +++ b/R/ensemble.R @@ -236,6 +236,18 @@ summarise_accounting <- function(result) { out } +`[.pva_ensemble` <- function(x, ...) { + prov <- attr(x, "provenance") + out <- NextMethod("[") + if (is.data.frame(out) && !is.null(prov)) { + attr(out, "provenance") <- prov + if (!inherits(out, "pva_ensemble")) { + class(out) <- c("pva_ensemble", class(out)) + } + } + out +} + print.pva_ensemble <- function(x, ...) { prov <- attr(x, "provenance") cat(sprintf("\n", diff --git a/R/lifecycle.R b/R/lifecycle.R new file mode 100644 index 0000000..ffd86b8 --- /dev/null +++ b/R/lifecycle.R @@ -0,0 +1,781 @@ +.lifecycle_roles <- list( + environment = list(label = "Environment", stroke = "#2E6F9E", fill = "#ECF4FA", text = "#173D59"), + demography = list(label = "Demography", stroke = "#1B6B78", fill = "#E7F4F6", text = "#0F3D45"), + spatial = list(label = "Spatial", stroke = "#2A8565", fill = "#E8F6F0", text = "#144736"), + management = list(label = "Management", stroke = "#C97A24", fill = "#FDF3E6", text = "#6E3F0C"), + survey = list(label = "Survey", stroke = "#72559B", fill = "#F3EFF9", text = "#3D2A57"), + census = list(label = "Census", stroke = "#4D646E", fill = "#EEF3F5", text = "#25343A"), + custom = list(label = "Custom", stroke = "#5D6D76", fill = "#F2F4F6", text = "#2B363C") +) + +.lifecycle_role <- function(process) { + if (identical(environment(process$run), environment(.run_survey)) && + (identical(process$run, .run_survey) || + identical(utils::removeSource(process$run), utils::removeSource(.run_survey)))) { + return("survey") + } + nm <- tolower(process$name) + desc <- tolower(if (is.null(process$description)) "" else process$description) + writes <- process$writes + creates <- process$creates + + if (!length(writes) && is.null(creates)) { + if (grepl("census|observe|record|count", paste(nm, desc))) { + return("census") + } + return("custom") + } + if (grepl("inbreed", paste(nm, desc))) { + return("demography") + } + if (grepl("catastroph|environment|climate|weather|cyclone|storm|drought", paste(nm, desc)) || + (length(writes) && all(grepl("^globals\\.", writes)) && !grepl("survey", nm))) { + return("environment") + } + if ("population.patch_id" %in% writes || grepl("dispers|move|\\bmigrat", desc)) { + return("spatial") + } + if (grepl("remov|harvest|cull|ceil|introduc|releas|transloc|assign|treat|quota", paste(nm, desc))) { + return("management") + } + if (!is.null(creates) && grepl("reproduc|birth|breed|offspring|litter", paste(nm, desc))) { + return("demography") + } + if (!is.null(creates)) { + return("management") + } + if (any(writes %in% c("population.age", "population.alive")) || + grepl("surviv|age|mating|pair|inbreed|breed|reproduc", paste(nm, desc))) { + return("demography") + } + "custom" +} + +.lifecycle_extract_processes <- function(x, state = NULL) { + meta <- list( + scenario_name = NULL, + n_runs = NA_integer_, + n_steps = NA_integer_, + dt = NA_real_, + seed = NA_integer_, + has_initial_census = FALSE, + state = NULL + ) + + if (inherits(x, "pva_lifecycle")) { + return(list(already = x)) + } + state_source <- "supplied" + if (inherits(x, "pva_run")) { + if (is.null(state) && length(x$states)) { + state <- x$states[[1L]] + state_source <- "final" + } + x <- x$scenario + } + if (inherits(x, "pva_scenario")) { + meta$scenario_name <- x$name + meta$n_runs <- x$n_runs + meta$n_steps <- x$n_steps + meta$dt <- x$dt + meta$seed <- if (is.null(x$seed)) NA_integer_ else x$seed + meta$has_initial_census <- !is.null(x$initial_census) + processes <- x$processes + initial <- x$initial_census + } else if (is.list(x)) { + processes <- validate_processes(x) + initial <- NULL + } else { + .stop("x must be a pva_scenario, pva_run, pva_lifecycle, or list of pva_process objects") + } + + if (!is.null(state)) { + state <- .validate_state(state) + meta$state <- list( + n_living = length(state$population$id), + source = state_source, + fields = names(state$population), + pedigree = !is.null(state$kinship), + n_loci = if (is.null(state$markers)) 0L else state$markers$n_loci, + mate_field = if (is.null(state$sires)) NULL else state$sires$field + ) + } + + list(processes = processes, initial = initial, meta = meta) +} + +.lifecycle_edges <- function(processes) { + n <- length(processes) + if (!n) { + return(data.frame( + from_step = integer(), + to_step = integer(), + from_name = character(), + to_name = character(), + field = character(), + kind = character(), + stringsAsFactors = FALSE + )) + } + writes_list <- lapply(processes, `[[`, "writes") + requires_list <- lapply(processes, `[[`, "requires") + names_vec <- vapply(processes, `[[`, character(1), "name") + + from_step <- integer() + to_step <- integer() + field_vec <- character() + kind_vec <- character() + + for (j in seq_len(n)) { + reqs <- setdiff(requires_list[[j]], "population.alive") + for (f in reqs) { + writers <- which(vapply(writes_list, function(w) f %in% w, logical(1))) + if (!length(writers)) next + earlier <- writers[writers < j] + if (length(earlier)) { + src <- max(earlier) + from_step <- c(from_step, src) + to_step <- c(to_step, j) + field_vec <- c(field_vec, f) + kind_vec <- c(kind_vec, "same_interval") + } else { + later <- writers[writers > j] + if (length(later)) { + src <- max(later) + from_step <- c(from_step, src) + to_step <- c(to_step, j) + field_vec <- c(field_vec, f) + kind_vec <- c(kind_vec, "carryover") + } + } + } + } + + data.frame( + from_step = from_step, + to_step = to_step, + from_name = names_vec[from_step], + to_name = names_vec[to_step], + field = field_vec, + kind = kind_vec, + stringsAsFactors = FALSE + ) +} + +describe_lifecycle <- function(x, state = NULL) { + extracted <- .lifecycle_extract_processes(x, state = state) + if (!is.null(extracted$already)) { + if (!is.null(state)) { + state <- .validate_state(state) + meta <- attr(extracted$already, "metadata") + meta$state <- list( + n_living = length(state$population$id), + source = "supplied", + fields = names(state$population), + pedigree = !is.null(state$kinship), + n_loci = if (is.null(state$markers)) 0L else state$markers$n_loci, + mate_field = if (is.null(state$sires)) NULL else state$sires$field + ) + attr(extracted$already, "metadata") <- meta + } + return(extracted$already) + } + + processes <- extracted$processes + initial <- extracted$initial + meta <- extracted$meta + + make_row <- function(step, phase, proc) { + data.frame( + step = as.integer(step), + phase = phase, + name = proc$name, + role = .lifecycle_role(proc), + requires = paste(proc$requires, collapse = ", "), + writes = paste(proc$writes, collapse = ", "), + creates = if (is.null(proc$creates)) "" else paste(proc$creates, collapse = ", "), + description = if (is.null(proc$description)) "" else proc$description, + stringsAsFactors = FALSE + ) + } + + rows <- list() + if (!is.null(initial)) { + rows[[length(rows) + 1L]] <- make_row(0L, "initial", initial) + } + for (i in seq_along(processes)) { + rows[[length(rows) + 1L]] <- make_row(i, "interval", processes[[i]]) + } + + out <- if (length(rows)) { + do.call(rbind, rows) + } else { + data.frame( + step = integer(), phase = character(), name = character(), role = character(), + requires = character(), writes = character(), creates = character(), + description = character(), stringsAsFactors = FALSE + ) + } + rownames(out) <- NULL + class(out) <- c("pva_lifecycle", "data.frame") + attr(out, "edges") <- .lifecycle_edges(processes) + attr(out, "metadata") <- meta + out +} + +`[.pva_lifecycle` <- function(x, ...) { + out <- NextMethod("[") + if (is.data.frame(out)) { + attr(out, "edges") <- NULL + attr(out, "metadata") <- NULL + class(out) <- setdiff(class(out), "pva_lifecycle") + } + out +} + +print.pva_lifecycle <- function(x, ...) { + meta <- attr(x, "metadata") + edges <- attr(x, "edges") + n_interval <- sum(x$phase == "interval") + header_parts <- character() + if (!is.null(meta$scenario_name)) { + header_parts <- c(header_parts, sprintf("'%s'", meta$scenario_name)) + } + if (!is.null(meta$n_runs) && !is.na(meta$n_runs)) { + header_parts <- c(header_parts, sprintf("%d runs x %d steps (dt = %g)", meta$n_runs, meta$n_steps, meta$dt)) + } + step_label <- sprintf( + "%d interval %s%s", + n_interval, + if (n_interval == 1L) "process" else "processes", + if (isTRUE(meta$has_initial_census)) " + initial census" else "" + ) + header_parts <- c(header_parts, step_label) + if (!is.null(meta$state)) { + st <- meta$state + n_tag <- if (identical(st$source, "final")) "N_end" else "N" + st_bits <- c( + sprintf("%s = %d", n_tag, st$n_living), + if (st$pedigree) "pedigree: on" else "pedigree: off", + if (st$n_loci > 0L) sprintf("loci: %d", st$n_loci) else NULL, + if (!is.null(st$mate_field)) sprintf("mate_field: %s", st$mate_field) else NULL + ) + header_parts <- c(header_parts, paste(st_bits, collapse = ", ")) + } + cat(sprintf("\n", paste(header_parts, collapse = " | "))) + + display <- x[, c("step", "phase", "name", "role", "requires", "writes", "creates"), drop = FALSE] + for (col in c("requires", "writes", "creates")) { + display[[col]][!nzchar(display[[col]])] <- "-" + } + print.data.frame(display, row.names = FALSE, right = FALSE) + + if (is.data.frame(edges) && nrow(edges)) { + flow_txt <- vapply(seq_len(nrow(edges)), function(i) { + tag <- if (edges$kind[[i]] == "carryover") " [next interval]" else "" + sprintf("%s -> %s (%s)%s", edges$from_name[[i]], edges$to_name[[i]], edges$field[[i]], tag) + }, character(1)) + cat(sprintf("Data flows (%d): %s\n", nrow(edges), paste(flow_txt, collapse = "; "))) + } + invisible(x) +} + +.short_field <- function(x) { + sub("^(population|globals)\\.", "", x) +} + +.escape_dot <- function(x) { + x <- gsub("\\\\", "\\\\\\\\", x) + gsub("\"", "\\\\\"", x) +} + +.escape_mermaid <- function(x) { + gsub("\"", "#quot;", x, fixed = TRUE) +} + +format_lifecycle <- function(x, format = c("text", "mermaid", "dot"), state = NULL) { + format <- match.arg(format) + lc <- describe_lifecycle(x, state = state) + edges <- attr(lc, "edges") + meta <- attr(lc, "metadata") + interval <- lc[lc$phase == "interval", , drop = FALSE] + + if (format == "text") { + lines <- utils::capture.output(print(lc)) + return(paste(lines, collapse = "\n")) + } + + if (format == "mermaid") { + lines <- c("flowchart LR") + if (isTRUE(meta$has_initial_census)) { + init_row <- lc[lc$phase == "initial", , drop = FALSE][1L, ] + lines <- c( + lines, + sprintf(' S0["0. %s (t = 0)"]:::census', .escape_mermaid(init_row$name)) + ) + } + for (i in seq_len(nrow(interval))) { + nm <- .escape_mermaid(interval$name[[i]]) + sub_bits <- character() + if (nzchar(interval$writes[[i]])) { + w <- paste(.short_field(trimws(strsplit(interval$writes[[i]], ",")[[1L]])), collapse = ", ") + sub_bits <- c(sub_bits, paste0("writes: ", w)) + } + if (nzchar(interval$creates[[i]])) { + sub_bits <- c(sub_bits, paste0("creates: ", interval$creates[[i]])) + } + lbl <- if (length(sub_bits)) { + sprintf("%d. %s (%s)", interval$step[[i]], nm, .escape_mermaid(paste(sub_bits, collapse = "; "))) + } else { + sprintf("%d. %s", interval$step[[i]], nm) + } + lines <- c(lines, sprintf(' S%d["%s"]:::%s', interval$step[[i]], lbl, interval$role[[i]])) + } + if (isTRUE(meta$has_initial_census) && nrow(interval)) { + lines <- c(lines, sprintf(" S0 --> S%d", interval$step[[1L]])) + } + if (nrow(interval) > 1L) { + for (i in seq_len(nrow(interval) - 1L)) { + lines <- c(lines, sprintf(" S%d ==> S%d", interval$step[[i]], interval$step[[i + 1L]])) + } + } + if (nrow(interval) >= 1L) { + dt_lbl <- if (!is.na(meta$dt)) sprintf("t + %g", meta$dt) else "next interval" + lines <- c(lines, sprintf(' S%d -. "%s" .-> S%d', + interval$step[[nrow(interval)]], dt_lbl, interval$step[[1L]])) + } + if (is.data.frame(edges) && nrow(edges)) { + for (i in seq_len(nrow(edges))) { + fld <- .escape_mermaid(.short_field(edges$field[[i]])) + tag <- if (edges$kind[[i]] == "carryover") paste0(fld, " (carryover)") else fld + lines <- c(lines, sprintf(' S%d -. "%s" .-> S%d', + edges$from_step[[i]], tag, edges$to_step[[i]])) + } + } + roles_used <- unique(lc$role) + for (r in roles_used) { + pal <- .lifecycle_roles[[r]] + lines <- c(lines, sprintf(" classDef %s fill:%s,stroke:%s,color:%s,stroke-width:2px", + r, pal$fill, pal$stroke, pal$text)) + } + return(paste(lines, collapse = "\n")) + } + + # Graphviz DOT format + lines <- c( + "digraph OpenPVA_Lifecycle {", + ' rankdir=LR;', + ' node [shape=box, style="rounded,filled", fontname="Helvetica", fontsize=10];', + ' edge [fontname="Helvetica", fontsize=9];' + ) + if (isTRUE(meta$has_initial_census)) { + init_row <- lc[lc$phase == "initial", , drop = FALSE][1L, ] + pal <- .lifecycle_roles[["census"]] + lines <- c( + lines, + sprintf(' S0 [label="0. %s\\n(t = 0)", fillcolor="%s", color="%s", fontcolor="%s"];', + .escape_dot(init_row$name), pal$fill, pal$stroke, pal$text) + ) + } + for (i in seq_len(nrow(interval))) { + pal <- .lifecycle_roles[[interval$role[[i]]]] + sub_bits <- character() + if (nzchar(interval$writes[[i]])) { + w <- paste(.short_field(trimws(strsplit(interval$writes[[i]], ",")[[1L]])), collapse = ", ") + sub_bits <- c(sub_bits, paste0("writes: ", w)) + } + if (nzchar(interval$creates[[i]])) { + sub_bits <- c(sub_bits, paste0("creates: ", interval$creates[[i]])) + } + lbl <- if (length(sub_bits)) { + sprintf("%d. %s\\n%s", interval$step[[i]], .escape_dot(interval$name[[i]]), + .escape_dot(paste(sub_bits, collapse = "; "))) + } else { + sprintf("%d. %s", interval$step[[i]], .escape_dot(interval$name[[i]])) + } + lines <- c( + lines, + sprintf(' S%d [label="%s", fillcolor="%s", color="%s", fontcolor="%s"];', + interval$step[[i]], lbl, pal$fill, pal$stroke, pal$text) + ) + } + if (isTRUE(meta$has_initial_census) && nrow(interval)) { + lines <- c(lines, sprintf(' S0 -> S%d [style=dashed, color="#4D646E"];', interval$step[[1L]])) + } + if (nrow(interval) > 1L) { + for (i in seq_len(nrow(interval) - 1L)) { + lines <- c(lines, sprintf(' S%d -> S%d [penwidth=2, color="#102C37"];', + interval$step[[i]], interval$step[[i + 1L]])) + } + } + if (nrow(interval) >= 1L) { + dt_lbl <- if (!is.na(meta$dt)) sprintf("next interval (t + %g)", meta$dt) else "next interval" + lines <- c(lines, sprintf(' S%d -> S%d [style=dashed, color="#8C9AA1", label="%s"];', + interval$step[[nrow(interval)]], interval$step[[1L]], dt_lbl)) + } + if (is.data.frame(edges) && nrow(edges)) { + for (i in seq_len(nrow(edges))) { + fld <- .escape_dot(.short_field(edges$field[[i]])) + col <- if (edges$kind[[i]] == "carryover") "#C97A24" else "#1B6B78" + lines <- c(lines, sprintf(' S%d -> S%d [style=dotted, color="%s", fontcolor="%s", label="%s"];', + edges$from_step[[i]], edges$to_step[[i]], col, col, fld)) + } + } + lines <- c(lines, "}") + paste(lines, collapse = "\n") +} + +.draw_rounded_box <- function(x0, y0, x1, y1, r, col, border, lwd = 1.6) { + rx <- min(r, (x1 - x0) / 4) + ry <- min(r * 1.15, (y1 - y0) / 4) + angles <- seq(0, pi / 2, length.out = 10L) + xs <- c( + x1 - rx + rx * cos(angles), + x0 + rx - rx * sin(angles), + x0 + rx - rx * cos(angles), + x1 - rx + rx * sin(angles) + ) + ys <- c( + y1 - ry + ry * sin(angles), + y1 - ry + ry * cos(angles), + y0 + ry - ry * sin(angles), + y0 + ry - ry * cos(angles) + ) + graphics::polygon(xs, ys, col = col, border = border, lwd = lwd) +} + +.draw_top_bar <- function(x0, y0, x1, y1, r, col) { + rx <- min(r, (x1 - x0) / 4) + ry <- min(r * 1.15, (y1 - y0) / 2) + angles <- seq(0, pi / 2, length.out = 10L) + xs <- c( + x1, + x1 - rx + rx * cos(angles), + x0 + rx - rx * sin(angles), + x0 + ) + ys <- c( + y0, + y1 - ry + ry * sin(angles), + y1 - ry + ry * cos(angles), + y0 + ) + graphics::polygon(xs, ys, col = col, border = NA) +} + +.draw_pill_label <- function(x, y, label, col, cex = 0.68) { + w <- graphics::strwidth(label, cex = cex, font = 3) + h <- graphics::strheight(label, cex = cex, font = 3) + pad_x <- 0.85 + pad_y <- 0.75 + graphics::rect( + x - w / 2 - pad_x, y - h / 2 - pad_y, + x + w / 2 + pad_x, y + h / 2 + pad_y, + col = grDevices::adjustcolor("white", alpha.f = 0.90), + border = NA + ) + graphics::text(x, y, label, cex = cex, col = col, font = 3) +} + +.draw_bezier <- function(x0, y0, cx, cy, x1, y1, col, lty = 1, lwd = 1.5, arrow = TRUE) { + t <- seq(0, 1, length.out = 36L) + bx <- (1 - t)^2 * x0 + 2 * (1 - t) * t * cx + t^2 * x1 + by <- (1 - t)^2 * y0 + 2 * (1 - t) * t * cy + t^2 * y1 + graphics::lines(bx, by, col = col, lty = lty, lwd = lwd) + if (arrow) { + n <- length(bx) + graphics::arrows(bx[n - 1L], by[n - 1L], bx[n], by[n], + length = 0.08, angle = 24, col = col, lwd = lwd) + } + c(x = bx[18L], y = by[18L]) +} + +.trunc_label <- function(text, width) { + if (nchar(text) <= width) return(text) + paste0(substr(text, 1L, max(1L, width - 3L)), "...") +} + +plot.pva_lifecycle <- function(x, show_flows = TRUE, main = NULL, ...) { + if (!inherits(x, "pva_lifecycle")) { + .stop("x must be created by describe_lifecycle()") + } + if (!.is_flag(show_flows) && !identical(show_flows, "all")) { + .stop("show_flows must be TRUE, FALSE or \"all\"") + } + meta <- attr(x, "metadata") + edges <- attr(x, "edges") + if (isTRUE(show_flows) && is.data.frame(edges) && nrow(edges) && + sum(edges$field == "population.age") > 2L) { + edges <- edges[edges$field != "population.age", , drop = FALSE] + } + draw_flows <- isTRUE(show_flows) || identical(show_flows, "all") + interval <- x[x$phase == "interval", , drop = FALSE] + n <- nrow(interval) + + if (is.null(main)) { + main <- if (!is.null(meta$scenario_name)) { + paste0(meta$scenario_name, ": lifecycle flow") + } else { + "OpenPVA lifecycle flow" + } + } + + sub_bits <- character() + if (!is.null(meta$n_runs) && !is.na(meta$n_runs)) { + sub_bits <- c(sub_bits, sprintf("%d runs x %d steps (dt = %g)", meta$n_runs, meta$n_steps, meta$dt)) + } + if (!is.null(meta$seed) && !is.na(meta$seed)) { + sub_bits <- c(sub_bits, sprintf("seed = %d", meta$seed)) + } + if (isTRUE(meta$has_initial_census)) { + sub_bits <- c(sub_bits, "initial census at t = 0") + } + if (!is.null(meta$state)) { + st <- meta$state + n_tag <- if (identical(st$source, "final")) "N_end" else "N" + sub_bits <- c( + sub_bits, + sprintf("%s = %d", n_tag, st$n_living), + if (st$pedigree) "pedigree = TRUE" else NULL, + if (st$n_loci > 0L) sprintf("n_loci = %d", st$n_loci) else NULL, + if (!is.null(st$mate_field)) sprintf("mate_field = '%s'", st$mate_field) else NULL + ) + } + + op <- graphics::par(mar = c(0.6, 0.6, 2.8, 0.6), xpd = NA) + on.exit(graphics::par(op), add = TRUE) + + graphics::plot.new() + graphics::plot.window(xlim = c(0, 100), ylim = c(0, 100)) + graphics::title(main = main, col.main = "#102C37", cex.main = 1.15, line = 1.4) + if (length(sub_bits)) { + graphics::mtext(paste(sub_bits, collapse = " | "), side = 3L, line = 0.2, + cex = 0.80, col = "#4A616A") + } + + if (!n) { + graphics::text(50, 52, "No interval processes", col = "#4A616A", cex = 1.0) + return(invisible(x)) + } + + # Layout: single horizontal row for <= 5 processes; 2-row clockwise loop for >= 6. + two_row <- n >= 6L + if (!two_row) { + n_cols <- n + margin_x <- 6 + gap_x <- if (n > 1L) 4.5 else 0 + box_w <- min(20, (100 - 2 * margin_x - (n_cols - 1L) * gap_x) / n_cols) + total_w <- n_cols * box_w + (n_cols - 1L) * gap_x + start_x <- (100 - total_w) / 2 + cx <- start_x + (seq_len(n) - 1L) * (box_w + gap_x) + box_w / 2 + cy <- rep(50, n) + box_h <- 20 + row_id <- rep(1L, n) + } else { + n_top <- ceiling(n / 2) + n_bot <- n - n_top + n_cols <- max(n_top, n_bot) + margin_x <- if (n_cols <= 6L) 9 else 4 + avail_w <- 100 - 2 * margin_x + gap_x <- if (n_cols > 1L) min(4.5, avail_w / (3 * n_cols)) else 0 + box_w <- max(1.5, min(18.5, (avail_w - (n_cols - 1L) * gap_x) / n_cols)) + total_w <- n_cols * box_w + (n_cols - 1L) * gap_x + start_x <- (100 - total_w) / 2 + col_x <- start_x + (seq_len(n_cols) - 1L) * (box_w + gap_x) + box_w / 2 + # Clockwise loop: top row left->right, bottom row right->left + bot_cols <- rev(col_x[seq_len(n_bot)]) + if (n_bot < n_cols) { + bot_cols <- rev(seq(col_x[1L], col_x[n_cols], length.out = max(2L, n_bot)))[seq_len(n_bot)] + } + cx <- c(col_x[seq_len(n_top)], bot_cols) + cy <- c(rep(70, n_top), rep(30, n_bot)) + box_h <- 18 + row_id <- c(rep(1L, n_top), rep(2L, n_bot)) + } + + # 1. Execution backbone arrows + arrow_col <- "#102C37" + if (n > 1L) { + for (i in seq_len(n - 1L)) { + if (row_id[i] == row_id[i + 1L]) { + dir_x <- sign(cx[i + 1L] - cx[i]) + graphics::arrows( + cx[i] + dir_x * (box_w / 2 + 0.5), cy[i], + cx[i + 1L] - dir_x * (box_w / 2 + 0.5), cy[i + 1L], + length = 0.09, angle = 24, col = arrow_col, lwd = 2.0 + ) + } else { + # Turn cleanly down right-hand side from end of top row to start of bottom row + turn_x <- max(cx[i], cx[i + 1L]) + box_w / 2 + 3.5 + graphics::lines( + c(cx[i] + box_w / 2 + 0.4, turn_x, turn_x), + c(cy[i], cy[i], cy[i + 1L]), + col = arrow_col, lwd = 2.0 + ) + graphics::arrows( + turn_x, cy[i + 1L], + cx[i + 1L] + box_w / 2 + 0.6, cy[i + 1L], + length = 0.09, angle = 24, col = arrow_col, lwd = 2.0 + ) + } + } + } + + # 2. Cycle-return loop arrow (closes the interval back to step 1) + dt_lbl <- if (!is.na(meta$dt)) sprintf("next interval (t + %g)", meta$dt) else "next interval" + loop_col <- "#7D919A" + if (!two_row) { + y_bot <- cy[1L] - box_h / 2 - 11 + x_out <- if (n == 1L) cx[1L] + box_w * 0.24 else cx[n] + x_in <- if (n == 1L) cx[1L] - box_w * 0.24 else cx[1L] + graphics::lines( + c(x_out, x_out, x_in), + c(cy[n] - box_h / 2 - 0.5, y_bot, y_bot), + col = loop_col, lwd = 1.6, lty = 2 + ) + graphics::arrows( + x_in, y_bot, x_in, cy[1L] - box_h / 2 - 0.8, + length = 0.08, angle = 24, col = loop_col, lwd = 1.6 + ) + graphics::text((x_out + x_in) / 2, y_bot - 3.0, dt_lbl, cex = 0.74, col = "#5B6F78", font = 3) + } else { + left_x <- min(cx) - box_w / 2 - 3.8 + graphics::lines( + c(cx[n] - box_w / 2 - 0.4, left_x, left_x), + c(cy[n], cy[n], cy[1L]), + col = loop_col, lwd = 1.6, lty = 2 + ) + graphics::arrows( + left_x, cy[1L], cx[1L] - box_w / 2 - 0.6, cy[1L], + length = 0.08, angle = 24, col = loop_col, lwd = 1.6 + ) + graphics::text(left_x - 2.2, (cy[1L] + cy[n]) / 2, dt_lbl, + srt = 90, cex = 0.72, col = "#5B6F78", font = 3) + } + + # 3. Data-flow dependency arcs (drawn behind text labels, cleanly offset) + if (draw_flows && is.data.frame(edges) && nrow(edges)) { + # Collapse parallel edges between the same (from_step, to_step, kind) pair + keys <- paste(edges$from_step, edges$to_step, edges$kind, sep = ":") + uniq <- unique(keys) + # Track arc index per zone so multiple arcs stack gracefully without collision + zone_counts <- list(top = 0L, mid = 0L, bot = 0L) + for (u in uniq) { + sub_e <- edges[keys == u, , drop = FALSE] + s <- sub_e$from_step[[1L]] + t_idx <- sub_e$to_step[[1L]] + carry <- sub_e$kind[[1L]] == "carryover" + lbl <- paste(.short_field(sub_e$field), collapse = ", ") + if (carry) lbl <- paste0(lbl, " (t+1)") + fcol <- if (carry) "#C97A24" else "#1B6B78" + + if (!two_row) { + zone_counts$top <- zone_counts$top + 1L + lift <- 12 + 8 * (zone_counts$top - 1L) + y_edge <- cy[1L] + box_h / 2 + 0.5 + mid <- .draw_bezier( + cx[s], y_edge, (cx[s] + cx[t_idx]) / 2, y_edge + lift, + cx[t_idx], y_edge, col = fcol, lty = if (carry) 3 else 2, lwd = 1.45 + ) + .draw_pill_label(mid["x"], mid["y"] + 1.8, .trunc_label(lbl, 24L), col = fcol) + } else if (row_id[s] == 1L && row_id[t_idx] == 1L) { + zone_counts$top <- zone_counts$top + 1L + lift <- 9 + 6.5 * (zone_counts$top - 1L) + y_edge <- cy[s] + box_h / 2 + 0.5 + mid <- .draw_bezier( + cx[s], y_edge, (cx[s] + cx[t_idx]) / 2, min(97, y_edge + lift), + cx[t_idx], y_edge, col = fcol, lty = if (carry) 3 else 2, lwd = 1.45 + ) + .draw_pill_label(mid["x"], mid["y"] + 1.8, .trunc_label(lbl, 24L), col = fcol) + } else if (row_id[s] == 2L && row_id[t_idx] == 2L) { + zone_counts$bot <- zone_counts$bot + 1L + drop <- 9 + 6.5 * (zone_counts$bot - 1L) + y_edge <- cy[s] - box_h / 2 - 0.5 + mid <- .draw_bezier( + cx[s], y_edge, (cx[s] + cx[t_idx]) / 2, max(12, y_edge - drop), + cx[t_idx], y_edge, col = fcol, lty = if (carry) 3 else 2, lwd = 1.45 + ) + .draw_pill_label(mid["x"], mid["y"] - 1.9, .trunc_label(lbl, 24L), col = fcol) + } else { + # Cross-row flow through the clean central channel between y = 39 and y = 61 + zone_counts$mid <- zone_counts$mid + 1L + y_start <- if (row_id[s] == 1L) cy[s] - box_h / 2 - 0.5 else cy[s] + box_h / 2 + 0.5 + y_end <- if (row_id[t_idx] == 1L) cy[t_idx] - box_h / 2 - 0.5 else cy[t_idx] + box_h / 2 + 0.5 + x_shift <- ((zone_counts$mid %% 2L) * 2L - 1L) * (4.5 * ceiling(zone_counts$mid / 2)) + mid <- .draw_bezier( + cx[s], y_start, (cx[s] + cx[t_idx]) / 2 + x_shift, 50, + cx[t_idx], y_end, col = fcol, lty = if (carry) 3 else 2, lwd = 1.45 + ) + .draw_pill_label(mid["x"], mid["y"], .trunc_label(lbl, 22L), col = fcol) + } + } + } + + # 4. Process node boxes + for (i in seq_len(n)) { + role <- interval$role[[i]] + pal <- .lifecycle_roles[[role]] + x0 <- cx[i] - box_w / 2 + x1 <- cx[i] + box_w / 2 + y0 <- cy[i] - box_h / 2 + y1 <- cy[i] + box_h / 2 + + .draw_rounded_box(x0, y0, x1, y1, r = 1.6, col = pal$fill, border = NA) + # Crisp role-colored top bar with matching rounded upper corners + bar_h <- 4.5 + .draw_top_bar(x0, y1 - bar_h, x1, y1, r = 1.6, col = pal$stroke) + .draw_rounded_box(x0, y0, x1, y1, r = 1.6, col = NA, border = pal$stroke, lwd = 1.8) + graphics::text(x0 + 1.3, y1 - bar_h / 2, sprintf("%d", interval$step[[i]]), + adj = c(0, 0.5), cex = 0.72, font = 2, col = "white") + graphics::text(x1 - 1.2, y1 - bar_h / 2, pal$label, + adj = c(1, 0.5), cex = 0.62, col = "#F2F7F8") + + # Process name centered + max_chars <- max(10L, floor(box_w * 1.15)) + graphics::text(cx[i], cy[i] + 1.0, .trunc_label(interval$name[[i]], max_chars), + cex = 0.85, font = 2, col = pal$text) + + # Concise field-effect subtitle + tag <- if (nzchar(interval$creates[[i]])) { + cf <- trimws(strsplit(interval$creates[[i]], ",")[[1L]]) + extra <- setdiff(cf, c("sex", "age", "mother_id", "father_id")) + if (role == "demography") { + if (length(extra)) paste0("+ births (", paste(extra, collapse = ", "), ")") else "+ births" + } else { + if (length(extra)) paste0("+ releases (", paste(extra, collapse = ", "), ")") else "+ releases" + } + } else if (nzchar(interval$writes[[i]])) { + w <- .short_field(trimws(strsplit(interval$writes[[i]], ",")[[1L]])) + paste0("writes: ", paste(w, collapse = ", ")) + } else { + "observer" + } + graphics::text(cx[i], cy[i] - 4.3, .trunc_label(tag, max_chars + 5L), + cex = 0.67, col = "#4A616A") + } + + # 5. Compact bottom role legend (only roles actually present) + roles_used <- intersect(names(.lifecycle_roles), unique(interval$role)) + if (length(roles_used)) { + leg_labels <- vapply(roles_used, function(r) .lifecycle_roles[[r]]$label, character(1)) + leg_fills <- vapply(roles_used, function(r) .lifecycle_roles[[r]]$fill, character(1)) + leg_borders <- vapply(roles_used, function(r) .lifecycle_roles[[r]]$stroke, character(1)) + graphics::legend( + "bottom", + legend = leg_labels, + fill = leg_fills, + border = leg_borders, + horiz = TRUE, + bty = "n", + cex = 0.75, + inset = c(0, -0.02) + ) + } + + invisible(x) +} + +plot.pva_scenario <- function(x, state = NULL, show_flows = TRUE, main = NULL, ...) { + lc <- describe_lifecycle(x, state = state) + plot.pva_lifecycle(lc, show_flows = show_flows, main = main, ...) +} diff --git a/R/plot.R b/R/plot.R index 30a9b22..8a28aac 100644 --- a/R/plot.R +++ b/R/plot.R @@ -135,7 +135,9 @@ plot.pva_ensemble <- function(x, y = "p_ever_below", by = NULL, ...) { if (!.is_name(y) || !is.numeric(x[[y]])) { .stop("y must name one numeric summary column of the ensemble") } - if (is.null(by)) by <- attr(x, "provenance")$design + if (is.null(by)) { + by <- intersect(attr(x, "provenance")$design, names(x)) + } if (!is.character(by) || !length(by) || !all(by %in% names(x))) { .stop("by must name one or more columns of the ensemble") } @@ -156,6 +158,8 @@ plot.pva_ensemble <- function(x, y = "p_ever_below", by = NULL, ...) { ) position <- seq_len(nrow(table)) dots <- list(...) + ink <- rep_len(if (is.null(dots[["col"]])) "#1F4E79" else dots[["col"]], nrow(table)) + dots[["col"]] <- NULL xaxt <- if (is.null(dots$xaxt)) graphics::par("xaxt") else dots$xaxt dots$xaxt <- "n" .plot_frame( @@ -169,7 +173,7 @@ plot.pva_ensemble <- function(x, y = "p_ever_below", by = NULL, ...) { graphics::axis(1L, at = position, labels = label, xaxt = xaxt) } ok <- !is.na(lower) & !is.na(upper) - graphics::segments(position[ok], lower[ok], position[ok], upper[ok], col = "#1F4E79", lwd = 2) - graphics::points(position, estimate, pch = 21, bg = "white", col = "#1F4E79", cex = 1.3) + graphics::segments(position[ok], lower[ok], position[ok], upper[ok], col = ink[ok], lwd = 2) + graphics::points(position, estimate, pch = 21, bg = "white", col = ink, cex = 1.3) invisible(table) } diff --git a/R/processes_environment.R b/R/processes_environment.R index 5054006..3157724 100644 --- a/R/processes_environment.R +++ b/R/processes_environment.R @@ -327,11 +327,15 @@ qbeta_norm <- function(z, mean, sd) { } shift_logit <- function(probability, deviation) { + if (is.logical(probability) && !length(probability)) { + probability <- numeric(0) + } if (!is.numeric(probability) || anyNA(probability) || any(probability < 0 | probability > 1)) { .stop("probability must be non-missing values in [0, 1]") } if (!is.numeric(deviation) || anyNA(deviation)) .stop("deviation must be non-missing numeric") + if (!length(probability)) return(numeric(0)) result <- stats::plogis(stats::qlogis(probability) + deviation) p <- rep_len(probability, length(result)) result[p == 0 | p == 1] <- p[p == 0 | p == 1] diff --git a/README.md b/README.md index d8bf483..07f23c7 100644 --- a/README.md +++ b/README.md @@ -1,59 +1,49 @@ -# OpenPVA - -OpenPVA 2.2.0 is a modular, individual-based engine for population viability -analysis in R. A model specifies a population, the order of biological processes -within each interval, and the census that defines the risk endpoint. Processes -declare the fields they read, write and create. The engine assigns individual -IDs, tracks parentage, reconciles population changes and allocates a -reproducible random stream to each replicate. - -Install from this checkout with `R CMD INSTALL .`. The package uses base and -recommended R packages and supports R 4.1.0 and later. - -## What the engine provides - -- A columnar population of living individuals (`pva_population()`, - `pva_state()`), with the dead moved to an optional ledger. -- One generic execution loop with strict validation after every process: - declared writes, field types, engine-owned fields, and accounting reconciled - separately for existing and newly created individuals, by cohort. -- Exact pedigree inbreeding from recorded parentage, including a known sire - lost after mating. A declared mate field can retain a sire across seasons. Above the dense slot limit the engine traces ancestors of - the breeders, retaining any specified starting kinships. -- One preassigned L'Ecuyer-CMRG stream per replicate: results are bit-identical - on one core, on fork workers and on a PSOCK cluster. -- Reusable processes: `age_process()`, `survival_process()`, - `staged_survival_process()`, `reproduction_process()` with Poisson, bounded - and categorical litters, `pairing_process()` for mate and territory limits, - `removal_process()`, `ceiling_process()`, `introduction_process()`, - `environment_process()`, `catastrophe_process()`, - `inbreeding_proxy_process()`, dispersal among patches, and `census_process()`. -- Imperfect surveys on a separate random stream, with observation-based quotas - for removals, releases and treatment. -- Helpers: analytical life tables, age-by-sex rate tables, Beverton–Holt, Ricker and ceiling density - multipliers, lethal-equivalent inbreeding depression. -- Choose mates by pair kinship or give scarce territories to breeders with - low mean kinship to the living population. Both mating rules accept - `by = "patch_id"` for local mating. `summarise_pedigree()` reports founder - genome equivalents. `pva_state(n_loci = )` tracks neutral alleles on - independent segregation substreams, including in ensembles that start - from a shared family. -- `spatial_correlation()` supplies common or distance-dependent correlations - for `env_ar1()`. Named standard deviations follow their patches. - `env_trend()` adds deterministic changes or regime shifts. -- `run_scenario()`, `summarise_pva()` (first-crossing and horizon risk, time to - threshold and final abundance with Monte Carlo standard errors), - `summarise_trajectory()`, `summarise_accounting()` and `run_pva_ensemble()`, - which separates a structural, parametric and management design from the inner - Monte Carlo replicates. -- Base graphics show 50% and 90% trajectory ribbons, cumulative risk with - stepwise Wilson intervals, cohort accounting and ensemble contrasts. - Each plot returns its data and accepts annotations in the plotted coordinates. - -The vignette `vignette("rosetta", package = "OpenPVA")` translates GAPPS, -Vortex-style and Leslie-matrix idioms into process lists. - -## A minimal model +# OpenPVA OpenPVA hex logo + + +

+ Package check + DOI + License: MIT + R >= 4.1.0 +

+ + +> *The modeller defines the biological programme; OpenPVA supplies the execution engine, reusable processes, scientific contracts, and reproducible analysis machinery.* + +**OpenPVA** is a composable, individual-based Population Viability Analysis (PVA) engine written in pure base R. Instead of locking your species into a fixed menu-driven lifecycle, you assemble an explicit, ordered list of ordinary R processes—declaring what each step reads, writes, and creates—while the engine protects interval time, individual IDs, exact pedigree inbreeding, cohort accounting, and bit-identical parallel random streams. + +

+ OpenPVA 3-panel output showing stochastic population trajectories, cumulative quasi-extinction risk with Wilson intervals, and an ensemble management comparison +

+ +*Real OpenPVA output ([`scripts/make_readme_hero.R`](https://github.com/BWBrook/OpenPVA/blob/main/scripts/make_readme_hero.R)): 300 paired replicates of an island population with AR(1) environmental variation, cyclones, exact pedigree inbreeding depression, minimum-kinship mating, and imperfect biennial surveys (`p = 0.70`) triggering adaptive releases.* + +## Why OpenPVA + +- **Transparent, ordered biology:** A lifecycle is a plain R list of `pva_process()` objects. Repeat, reorder, omit, or add custom processes without touching the engine controller. +- **Engine-owned scientific invariants:** Strict validation after every process reconciles births, deaths, removals, introductions, and cohort stocks; preassigned L'Ecuyer-CMRG streams make serial, fork, and PSOCK parallel runs bit-identical. +- **Exact genetics & adaptive management out of the box:** Exact conditional pedigree inbreeding (dense matrix with automatic switch to level-batched sparse ancestor tracing), non-perturbing neutral-locus gene drop, kinship-aware and seasonal mating with cross-interval sire retention, and isolated-stream imperfect surveys driving management quotas. +- **Pure base R, zero runtime dependency bloat:** `NeedsCompilation: no`, `R (>= 4.1.0)`, and only base/recommended packages at runtime. + +## Installation + +Install the latest version from GitHub: + +```r +# Using remotes or pak +remotes::install_github("BWBrook/OpenPVA") +``` + +Or install directly from a local checkout: + +```sh +R CMD INSTALL . +``` + +## Quickstart + +Build, run, check, and plot a two-sex stochastic PVA in ~25 lines of ordinary R: ```r library(OpenPVA) @@ -63,7 +53,7 @@ survival <- survival_process( ifelse(pop$age == 0, params$juvenile, params$adult) }, requires = "population.age", - params = list(juvenile = 0.5, adult = 0.9) + params = list(juvenile = 0.52, adult = 0.88) ) breeding <- reproduction_process( @@ -80,45 +70,24 @@ scenario <- scenario_spec( n_steps = 20, init_fun = function() pva_population(sex = rep(c("F", "M"), 10), age = 3), processes = list(survival, age_process(), breeding, census_process()), + initial_census = census_process(), seed = 2026 ) result <- run_scenario(scenario) summarise_pva(result, threshold = 10) all(summarise_accounting(result)$reconciled) -``` - -These illustrative rates specify a two-sex model. Each breeding female needs -an eligible male. With `mate = NULL` the model is female-dominant and a -breeding female can produce offspring with an unknown sire. - -For seasonal mating, `mate_from_field()` preserves the recorded sire if he -dies or is removed earlier in the birth interval. By default, a recorded -sire who is absent for any other reason raises an error. For multi-year -pair bonds, `mate_from_field(stale = "unpaired")` treats that female as -unpaired for breeding and leaves her stored mate ID intact. In either mode, -a recorded sire who is living must be male. - -`age_sex_rate()` requires a rate for each sex present in the population. -To give an omitted sex a rate of zero, as with a female-only fecundity -table, use `age_sex_rate(table, "fecundity", missing_sex = "zero")`. - -The census follows breeding here, so each interval's abundance includes its -newborns. Supply `initial_census = census_process()` to count year zero as -well. Both risk summaries use the same observations and check the schedule -against the full replicate design. The default run keeps census, events and -accounting. Request `keep = c("census", "state", "ledger")` to inspect the -survivors and individual histories. -## A project-defined process +plot(result, type = "trajectory", threshold = 10) +``` -Anything that satisfies the contract composes with the built-in processes; no -registration is needed. +Custom biological or management rules compose through the exact same contract—no registration required: ```r harvest_oldest <- pva_process( name = "harvest_oldest", run = function(state, context, params) { + if (!length(state$population$id)) return(pva_result(state)) oldest <- which.max(state$population$age) state$population$alive[oldest] <- FALSE pva_result(state, pva_events("removal", length(oldest), "harvest")) @@ -128,41 +97,38 @@ harvest_oldest <- pva_process( ) ``` -If that process forgot its `removal` event, or changed a field it did not -declare, strict validation would stop the run and name the process. +If a custom process forgets its `removal` event or mutates an undeclared field, strict validation halts immediately and names the process. + +## Capability map + +| Ecological layer | Key building blocks | +|---|---| +| **State & cohorts** | `pva_population()`, `pva_state()` (`pedigree`, `n_loci`, `mate_field`), `add_individuals()` | +| **Demography & mating** | `survival_process()`, `staged_survival_process()`, `age_process()`, `reproduction_process()`, `pairing_process()`, `mating_process()`, `mate_random()`, `mate_min_kinship()`, `mate_from_field()` | +| **Environment & space** | `environment_process()`, `env_ar1()`, `spatial_correlation()`, `env_trend()`, `catastrophe_process()`, `dispersal_process()`, `markov_dispersal_process()`, `shift_logit()`, `qbeta_norm()` | +| **Management & MSE** | `removal_process()`, `ceiling_process()`, `introduction_process()`, `assign_process()`, `survey_process()` (isolated substream 5), `survey_quota()` | +| **Genetics & life tables** | `kinship_matrix()`, `mean_kinship()`, `summarise_pedigree()`, `summarise_markers()`, `marker_founder_shares()`, `genetic_metrics()`, `inbreeding_multiplier()`, `inbreeding_proxy_process()`, `life_table_metrics()` | +| **Execution, summaries & plots** | `scenario_spec()`, `run_scenario()`, `run_pva_ensemble()`, `summarise_pva()` (risk, EMA, MCSE), `summarise_trajectory()`, `summarise_accounting()`, `describe_lifecycle()`, `format_lifecycle()`, `plot()` | + +## Examples & documentation -## Species examples +- **Visual workflow walkthrough:** `vignette("workflow", package = "OpenPVA")` (lifecycle diagrams, life-table checks, accounting, adaptive surveys, ensembles & genetics) +- **GAPPS / Vortex / Leslie translation guide:** `vignette("rosetta", package = "OpenPVA")` +- **Agent modelling guide:** [For AI agents & script authors](https://github.com/BWBrook/OpenPVA/blob/main/docs/for-agents.md) +- **Grizzly bear seasonal lifecycle:** summer mating (`mating_process()`), autumn harvest, cross-interval sire retention, winter birth, and 3-year maternal dependency — [Grizzly model](https://github.com/BWBrook/OpenPVA/blob/main/inst/examples/grizzly/README.md) +- **Lord Howe Island woodhen recovery:** sex-specific survival, shared environmental stochasticity, territorial pairing, captive releases, and parameter-evidence table — [Woodhen model](https://github.com/BWBrook/OpenPVA/blob/main/inst/examples/woodhen/README.md) +- **Design & heritage documents:** [Vision and scope](https://github.com/BWBrook/OpenPVA/blob/main/docs/vision_and_scope.md) · [Lifecycle-process contract](https://github.com/BWBrook/OpenPVA/blob/main/docs/design/lifecycle_process_contract.md) · [Public API](https://github.com/BWBrook/OpenPVA/blob/main/docs/reference/public_api.md) · [GAPPS heritage](https://github.com/BWBrook/OpenPVA/blob/main/docs/gapps_heritage.md) · [GAPPS evidence review](https://github.com/BWBrook/OpenPVA/blob/main/docs/literature/gapps_evidence_review.md) -- Follow a breeding female through summer mating, autumn harvest, winter birth - and three years of maternal care. This example links adult-female mortality - to cub survival and inter-birth intervals. [Grizzly model](inst/examples/grizzly/README.md) -- Compare recovery scenarios with sex-specific survival, shared environmental - variation, territorial pairs and captive releases. The example provides - parameters, their evidence and a script that runs on a socket cluster. - [Lord Howe Island woodhen model](inst/examples/woodhen/README.md) +## Citation -Both projects use the exported API and include runnable scripts. Their rates -illustrate model construction and management comparisons. +If you use OpenPVA in research or conservation assessments, please cite the software archive (Zenodo Concept DOI [`10.5281/zenodo.24521838`](https://doi.org/10.5281/zenodo.24521838)) or run `citation("OpenPVA")` in R. ## Development ```sh -Rscript scripts/run_tests.R # install to a temporary library and run all tests -Rscript scripts/build_rd.R # regenerate man/*.Rd from scripts/rd_topics.R +Rscript --vanilla scripts/run_tests.R # install to temp library and run all tests +Rscript --vanilla scripts/build_rd.R # regenerate man/*.Rd from scripts/rd_topics.R R CMD build . && R CMD check --as-cran OpenPVA_*.tar.gz ``` -Building needs the suggested package `litedown` for the vignette. Run the -build in a scratch directory so the tarball and check directory stay out of -the checkout. - -Documentation is generated by `scripts/build_rd.R`, which builds every usage -section from the functions' formals, so `roxygen2` is not required. - -## Design documents - -- [Vision and scope](https://github.com/BWBrook/OpenPVA/blob/main/docs/vision_and_scope.md) -- [Lifecycle-process contract](https://github.com/BWBrook/OpenPVA/blob/main/docs/design/lifecycle_process_contract.md) -- [Public API](https://github.com/BWBrook/OpenPVA/blob/main/docs/reference/public_api.md) -- [GAPPS heritage](https://github.com/BWBrook/OpenPVA/blob/main/docs/gapps_heritage.md) and - [evidence review](https://github.com/BWBrook/OpenPVA/blob/main/docs/literature/gapps_evidence_review.md) +Documentation is generated directly from live function formals via `scripts/build_rd.R` (`roxygen2` is not required); building the vignette requires the suggested package `litedown`. diff --git a/docs/for-agents.md b/docs/for-agents.md new file mode 100644 index 0000000..838ef7b --- /dev/null +++ b/docs/for-agents.md @@ -0,0 +1,146 @@ +# Agent Modelling Guide for OpenPVA + +This guide is for AI coding agents (and human script authors) building, checking, and running Population Viability Analyses with **OpenPVA**. For package development rules inside this repository, see [`AGENTS.md`](../AGENTS.md); for formal engine invariants, see [`docs/design/lifecycle_process_contract.md`](design/lifecycle_process_contract.md). + +## 1. Core mental model + +1. **A lifecycle is an ordinary ordered R list of `pva_process()` objects.** Order is biology: putting `survival_process()` before `age_process()` models pre-ageing mortality; putting `reproduction_process()` before `census_process()` produces a post-breeding census. +2. **State is columnar and explicit.** `pva_state()` holds: + - `population`: named list of equal-length plain atomic vectors (no vector `names` or S3 attributes) for living individuals. Core fields are `id`, `sex` (`"F"`/`"M"`), `age` (non-negative integer), `alive`, `mother_id`, `father_id`, `origin`, `entry_time` (plus engine-owned `pedigree_F` when `pedigree = TRUE`). + - `globals`: named list of shared interval/scenario variables (e.g. environmental anomalies, catastrophe flags, survey records). + - Engine-owned internals: `next_id`, `kinship`, `markers` (`n_loci > 0`), `sires` (`mate_field`), and `survey_seed`. Never mutate these directly. +3. **Every process declares what it touches:** `requires`, `writes`, and `creates` (`population.` or `globals.`). In default `validation = "strict"`, undeclared mutations or unreconciled births/deaths/removals/introductions halt immediately and name the offending process. +4. **RNG is owned by the engine.** `run_scenario()` preassigns one L'Ecuyer-CMRG stream per replicate (`seed`), giving bit-identical results across serial, fork, and PSOCK workers while restoring the caller's `.Random.seed` and pending Box–Muller normal. Neutral-locus segregation uses an isolated substream; `survey_process()` uses isolated substream 5. + +## 2. Exact signatures and common parameter traps + +Verify argument names against live formals (`args(OpenPVA::fn)`). The most frequent signature mistakes agents make: + +| Function | Exact signature / key arguments | Common trap to avoid | +|---|---|---| +| `env_ar1()` | `env_ar1(sd = 1, phi = 0, cor = NULL, names = NULL)` | Autocorrelation is `phi` (not `rho`), with `abs(phi) < 1`. | +| `catastrophe_process()` | `catastrophe_process(probability, mortality = NULL, eligible = NULL, name = "catastrophe", ...)` | Effect argument is `mortality` (fraction killed, or function), not `survival_multiplier`. | +| `ceiling_density_multiplier()` | `ceiling_density_multiplier(n, capacity)` | Second argument is `capacity` (not `ceiling` or `K`). | +| `beverton_holt_multiplier()` | `beverton_holt_multiplier(n, capacity, growth)` | Requires `growth >= 1` (`growth = 1` returns `1`). | +| `reproduction_process()` | `reproduction_process(breeding_probability, litter_size, offspring_sex, mate = NULL, require_mate = !is.null(mate), newborn_fields = NULL, newborn_field_names = character(), inherit = character(), ...)` | When the population has custom user columns (e.g. `mate_id`, `patch_id`), list their names in `newborn_field_names` (or `inherit`) and return them from `newborn_fields`. | +| `age_sex_rate()` | `age_sex_rate(table, value, missing_sex = c("error", "zero"))` | Pass `missing_sex = "zero"` for female-only fecundity tables in a two-sex population. | +| `survey_process()` / `survey_quota()` | `survey_process(detection, eligible = NULL, when = TRUE, field = "survey", ...)` and `survey_quota(rule, field = "survey", on_skip = "error")` | Place `survey_process()` **before** the management process consuming `survey_quota()`. On unvisited intervals (`when`), `on_skip = "error"` intentionally errors unless set to a count (e.g. `0L`) or callback. | +| `run_pva_ensemble()` | `run_pva_ensemble(design, build, n_runs, summarise = NULL, seed = NULL, seed_by = NULL, ...)` | `build` takes **one** argument (`row`, a named list of the design row) and returns a list containing `init_fun`, `processes`, and `n_steps` (a `scenario_spec()` object works because it is such a list). | +| `pva_state(..., mate_field = ...)` | `pva_state(population, globals = list(), pedigree = FALSE, kinship = NULL, max_dense_kinship = 2000L, n_loci = 0L, mate_field = NULL)` | Initial female `mate_field` IDs must reference living initial males. Use `mate_field` whenever sires may die between mating and birth across intervals. | + +## 3. Standard agent verification workflow + +Never present stochastic PVA results without running these five checks in order: + +1. **Validate and visually inspect the lifecycle before simulating:** + ```r + init_state <- scenario$init_fun() + if (!inherits(init_state, "pva_state")) init_state <- pva_state(init_state) + validate_processes(scenario$processes, init_state) + lc <- describe_lifecycle(scenario, state = init_state) + print(lc) + plot(lc) # base-R flow diagram + cat(format_lifecycle(lc, "mermaid"), "\n") + ``` +2. **Check deterministic expectations against `life_table_metrics()`:** + Verify λ, R₀, and `generation_time` match the intended vital rates and census convention (`timing = "post_breeding"` vs `"pre_breeding"`, `plus_group = TRUE/FALSE`) before interpreting stochastic risk. +3. **Run a small smoke test under `validation = "strict"` and verify accounting:** + ```r + smoke <- run_scenario(scenario, validation = "strict") + stopifnot(all(summarise_accounting(smoke)$reconciled)) + ``` + Only switch to `validation = "fast"` for large production runs *after* `strict` passes cleanly. +4. **Use common random numbers when comparing management or structural options:** + In `run_pva_ensemble()`, `seed_by = NULL` assigns a distinct seed to every row. To share common replicate streams across strategies, include a shared grouping column in `design` and pass it to `seed_by` (e.g., a constant column `pair = 1L` with `seed_by = "pair"` to pair every row, or `seed_by = "climate"` to pair management strategies within each climate regime). +5. **Preserve provenance and uncertainty:** + Report `p_ever_below` with Wilson limits (`p_ever_below_lower`, `p_ever_below_upper`), `ema` / `ema_mcse`, `n_runs`, `seed`, and `attr(ensemble, "provenance")`. Subsetting `ensemble[, cols]` retains class `pva_ensemble` and its `provenance` attribute. + +## 4. Minimal composition templates + +### Two-sex stochastic model with environment, pedigree, and adaptive survey + +```r +library(OpenPVA) + +make_scenario <- function(n_runs = 200L, seed = 2026L) { + init_fun <- function() { + pva_state( + pva_population(sex = rep(c("F", "M"), each = 15L), age = rep(1:5, 6L)), + pedigree = TRUE, + n_loci = 10L + ) + } + + processes <- list( + environment_process(list(env = env_ar1(sd = 0.35, phi = 0.4))), + survival_process( + probability = function(pop, state, context, params) { + base <- ifelse(pop$age == 0L, 0.55, 0.85) + dens <- ceiling_density_multiplier(length(pop$id), capacity = 90) + inb <- inbreeding_multiplier(pop$pedigree_F, lethal_equivalents = 3.14) + shift_logit(base, state$globals$env) * dens * inb + }, + requires = c("population.age", "population.pedigree_F", "globals.env") + ), + age_process(), + reproduction_process( + breeding_probability = function(pop, state, context, params) as.numeric(pop$age >= 2L) * 0.8, + litter_size = litter_poisson(1.15), + offspring_sex = offspring_sex_bernoulli(0.5), + mate = mate_min_kinship(function(pop, state, context, params) pop$age >= 2L, max_kinship = 0.25), + requires = "population.age" + ), + survey_process(detection = 0.70, when = seq.int(0L, 39L, by = 2L), field = "obs"), + introduction_process( + count = survey_quota( + rule = function(obs, state, context, params) if (obs$count < 24L) 6L else 0L, + field = "obs", + on_skip = 0L + ), + fields = function(n, state, context, params) { + list(sex = rep(c("F", "M"), length.out = n), age = rep(2L, n)) + }, + name = "adaptive_release" + ), + census_process(genetic_metrics()) + ) + + scenario_spec( + name = "island-adaptive", + n_runs = n_runs, + n_steps = 40L, + init_fun = init_fun, + processes = processes, + initial_census = census_process(genetic_metrics()), + seed = seed + ) +} +``` + +### Custom process respecting the strict contract + +```r +selective_cull <- pva_process( + name = "selective_cull", + run = function(state, context, params) { + pop <- state$population + eligible <- which(pop$age >= params$min_age) + n_take <- min(length(eligible), params$quota) + if (!n_take) return(pva_result(state)) + chosen <- eligible[order(pop$age[eligible], decreasing = TRUE)][seq_len(n_take)] + state$population$alive[chosen] <- FALSE + pva_result(state, pva_events("removal", n_take, "selective_cull")) + }, + params = list(min_age = 5L, quota = 2L), + requires = "population.age", + writes = "population.alive", + description = "Remove up to quota oldest individuals above min_age." +) +``` + +## 5. Edge-case checklist + +- **Extinct replicates (`N == 0`):** Every custom callback must safely return a length-0 vector or unmodified `pva_result(state)` when `length(pop$id) == 0L`. (Built-in `shift_logit()` and `.per_individual()` handle empty `logical(0)` from `ifelse()` safely.) +- **Repeated standalone `execute_processes()` with surveys:** Always pass the returned `out$state` into the next step; re-entering the same initial state at the same caller RNG position derives the same survey stream. +- **Pedigree scaling:** Dense kinship is used up to `max_dense_kinship = 2000L`, switching automatically to level-batched sparse ancestor tracing above that threshold. Keep `max_dense_kinship` at default unless profiling large populations. +- **Genetics without perturbing demography:** Enabling `n_loci > 0` never alters demographic draws in a seeded run; use `census_process(genetic_metrics())` to record `mean_inbreeding`, `expected_heterozygosity`, and `allelic_richness` over time alongside `n_alive`. diff --git a/docs/reference/public_api.md b/docs/reference/public_api.md index 690bdbb..6dd60f8 100644 --- a/docs/reference/public_api.md +++ b/docs/reference/public_api.md @@ -1,4 +1,4 @@ -# Public API (OpenPVA 2.2.0) +# Public API (OpenPVA 2.3.0) The help pages under `man/` are the reference; this page is the map. Every entry is exported. @@ -19,7 +19,8 @@ entry is exported. | Space | `patch_counts()`, `dispersal_process()`, `markov_dispersal_process()` | | Scenarios | `scenario_spec()`, `run_scenario()` | | Summaries and ensembles | `summarise_pva()`, `summarise_trajectory()`, `summarise_accounting()`, `run_pva_ensemble()` | -| Plots (S3 methods) | `plot()` for a `pva_run` and for a `pva_ensemble` | +| Lifecycle inspection | `describe_lifecycle()`, `format_lifecycle()` (`text`, `mermaid`, `dot`) | +| Plots and printing (S3 methods) | `plot()` for `pva_run`, `pva_ensemble`, `pva_scenario` and `pva_lifecycle`; `print()` methods; `[` for `pva_ensemble` | ## Outputs of `run_scenario()` diff --git a/docs/vision_and_scope.md b/docs/vision_and_scope.md index ccc22bd..f0c06e5 100644 --- a/docs/vision_and_scope.md +++ b/docs/vision_and_scope.md @@ -108,17 +108,25 @@ OpenPVA is not: or every available feature; - currently a GUI product or a new modelling language. -## Current decision boundary - -OpenPVA 2.0.0 keeps the lifecycle contract and replaces the engine's internals: -columnar state of living individuals, cohort-level accounting, engine-owned -exact pedigree inbreeding, serial, fork and PSOCK execution, and the PVA -essentials (removal, environmental variation, catastrophes, density feedback, -pairing and territories, inbreeding depression, viability summaries and -designed ensembles) as ordinary processes and helpers. -`docs/design/lifecycle_process_contract.md` is the engine contract. Empirical -parameterisation, marker genetics, observation models and management inference -remain later goals. +## Current status and decision boundary + +OpenPVA 2.2+ implements the full `GAPPS++` core engine in pure base R: +columnar living-state storage, strict cohort-level accounting, exact conditional +pedigree inbreeding (dense kinship store switching automatically to +level-batched sparse ancestor tracing), optional non-perturbing neutral-locus +gene drop, kinship-aware and seasonal mating with engine-owned cross-interval +sire retention, temporally and spatially correlated environmental variation, +catastrophes, density feedback, inbreeding depression, successive weighted +management and individual state assignments, isolated-stream imperfect surveys +with observation-based quotas, analytical female life tables, expected minimum +abundance, designed ensembles, serial/fork/PSOCK L'Ecuyer-CMRG bit-parity, and +base-graphics plotting. `docs/design/lifecycle_process_contract.md` is the +engine contract. + +Empirical parameterisation, formal hindcasting, structured global sensitivity +wrappers, and external calibration workflows remain deliberately outside the +core execution loop and compose around `run_scenario()` and +`run_pva_ensemble()`. Current capabilities and historical roadmaps are evidence about the starting point, not the authority for product direction. This document is the authority. diff --git a/inst/CITATION b/inst/CITATION index 4045638..100c343 100644 --- a/inst/CITATION +++ b/inst/CITATION @@ -6,5 +6,6 @@ bibentry( author = person("Barry W.", "Brook"), year = "2026", note = paste("R package version", meta$Version), + doi = "10.5281/zenodo.24521838", url = "https://github.com/BWBrook/OpenPVA" ) diff --git a/man/figures/logo.png b/man/figures/logo.png new file mode 100644 index 0000000..3fd0daf Binary files /dev/null and b/man/figures/logo.png differ diff --git a/man/figures/readme-hero.png b/man/figures/readme-hero.png new file mode 100644 index 0000000..e5e7d2b Binary files /dev/null and b/man/figures/readme-hero.png differ diff --git a/man/lifecycle.Rd b/man/lifecycle.Rd new file mode 100644 index 0000000..f79cb02 --- /dev/null +++ b/man/lifecycle.Rd @@ -0,0 +1,70 @@ +% Generated by scripts/build_rd.R from scripts/rd_topics.R; edit those files. +\name{lifecycle} +\alias{lifecycle} +\alias{describe_lifecycle} +\alias{format_lifecycle} +\alias{plot.pva_scenario} +\alias{plot.pva_lifecycle} +\title{Inspect and diagram a model lifecycle} +\usage{ +describe_lifecycle(x, state = NULL) + +format_lifecycle(x, format = c("text", "mermaid", "dot"), state = NULL) + +\method{plot}{pva_scenario}( + x, + state = NULL, + show_flows = TRUE, + main = NULL, + ... +) + +\method{plot}{pva_lifecycle}(x, show_flows = TRUE, main = NULL, ...) +} +\arguments{ +\item{x}{A \code{pva_scenario} from \code{\link{scenario_spec}()}, a \code{pva_run} from \code{\link{run_scenario}()}, a \code{pva_lifecycle} from \code{describe_lifecycle()}, or an ordered list of \code{\link{pva_process}()} objects.} +\item{state}{Optional \code{\link{pva_state}()} object used to annotate the summary and diagram with starting abundance, pedigree tracking, neutral loci and \code{mate_field} without invoking \code{init_fun()}.} +\item{format}{Output format for \code{format_lifecycle()}: \code{"text"} for a console summary, \code{"mermaid"} for a Mermaid flowchart or \code{"dot"} for Graphviz DOT.} +\item{show_flows}{Whether to draw dashed inter-process data-flow arcs inferred from declared \code{writes} and \code{requires} fields. \code{TRUE} (the default) suppresses broadcast \code{population.age} fans when three or more steps read age; use \code{"all"} to draw every arc or \code{FALSE} to omit arcs.} +\item{main}{Optional title for the lifecycle diagram.} +\item{\dots}{Reserved for future graphical extensions.} +} +\description{ +Translate any OpenPVA process list, scenario or run into an ordered audit table, a base-graphics node-and-edge lifecycle flow diagram or a Mermaid/Graphviz specification. Inspection draws no random numbers. +} +\details{ +\code{describe_lifecycle()} classifies each process into an ecological role (\code{environment}, \code{demography}, \code{spatial}, \code{management}, \code{survey}, \code{census} or \code{custom}) and infers inter-process data flows from declared \code{writes} and \code{requires} paths. A field required before it is written later in the same interval is recorded as a \code{carryover} dependency for the next interval. + +\code{plot.pva_scenario()} and \code{plot.pva_lifecycle()} render a pure-base-R node-and-edge flow diagram: a single left-to-right row for up to five interval processes, or a two-row clockwise cycle for six or more processes, with dashed data-flow arcs and an interval-return loop. + +\code{format_lifecycle()} returns a single character string ready to paste into Markdown/Quarto (\code{"mermaid"}), Graphviz (\code{"dot"}) or plain-text reports (\code{"text"}). +} +\value{ +\code{describe_lifecycle()} returns a data frame of class \code{pva_lifecycle} with one row per ordered step and \code{"edges"} and \code{"metadata"} attributes. \code{format_lifecycle()} returns a length-one character string. \code{plot.pva_scenario()} and \code{plot.pva_lifecycle()} return the \code{pva_lifecycle} object invisibly. +} +\examples{ +scenario <- scenario_spec( + name = "island-adaptive", n_runs = 50, n_steps = 20, seed = 1, + init_fun = function() pva_population(sex = rep(c("F", "M"), 8), age = 2), + processes = list( + environment_process(list(env = env_ar1(sd = 0.3, phi = 0.4))), + survival_process( + function(pop, state, context, params) shift_logit(0.85, state$globals$env), + requires = "globals.env" + ), + age_process(), + survey_process(0.7, field = "obs"), + introduction_process( + count = survey_quota(function(obs, state, context, params) as.integer(obs$count < 10L), + field = "obs", on_skip = 0L), + fields = function(n, state, context, params) list(sex = rep("F", n), age = rep(2L, n)) + ), + census_process() + ), + initial_census = census_process() +) +lc <- describe_lifecycle(scenario) +lc +plot(scenario) +cat(format_lifecycle(scenario, "mermaid"), "\n") +} diff --git a/man/print.pva_state.Rd b/man/print.pva_state.Rd index 3dd664d..860d912 100644 --- a/man/print.pva_state.Rd +++ b/man/print.pva_state.Rd @@ -3,9 +3,12 @@ \alias{print.pva_state} \alias{print.pva_process} \alias{print.pva_scenario} +\alias{print.pva_lifecycle} \alias{print.pva_run} \alias{print.pva_ensemble} -\title{Print OpenPVA objects} +\alias{[.pva_ensemble} +\alias{[.pva_lifecycle} +\title{Print and subset OpenPVA objects} \usage{ \method{print}{pva_state}(x, ...) @@ -13,13 +16,19 @@ \method{print}{pva_scenario}(x, ...) +\method{print}{pva_lifecycle}(x, ...) + \method{print}{pva_run}(x, ...) \method{print}{pva_ensemble}(x, ...) + +\method{[}{pva_ensemble}(x, ...) + +\method{[}{pva_lifecycle}(x, ...) } \arguments{ -\item{x}{An OpenPVA state, process, scenario, run or ensemble.} -\item{\dots}{For ensembles, arguments passed to the data-frame print method.} +\item{x}{An OpenPVA state, process, scenario, lifecycle, run or ensemble.} +\item{\dots}{Additional arguments passed to the underlying data-frame print or subset method.} } -\description{Summarise an OpenPVA object. For ensembles, print the run count and root seed above the design and summary rows.} -\value{\code{x}, invisibly.} +\description{Summarise an OpenPVA object, subset a \code{pva_ensemble} data frame while preserving its provenance metadata, or slice a \code{pva_lifecycle} table into a plain data frame.} +\value{For \code{print} methods, \code{x} invisibly. For \code{[} on \code{pva_ensemble}, a subsetted \code{pva_ensemble} data frame (preserving provenance) or a vector when reduced to a single column. For \code{[} on \code{pva_lifecycle}, a plain data frame or vector.} diff --git a/scripts/build_rd.R b/scripts/build_rd.R index 7f8df10..aaeb119 100644 --- a/scripts/build_rd.R +++ b/scripts/build_rd.R @@ -99,9 +99,12 @@ writeLines(c( "\\alias{print.pva_state}", "\\alias{print.pva_process}", "\\alias{print.pva_scenario}", + "\\alias{print.pva_lifecycle}", "\\alias{print.pva_run}", "\\alias{print.pva_ensemble}", - "\\title{Print OpenPVA objects}", + "\\alias{[.pva_ensemble}", + "\\alias{[.pva_lifecycle}", + "\\title{Print and subset OpenPVA objects}", "\\usage{", "\\method{print}{pva_state}(x, ...)", "", @@ -109,16 +112,22 @@ writeLines(c( "", "\\method{print}{pva_scenario}(x, ...)", "", + "\\method{print}{pva_lifecycle}(x, ...)", + "", "\\method{print}{pva_run}(x, ...)", "", "\\method{print}{pva_ensemble}(x, ...)", + "", + "\\method{[}{pva_ensemble}(x, ...)", + "", + "\\method{[}{pva_lifecycle}(x, ...)", "}", "\\arguments{", - "\\item{x}{An OpenPVA state, process, scenario, run or ensemble.}", - "\\item{\\dots}{For ensembles, arguments passed to the data-frame print method.}", + "\\item{x}{An OpenPVA state, process, scenario, lifecycle, run or ensemble.}", + "\\item{\\dots}{Additional arguments passed to the underlying data-frame print or subset method.}", "}", - "\\description{Summarise an OpenPVA object. For ensembles, print the run count and root seed above the design and summary rows.}", - "\\value{\\code{x}, invisibly.}" + "\\description{Summarise an OpenPVA object, subset a \\code{pva_ensemble} data frame while preserving its provenance metadata, or slice a \\code{pva_lifecycle} table into a plain data frame.}", + "\\value{For \\code{print} methods, \\code{x} invisibly. For \\code{[} on \\code{pva_ensemble}, a subsetted \\code{pva_ensemble} data frame (preserving provenance) or a vector when reduced to a single column. For \\code{[} on \\code{pva_lifecycle}, a plain data frame or vector.}" ), "man/print.pva_state.Rd") documented <- unlist(lapply(topics, `[[`, "functions")) diff --git a/scripts/build_site.R b/scripts/build_site.R new file mode 100644 index 0000000..9922afc --- /dev/null +++ b/scripts/build_site.R @@ -0,0 +1,81 @@ +# Build the OpenPVA static documentation site using litedown::pkg_site(). +# Run from the repository root with OpenPVA (and litedown) installed: +# Rscript --vanilla scripts/build_site.R [_site] + +args <- commandArgs(trailingOnly = TRUE) +out_dir <- if (length(args) >= 1L && nzchar(args[[1L]])) args[[1L]] else "_site" + +if (!requireNamespace("litedown", quietly = TRUE)) { + stop("Building the documentation site requires the suggested package 'litedown'.", call. = FALSE) +} +if (!requireNamespace("OpenPVA", quietly = TRUE)) { + stop("Install OpenPVA first (e.g. R CMD INSTALL .) before building the site.", call. = FALSE) +} + +root_abs <- normalizePath(".", mustWork = TRUE) +site_abs <- normalizePath("site", mustWork = TRUE) +out_abs <- normalizePath(out_dir, mustWork = FALSE) + +same_or_inside <- function(a, b) { + a <- sub("/+$", "", a) + b <- sub("/+$", "", b) + identical(a, b) || startsWith(a, paste0(b, "/")) +} +if (same_or_inside(site_abs, out_abs) || same_or_inside(out_abs, site_abs) || + same_or_inside(root_abs, out_abs)) { + stop("Refusing to overwrite repository root or site/ source directory: ", out_dir, call. = FALSE) +} + +unlink(out_dir, recursive = TRUE, force = TRUE) +dir.create(out_dir, recursive = TRUE, showWarnings = FALSE) + +# Copy repo-local site overrides into the build directory before pkg_site() fills in defaults. +src_files <- list.files("site", all.files = TRUE, no.. = TRUE, full.names = TRUE) +ok <- file.copy(src_files, out_dir, recursive = TRUE, overwrite = TRUE) +if (!all(ok)) { + stop("Failed to copy site/ sources into ", out_dir, call. = FALSE) +} + +pkg_name <- structure("OpenPVA", path = normalizePath(".", mustWork = TRUE)) +litedown::pkg_site(name = pkg_name, output = out_dir) + +# Remove build-only source files so out_dir holds deployable static assets only. +unlink( + c( + file.path(out_dir, c("_litedown.yml", "_footer.md", "index.Rmd", "manual.Rmd", "articles.Rmd", "news.Rmd")), + file.path(out_dir, "playground") + ), + recursive = TRUE, + force = TRUE +) +# Replace external CDN GitHub octicon in the top nav with an inline crisp SVG icon +# so the navigation bar renders cleanly even offline or behind strict firewalls. +github_svg <- paste0( + '', + 'GitHub' +) +html_files <- list.files(out_dir, pattern = "\\.html$", full.names = TRUE) +for (f in html_files) { + txt <- readLines(f, warn = FALSE, encoding = "UTF-8") + txt <- gsub( + ' + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + OpenPVA + + + + INDIVIDUAL-BASED PVA IN R + diff --git a/scripts/make_readme_hero.R b/scripts/make_readme_hero.R new file mode 100644 index 0000000..10c22c8 --- /dev/null +++ b/scripts/make_readme_hero.R @@ -0,0 +1,243 @@ +# Generate the reproducible README hero figure from real OpenPVA output. +# Run from the repository root with OpenPVA installed: +# Rscript --vanilla scripts/make_readme_hero.R + +suppressPackageStartupMessages(library(OpenPVA)) + +build_island_scenario <- function(name, strategy = c("status_quo", "adaptive_release", "annual_release")) { + strategy <- match.arg(strategy) + + init_fun <- function() { + pva_state( + pva_population( + sex = rep(c("F", "M"), each = 18L), + age = rep(c(1L, 2L, 3L, 4L, 5L, 6L), times = 6L) + ), + pedigree = TRUE, + n_loci = 12L + ) + } + + env_proc <- environment_process( + list(env = env_ar1(sd = 0.42, phi = 0.45)) + ) + + catastrophe <- catastrophe_process( + probability = 0.06, + mortality = 0.28, + name = "cyclone" + ) + + surv_proc <- survival_process( + probability = function(pop, state, context, params) { + if (!length(pop$id)) return(numeric(0)) + base <- ifelse(pop$age == 0L, 0.56, 0.84) + dens <- ceiling_density_multiplier(length(pop$id), capacity = 95) + inb <- inbreeding_multiplier(pop$pedigree_F, lethal_equivalents = 3.14) + shift_logit(base, state$globals$env) * dens * inb + }, + requires = c("population.age", "population.pedigree_F", "globals.env") + ) + + breed_proc <- reproduction_process( + breeding_probability = function(pop, state, context, params) { + as.numeric(pop$age >= 2L) * 0.78 + }, + litter_size = litter_poisson(1.15), + offspring_sex = offspring_sex_bernoulli(0.5), + mate = mate_min_kinship( + eligible = function(pop, state, context, params) pop$age >= 2L, + max_kinship = 0.25 + ), + requires = "population.age" + ) + + survey <- survey_process( + detection = 0.70, + when = seq.int(0L, 39L, by = 2L), + field = "obs" + ) + + release_fields <- function(n, state, context, params) { + list(sex = rep(c("F", "M"), length.out = n), age = rep(2L, n)) + } + + mgmt <- switch( + strategy, + status_quo = list(), + adaptive_release = list( + survey, + introduction_process( + count = survey_quota( + rule = function(obs, state, context, params) { + if (obs$count < 26L) 6L else 0L + }, + field = "obs", + on_skip = 0L + ), + fields = release_fields, + name = "adaptive_release" + ) + ), + annual_release = list( + introduction_process( + count = function(state, context, params) if (context$time < 15L) 4L else 0L, + fields = release_fields, + name = "annual_release" + ) + ) + ) + + scenario_spec( + name = name, + n_runs = 300L, + n_steps = 40L, + init_fun = init_fun, + processes = c( + list(env_proc, catastrophe, surv_proc, age_process(), breed_proc), + mgmt, + list(census_process()) + ), + initial_census = census_process(), + seed = 202603L + ) +} + +threshold <- 15 +col_sq <- "#B84A39" +col_ar <- "#1B6B78" +col_an <- "#C88A2B" + +# Run one paired common-random-number ensemble (constant seed_by = "pair") on +# one worker so Panels A–C plot the exact same 300 paired replicates. +stored_runs <- new.env(parent = emptyenv()) +ens <- run_pva_ensemble( + design = data.frame( + strategy = c("status_quo", "adaptive_release", "annual_release"), + label = c("Status quo", "Survey-triggered", "Fixed 15-yr release"), + pair = 1L, + stringsAsFactors = FALSE + ), + build = function(row) build_island_scenario(row$label, row$strategy), + n_runs = 300L, + summarise = function(run, row) { + stored_runs[[row$strategy]] <- run + summarise_pva(run, threshold = threshold) + }, + seed = 202603L, + seed_by = "pair", + workers = 1L +) +stopifnot(length(unique(ens$member_seed)) == 1L) +run_sq <- stored_runs[["status_quo"]] +run_ar <- stored_runs[["adaptive_release"]] + +dir.create("man/figures", recursive = TRUE, showWarnings = FALSE) +out_file <- file.path("man", "figures", "readme-hero.png") + +grDevices::png(out_file, width = 1800, height = 560, res = 180, bg = "white") +op <- graphics::par( + mfrow = c(1L, 3L), + mar = c(4.3, 4.4, 3.0, 1.2), + mgp = c(2.5, 0.7, 0), + las = 1, + bty = "l", + cex.main = 1.04, + cex.lab = 0.96, + cex.axis = 0.88, + family = "sans" +) +on.exit({ + graphics::par(op) + grDevices::dev.off() +}, add = TRUE) + +# Panel A: Abundance trajectories (50% & 90% envelopes + medians) +plot( + run_sq, + type = "trajectory", + threshold = threshold, + runs = 0L, + col = col_sq, + ylim = c(0, 118), + xlab = "Year", + ylab = "Living individuals (N)", + main = "A. Stochastic trajectories (50% & 90%)" +) +graphics::grid(col = "grey92", lty = 1) +plot( + run_ar, + type = "trajectory", + threshold = threshold, + runs = 0L, + col = col_ar, + add = TRUE +) +graphics::abline(h = threshold, lty = 2, col = "grey30", lwd = 1.2) +graphics::text(0.5, threshold - 3.2, sprintf("Threshold (N = %d)", threshold), + adj = c(0, 1), cex = 0.78, col = "grey30") +graphics::legend( + "topleft", + legend = c("Survey-triggered release", "Status quo"), + col = c(col_ar, col_sq), + lwd = 2.6, + bty = "n", + cex = 0.84 +) + +# Panel B: Cumulative quasi-extinction risk with Wilson 95% intervals +plot( + run_sq, + type = "risk", + threshold = threshold, + col = col_sq, + ylim = c(0, 0.92), + xlab = "Year", + ylab = sprintf("P(N < %d by year t)", threshold), + main = "B. Cumulative risk (95% Wilson CI)" +) +graphics::grid(col = "grey92", lty = 1) +plot( + run_ar, + type = "risk", + threshold = threshold, + col = col_ar, + add = TRUE +) +graphics::legend( + "topleft", + legend = c("Status quo", "Survey-triggered release"), + col = c(col_sq, col_ar), + lwd = 2.6, + bty = "n", + cex = 0.84 +) + +# Panel C: Management ensemble contrast +cols <- c(col_sq, col_ar, col_an) +plot( + ens, + y = "p_ever_below", + by = "label", + col = cols, + ylim = c(0, 0.92), + xlab = "", + ylab = sprintf("40-yr quasi-extinction risk (N < %d)", threshold), + main = "C. Ensemble management comparison", + xaxt = "n" +) +graphics::grid(nx = NA, ny = NULL, col = "grey92", lty = 1) +pos <- seq_len(nrow(ens)) +graphics::axis(1L, at = pos, labels = c("Status\nquo", "Survey-\ntriggered", "Fixed 15-yr\nrelease"), + tick = FALSE, line = 0.4, cex.axis = 0.86) +graphics::text( + pos, + ens$p_ever_below_upper + 0.04, + sprintf("%.0f%%\n(EMA %.0f)", 100 * ens$p_ever_below, ens$ema), + adj = c(0.5, 0), + cex = 0.78, + col = "grey25" +) + +cat("Wrote", out_file, "\n") +print(as.data.frame(ens[, c("label", "p_ever_below", "p_ever_below_lower", "p_ever_below_upper", "ema", "final_mean")])) diff --git a/scripts/rd_topics.R b/scripts/rd_topics.R index e21fe9b..1b5ecbf 100644 --- a/scripts/rd_topics.R +++ b/scripts/rd_topics.R @@ -632,5 +632,49 @@ build <- function(row) { ensemble <- run_pva_ensemble(design, build, n_runs = 60, seed = 7, summarise = function(result, row) summarise_pva(result, threshold = 4)) plot(ensemble))" + ), + lifecycle = list( + title = "Inspect and diagram a model lifecycle", + functions = c("describe_lifecycle", "format_lifecycle"), + methods = c("plot.pva_scenario", "plot.pva_lifecycle"), + arguments = list( + x = r"(A \code{pva_scenario} from \code{\link{scenario_spec}()}, a \code{pva_run} from \code{\link{run_scenario}()}, a \code{pva_lifecycle} from \code{describe_lifecycle()}, or an ordered list of \code{\link{pva_process}()} objects.)", + state = r"(Optional \code{\link{pva_state}()} object used to annotate the summary and diagram with starting abundance, pedigree tracking, neutral loci and \code{mate_field} without invoking \code{init_fun()}.)", + format = r"(Output format for \code{format_lifecycle()}: \code{"text"} for a console summary, \code{"mermaid"} for a Mermaid flowchart or \code{"dot"} for Graphviz DOT.)", + show_flows = r"(Whether to draw dashed inter-process data-flow arcs inferred from declared \code{writes} and \code{requires} fields. \code{TRUE} (the default) suppresses broadcast \code{population.age} fans when three or more steps read age; use \code{"all"} to draw every arc or \code{FALSE} to omit arcs.)", + main = r"(Optional title for the lifecycle diagram.)", + `...` = r"(Reserved for future graphical extensions.)" + ), + description = r"(Translate any OpenPVA process list, scenario or run into an ordered audit table, a base-graphics node-and-edge lifecycle flow diagram or a Mermaid/Graphviz specification. Inspection draws no random numbers.)", + details = r"(\code{describe_lifecycle()} classifies each process into an ecological role (\code{environment}, \code{demography}, \code{spatial}, \code{management}, \code{survey}, \code{census} or \code{custom}) and infers inter-process data flows from declared \code{writes} and \code{requires} paths. A field required before it is written later in the same interval is recorded as a \code{carryover} dependency for the next interval. + +\code{plot.pva_scenario()} and \code{plot.pva_lifecycle()} render a pure-base-R node-and-edge flow diagram: a single left-to-right row for up to five interval processes, or a two-row clockwise cycle for six or more processes, with dashed data-flow arcs and an interval-return loop. + +\code{format_lifecycle()} returns a single character string ready to paste into Markdown/Quarto (\code{"mermaid"}), Graphviz (\code{"dot"}) or plain-text reports (\code{"text"}).)", + value = r"(\code{describe_lifecycle()} returns a data frame of class \code{pva_lifecycle} with one row per ordered step and \code{"edges"} and \code{"metadata"} attributes. \code{format_lifecycle()} returns a length-one character string. \code{plot.pva_scenario()} and \code{plot.pva_lifecycle()} return the \code{pva_lifecycle} object invisibly.)", + examples = r"(scenario <- scenario_spec( + name = "island-adaptive", n_runs = 50, n_steps = 20, seed = 1, + init_fun = function() pva_population(sex = rep(c("F", "M"), 8), age = 2), + processes = list( + environment_process(list(env = env_ar1(sd = 0.3, phi = 0.4))), + survival_process( + function(pop, state, context, params) shift_logit(0.85, state$globals$env), + requires = "globals.env" + ), + age_process(), + survey_process(0.7, field = "obs"), + introduction_process( + count = survey_quota(function(obs, state, context, params) as.integer(obs$count < 10L), + field = "obs", on_skip = 0L), + fields = function(n, state, context, params) list(sex = rep("F", n), age = rep(2L, n)) + ), + census_process() + ), + initial_census = census_process() +) +lc <- describe_lifecycle(scenario) +lc +plot(scenario) +cat(format_lifecycle(scenario, "mermaid"), "\n"))" ) ) diff --git a/site/_litedown.yml b/site/_litedown.yml new file mode 100644 index 0000000..af64a96 --- /dev/null +++ b/site/_litedown.yml @@ -0,0 +1,34 @@ +site: + rebuild: "always" + exclude: ["code.Rmd", "playground"] + manual: + State & Process Contract: + desc: Living-state constructors, individual allocation, and the ordered process execution contract. + contents: [pva_state, pva_process] + Demography, Life Tables & Mating: + desc: Core vital-rate processes, litter and sex helpers, age-sex rate tables, and deterministic life-table projections. + contents: [demography_processes, reproduction_helpers, age_sex_rate, life_table_metrics] + Environment, Density & Space: + desc: Correlated environmental anomalies, catastrophes, density multipliers, and discrete-patch dispersal. + contents: [environment_processes, density_multipliers, spatial] + Management, Surveys & Adaptive Control: + desc: Targeted removals, ceilings, introductions, individual assignments, seasonal mating, and substream-5 imperfect surveys. + contents: [management_processes, survey_processes] + Genetics, Pedigree & Neutral Markers: + desc: Exact conditional pedigree kinship, inbreeding depression, and non-perturbing neutral-locus gene drop. + contents: [inbreeding, markers] + Execution, Ensembles & Summaries: + desc: Replicated scenario execution, designed multi-factor ensembles, viability risk, EMA, and cohort accounting. + contents: [scenario, run_pva_ensemble, summaries] + Visualisation & Printing: + desc: Base-graphics trajectory, risk, accounting, ensemble and lifecycle flow diagrams, Mermaid/DOT export, plus print and subset methods. + contents: [plot.pva_run, lifecycle, print.pva_state] + +output: + html: + meta: + css: ["default", "@site", "custom.css"] + include_after: "_footer.md" + options: + number_sections: false + toc: false diff --git a/site/articles.Rmd b/site/articles.Rmd new file mode 100644 index 0000000..51a9cfe --- /dev/null +++ b/site/articles.Rmd @@ -0,0 +1,27 @@ +--- +title: "Articles, examples & design" +subtitle: "Vignettes, worked conservation case studies, and architecture documents" +--- + +```{r, include = FALSE} +litedown::reactor(echo = FALSE) +``` + +## Package vignettes + +`{r} litedown::pkg_articles()` + +## Worked species examples + +Both worked models live under `inst/examples/`, use only the public OpenPVA API, and ship with runnable scripts: + +- **[Lord Howe Island woodhen (`inst/examples/woodhen/`)](https://github.com/BWBrook/OpenPVA/blob/main/inst/examples/woodhen/README.md)** — territorial island bird recovery with sex-specific survival, shared environmental variation, territorial pairing, captive releases, socket-cluster execution, and a structured parameter-evidence table. +- **[Grizzly bear (`inst/examples/grizzly/`)](https://github.com/BWBrook/OpenPVA/blob/main/inst/examples/grizzly/README.md)** — seasonal lifecycle combining summer `mating_process()`, autumn harvest, engine-owned cross-interval sire retention, winter birth, and three-year maternal dependency. + +## Architecture, agent guide & heritage documents + +- **[Agent modelling guide (`docs/for-agents.md`)](https://github.com/BWBrook/OpenPVA/blob/main/docs/for-agents.md)** — exact signatures, verification protocol, and composition templates for AI agents and script authors. +- **[Vision and scope](https://github.com/BWBrook/OpenPVA/blob/main/docs/vision_and_scope.md)** — North Star mission, scope boundaries, and product commitments. +- **[Lifecycle-process contract](https://github.com/BWBrook/OpenPVA/blob/main/docs/design/lifecycle_process_contract.md)** — strict state, field-declaration, accounting, pedigree, marker, and RNG invariants. +- **[Public API reference](https://github.com/BWBrook/OpenPVA/blob/main/docs/reference/public_api.md)** — curated overview of exported builders, helpers, and summaries. +- **[GAPPS heritage](https://github.com/BWBrook/OpenPVA/blob/main/docs/gapps_heritage.md)** and **[GAPPS evidence review](https://github.com/BWBrook/OpenPVA/blob/main/docs/literature/gapps_evidence_review.md)** — primary-source comparison against GAPPS II 1.3 and the Brook et al. (2000) species scripts. diff --git a/site/custom.css b/site/custom.css new file mode 100644 index 0000000..18b63fb --- /dev/null +++ b/site/custom.css @@ -0,0 +1,362 @@ +/* OpenPVA documentation site theme — self-contained, zero external CSS dependency */ +:root { + --openpva-ink: #102c37; + --openpva-ink-soft: #2e4852; + --openpva-teal: #1b6b78; + --openpva-teal-dark: #114b56; + --openpva-gold: #d49234; + --openpva-bg: #ffffff; + --openpva-bg-soft: #f4f8f9; + --openpva-border: #d8e3e7; + --openpva-code-bg: #f6f9fa; + --openpva-font: "IBM Plex Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; + --openpva-mono: "IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; +} + +* { + box-sizing: border-box; +} + +body { + margin: 0; + padding: 0; + background: var(--openpva-bg); + color: #1f2d33; + font-family: var(--openpva-font); + font-size: 16px; + line-height: 1.62; + max-width: none !important; +} + +/* Top navigation bar */ +nav.site-nav { + background: var(--openpva-ink); + border-bottom: 3px solid var(--openpva-gold); + padding: 0; + margin: 0; + position: sticky; + top: 0; + z-index: 100; +} + +nav.site-nav p { + max-width: 1180px; + margin: 0 auto; + padding: 0.72rem 1.5rem; + display: flex; + align-items: center; + gap: 1.5rem; + flex-wrap: wrap; +} + +nav.site-nav a { + color: #e9f3f5 !important; + text-decoration: none; + font-weight: 500; + font-size: 0.96rem; + letter-spacing: 0.01em; +} + +nav.site-nav a:hover, +nav.site-nav a.active { + color: #f4c26b !important; +} + +nav.site-nav a.right { + margin-left: auto; + display: inline-flex; + align-items: center; + font-size: 0.9rem; +} + +nav.site-nav img.no-invert { + width: 20px; + height: 20px; + filter: invert(1) brightness(1.1); +} + +/* Page header */ +header.frontmatter { + max-width: 1180px; + margin: 0 auto; + padding: 2rem 1.5rem 0.85rem 1.5rem; + border-bottom: 1px solid var(--openpva-border); +} + +header.frontmatter h1 { + margin: 0; + font-size: 2.05rem; + line-height: 1.2; + color: var(--openpva-ink); + letter-spacing: -0.02em; +} + +header.frontmatter .subtitle, +header.frontmatter h2.subtitle, +header.frontmatter h2 { + margin: 0.35rem 0 0 0; + font-size: 1.08rem; + font-weight: 400; + color: var(--openpva-ink-soft); + border-bottom: none !important; + padding-bottom: 0; +} + +main, article, p, li, dd, dt, td, th { + font-family: var(--openpva-font); +} + +/* Main container */ +main { + max-width: 1180px; + margin: 0 auto; + padding: 1.5rem 1.5rem 3rem 1.5rem; +} + +article { + max-width: none; +} + +/* Responsive 2-column home grid */ +.openpva-home-grid { + display: grid; + grid-template-columns: minmax(0, 1fr) 265px; + gap: 2.25rem; + align-items: start; +} + +.openpva-sidebar { + background: var(--openpva-bg-soft); + border: 1px solid var(--openpva-border); + border-radius: 10px; + padding: 1.25rem; + position: sticky; + top: 4.4rem; +} + +.openpva-logo { + text-align: center; + margin: 0 0 0.85rem 0; +} + +.openpva-logo img { + max-width: 185px; + width: 100%; + height: auto; + display: inline-block; +} + +.openpva-pills { + display: flex; + justify-content: center; + flex-wrap: wrap; + gap: 0.4rem; + margin-bottom: 1rem; +} + +.openpva-pills .pill { + background: var(--openpva-ink); + color: #f2f7f8; + font-size: 0.76rem; + font-weight: 600; + padding: 0.18rem 0.55rem; + border-radius: 999px; + letter-spacing: 0.02em; +} + +.openpva-meta { + margin: 0; + font-size: 0.88rem; +} + +.openpva-meta dt { + font-weight: 600; + color: var(--openpva-ink); + margin-top: 0.75rem; + font-size: 0.78rem; + text-transform: uppercase; + letter-spacing: 0.05em; +} + +.openpva-meta dt:first-child { + margin-top: 0; +} + +.openpva-meta dd { + margin: 0.15rem 0 0 0; + color: var(--openpva-ink-soft); + line-height: 1.48; +} + +/* Typography & links */ +h2 { + color: var(--openpva-ink); + font-size: 1.42rem; + margin: 2rem 0 0.7rem 0; + padding-bottom: 0.3rem; + border-bottom: 1px solid var(--openpva-border); + text-align: left !important; +} + +h3 { + color: var(--openpva-ink); + font-size: 1.12rem; + margin: 1.45rem 0 0.4rem 0; +} + +a { + color: var(--openpva-teal); + text-decoration: none; +} + +a:hover { + color: var(--openpva-teal-dark); + text-decoration: underline; +} + +blockquote { + margin: 0 0 1.25rem 0; + border-left: 4px solid var(--openpva-gold); + background: var(--openpva-bg-soft); + padding: 0.8rem 1.1rem; + border-radius: 0 8px 8px 0; + color: var(--openpva-ink); +} + +blockquote p { + margin: 0; +} + +img { + max-width: 100%; + height: auto; +} + +/* Code & pre */ +code { + font-family: var(--openpva-mono); + font-size: 0.88em; + background: var(--openpva-code-bg); + padding: 0.12em 0.35em; + border-radius: 4px; + color: #143b46; +} + +pre { + background: var(--openpva-code-bg); + border: 1px solid var(--openpva-border); + border-radius: 8px; + padding: 0.9rem 1.05rem; + overflow-x: auto; + line-height: 1.45; +} + +pre code { + background: none; + padding: 0; + font-size: 0.86rem; +} + +/* Tables */ +table { + border-collapse: collapse; + width: 100%; + margin: 1rem 0 1.25rem 0; + font-size: 0.94rem; +} + +th, td { + border: 1px solid var(--openpva-border); + padding: 0.55rem 0.75rem; + text-align: left; + vertical-align: top; +} + +th { + background: var(--openpva-bg-soft); + color: var(--openpva-ink); + font-weight: 600; +} + +/* Manual index card */ +.callout-tip { + background: var(--openpva-bg-soft); + border: 1px solid var(--openpva-border); + border-top: 4px solid var(--openpva-teal); + border-radius: 10px; + padding: 1.2rem 1.5rem 1.4rem 1.5rem; + margin-bottom: 2rem; +} + +.callout-tip h3 { + margin: 1.2rem 0 0.25rem 0; + color: var(--openpva-ink); + font-size: 1.05rem; + border-bottom: 1px dashed var(--openpva-border); + padding-bottom: 0.2rem; +} + +.callout-tip h3:first-child { + margin-top: 0; +} + +.callout-tip p { + margin: 0.3rem 0 0.55rem 0; + color: var(--openpva-ink-soft); + font-size: 0.92rem; +} + +.callout-tip a code { + display: inline-block; + margin: 0.16rem 0.25rem 0.16rem 0; + background: #ffffff; + border: 1px solid #c4d7dd; + color: var(--openpva-teal-dark); + padding: 0.18rem 0.5rem; + border-radius: 6px; + font-size: 0.84rem; + transition: background 0.12s ease, border-color 0.12s ease; +} + +.callout-tip a:hover { + text-decoration: none; +} + +.callout-tip a:hover code { + background: var(--openpva-ink); + border-color: var(--openpva-ink); + color: #ffffff; +} + +/* Footer */ +footer { + border-top: 1px solid var(--openpva-border); + background: var(--openpva-bg-soft); + color: var(--openpva-ink-soft); + font-size: 0.88rem; + margin-top: 2rem; +} + +footer .flex-col { + max-width: 1180px; + margin: 0 auto; + padding: 1.1rem 1.5rem; + display: flex; + justify-content: space-between; + flex-wrap: wrap; + gap: 0.75rem; +} + +footer p { + margin: 0; +} + +@media (max-width: 900px) { + .openpva-home-grid { + grid-template-columns: 1fr; + } + .openpva-sidebar { + position: static; + order: -1; + } +} diff --git a/site/index.Rmd b/site/index.Rmd new file mode 100644 index 0000000..814c9dc --- /dev/null +++ b/site/index.Rmd @@ -0,0 +1,82 @@ +--- +title: "`{r} pkg_name`" +subtitle: "`{r} packageDescription(pkg_name, fields = 'Title')`" +--- + +```{r, order = 0, include = FALSE} +litedown::reactor(echo = FALSE) +pkg_name = litedown:::detect_pkg() +pkg_path = attr(pkg_name, 'path') +readme = file.path(pkg_path, 'README.md') +has_readme = file.exists(readme) +fig = file.path(pkg_path, 'man/figures') +if (!xfun::same_path('.', pkg_path) && dir.exists(fig)) { + xfun::dir_create('man') + file.copy(fig, 'man', recursive = TRUE) +} +``` + +
+
+ +```{r, results = 'asis'} +if (has_readme) { + x = xfun::read_utf8(readme) + # Strip top title and badges block (rendered cleanly in the sidebar) + i = which(x == '') + if (length(i)) x = x[seq_along(x) > i[1]] + # Drop the brief Citation heading from README so the full citation block below is authoritative + c_start = which(grepl('^##\\s+Citation\\s*$', x)) + if (length(c_start)) { + next_h = which(grepl('^##\\s+', x) & seq_along(x) > c_start[1]) + c_end = if (length(next_h)) next_h[1] - 1L else length(x) + x = x[-seq.int(c_start[1], c_end)] + } + xfun::raw_string(x) +} +``` + +## Citation + +To cite **`{r} pkg_name`** in publications, please use: + +```{r, warning = FALSE} +litedown::pkg_citation(pkg_name) +``` + +
+ +
diff --git a/site/manual.Rmd b/site/manual.Rmd new file mode 100644 index 0000000..571d6a4 --- /dev/null +++ b/site/manual.Rmd @@ -0,0 +1,10 @@ +--- +title: "Function reference" +subtitle: "All 62 exported functions and S3 methods grouped by ecological role" +--- + +```{r, include = FALSE} +litedown::reactor(echo = FALSE) +``` + +`{r} litedown::pkg_manual(toc = FALSE, number_sections = FALSE)` diff --git a/tests/testthat/test-lifecycle.R b/tests/testthat/test-lifecycle.R new file mode 100644 index 0000000..7a6a305 --- /dev/null +++ b/tests/testthat/test-lifecycle.R @@ -0,0 +1,292 @@ +test_that("describe_lifecycle inspects scenarios, runs and process lists cleanly", { + scenario <- scenario_spec( + name = "adaptive-island", + n_runs = 10L, + n_steps = 5L, + seed = 7L, + init_fun = function() { + pva_state( + pva_population(sex = rep(c("F", "M"), 4L), age = 2L, mate_id = NA_integer_), + pedigree = TRUE, + n_loci = 4L, + mate_field = "mate_id" + ) + }, + processes = list( + environment_process(list(env = env_ar1(sd = 0.2, phi = 0.3))), + survival_process( + function(pop, state, context, params) { + shift_logit(ifelse(pop$age == 0L, 0.5, 0.85), state$globals$env) + }, + requires = c("population.age", "globals.env") + ), + age_process(), + mating_process(field = "mate_id"), + reproduction_process( + breeding_probability = function(pop, state, context, params) as.numeric(pop$age >= 2L), + litter_size = litter_poisson(1.1), + offspring_sex = offspring_sex_bernoulli(0.5), + mate = mate_from_field("mate_id"), + newborn_fields = function(mothers, fathers, offspring_mother, pop, state, context, params) { + list(mate_id = NA_integer_) + }, + newborn_field_names = "mate_id", + requires = c("population.age", "population.mate_id") + ), + survey_process(0.7, field = "obs"), + introduction_process( + count = survey_quota( + function(obs, state, context, params) as.integer(obs$count < 6L), + field = "obs", + on_skip = 0L + ), + fields = function(n, state, context, params) { + list(sex = rep("F", n), age = rep(2L, n), mate_id = rep(NA_integer_, n)) + }, + creates = c("sex", "age", "mate_id"), + name = "adaptive_release" + ), + census_process() + ), + initial_census = census_process() + ) + + # Does not touch RNG or run init_fun unless state is passed + set.seed(123) + seed_before <- .GlobalEnv$.Random.seed + lc <- describe_lifecycle(scenario) + expect_identical(.GlobalEnv$.Random.seed, seed_before) + expect_s3_class(lc, "pva_lifecycle") + expect_s3_class(lc, "data.frame") + expect_identical(nrow(lc), 9L) + expect_identical(lc$step, 0:8) + expect_identical(lc$phase, c("initial", rep("interval", 8L))) + expect_identical( + lc$role, + c("census", "environment", "demography", "demography", "demography", + "demography", "survey", "management", "census") + ) + + edges <- attr(lc, "edges") + expect_true(any(edges$from_name == "environment" & edges$to_name == "survival" & + edges$field == "globals.env" & edges$kind == "same_interval")) + expect_true(any(edges$from_name == "age" & edges$to_name == "survival" & + edges$field == "population.age" & edges$kind == "carryover")) + expect_true(any(edges$from_name == "mating" & edges$to_name == "reproduction" & + edges$field == "population.mate_id" & edges$kind == "same_interval")) + expect_true(any(edges$from_name == "survey" & edges$to_name == "adaptive_release" & + edges$field == "globals.obs" & edges$kind == "same_interval")) + + # State annotation + printing + text/mermaid/dot export + lc_state <- describe_lifecycle(scenario, state = scenario$init_fun()) + expect_true(attr(lc_state, "metadata")$state$pedigree) + expect_identical(attr(lc_state, "metadata")$state$n_loci, 4L) + expect_identical(attr(lc_state, "metadata")$state$mate_field, "mate_id") + + txt <- format_lifecycle(lc_state, "text") + expect_match(txt, "adaptive-island") + expect_match(txt, "pedigree: on") + expect_match(txt, "mate_field: mate_id") + + mmd <- format_lifecycle(scenario, "mermaid") + expect_match(mmd, "^flowchart LR") + expect_match(mmd, 'S1 ==> S2') + expect_match(mmd, 'S1 -. "env" .-> S2') + expect_match(mmd, "classDef survey") + + dot <- format_lifecycle(scenario, "dot") + expect_match(dot, "^digraph OpenPVA_Lifecycle") + expect_match(dot, 'S6 -> S7 .*label="obs"') + + # Works directly on a process list and on a pva_run + lc_list <- describe_lifecycle(scenario$processes) + expect_identical(nrow(lc_list), 8L) + run <- run_scenario(scenario) + lc_run <- describe_lifecycle(run) + expect_identical(lc_run$name, lc$name) + + expect_error(describe_lifecycle(42), "pva_scenario") +}) + +test_that("plot.pva_scenario and plot.pva_lifecycle render single- and two-row diagrams without touching RNG", { + short_sc <- scenario_spec( + name = "short", + n_runs = 5L, + n_steps = 5L, + seed = 1L, + init_fun = function() pva_population(sex = c("F", "M"), age = 2L), + processes = list(survival_process(0.8), age_process(), census_process()) + ) + long_sc <- scenario_spec( + name = "long", + n_runs = 5L, + n_steps = 5L, + seed = 1L, + init_fun = function() pva_population(sex = c("F", "M"), age = 2L), + processes = list( + environment_process(list(env = env_ar1(sd = 0.2, phi = 0.3))), + catastrophe_process(0.05, 0.2, name = "storm"), + survival_process(function(pop, state, context, params) shift_logit(0.85, state$globals$env), + requires = "globals.env"), + age_process(), + survey_process(0.8, field = "obs"), + removal_process(count = survey_quota(function(obs, state, context, params) 0L, field = "obs", on_skip = 0L)), + census_process() + ), + initial_census = census_process() + ) + + tf <- tempfile(fileext = ".pdf") + on.exit(unlink(tf), add = TRUE) + grDevices::pdf(tf, width = 9, height = 5) + on.exit(grDevices::dev.off(), add = TRUE) + + set.seed(99) + seed_before <- .GlobalEnv$.Random.seed + res1 <- plot(short_sc) + res2 <- plot(long_sc, state = pva_state(long_sc$init_fun(), pedigree = TRUE)) + res3 <- plot(describe_lifecycle(long_sc), show_flows = FALSE) + expect_identical(.GlobalEnv$.Random.seed, seed_before) + expect_s3_class(res1, "pva_lifecycle") + expect_s3_class(res2, "pva_lifecycle") + expect_s3_class(res3, "pva_lifecycle") +}) + +test_that("Layer 4 UX fixes: shift_logit handles empty ifelse(), ensemble subset keeps provenance, plot.pva_ensemble respects col", { + # 1. Empty logical(0) from ifelse() on extinct replicate + expect_identical(shift_logit(ifelse(integer(0) == 0L, 0.5, 0.8), 0.3), numeric(0)) + expect_error(shift_logit(TRUE, 0.3), "probability") + expect_error(shift_logit(numeric(0), NA_real_), "deviation") + + # End-to-end extinct replicate with ifelse() inside shift_logit() + extinct_sc <- scenario_spec( + name = "extinct-ifelse", + n_runs = 4L, + n_steps = 4L, + seed = 1L, + init_fun = function() pva_population(sex = "F", age = 1L), + processes = list( + environment_process(list(env = env_ar1(sd = 0.2, phi = 0))), + survival_process( + function(pop, state, context, params) { + shift_logit(ifelse(pop$age == 0L, 0.0, 0.0), state$globals$env) + }, + requires = c("population.age", "globals.env") + ), + census_process() + ) + ) + ext_run <- run_scenario(extinct_sc) + expect_identical(summarise_pva(ext_run, threshold = 1)$p_ever_below, 1) + + # 2. Subsetting pva_ensemble preserves provenance + design <- data.frame(s = c(0.7, 0.9), label = c("low", "high"), stringsAsFactors = FALSE) + ens <- run_pva_ensemble( + design = design, + build = function(row) list( + n_steps = 5L, + init_fun = function() pva_population(sex = rep(c("F", "M"), 5L), age = 2L), + processes = list(survival_process(row$s), census_process()) + ), + n_runs = 10L, + seed = 42L, + summarise = function(run, row) summarise_pva(run, threshold = 3) + ) + sub_ens <- ens[, c("label", "p_ever_below")] + expect_s3_class(sub_ens, "pva_ensemble") + expect_identical(attr(sub_ens, "provenance")$n_runs, 10L) + expect_identical(attr(sub_ens, "provenance")$root_seed, 42L) + out_txt <- paste(utils::capture.output(print(sub_ens)), collapse = "\n") + expect_match(out_txt, "runs/member: 10") + expect_match(out_txt, "root seed: 42") + expect_true(is.numeric(ens[, "p_ever_below"])) + + # 3. plot.pva_ensemble accepts scalar and per-member col cleanly + tf <- tempfile(fileext = ".pdf") + on.exit(unlink(tf), add = TRUE) + grDevices::pdf(tf, width = 6, height = 4) + on.exit(grDevices::dev.off(), add = TRUE) + expect_silent(plot(ens, y = "p_ever_below", by = "label", col = c("#B84A39", "#1B6B78"))) + expect_silent(plot(ens, y = "p_ever_below", by = "label", col = "#1B6B78")) + # Default col must draw non-NA intervals for all members, and subsetted design cols must auto-label + expect_silent(plot(sub_ens, y = "p_ever_below")) + ens3 <- run_pva_ensemble( + design = data.frame(s = c(0.7, 0.8, 0.9), label = c("low", "mid", "high"), pair = 1L, + stringsAsFactors = FALSE), + build = function(row) list( + n_steps = 5L, + init_fun = function() pva_population(sex = rep(c("F", "M"), 5L), age = 2L), + processes = list(survival_process(row$s), census_process()) + ), + n_runs = 10L, + seed = 42L, + seed_by = "pair", + summarise = function(run, row) summarise_pva(run, threshold = 3) + ) + expect_identical(length(unique(ens3$member_seed)), 1L) + cap <- new.env(parent = emptyenv()) + cap$cols <- NULL + suppressMessages(trace( + graphics::segments, + tracer = bquote(assign("cols", col, envir = .(cap))), + print = FALSE + )) + on.exit(suppressMessages(untrace(graphics::segments)), add = TRUE) + plot(ens3, y = "p_ever_below") + expect_length(cap$cols, 3L) + expect_false(anyNA(cap$cols)) +}) + +test_that("Astra challenge regressions: pva_lifecycle subsetting, N_end label, roles, escaping, and large-n layout", { + # Subsetting pva_lifecycle drops lifecycle class so print() works cleanly on any slice + sc <- scenario_spec( + name = "die", n_runs = 1L, n_steps = 1L, seed = 5L, + init_fun = function() { + pva_state( + pva_population(sex = c("F", "M"), age = 2L), + globals = list(inbreeding_proxy = 0) + ) + }, + processes = list( + inbreeding_proxy_process(function(pop, state, context, params) 10, generation_time = 2), + survival_process(0), + census_process() + ) + ) + run <- run_scenario(sc, keep = c("census", "state")) + lc <- describe_lifecycle(run) + expect_identical(lc$role[[1L]], "demography") + expect_identical(attr(lc, "metadata")$state$source, "final") + txt <- paste(utils::capture.output(print(lc)), collapse = "\n") + expect_match(txt, "N_end = 0") + expect_false(grepl("N0 = 0", txt, fixed = TRUE)) + + sub_lc <- lc[, c("name", "role")] + expect_false(inherits(sub_lc, "pva_lifecycle")) + expect_s3_class(sub_lc, "data.frame") + expect_null(attr(sub_lc, "edges")) + expect_output(print(sub_lc), "inbreeding_proxy") + + # Double quotes preserved via Mermaid #quot; entity + quoted <- pva_process('step "A"', function(state, context, params) pva_result(state)) + mmd <- format_lifecycle(list(quoted), "mermaid") + expect_match(mmd, "#quot;A#quot;", fixed = TRUE) + + # Single-step and 39-step diagrams keep strictly positive box widths + tf <- tempfile(fileext = ".pdf") + on.exit(unlink(tf), add = TRUE) + grDevices::pdf(tf, width = 9, height = 5) + on.exit(grDevices::dev.off(), add = TRUE) + cap_w <- new.env(parent = emptyenv()) + cap_w$widths <- numeric() + suppressMessages(trace( + OpenPVA:::.draw_rounded_box, + tracer = bquote(assign("widths", c(get("widths", envir = .(cap_w)), x1 - x0), envir = .(cap_w))), + print = FALSE + )) + on.exit(suppressMessages(untrace(OpenPVA:::.draw_rounded_box)), add = TRUE) + plot(describe_lifecycle(list(age_process()))) + plot(describe_lifecycle(rep(list(age_process()), 39L))) + expect_true(length(cap_w$widths) > 0L) + expect_true(all(cap_w$widths > 0)) +}) diff --git a/vignettes/workflow.Rmd b/vignettes/workflow.Rmd new file mode 100644 index 0000000..b8b2f85 --- /dev/null +++ b/vignettes/workflow.Rmd @@ -0,0 +1,296 @@ +--- +title: "Inspecting, Checking, and Comparing PVAs in OpenPVA" +output: + html: + options: + toc: true +--- + + + +`{r} if (!capabilities("png")) invisible(litedown::reactor(dev = "pdf"))` + +```{r setup, include=FALSE} +library(OpenPVA) +litedown::reactor(fig.width = 7.2, fig.height = 4.2) +``` + +An individual-based Population Viability Analysis (PVA) is only as trustworthy +as its biological assumptions, accounting identities, and sensitivity comparisons. +This walkthrough demonstrates the standard OpenPVA workflow on a small island +population facing environmental variability, cyclones, and inbreeding +depression: + +1. **Assemble and visually inspect the lifecycle** *before* simulating. +2. **Check the deterministic baseline** with `life_table_metrics()`. +3. **Run and audit stochastic trajectories** with cohort accounting and + diagnostic plots. +4. **Compare management options and genetic retention** in a paired ensemble. + +Every chunk uses small replicate counts and fixed seeds so the vignette builds +in seconds; real assessments should scale `n_runs` to achieve the desired Monte +Carlo precision. + +## 1. Assemble and inspect the lifecycle + +We define a helper that builds our island population (`N0 = 36`, exact pedigree +tracking, and 8 neutral microsatellite-like loci) under three management +options: **status quo**, **biennial imperfect surveys (`p = 0.70`) triggering +adaptive releases**, and a **fixed 12-year release schedule**. + +```{r model} +build_island <- function(name, strategy = c("status_quo", "adaptive", "fixed"), + n_runs = 40L, seed = 2026L) { + strategy <- match.arg(strategy) + + init_fun <- function() { + pva_state( + pva_population( + sex = rep(c("F", "M"), each = 18L), + age = rep(1:6, times = 6L) + ), + pedigree = TRUE, + n_loci = 8L + ) + } + + env_proc <- environment_process(list(env = env_ar1(sd = 0.42, phi = 0.45))) + cyclone <- catastrophe_process(probability = 0.06, mortality = 0.28, name = "cyclone") + + surv_proc <- survival_process( + probability = function(pop, state, context, params) { + base <- ifelse(pop$age == 0L, 0.56, 0.84) + dens <- ceiling_density_multiplier(length(pop$id), capacity = 95) + inb <- inbreeding_multiplier(pop$pedigree_F, lethal_equivalents = 3.14) + shift_logit(base, state$globals$env) * dens * inb + }, + requires = c("population.age", "population.pedigree_F", "globals.env") + ) + + breed_proc <- reproduction_process( + breeding_probability = function(pop, state, context, params) { + as.numeric(pop$age >= 2L) * 0.78 + }, + litter_size = litter_poisson(1.15), + offspring_sex = offspring_sex_bernoulli(0.5), + mate = mate_min_kinship( + eligible = function(pop, state, context, params) pop$age >= 2L, + max_kinship = 0.25 + ), + requires = "population.age" + ) + + release_fields <- function(n, state, context, params) { + list(sex = rep(c("F", "M"), length.out = n), age = rep(2L, n)) + } + + mgmt <- switch( + strategy, + status_quo = list(), + adaptive = list( + survey_process(detection = 0.70, when = seq.int(0L, 29L, by = 2L), field = "obs"), + introduction_process( + count = survey_quota( + rule = function(obs, state, context, params) if (obs$count < 26L) 6L else 0L, + field = "obs", + on_skip = 0L + ), + fields = release_fields, + name = "adaptive_release" + ) + ), + fixed = list( + introduction_process( + count = function(state, context, params) if (context$time < 12L) 4L else 0L, + fields = release_fields, + name = "fixed_release" + ) + ) + ) + + census <- census_process(genetic_metrics()) + + scenario_spec( + name = name, + n_runs = n_runs, + n_steps = 30L, + init_fun = init_fun, + processes = c( + list(env_proc, cyclone, surv_proc, age_process(), breed_proc), + mgmt, + list(census) + ), + initial_census = census, + seed = seed + ) +} + +sc_adaptive <- build_island("Island adaptive management", "adaptive") +``` + +Before running a single replicate, `describe_lifecycle()` audits process order, +ecological roles, declared field effects, and inter-process data flows—without +advancing the RNG: + +```{r inspect} +lc <- describe_lifecycle(sc_adaptive, state = sc_adaptive$init_fun()) +lc[, c("step", "phase", "name", "role", "writes", "creates")] +``` + +Calling `plot()` on a scenario (or `pva_lifecycle`) translates that declared +contract into a pure-base-R lifecycle flow diagram. Dashed arcs highlight +inter-process state and global couplings (`env`, `age`, `obs`), while the +outer loop closes the annual step: + +```{r lifecycle-plot, fig.width = 8.2, fig.height = 4.4} +plot(lc) +``` + +For manuscripts, reports, or GitHub READMEs, `format_lifecycle()` exports the +exact same structure as Mermaid or Graphviz DOT: + +```{r mermaid} +cat(format_lifecycle(lc, "mermaid"), "\n") +``` + +## 2. Check the deterministic baseline + +Before interpreting stochastic risk, compare the baseline mean vital rates +against an analytical female projection using `life_table_metrics()`. Here our +post-breeding census counts newborns at age 0, females survive with baseline +rates `0.56` (age 0) and `0.84` (ages 1+), and produce an expected +`0.78 * 1.15 * 0.5 = 0.4485` daughters per year from age 2 onward: + +```{r life-table} +lt <- life_table_metrics( + survival = c(0.56, 0.84, 0.84), + fecundity = c(0, 0, 0.78 * 1.15 * 0.5), + timing = "post_breeding", + plus_group = TRUE +) +round(c( + lambda = lt$lambda, + r = lt$r, + R0 = lt$R0, + generation_time = lt$generation_time, + cohort_generation_time = lt$cohort_generation_time +), 3) +``` + +Without cyclones, environmental autocorrelation, density caps, or inbreeding +depression, the baseline demography grows gently (λ = `{r} round(lt$lambda, 3)`, +stable generation time = `{r} round(lt$generation_time, 1)` years, cohort +generation time = `{r} round(lt$cohort_generation_time, 1)` years). +Stochasticity, cyclones, and inbreeding depression in a small founder pool of +36 animals are therefore what drive quasi-extinction risk below. + +## 3. Run, audit accounting, and visualise trajectories + +Let us run the status-quo and survey-triggered scenarios on the same seed and +verify strict cohort accounting first: + +```{r run-pair} +sc_sq <- build_island("Status quo", "status_quo") +run_sq <- run_scenario(sc_sq) +run_ar <- run_scenario(sc_adaptive) + +c( + status_quo_reconciled = all(summarise_accounting(run_sq)$reconciled), + adaptive_reconciled = all(summarise_accounting(run_ar)$reconciled) +) +``` + +`plot(run, type = "accounting")` inspects mean annual births, introductions, +deaths, and net population change across replicates (flagging any unreconciled +interval with a red cross): + +```{r accounting-plot, fig.width = 7.4, fig.height = 3.9} +op <- par(mar = c(4.2, 4.4, 2.6, 1.0), las = 1, bty = "l") +plot(run_ar, type = "accounting", main = "Survey-triggered release: cohort accounting") +par(op) +``` + +Next, overlay the two strategies' abundance ribbons and cumulative +quasi-extinction risk curves (`N < 15`) using `add = TRUE`: + +```{r traj-risk-plot, fig.width = 8.0, fig.height = 3.8} +col_sq <- "#B84A39" +col_ar <- "#1B6B78" + +op <- par(mfrow = c(1L, 2L), mar = c(4.2, 4.4, 2.8, 1.0), las = 1, bty = "l") +plot(run_sq, type = "trajectory", threshold = 15, runs = 0L, col = col_sq, + ylim = c(0, 120), ylab = "Living individuals (N)", + main = "Trajectories (50% & 90% bands)") +plot(run_ar, type = "trajectory", threshold = 15, runs = 0L, col = col_ar, add = TRUE) +legend("topleft", c("Survey-triggered", "Status quo"), + col = c(col_ar, col_sq), lwd = 2.4, bty = "n", cex = 0.85) + +plot(run_sq, type = "risk", threshold = 15, col = col_sq, ylim = c(0, 0.9), + ylab = "P(N < 15 by year t)", main = "Cumulative risk (95% Wilson CI)") +plot(run_ar, type = "risk", threshold = 15, col = col_ar, add = TRUE) +legend("topleft", c("Status quo", "Survey-triggered"), + col = c(col_sq, col_ar), lwd = 2.4, bty = "n", cex = 0.85) +par(op) +``` + +## 4. Paired management ensemble and genetic retention + +`run_pva_ensemble()` separates the experimental design from the inner Monte +Carlo replicates. Supplying a shared grouping column in `seed_by` (here a +constant column `pair = 1L`) pairs all three strategies on the exact same +replicate streams (`seed_by = NULL` gives each row an independent seed). +Subsetting the returned `pva_ensemble` data frame keeps its provenance header +intact: + +```{r ensemble} +design <- data.frame( + strategy = c("status_quo", "adaptive", "fixed"), + label = c("Status quo", "Adaptive", "Fixed 12-yr"), + pair = 1L, + stringsAsFactors = FALSE +) + +ens <- run_pva_ensemble( + design = design, + build = function(row) build_island(row$label, row$strategy), + n_runs = 40L, + summarise = function(run, row) summarise_pva(run, threshold = 15), + seed = 2026L, + seed_by = "pair" +) + +stopifnot(length(unique(ens$member_seed)) == 1L) +ens[, c("label", "p_ever_below", "ema", "final_mean")] +``` + +Finally, contrast the three management options alongside neutral genetic +diversity (`expected_heterozygosity` tracked on isolated marker substreams via +`n_loci = 8L` and `census_process(genetic_metrics())`): + +```{r ensemble-genetics-plot, fig.width = 8.0, fig.height = 3.8} +cols <- c(col_sq, col_ar, "#C88A2B") + +op <- par(mfrow = c(1L, 2L), mar = c(4.2, 4.4, 2.8, 1.0), las = 1, bty = "l") +plot(ens, y = "p_ever_below", by = "label", col = cols, ylim = c(0, 0.95), + cex.axis = 0.78, xlab = "", ylab = "30-yr quasi-extinction risk (N < 15)", + main = "Ensemble risk contrast") + +plot(run_sq, type = "trajectory", metric = "expected_heterozygosity", + threshold = 0, runs = 0L, col = col_sq, ylim = c(0.65, 1.0), + ylab = "Expected heterozygosity (He)", + main = "Neutral genetic retention (8 loci)") +plot(run_ar, type = "trajectory", metric = "expected_heterozygosity", + threshold = 0, runs = 0L, col = col_ar, add = TRUE) +legend("bottomleft", c("Survey-triggered", "Status quo"), + col = c(col_ar, col_sq), lwd = 2.4, bty = "n", cex = 0.85) +par(op) +``` + +Notice how survey-triggered supplementation both slashes 30-year quasi-extinction +risk and arrests the erosion of neutral heterozygosity—and every diagnostic +figure was drawn directly from reproducible base-R `OpenPVA` summaries with no +external plotting dependencies.