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 viafrs_wsg_species().- aoi
AOI specification or
NULL. Overrides the spatial extent. Accepts anythingfrs_extract()handles:sfpolygon, character WSG code, WHERE clause string, or named list. WhenNULLwithwsg, uses the WSG polygon.- species
Character or
NULL. Species codes to classify (e.g.c("CO", "BT")). WhenNULLwithwsg, auto-detected. Required whenwsgisNULL.- label
Character or
NULL. Short label for working table names. Auto-generated fromwsgwhen available. Required whenwsgisNULLandaoiis provided.- to_streams
Character or
NULL. Schema-qualified table for persistent stream segments. Accumulates across runs, and must not be the working tableworking.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
wsgand noaoi, the partition is the watershed group. Otherwise — a customaoi, orwsgandaoitogether, where a characteraoiis ANDed into the group filter and ansfor listaoireplaces it, so the run covers part of the group or ground outside it — the partition is the FWA segments the run covers, keyed onlinear_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_idis not the Freshwater Atlas, and the custom-AOI key falls back toid_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 onid_segmentalone, which is unique only within a watershed group, so it could remove rows no run put back. Re-running an affected group withwsgand noaoirepairs it, the whole-group overwrite being self-healing — but a table that must also gainlinear_feature_idis 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 fromspawn_gradient_maxandrear_gradient_maxinparams. 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. IfFALSE, 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 likegradient_1500for 15%, or the legacygradient_Nlikegradient_15) are always threshold-aware regardless of this parameter. Set toc("blocked", "potential")for conservative analysis.- rules
Character path to a habitat rules YAML,
FALSE, orNULL. DefaultNULLuses the bundledinst/extdata/parameters_habitat_rules.yaml. Pass a path string to load a custom rules file (e.g. one shipped by thelinkpackage). PassFALSEto 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 ownparamsfromfrs_params(), the rules are baked into that object andruleshere is ignored.See
frs_params()for the rules format. A rule'snear_riverpair, its own or inherited from the thresholds CSV (seefrs_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. IfFALSE, child segments inherit the parent gradient. Seefrs_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 vialnk_barrier_overrides(). Must have columnsblue_line_key,downstream_route_measure,species_code. When provided, matched barriers are excluded from per-species access gating. DefaultNULL(no overrides).- to_barriers
Character or
NULL. Schema-qualified table for persisting gradient barriers. Includesblue_line_key,downstream_route_measure,gradient_class,label,wscode_ltree,localcode_ltree. Useful for link'slnk_barrier_overrides(). DefaultNULL(barriers dropped after segmentation).- params
Named list from
frs_params(), orNULLto use bundledparameters_habitat_thresholds.csvand rules YAML.- params_fresh
Data frame from
parameters_fresh.csv, orNULLto use bundled default.- params_method
Data frame with
watershed_group_codeandmodel("cw"or"mad") columns picking the habitat size model per watershed group (bcfishpassparameters_habitat_method.csv), orNULLto use the bundled default (allcw). Groups missing from it usecw. Seefrs_habitat_classify().- workers
Integer. Number of parallel workers. Default
1. Values > 1 require themiraipackage. 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.
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
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.
See also
Other habitat:
frs_aggregate(),
frs_break(),
frs_break_apply(),
frs_break_find(),
frs_break_validate(),
frs_categorize(),
frs_channel_width(),
frs_classify(),
frs_cluster(),
frs_col_generate(),
frs_col_join(),
frs_extract(),
frs_feature_find(),
frs_feature_index(),
frs_habitat_access(),
frs_habitat_classify(),
frs_habitat_overlay(),
frs_habitat_partition(),
frs_habitat_predicates(),
frs_habitat_species(),
frs_near_river(),
frs_network_segment()
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)
} # }
