### Example: Build LSN and assemble SSN Source: https://pet221.github.io/SSNbler/reference/ssn_assemble.html Complete example workflow: creates a temporary directory, builds an LSN from MF_streams, incorporates observed sites (MF_obs) and prediction sites (MF_preds), then assembles the SSN object. Note that lsn_path is a temporary directory in this example; for your own data, use a local folder. ```r # Get temporary directory, where the example LSN will be stored # locally. temp_dir <- tempdir() # Build the LSN. When working with your own data, lsn_path will be # a local folder of your choice rather than a temporary directory. edges<- lines_to_lsn( streams = MF_streams, lsn_path = temp_dir, snap_tolerance = 1, check_topology = FALSE, overwrite = TRUE, verbose = FALSE ) # Incorporate observed sites, MF_obs, into LSN obs<- sites_to_lsn( sites = MF_obs, edges = edges, save_local = FALSE, snap_tolerance = 100, overwrite = TRUE, verbose = FALSE ) # Incorporate prediction dataset, MF_preds, into LSN preds<- sites_to_lsn(sites = MF_preds, edges = edges, save_local = FALSE, snap_tolerance = 1, overwrite = TRUE, verbose = FALSE ) ssn<- ssn_assemble( edges = edges, lsn_path = temp_dir, obs_sites = obs, preds_list = list(preds), ssn_path = file.path(temp_dir, "MF_ssn"), import = TRUE, check = TRUE, afv_col = "afvArea", overwrite = TRUE, verbose = TRUE ) ``` -------------------------------- ### Install and load SSNbler from GitHub Source: https://pet221.github.io/SSNbler/index.html Install and load the development version of SSNbler from GitHub. Requires the remotes package and uses the main branch. ```r # Installing from GitHub requires you first install the remotes package install.packages("remotes") # install the most recent version from GitHub remotes::install_github("pet221/SSNbler", ref = "main") # load the most recent development version from GitHub library(SSNbler) ``` -------------------------------- ### Example: Build LSN and calculate upstream distance for edges Source: https://pet221.github.io/SSNbler/reference/updist_edges.html Complete example showing how to build an LSN using lines_to_lsn() and then calculate upstream distances with updist_edges(). The example uses a temporary directory, sets calc_length = TRUE to add a 'Length' column, and saves the result locally. The output shows the new columns 'Length' and 'upDist' added to the edges object. ```r # Get temporary directory, where the example LSN will be stored # locally. temp_dir <- tempdir() # Build the LSN. When working with your own data, lsn_path will be # a local folder of your choice rather than a temporary directory. edges<- lines_to_lsn( streams = MF_streams, lsn_path = temp_dir, snap_tolerance = 1, check_topology = FALSE, overwrite = TRUE, verbose = FALSE ) # Calculate upstream distance for edges edges<- updist_edges( edges = edges, lsn_path = temp_dir, calc_length = TRUE, length_col = "Length", overwrite = TRUE, save_local = FALSE, verbose = FALSE ) # Notice that two new columns have been added to edges containing # line feature length (Length) and the upstream distance (upDist) names(edges) #> [1] "rid" "COMID" "GNIS_NAME" "REACHCODE" "FTYPE" #> [6] "FCODE" "AREAWTMAP" "SLOPE" "rcaAreaKm2" "h2oAreaKm2" #> [11] "Length" "upDist" "geom" summary(edges[,c("Length", "upDist")]) #> Length upDist geom #> Min. : 16.55 Min. : 270.6 LINESTRING :163 #> 1st Qu.: 588.88 1st Qu.: 7719.2 epsg:5070 : 0 #> Median :1374.09 Median :11270.8 +proj=aea ...: 0 #> Mean :1600.88 Mean :11684.1 #> 3rd Qu.:2417.89 3rd Qu.:14791.9 #> Max. :6321.20 Max. :26164.3 ``` -------------------------------- ### Incorporate observed and prediction sites into LSN Source: https://pet221.github.io/SSNbler/reference/sites_to_lsn.html Example workflow that builds an LSN from MF_streams using lines_to_lsn, then incorporates observed sites (MF_obs) and prediction sites (MF_preds) into the LSN with sites_to_lsn. The output 'obs' gains three new columns: rid, ratio, and snapdist. The example uses save_local = FALSE and snap_tolerance values of 100 for observed sites and 1 for predictions. ```r # Get temporary directory, where the example LSN will be stored # locally. temp_dir <- tempdir() # Build the LSN. When working with your own data, lsn_path will be # a local folder of your choice rather than a temporary directory. edges<- lines_to_lsn( streams = MF_streams, lsn_path = temp_dir, snap_tolerance = 1, check_topology = FALSE, overwrite = TRUE, verbose = FALSE ) # # Incorporate observed sites, MF_obs, into LSN obs<- sites_to_lsn( sites = MF_obs, edges = edges, save_local = FALSE, snap_tolerance = 100, overwrite = TRUE, verbose = FALSE ) # Notice that 3 new columns have been added to obs names(obs) #> [1] "STREAMNAME" "COMID" "AREAWTMAP" "SLOPE" "ELEV_DEM" #> [6] "Source" "Summer_mn" "MaxOver20" "C16" "C20" #> [11] "C24" "FlowCMS" "AirMEANc" "AirMWMTc" "rcaAreaKm2" #> [16] "h2oAreaKm2" "geometry" "rid" "ratio" "snapdist" # Incorporate prediction dataset, MF_preds, into LSN preds<- sites_to_lsn(sites = MF_preds, edges = edges, save_local = FALSE, snap_tolerance = 1, overwrite = TRUE, verbose = FALSE ) ``` -------------------------------- ### Install and load SSNbler from CRAN Source: https://pet221.github.io/SSNbler/index.html Install and load the approved version of SSNbler from CRAN. Use this when you want the stable release. ```r # install the most recent approved version from CRAN install.packages("SSNbler") # load the most recent approved version from CRAN library(SSNbler) ``` -------------------------------- ### Calculate AFVs for sites with afv_sites() Source: https://pet221.github.io/SSNbler/reference/afv_sites.html Complete example workflow: builds the LSN with lines_to_lsn(), snaps observed and prediction sites with sites_to_lsn(), computes edge AFVs with afv_edges(), then calculates site AFVs with afv_sites(). The output shows names(site.list) and summary() of the new afvArea column for both obs and preds, confirming AFVs are between 0 and 1. ```r #' # Get temporary directory, where the example LSN will be stored # locally. temp_dir <- tempdir() # Build the LSN. When working with your own data, lsn_path will be # a local folder of your choice rather than a temporary directory. edges<- lines_to_lsn( streams = MF_streams, lsn_path = temp_dir, snap_tolerance = 1, check_topology = FALSE, overwrite = TRUE, verbose = FALSE ) # Incorporate observed sites into the LSN obs<- sites_to_lsn( sites = MF_obs, edges = edges, save_local = FALSE, snap_tolerance = 100, overwrite = TRUE, verbose = FALSE ) # Incorporate the prediction dataset, preds, into the LSN preds<- sites_to_lsn(sites = MF_preds, edges = edges, save_local = FALSE, snap_tolerance = 1, overwrite = TRUE, verbose = FALSE ) # Calculate the AFVs for the edges using a column representing # watershed area (h2oAreaKm2) for the downstream node of each edge # feature. edges<- afv_edges( edges=edges, infl_col = "h2oAreaKm2", segpi_col = "areaPI", lsn_path = temp_dir, afv_col = "afvArea", overwrite = TRUE, save_local = FALSE ) # Calculate AFVs for observed sites (obs) and the prediction # dataset, preds. site.list<- afv_sites( sites = list(obs = obs, preds = preds), edges=edges, afv_col = "afvArea", save_local = FALSE, overwrite = TRUE ) # Get names of sites in site.list names(site.list) #> [1] "obs" "preds" # Check AFVs stored in new column afvArea to ensure that 0 <= AFV # <= 1 and that there are no NULL values. summary(site.list$obs$afvArea) #> Min. 1st Qu. Median Mean 3rd Qu. Max. #> 0.05144 0.15212 0.17089 0.24583 0.29944 1.00000 summary(site.list$preds$afvArea) #> Min. 1st Qu. Median Mean 3rd Qu. Max. #> 0.009894 0.031486 0.047469 0.092485 0.108067 0.672706 ``` -------------------------------- ### Source file notice template Source: https://pet221.github.io/SSNbler/LICENSE.html Attach this notice to the start of each source file to state the exclusion of warranty and provide a pointer to the full license. Replace the placeholders with the program's name, copyright year, and author name. ```plaintext Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . ``` -------------------------------- ### Example: Build LSN and accumulate RCA area downstream Source: https://pet221.github.io/SSNbler/reference/accum_edges.html Complete example that builds an LSN with lines_to_lsn, then accumulates the rcaAreaKm2 column downstream into a new column WArea_km2 using accum_edges. The example uses a temporary directory and disables saving locally. The summary output shows the distribution of the accumulated values. ```r # Get temporary directory, where the example LSN will be stored # locally. temp_dir <- tempdir() # Build the LSN. When working with your own data, lsn_path will be # a local folder of your choice rather than a temporary directory. edges <- lines_to_lsn( streams = MF_streams, lsn_path = temp_dir, snap_tolerance = 1, check_topology = FALSE, overwrite = TRUE, verbose = FALSE ) # Accumulate RCA area (rcaAreaKm2) downstream and store in a new # column named WArea_km2 edges <- accum_edges( edges = edges, lsn_path = temp_dir, sum_col = "rcaAreaKm2", acc_col = "WArea_km2", save_local = FALSE, overwrite = TRUE, verbose = FALSE ) summary(edges$WArea_km2) #> Min. 1st Qu. Median Mean 3rd Qu. Max. #> 0.0036 2.4534 5.9877 22.6237 28.2600 209.8989 ``` -------------------------------- ### Check SSN object with afvArea in example Source: https://pet221.github.io/SSNbler/reference/ssn_check.html Example usage of ssn_check on an imported SSN object. Copies MiddleFork04.ssn to a temporary location, imports it with prediction points pred1km, then checks the object with the additive function column afvArea. The output shows the SSN object is valid: TRUE. ```r ## Create local temporary copy of MiddleFork04.ssn found in ## the SSN2 package. Only necessary for this example. SSN2::copy_lsn_to_temp() # Import the SSN object with prediction points, pred1km mf04 <- SSN2::ssn_import( paste0(tempdir(), "/MiddleFork04.ssn"), predpts = c("pred1km"), overwrite = TRUE ) # Check the SSN object, including the additive function column, # afvArea ssn_check(mf04, afv_col = "afvArea") #> #> #> SSN object is valid: TRUE ``` -------------------------------- ### Interactive mode notice template Source: https://pet221.github.io/SSNbler/LICENSE.html Output this short notice when the program starts in interactive mode. The hypothetical commands 'show w' and 'show c' should display the appropriate parts of the General Public License; adjust them for your program's interface. ```plaintext Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'. This is free software, and you are welcome to redistribute it under certain conditions; type 'show c' for details. ``` -------------------------------- ### Complete workflow for computing upstream distances Source: https://pet221.github.io/SSNbler/reference/updist_sites.html A full example that builds the LSN from MF_streams, incorporates observed and prediction sites, calculates edge lengths, and applies updist_sites on a combined list. The subsequent summary commands show the new upDist column values for both `obs` and `preds`. ```R # Get temporary directory, where the example LSN will be stored # locally. temp_dir <- tempdir() # Build the LSN. When working with your own data, lsn_path will be # a local folder of your choice rather than a temporary directory. edges<- lines_to_lsn( streams = MF_streams, lsn_path = temp_dir, snap_tolerance = 1, check_topology = FALSE, overwrite = TRUE, verbose = FALSE ) # Incorporate observed sites, MF_obs, into LSN obs<- sites_to_lsn( sites = MF_obs, edges = edges, save_local = FALSE, snap_tolerance = 100, overwrite = TRUE, verbose = FALSE ) # Incorporate prediction dataset, MF_preds, into LSN preds<- sites_to_lsn( sites = MF_preds, edges = edges, save_local = FALSE, snap_tolerance = 1, overwrite = TRUE, verbose = FALSE ) # Calculate upstream distance for edges edges<- updist_edges( edges = edges, lsn_path = temp_dir, calc_length = TRUE, length_col = "Length", overwrite = TRUE, save_local = FALSE, verbose = FALSE ) # Calculate upstream distance for observed sites (obs) and one # prediction dataset (preds) site.list<- updist_sites( sites = list(obs = obs, preds = preds), edges = edges, length_col= "Length", lsn_path = temp_dir, save_local = FALSE, overwrite = TRUE ) # Summarize the new column upDist in obs summary(site.list$obs$upDist) #> Min. 1st Qu. Median Mean 3rd Qu. Max. #> 909.9 6281.2 10020.0 10176.9 14295.2 19566.2 # Summarize the new column upDist in preds summary(site.list$preds$upDist) #> Min. 1st Qu. Median Mean 3rd Qu. Max. #> 3863 8030 12189 12370 15870 24337 ``` -------------------------------- ### Calculate AFV for edges with afv_edges Source: https://pet221.github.io/SSNbler/reference/afv_edges.html Builds an LSN from MF_streams with lines_to_lsn, then calculates additive function values (AFVs) for edges using afv_edges with watershed area (h2oAreaKm2) as the influence column. The example saves the updated edges locally (save_local = FALSE) and checks the new afvArea column with summary(), showing AFVs between 0 and 1 with no NULL values. ```R # Get temporary directory, where the example LSN will be stored # locally. temp_dir <- tempdir() # Build the LSN. When working with your own data, lsn_path will be # a local folder of your choice rather than a temporary directory. edges <- lines_to_lsn( streams = MF_streams, lsn_path = temp_dir, snap_tolerance = 1, check_topology = FALSE, overwrite = TRUE, verbose = FALSE ) # Calculate the AFV for the edges using an existing column # representing watershed area for the downstream node of each line # feature (h2oAreaKm2). edges <- afv_edges( edges = edges, infl_col = "h2oAreaKm2", segpi_col = "areaPI", lsn_path = temp_dir, afv_col = "afvArea", overwrite = TRUE, save_local = FALSE ) # Check AFVs stored in new column afvArea to ensure that 0 <= AFV # <= 1 and that there are no NULL values. summary(edges$afvArea) #> Min. 1st Qu. Median Mean 3rd Qu. Max. #> 0.004709 0.026168 0.066095 0.160335 0.169575 1.000000 ``` -------------------------------- ### Copy streams data to temporary directory Source: https://pet221.github.io/SSNbler/reference/copy_streams_to_temp.html Copies the Middle Fork streams data to R's temporary directory. Use this before running SSNbler examples to avoid writing to the local library. ```R copy_streams_to_temp() ``` ```R copy_streams_to_temp() # getwd() # setwd(tempdir()) # getwd() # if unix-alike, list temporary directory contents using: system('ls') # if windows, list temporary directory contents using: shell('dir') ``` -------------------------------- ### Copy streamsdata to temp directory Source: https://pet221.github.io/SSNbler/articles/introduction.html Copies the streamsdata folder to R's temporary directory and stores its path. Prevents SSNbler functions from reading and writing to the original installed folder. ```r copy_streams_to_temp() path <- paste0(tempdir(), "/streamsdata") ``` -------------------------------- ### Load SSNbler data and plot streams with ggplot2 Source: https://pet221.github.io/SSNbler/articles/introduction.html Loads the SSNbler package, copies example stream data to a temporary directory, reads the stream and site GeoPackages, and creates an initial map of the data. The map uses ggplot2 with geom_sf layers for streams, CapeHorn, pred1km, and obs, and sets the coordinate system to the stream CRS. The knitr::include_graphics call embeds a validation image of nodes. ```R library(SSNbler) copy_streams_to_temp() path <- paste0(tempdir(), "/streamsdata") library(sf) MF_streams <- st_read(paste0(path, "/MF_streams.gpkg")) MF_obs <- st_read(paste0(path, "/MF_obs.gpkg")) MF_pred1km <- st_read(paste0(path, "/MF_pred1km.gpkg")) MF_CapeHorn <- st_read(paste0(path, "/MF_CapeHorn.gpkg")) library(ggplot2) ``` ```R ggplot() + geom_sf(data = MF_streams) + geom_sf(data = MF_CapeHorn, color = "gold", size = 1.7) + geom_sf(data = MF_pred1km, colour = "purple", size = 1.7) + geom_sf(data = MF_obs, color = "blue", size = 2) + coord_sf(datum = st_crs(MF_streams)) ``` ```R knitr::include_graphics("valid_nodes.png") ``` -------------------------------- ### Get class of SSN object Source: https://pet221.github.io/SSNbler/articles/introduction.html Checks the class of the assembled SSN object. The output confirms that the object is of class "SSN". ```r class(mf04_ssn) ## Get class ``` ```r #> [1] "SSN" ``` -------------------------------- ### Build LSN edges and snap sites with lines_to_lsn and sites_to_lsn Source: https://pet221.github.io/SSNbler/articles/introduction.html Sets the LSN path and converts stream lines to an LSN with topology checks, then snaps observation and prediction sites to the edges. Each sites_to_lsn call saves the result locally to the specified file name with a snap tolerance of 100 and overwrites existing files. The edges object is required by all subsequent site conversions. ```R lsn.path <- paste0(tempdir(), "/mf04") edges <- lines_to_lsn( streams = MF_streams, lsn_path = lsn.path, check_topology = TRUE, snap_tolerance = 0.05, topo_tolerance = 20, overwrite = TRUE ) ``` ```R obs <- sites_to_lsn( sites = MF_obs, edges = edges, lsn_path = lsn.path, file_name = "obs", snap_tolerance = 100, save_local = TRUE, overwrite = TRUE ) ``` ```R preds <- sites_to_lsn( sites = MF_pred1km, edges = edges, save_local = TRUE, lsn_path = lsn.path, file_name = "pred1km.gpkg", snap_tolerance = 100, overwrite = TRUE ) ``` ```R capehorn <- sites_to_lsn( sites = MF_CapeHorn, edges = edges, save_local = TRUE, lsn_path = lsn.path, file_name = "CapeHorn.gpkg", snap_tolerance = 100, overwrite = TRUE ) ``` -------------------------------- ### Create LSN with lines_to_lsn() Source: https://pet221.github.io/SSNbler/articles/introduction.html Creates a temporary directory path and builds a landscape network (LSN) from stream lines using the `lines_to_lsn()` function. With `check_topology = TRUE`, it checks network topology and writes a `node_errors.gpkg` if potential errors are found; otherwise it prints a message that no errors were detected. The function writes five core files (`nodes.gpkg`, `edges.gpkg`, `nodexy.csv`, `noderelationships.csv`, `relationships.csv`) to `lsn_path`. ```R lsn.path <- paste0(tempdir(), "/mf04") edges <- lines_to_lsn( streams = MF_streams, lsn_path = lsn.path, check_topology = TRUE, snap_tolerance = 0.05, topo_tolerance = 20, overwrite = TRUE ) ``` -------------------------------- ### Snap sites to LSN with sites_to_lsn() Source: https://pet221.github.io/SSNbler/articles/introduction.html Snaps observed site locations to the LSN edges using `sites_to_lsn()`. It writes a GeoPackage named `obs.gpkg` to `lsn_path` and returns the snapped sites as an `sf` object. The output adds three columns: `rid`, `ratio`, and `snapdist`. ```R obs <- sites_to_lsn( sites = MF_obs, edges = edges, lsn_path = lsn.path, file_name = "obs", snap_tolerance = 100, save_local = TRUE, overwrite = TRUE ) ``` -------------------------------- ### Add AFV column with afv_sites() and view column names Source: https://pet221.github.io/SSNbler/articles/introduction.html Calls afv_sites() to add an AFV column to a list of sites, then prints the column names of the pred1km site dataset. The output shows the new afvArea column among the existing columns. ```r site.list <- afv_sites( sites = site.list, edges = edges, afv_col = "afvArea", save_local = TRUE, lsn_path = lsn.path ) names(site.list$pred1km) ## View column names in pred1km ``` ```r #> [1] "rid" "COMID" "AREAWTMAP" "SLOPE" "ELEV_DEM" #> [6] "FlowCMS" "AirMEANc" "AirMWMTc" "rcaAreaKm2" "h2oAreaKm2" #> [11] "ratio" "snapdist" "upDist" "afvArea" "geom" ``` -------------------------------- ### View column names in obs site list after updist_sites() Source: https://pet221.github.io/SSNbler/articles/introduction.html Displays the column names of the obs site object after updist_sites() has run. The output includes the added "upDist" column along with existing attributes such as rid, STREAMNAME, COMID, and geometry. ```r names(site.list$obs) ## View column names in obs ``` ```r #> [1] "rid" "STREAMNAME" "COMID" "AREAWTMAP" "SLOPE" #> [6] "ELEV_DEM" "Source" "Summer_mn" "MaxOver20" "C16" #> [11] "C20" "C24" "FlowCMS" "AirMEANc" "AirMWMTc" #> [16] "rcaAreaKm2" "h2oAreaKm2" "ratio" "snapdist" "geom" #> [21] "upDist" ``` -------------------------------- ### afv_sites() function signature Source: https://pet221.github.io/SSNbler/reference/afv_sites.html Function signature for afv_sites(). Use after snapping sites with sites_to_lsn() and creating edges with lines_to_lsn(). The afv_col must be a column in edges created by afv_edges(). save_local defaults to TRUE and requires lsn_path; overwrite defaults to TRUE. ```r afv_sites( sites, edges, afv_col, save_local = TRUE, lsn_path = NULL, overwrite = TRUE ) ``` -------------------------------- ### Assemble SSN object using ssn_assemble Source: https://pet221.github.io/SSNbler/reference/ssn_assemble.html Assembles an SSN object from the edges, observed sites, and prediction datasets. The function creates a .ssn file at the specified path and imports it. The output shows the creation of the file and validation of the SSN object. ```R ssn.obj<- ssn_assemble( edges = edges, lsn_path = temp_dir, obs_sites = site.list[["obs"]], preds_list = site.list[c("preds")], ssn_path = paste0(temp_dir, "/example.ssn"), import = TRUE, overwrite = TRUE ) #> #> Checking inputs #> #> C:\Users\Michael\AppData\Local\Temp\RtmpEpZoqa/example.ssn created. #> #> Creating binaryID.db #> Adding NetID and netgeom to edges #> #> pid, locID, netID, and netgeom added to ... #> #> obs_sites #> #> preds #> #> Saving files to C:\Users\Michael\AppData\Local\Temp\RtmpEpZoqa/example.ssn #> #> Creating SSN object #> #> Checking the SSN object #> #> #> SSN object is valid: TRUE ``` -------------------------------- ### Calculate upstream distance for sites with updist_sites() Source: https://pet221.github.io/SSNbler/articles/introduction.html Calls updist_sites() with a named list of site sf objects, edges, length column "Length", and save_local = TRUE with lsn_path. The output site.list names are printed with names(site.list), showing the three site names: obs, pred1km, CapeHorn. ```r site.list <- updist_sites( sites = list( obs = obs, pred1km = preds, CapeHorn = capehorn ), edges = edges, length_col = "Length", save_local = TRUE, lsn_path = lsn.path ) names(site.list) ## View output site.list names ``` ```r #> [1] "obs" "pred1km" "CapeHorn" ``` -------------------------------- ### sites_to_lsn() with observed sites Source: https://pet221.github.io/SSNbler/articles/introduction.html Creates a topologically corrected LSN with observed sites. Must be run separately for every observed and prediction dataset. The LSN is stored in memory and locally as a GeoPackage. ```R capehorn <- sites_to_lsn( sites = MF_CapeHorn, edges = edges, save_local = TRUE, lsn_path = lsn.path, file_name = "CapeHorn.gpkg", snap_tolerance = 100, overwrite = TRUE ) ``` -------------------------------- ### Summarize AFV column with summary() Source: https://pet221.github.io/SSNbler/articles/introduction.html Summarizes the afvArea column in the pred1km site dataset to check for zeros. The output shows the minimum, quartiles, mean, and maximum, with no zeros present. ```r summary(site.list$pred1km$afvArea) ## Summarize AFVs in pred1km and look for zeros ``` ```r #> Min. 1st Qu. Median Mean 3rd Qu. Max. #> 0.009894 0.031219 0.047469 0.104969 0.112882 1.000000 ``` -------------------------------- ### lines_to_lsn(streams, lsn_path, check_topology, snap_tolerance, topo_tolerance, remove_ZM, overwrite, use_parallel, no_cores, verbose) Source: https://pet221.github.io/SSNbler/reference/lines_to_lsn.html Converts an sf object with LINESTRING geometry to a landscape network (LSN). The function creates relationship tables and checks topological relationships. It saves the LSN components to a specified directory. ```APIDOC ## lines_to_lsn(streams, lsn_path, check_topology, snap_tolerance, topo_tolerance, remove_ZM, overwrite, use_parallel, no_cores, verbose) ### Description Converts an `sf` object containing features with LINESTRING geometry to a landscape network (LSN), which is a topological data model of streams/rivers represented as a directional graph embedded in 2-D geographic space. Relationship tables are created and topological relationships are checked. ### Usage ```r lines_to_lsn( streams, lsn_path, check_topology = TRUE, snap_tolerance = 0, topo_tolerance = 0, remove_ZM = FALSE, overwrite = FALSE, use_parallel = FALSE, no_cores = NULL, verbose = TRUE ) ``` ### Arguments - **streams** (sf object) - Required - An `sf` object with LINESTRING geometry representing streams. - **lsn_path** (character) - Required - Pathname to a directory in character format specifying where to store the outputs. The directory will be created if it does not already exist. - **check_topology** (logical) - Optional - If `TRUE`, the edges will be checked for topological errors and potential node errors will be flagged in an output file called `node_errors.gpkg`. Defaults to `TRUE`. - **snap_tolerance** (numeric) - Optional - Distance in map units >= 0. Two nodes separated by a distance less than or equal to `snap_tolerance` are assumed to be connected. Defaults to 0. - **topo_tolerance** (numeric) - Optional - Distance in map units >= 0. Only used if `check_topology = TRUE`. Two nodes on the network separated by a distance less than or equal to `topo_tolerance` are flagged as potential topological errors in the network. Defaults to 0. - **remove_ZM** (logical) - Optional - If `TRUE`, Z and M dimensions are removed from streams, if they exist. Default is `FALSE`. - **overwrite** (logical) - Optional - If `TRUE`, output files will overwrite existing files with the same names. If `FALSE` and files sharing the same names as the outputs exist in the `lsn_path`, the function will exit early with an error. - **use_parallel** (logical) - Optional - if `TRUE` parallel processing will be used. Default is `FALSE`. - **no_cores** (integer) - Optional - Integer representing the number of cores used when `use_parallel = TRUE`. - **verbose** (logical) - Optional - If `TRUE`, messages describing function progress will be printed to the console. Default is `TRUE`. ### Value An `sf` object representing edges in the LSN. The LSN, including edges.gpkg, nodes.gpkg, nodexy.csv, noderelationships.csv, and relationships.csv files, are saved locally to a directory defined by `lsn_path`. If `check_topology = TRUE` and topological errors are identified, then node_errors.gpkg is also saved to `lsn_path`. ### Details The LSN is saved to a local directory defined by `lsn_path` and has 5 components: - **nodes.gpkg**: A GeoPackage of features with POINT geometry representing topologic breaks in the stream network such as pseudonodes, confluences, stream sources, or stream outlets. A column containing a unique node identifier, pointid, is included. - **edges.gpkg**: A GeoPackage of features with LINESTRING geometry representing flow paths (i.e. line features) from node to node. A new column named rid is added that contains a unique identifier for each line feature. - **nodexy.csv**: a table with three columns: the pointid (unique node identifier), and the x-, y-coordinates for each node. - **noderelationships.csv**: a table describing the relationship between the nodes and their associated edges, as well as directionality in the LSN. The table contains three columns: the rid (for each edge), fromnode (pointid for the upstream node of each edge), and tonode (pointid for the downstream node of each edge). Directionality is defined based on the digitized direction of the line features. - **relationships.csv**: a table representing the downstream flow path from edge to edge. The table contains two columns: fromedge (upstream edge) and toedge (downstream edge). ``` -------------------------------- ### Load SSNbler package Source: https://pet221.github.io/SSNbler/articles/introduction.html Loads the SSNbler package into the current R session. Required before using any SSNbler functions. ```r library(SSNbler) ``` -------------------------------- ### Add prediction dataset to LSN with sites_to_lsn() Source: https://pet221.github.io/SSNbler/articles/introduction.html Adds the MF_pred1km prediction dataset to the LSN using sites_to_lsn(). The snap_tolerance is set to 100 and overwrite is TRUE. The function must be run for each dataset, even if site locations already intersect edge features. ```r preds <- sites_to_lsn( sites = MF_pred1km, edges = edges, save_local = TRUE, lsn_path = lsn.path, file_name = "pred1km.gpkg", snap_tolerance = 100, overwrite = TRUE ) ``` -------------------------------- ### sites_to_lsn function signature Source: https://pet221.github.io/SSNbler/reference/sites_to_lsn.html Function signature for incorporating point features into a landscape network. Required arguments are sites (an sf object with POINT geometry), edges (an sf object with LINESTRING geometry from lines_to_lsn), and snap_tolerance (numeric distance >= 0). Optional arguments control saving to a local GeoPackage (save_local, lsn_path, file_name, overwrite) and progress messages (verbose). ```r sites_to_lsn( sites, edges, snap_tolerance, save_local = TRUE, lsn_path = NULL, file_name = NULL, overwrite = FALSE, verbose = TRUE ) ``` -------------------------------- ### Convert sf streams to LSN with lines_to_lsn() Source: https://pet221.github.io/SSNbler/reference/lines_to_lsn.html Converts an sf object with LINESTRING geometry to a landscape network (LSN). The function creates nodes.gpkg, edges.gpkg, nodexy.csv, noderelationships.csv, and relationships.csv in the directory specified by lsn_path. If check_topology = TRUE, topological errors are flagged in node_errors.gpkg. ```r lines_to_lsn( streams, lsn_path, check_topology = TRUE, snap_tolerance = 0, topo_tolerance = 0, remove_ZM = FALSE, overwrite = FALSE, use_parallel = FALSE, no_cores = NULL, verbose = TRUE ) ``` -------------------------------- ### Assemble SSN with ssn_assemble and plot with ggplot2 Source: https://pet221.github.io/SSNbler/articles/introduction.html Assembles the SSN object from edges, observation sites, and prediction datasets, saving it to MiddleFork04.ssn and importing it. The code prints the class and names of the SSN object and its prediction datasets. A ggplot2 map visualizes the SSN edges, pred1km sites, and observations with temperature coloring, and the final line loads the SSN2 package for further analysis. ```R mf04_ssn <- ssn_assemble( edges = edges, lsn_path = lsn.path, obs_sites = site.list$obs, preds_list = site.list[c("pred1km", "CapeHorn")], ssn_path = paste0(path, "/MiddleFork04.ssn"), import = TRUE, check = TRUE, afv_col = "afvArea", overwrite = TRUE ) class(mf04_ssn) ## Get class names(mf04_ssn) ## print names of SSN object names(mf04_ssn$preds) ## print names of prediction datasets ``` ```R ggplot() + geom_sf( data = mf04_ssn$edges, color = "medium blue", aes(linewidth = h2oAreaKm2) ) + scale_linewidth(range = c(0.1, 2.5)) + geom_sf( data = mf04_ssn$preds$pred1km, size = 1.5, shape = 21, fill = "white", color = "dark grey" ) + geom_sf( data = mf04_ssn$obs, size = 1.7, aes(color = Summer_mn) ) + coord_sf(datum = st_crs(MF_streams)) + scale_color_viridis_c() + labs(color = "Temperature", linewidth = "WS Area") + theme( legend.text = element_text(size = 8), legend.title = element_text(size = 10) ) ``` ```R library(SSN2) ``` -------------------------------- ### Calculate AFV for sites using afv_sites Source: https://pet221.github.io/SSNbler/reference/ssn_assemble.html Calculates the AFV for observed sites (obs) and prediction dataset (preds). The function takes a list of sites, the edges object, and the AFV column name. It saves the result locally if save_local is TRUE, but here it is set to FALSE. ```R site.list<- afv_sites( sites = list(obs = obs, preds = preds), edges=edges, afv_col = "afvArea", save_local = FALSE, overwrite = TRUE ) ``` -------------------------------- ### Read stream network and point data with st_read Source: https://pet221.github.io/SSNbler/articles/introduction.html Loads the stream network, observed sites, prediction sites, and Cape Horn point features from GeoPackage files using the sf package's st_read function. Requires the path variable to be set to the directory containing the GeoPackage files. The input data must have LINESTRING or POINT geometry and a projected coordinate system. ```r library(sf) MF_streams <- st_read(paste0(path, "/MF_streams.gpkg")) MF_obs <- st_read(paste0(path, "/MF_obs.gpkg")) MF_pred1km <- st_read(paste0(path, "/MF_pred1km.gpkg")) MF_CapeHorn <- st_read(paste0(path, "/MF_CapeHorn.gpkg")) ``` -------------------------------- ### Check SSN object with ssn_check Source: https://pet221.github.io/SSNbler/reference/ssn_check.html Checks an SSN object for valid spatial, topological, and attribute information needed for SSN2 models. Arguments include ssn.object, check_obs (default TRUE), afv_col (default NULL), and verbose (default TRUE). Returns a boolean indicating validity, with additional console messages when verbose is TRUE. ```r ssn_check(ssn.object, check_obs = TRUE, afv_col = NULL, verbose = TRUE) ``` -------------------------------- ### updist_sites function signature Source: https://pet221.github.io/SSNbler/reference/updist_sites.html R function call showing the parameters for calculating upstream distances. The `length_col` must be a column in `edges` containing edge lengths, and `lsn_path` is required when `save_local = TRUE`. ```R updist_sites( sites, edges, length_col, lsn_path, save_local = TRUE, overwrite = TRUE ) ``` -------------------------------- ### Generate distance matrices and fit SSN2 model with ssn_lm Source: https://pet221.github.io/SSNbler/articles/introduction.html Generate hydrologic distance matrices with ssn_create_distmat, then fit a spatial stream network model with ssn_lm using the specified formula, covariance types, and additive area. The summary call prints model fit details. ```R ssn_create_distmat(mf04_ssn) ``` ```R ssn_mod <- ssn_lm( formula = Summer_mn ~ ELEV_DEM + AREAWTMAP, ssn.object = mf04_ssn, tailup_type = "exponential", taildown_type = "spherical", euclid_type = "gaussian", additive = "afvArea" ) summary(ssn_mod) ``` -------------------------------- ### Summarise SSN object using summary Source: https://pet221.github.io/SSNbler/reference/ssn_assemble.html Summarises the SSN object, showing the class, number of sites, prediction points, and variable names. The output includes the bounding box and variable lists for observations and predictions. ```R summary(ssn.obj) #> Object of class SSN #> #> Object includes observations on 26 variables across 45 sites within the bounding box #> xmin ymin xmax ymax #> -1531385 2521181 -1498448 2540274 #> #> Object also includes 1 set of prediction points with 43 locations #> #> Variable names are (found using ssn_names(object)): #> $obs #> [1] "rid" "pid" "STREAMNAME" "COMID" "AREAWTMAP" #> [6] "SLOPE" "ELEV_DEM" "Source" "Summer_mn" "MaxOver20" #> [11] "C16" "C20" "C24" "FlowCMS" "AirMEANc" #> [16] "AirMWMTc" "rcaAreaKm2" "h2oAreaKm2" "ratio" "snapdist" #> [21] "afvArea" "upDist" "locID" "netID" "geom" #> [26] "netgeom" #> #> $preds #> [1] "rid" "pid" "COMID" "AREAWTMAP" "SLOPE" #> [6] "ELEV_DEM" "FlowCMS" "AirMEANc" "AirMWMTc" "rcaAreaKm2" #> [11] "h2oAreaKm2" "ratio" "snapdist" "afvArea" "upDist" #> [16] "locID" "netID" "geom" "netgeom" #> #> ``` -------------------------------- ### ssn_assemble function signature Source: https://pet221.github.io/SSNbler/reference/ssn_assemble.html The function signature for ssn_assemble, showing all arguments and their defaults. Use this to understand the required and optional parameters. ```r ssn_assemble( edges, lsn_path = NULL, obs_sites = NULL, preds_list = NULL, ssn_path, import = TRUE, check = TRUE, afv_col = NULL, overwrite = FALSE, verbose = TRUE ) ``` -------------------------------- ### Fit SSN model with ssn_lm Source: https://pet221.github.io/SSNbler/articles/introduction.html Fits a spatial stream-network model using SSN2. First generates hydrologic distance matrices with ssn_create_distmat, then fits the model with ssn_lm using exponential tail-up, spherical tail-down, and Gaussian Euclidean covariance functions, with additive = "afvArea". ```R library(SSN2) ## Generate hydrologic distance matrices ssn_create_distmat(mf04_ssn) ## Fit the model ssn_mod <- ssn_lm( formula = Summer_mn ~ ELEV_DEM + AREAWTMAP, ssn.object = mf04_ssn, tailup_type = "exponential", taildown_type = "spherical", euclid_type = "gaussian", additive = "afvArea" ) summary(ssn_mod) ``` -------------------------------- ### Print names of SSN object Source: https://pet221.github.io/SSNbler/articles/introduction.html Prints the names of the elements in the SSN object. The output shows the four components: edges, obs, preds, and path. ```r names(mf04_ssn) ## print names of SSN object ``` ```r #> [1] "edges" "obs" "preds" "path" ```