Skip to contents

Orchestrate the full habitat pipeline: generate gradient access barriers, segment the network via frs_network_segment(), classify habitat via frs_habitat_classify(), and persist results.

Usage

frs_habitat(
  conn,
  wsg = NULL,
  aoi = NULL,
  species = NULL,
  label = NULL,
  to_streams = NULL,
  to_habitat = NULL,
  break_sources = NULL,
  breaks_gradient = NULL,
  gate = TRUE,
  label_block = "blocked",
  rules = NULL,
  gradient_recompute = TRUE,
  measure_precision = 0L,
  barrier_overrides = NULL,
  to_barriers = NULL,
  params = NULL,
  params_fresh = NULL,
  params_method = NULL,
  workers = 1L,
  password = "",
  cleanup = TRUE,
  verbose = TRUE
)

Arguments

conn

A DBI::DBIConnection object (from frs_db_conn()).

wsg

Character or NULL. One or more watershed group codes. When provided, species are auto-detected via frs_wsg_species().

aoi

AOI specification or NULL. Overrides the spatial extent. Accepts anything frs_extract() handles: sf polygon, character WSG code, WHERE clause string, or named list. When NULL with wsg, uses the WSG polygon.

species

Character or NULL. Species codes to classify (e.g. c("CO", "BT")). When NULL with wsg, auto-detected. Required when wsg is NULL.

label

Character or NULL. Short label for working table names. Auto-generated from wsg when available. Required when wsg is NULL and aoi is provided.

to_streams

Character or NULL. Schema-qualified table for persistent stream segments. Accumulates across runs, and must not be the working table working.streams_<label> that this call builds.

Each run overwrites its own partition of the table and inserts its rows in one transaction, so a run that fails leaves the partition as it was. With wsg and no aoi, the partition is the watershed group. Otherwise — a custom aoi, or wsg and aoi together, where a character aoi is ANDed into the group filter and an sf or list aoi replaces it, so the run covers part of the group or ground outside it — the partition is the FWA segments the run covers, keyed on linear_feature_id. An AOI selects whole segments, never part of one, so every row the run is about to replace goes, including sub-segments an earlier run broke at different measures. Rows for ground the run does not cover are untouched, whichever watershed group they belong to.

Two limits. A target that carries no linear_feature_id is not the Freshwater Atlas, and the custom-AOI key falls back to id_segment, which is only sound where that column is unique across the whole table; a target carrying it while the working table does not, or the reverse, is an error rather than a fallback. And a table written by a release before 0.53.0 may be missing rows: a custom-AOI run then keyed its delete on id_segment alone, which is unique only within a watershed group, so it could remove rows no run put back. Re-running an affected group with wsg and no aoi repairs it, the whole-group overwrite being self-healing — but a table that must also gain linear_feature_id is repaired one group at a time, and a custom-AOI run refuses a target still holding NULL-keyed rows from the groups not yet re-run.

to_habitat

Character or NULL. Schema-qualified table for habitat classifications. Long format: one row per segment x species.

break_sources

List of additional break source specs (falls, crossings, etc.), or NULL. Gradient access barriers are generated automatically from species parameters.

breaks_gradient

Numeric vector or NULL. Extra gradient thresholds at which to break the network for sub-segment resolution (in addition to species access thresholds, which are always generated). Three modes:

  • NULL (default) — auto-derive from spawn_gradient_max and rear_gradient_max in params. Captures every biologically meaningful threshold for the species being classified.

  • Numeric vector — explicit list (e.g. c(0.06, 0.12)). Replaces auto-derivation.

  • numeric(0) — disable extras. Only access thresholds are generated (the fresh 0.9.0 behavior).

Auto-derived breaks give cluster analysis (frs_cluster()) the gradient resolution to detect within-segment steep sections that would otherwise be hidden by averaging.

gate

Logical. If TRUE (default), breaks restrict classification — segments upstream of a blocking break are marked inaccessible. If FALSE, all segments are classified regardless of breaks (raw habitat potential).

label_block

Character vector. Labels that always block access. Default "blocked". Gradient labels (gradient_NNNN, the canonical 4-digit basis-point format like gradient_1500 for 15%, or the legacy gradient_N like gradient_15) are always threshold-aware regardless of this parameter. Set to c("blocked", "potential") for conservative analysis.

rules

Character path to a habitat rules YAML, FALSE, or NULL. Default NULL uses the bundled inst/extdata/parameters_habitat_rules.yaml. Pass a path string to load a custom rules file (e.g. one shipped by the link package). Pass FALSE to disable rules entirely and use only the CSV ranges path (the pre-0.12.0 behavior).

Only consulted when params = NULL. If you pass your own params from frs_params(), the rules are baked into that object and rules here is ignored.

See frs_params() for the rules format. A rule's near_river pair, its own or inherited from the thresholds CSV (see frs_habitat_predicates()), makes classify write <to_habitat>_near_river (or <streams>_habitat_near_river), which is kept.

gradient_recompute

Logical. If TRUE (default), recompute gradient from DEM vertices after splitting segments. If FALSE, child segments inherit the parent gradient. See frs_network_segment() for details.

measure_precision

Integer. Number of decimal places to round break point measures before splitting. Default 0 (integer rounding, matching bcfishpass v0.5.0). Also rounds the breaks table and deduplicates collapsed measures.

barrier_overrides

Character or NULL. Schema-qualified table of barrier overrides prepared by link via lnk_barrier_overrides(). Must have columns blue_line_key, downstream_route_measure, species_code. When provided, matched barriers are excluded from per-species access gating. Default NULL (no overrides).

to_barriers

Character or NULL. Schema-qualified table for persisting gradient barriers. Includes blue_line_key, downstream_route_measure, gradient_class, label, wscode_ltree, localcode_ltree. Useful for link's lnk_barrier_overrides(). Default NULL (barriers dropped after segmentation).

params

Named list from frs_params(), or NULL to use bundled parameters_habitat_thresholds.csv and rules YAML.

params_fresh

Data frame from parameters_fresh.csv, or NULL to use bundled default.

params_method

Data frame with watershed_group_code and model ("cw" or "mad") columns picking the habitat size model per watershed group (bcfishpass parameters_habitat_method.csv), or NULL to use the bundled default (all cw). Groups missing from it use cw. See frs_habitat_classify().

workers

Integer. Number of parallel workers. Default 1. Values > 1 require the mirai package. Only used in WSG mode.

password

Character. Database password for parallel workers.

cleanup

Logical. Drop working tables when done. Default TRUE.

verbose

Logical. Print progress. Default TRUE.

Value

A data frame with columns label, n_segments, n_species, elapsed_s.

Details

Supports three modes:

  • WSG mode (wsg): one or more watershed group codes. Species auto-detected. Parallelizes across WSGs.

  • Custom AOI (aoi + species): any spatial extent with explicit species. For sub-basins, territories, or cross-WSG study areas.

  • WSG + custom AOI (wsg + aoi): WSG for species lookup and table naming, custom AOI for spatial extent.

Lake and wetland rearing

lake_rearing / wetland_rearing come from a species' first rear rule with waterbody_type: L / W: an accessible segment inside a lake or wetland polygon of at least the rule's lake_ha_min / wetland_ha_min hectares. No channel-width or discharge test applies, under either habitat model. That rule may also carry

- waterbody_type: L
  lake_ha_min: 10
  requires_connected: spawning
  connected_distance_max: 3000

After classification, a polygon then keeps the flag only if same-species spawning lies on one of its lines, or within connected_distance_max metres downstream of it, or upstream of it within that distance (traced down mainstem lines to the polygon). The polygon is the unit: one connected line keeps all of it. Spawning on a sibling tributary or in another watershed group does not connect, and the trace has no gradient stop. Only the bucket flag is filtered: if the L / W rule also feeds the main rearing predicate (no area_only: true), rearing is unchanged. A rule without requires_connected keeps every polygon that passes the area test.

Examples

if (FALSE) { # \dontrun{
conn <- frs_db_conn()

# WSG mode — species auto-detected
frs_habitat(conn, "BULK",
  to_streams = "fresh.streams",
  to_habitat = "fresh.streams_habitat",
  break_sources = list(
    list(table = "working.falls", where = "barrier_ind = TRUE",
         label = "blocked")))

# Custom AOI — sub-basin via ltree filter
frs_habitat(conn,
  aoi = "wscode_ltree <@ '100.190442.999098'::ltree",
  species = c("BT", "CO"),
  label = "richfield",
  to_streams = "fresh.streams",
  to_habitat = "fresh.streams_habitat")

# WSG + custom AOI — WSG for species, polygon for extent
frs_habitat(conn, "ADMS",
  aoi = my_study_area_polygon,
  to_streams = "fresh.streams",
  to_habitat = "fresh.streams_habitat")

# Multiple WSGs, parallel
frs_habitat(conn, c("BULK", "MORR", "ZYMO"),
  to_streams = "fresh.streams",
  to_habitat = "fresh.streams_habitat",
  workers = 4, password = "postgres",
  break_sources = list(
    list(table = "working.falls", label = "blocked")))

# Custom parameters — project-specific thresholds override bundled
# defaults. Use when species have different gradient/channel width
# ranges for your study area, or when adding species not in the
# default parameter set.
frs_habitat(conn, "BULK",
  params = frs_params(csv = "path/to/my_thresholds.csv"),
  params_fresh = read.csv("path/to/my_fresh_params.csv"),
  to_streams = "fresh.streams",
  to_habitat = "fresh.streams_habitat")

# --- Custom habitat rules YAML ---

# Default: ships parameters_habitat_rules.yaml with NGE-derived
# multi-rule species (SK lake-only, CO wetland carve-out, all
# anadromous waterbody_type=R spawn). Behavior matches what
# consumers like the `link` package expect.

# Custom rules from a project: pass a path string
frs_habitat(conn, "BULK",
  rules = "path/to/project_habitat_rules.yaml",
  to_streams = "fresh.streams",
  to_habitat = "fresh.streams_habitat")

# Disable rules entirely (pre-0.12.0 behavior — only CSV ranges)
frs_habitat(conn, "BULK",
  rules = FALSE,
  to_streams = "fresh.streams",
  to_habitat = "fresh.streams_habitat")

# --- Controlling gradient resolution with breaks_gradient ---

# Default: auto-derive breaks from spawn_gradient_max +
# rear_gradient_max in params. For BULK with CO/BT/ST that's
# roughly: 0.0449, 0.0549, 0.0849, 0.1049 plus access (0.15, 0.20,
# 0.25). Every biologically meaningful threshold is captured.
# Recommended — gives frs_cluster() the resolution to find
# within-segment steep sections.
frs_habitat(conn, "BULK",
  to_streams = "fresh.streams",
  to_habitat = "fresh.streams_habitat")

# Custom override: explicit list. Use when you have project-specific
# gradient thresholds (e.g. local channel-type classification scheme)
# that aren't tied to a species threshold.
frs_habitat(conn, "BULK",
  breaks_gradient = c(0.03, 0.06, 0.10, 0.15),
  to_streams = "fresh.streams",
  to_habitat = "fresh.streams_habitat")

# Disable extras: only species access thresholds (15/20/25). Faster
# but coarser — fresh 0.9.0 behavior. Not recommended unless you
# specifically don't want sub-segment gradient resolution.
frs_habitat(conn, "BULK",
  breaks_gradient = numeric(0),
  to_streams = "fresh.streams",
  to_habitat = "fresh.streams_habitat")

DBI::dbDisconnect(conn)
} # }