content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
# Create testthat test from the specification file for Mustache, so it can be
# tested if lives up to the specification
#
# Please note:
# * You'll need rjson for reading the specifications
# * an installed whisker, because that is used for the generation of the test
# (eat your own dog food...)
library(rjson)
library(whisker)
header <-
"# Automatically generated from specification file: '{{file}}'
#
{{overview}}
library(testthat)
context('Spec v1.1, {{type}}')
"
testtemplate <-
"test_that( {{&name}}, {
#{{&desc}}
template <- {{&template}}
data <- {{&data}}
{{#partials}}
partials <- {{&partials}}
str <- whisker.render(template, partials=partials, data=data)
{{/partials}}
{{^partials}}
str <- whisker.render(template, data=data)
{{/partials}}
expect_equal(str, {{&expected}}, label=deparse(str), info={{&desc}})
})
"
convertToTest <- function(files){
for (json in files){
writeSpec(json)
}
}
writeSpec <- function(file){
outfile <- gsub("^(.+).json", "../tests/test\\1.R", file)
spec <- fromJSON(file=file)
con <- file(outfile, open="wt")
on.exit(close(con))
spec$file <- file
spec$overview <- gsub("(^|\n)", "\\1# ", spec$overview)
spec$type <- gsub(".json", "", file)
writeLines(whisker.render(header, data=spec), con)
test <- sapply(spec$test, writeTest)
writeLines(test, con)
}
writeTest <- function(test){
test <- lapply(test, deparse, control=c("keepNA"))
test$data <- paste(test$data, collapse="\n")
whisker.render(testtemplate, data=test)
}
spec <- c( "interpolation.json"
, "comments.json"
, "inverted.json"
, "sections.json"
, "partials.json"
, "delimiters.json"
#, "lambdas.json"
)
convertToTest(spec)
|
/scratch/gouwar.j/cran-all/cranData/whisker/inst/specs/convert.R
|
#' @title Add point coordinates to table
#'
#' @description Modifies the attribute table of a point vector by adding fields containing each point's X and Y coordinates.
#'
#' @param input Input vector Points file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_add_point_coordinates_to_table <- function(input, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "add_point_coordinates_to_table"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Clean vector
#'
#' @description Removes null features and lines/polygons with fewer than the required number of vertices.
#'
#' @param input Input vector file path. See `wbt_file_path()` for details.
#' @param output Output vector file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_clean_vector <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "clean_vector"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Convert nodata to zero
#'
#' @description Converts nodata values in a raster to zero.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_convert_nodata_to_zero <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "convert_nodata_to_zero"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Convert raster format
#'
#' @description Converts raster data from one format to another.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_convert_raster_format <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "convert_raster_format"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Csv points to vector
#'
#' @description Converts a CSV text file to vector points.
#'
#' @param input Input CSV file (i.e. source of data to be imported).
#' @param output Output vector file.
#' @param xfield X field number (e.g. 0 for first field).
#' @param yfield Y field number (e.g. 1 for second field).
#' @param epsg EPSG projection (e.g. 2958).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_csv_points_to_vector <- function(input, output, xfield=0, yfield=1, epsg=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(xfield)) {
args <- paste(args, paste0("--xfield=", xfield))
}
if (!is.null(yfield)) {
args <- paste(args, paste0("--yfield=", yfield))
}
if (!is.null(epsg)) {
args <- paste(args, paste0("--epsg=", epsg))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "csv_points_to_vector"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Export table to csv
#'
#' @description Exports an attribute table to a CSV text file.
#'
#' @param input Input vector file path. See `wbt_file_path()` for details.
#' @param output Output csv file.
#' @param headers Export field names as file header?.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_export_table_to_csv <- function(input, output, headers=TRUE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (headers) {
args <- paste(args, "--headers")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "export_table_to_csv"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Fix dangling arcs
#'
#' @description This tool fixes undershot and overshot arcs, two common topological errors, in an input vector lines file.
#'
#' @param input Name of the input lines vector file.
#' @param output Name of the output lines vector file.
#' @param dist Snap distance, in xy units (metres).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_fix_dangling_arcs <- function(input, output, dist="", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(dist)) {
args <- paste(args, paste0("--dist=", dist))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "fix_dangling_arcs"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Join tables
#'
#' @description Merge a vector's attribute table with another table based on a common field.
#'
#' @param input1 Input primary vector file (i.e. the table to be modified).
#' @param pkey Primary key field.
#' @param input2 Input foreign vector file (i.e. source of data to be imported).
#' @param fkey Foreign key field.
#' @param import_field Imported field (all fields will be imported if not specified).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_join_tables <- function(input1, pkey, input2, fkey, import_field=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--pkey=", wbt_file_path(pkey)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--fkey=", wbt_file_path(fkey)))
if (!is.null(import_field)) {
args <- paste(args, paste0("--import_field=", import_field))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "join_tables"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lines to polygons
#'
#' @description Converts vector polylines to polygons.
#'
#' @param input Input vector line file.
#' @param output Output vector polygon file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lines_to_polygons <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lines_to_polygons"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Merge table with csv
#'
#' @description Merge a vector's attribute table with a table contained within a CSV text file.
#'
#' @param input Input primary vector file (i.e. the table to be modified).
#' @param pkey Primary key field.
#' @param csv Input CSV file (i.e. source of data to be imported).
#' @param fkey Foreign key field.
#' @param import_field Imported field (all fields will be imported if not specified).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_merge_table_with_csv <- function(input, pkey, csv, fkey, import_field=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--pkey=", wbt_file_path(pkey)))
args <- paste(args, paste0("--csv=", wbt_file_path(csv)))
args <- paste(args, paste0("--fkey=", wbt_file_path(fkey)))
if (!is.null(import_field)) {
args <- paste(args, paste0("--import_field=", import_field))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "merge_table_with_csv"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Merge vectors
#'
#' @description Combines two or more input vectors of the same ShapeType creating a single, new output vector.
#'
#' @param inputs Input vector file paths, concatenated with `","` or `";"`. See `wbt_file_path()` for details.
#' @param output Output vector file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_merge_vectors <- function(inputs, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "merge_vectors"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Modify no data value
#'
#' @description Modifies nodata values in a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param new_value New NoData value.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_modify_no_data_value <- function(input, new_value="-32768.0", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(new_value)) {
args <- paste(args, paste0("--new_value=", new_value))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "modify_no_data_value"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Multi part to single part
#'
#' @description Converts a vector file containing multi-part features into a vector containing only single-part features.
#'
#' @param input Input vector line or polygon file.
#' @param output Output vector line or polygon file.
#' @param exclude_holes Exclude hole parts from the feature splitting? (holes will continue to belong to their features in output.).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_multi_part_to_single_part <- function(input, output, exclude_holes=TRUE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (exclude_holes) {
args <- paste(args, "--exclude_holes")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "multi_part_to_single_part"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title New raster from base
#'
#' @description Creates a new raster using a base image.
#'
#' @param base Input base raster file.
#' @param output Output raster file.
#' @param value Constant value to fill raster with; either 'nodata' or numeric value.
#' @param data_type Output raster data type; options include 'double' (64-bit), 'float' (32-bit), and 'integer' (signed 16-bit) (default is 'float').
#' @param cell_size Optionally specified cell size of output raster. Not used when base raster is specified.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_new_raster_from_base <- function(base, output, value="nodata", data_type="float", cell_size=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--base=", wbt_file_path(base)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(value)) {
args <- paste(args, paste0("--value=", value))
}
if (!is.null(data_type)) {
args <- paste(args, paste0("--data_type=", data_type))
}
if (!is.null(cell_size)) {
args <- paste(args, paste0("--cell_size=", cell_size))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "new_raster_from_base"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Polygons to lines
#'
#' @description Converts vector polygons to polylines.
#'
#' @param input Input vector polygon file.
#' @param output Output vector lines file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_polygons_to_lines <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "polygons_to_lines"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Print geo tiff tags
#'
#' @description Prints the tags within a GeoTIFF.
#'
#' @param input Input GeoTIFF file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_print_geo_tiff_tags <- function(input, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "print_geo_tiff_tags"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Raster to vector lines
#'
#' @description Converts a raster lines features into a vector of the POLYLINE shapetype.
#'
#' @param input Input raster lines file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_raster_to_vector_lines <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "raster_to_vector_lines"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Raster to vector points
#'
#' @description Converts a raster dataset to a vector of the POINT shapetype.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output vector points file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_raster_to_vector_points <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "raster_to_vector_points"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Raster to vector polygons
#'
#' @description Converts a raster dataset to a vector of the POLYGON shapetype.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output vector polygons file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_raster_to_vector_polygons <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "raster_to_vector_polygons"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Reinitialize attribute table
#'
#' @description Reinitializes a vector's attribute table deleting all fields but the feature ID (FID).
#'
#' @param input Input vector file path. See `wbt_file_path()` for details.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_reinitialize_attribute_table <- function(input, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "reinitialize_attribute_table"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Remove polygon holes
#'
#' @description Removes holes within the features of a vector polygon file.
#'
#' @param input Input vector polygon file.
#' @param output Output vector polygon file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_remove_polygon_holes <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "remove_polygon_holes"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Remove raster polygon holes
#'
#' @description Removes polygon holes, or 'donut-holes', from raster polygons.
#'
#' @param input Name of the input raster image file.
#' @param output Name of the output raster file.
#' @param threshold Maximum size of removed holes, in grid cells. Blank for no threshold, i.e. remove all holes.
#' @param use_diagonals Use diagonal neighbours during clumping operation.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_remove_raster_polygon_holes <- function(input, output, threshold=3, use_diagonals=TRUE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(threshold)) {
args <- paste(args, paste0("--threshold=", threshold))
}
if (use_diagonals) {
args <- paste(args, "--use_diagonals")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "remove_raster_polygon_holes"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Set nodata value
#'
#' @description Assign the NoData value for an input image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param back_value Background value to set to nodata.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_set_nodata_value <- function(input, output, back_value=0.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(back_value)) {
args <- paste(args, paste0("--back_value=", back_value))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "set_nodata_value"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Single part to multi part
#'
#' @description Converts a vector file containing multi-part features into a vector containing only single-part features.
#'
#' @param input Input vector line or polygon file.
#' @param field Grouping ID field name in attribute table.
#' @param output Output vector line or polygon file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_single_part_to_multi_part <- function(input, output, field=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(field)) {
args <- paste(args, paste0("--field=", field))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "single_part_to_multi_part"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Vector lines to raster
#'
#' @description Converts a vector containing polylines into a raster.
#'
#' @param input Input vector lines file.
#' @param field Input field name in attribute table.
#' @param output Output raster file.
#' @param nodata Background value to set to NoData. Without this flag, it will be set to 0.0.
#' @param cell_size Optionally specified cell size of output raster. Not used when base raster is specified.
#' @param base Optionally specified input base raster file. Not used when a cell size is specified.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_vector_lines_to_raster <- function(input, output, field="FID", nodata=TRUE, cell_size=NULL, base=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(field)) {
args <- paste(args, paste0("--field=", field))
}
if (nodata) {
args <- paste(args, "--nodata")
}
if (!is.null(cell_size)) {
args <- paste(args, paste0("--cell_size=", cell_size))
}
if (!missing(base)) {
args <- paste(args, paste0("--base=", wbt_file_path(base)))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "vector_lines_to_raster"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Vector points to raster
#'
#' @description Converts a vector containing points into a raster.
#'
#' @param input Input vector Points file.
#' @param field Input field name in attribute table.
#' @param output Output raster file.
#' @param assign Assignment operation, where multiple points are in the same grid cell; options include 'first', 'last' (default), 'min', 'max', 'sum', 'number'.
#' @param nodata Background value to set to NoData. Without this flag, it will be set to 0.0.
#' @param cell_size Optionally specified cell size of output raster. Not used when base raster is specified.
#' @param base Optionally specified input base raster file. Not used when a cell size is specified.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_vector_points_to_raster <- function(input, output, field="FID", assign="last", nodata=TRUE, cell_size=NULL, base=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(field)) {
args <- paste(args, paste0("--field=", field))
}
if (!is.null(assign)) {
args <- paste(args, paste0("--assign=", assign))
}
if (nodata) {
args <- paste(args, "--nodata")
}
if (!is.null(cell_size)) {
args <- paste(args, paste0("--cell_size=", cell_size))
}
if (!missing(base)) {
args <- paste(args, paste0("--base=", wbt_file_path(base)))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "vector_points_to_raster"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Vector polygons to raster
#'
#' @description Converts a vector containing polygons into a raster.
#'
#' @param input Input vector polygons file.
#' @param field Input field name in attribute table.
#' @param output Output raster file.
#' @param nodata Background value to set to NoData. Without this flag, it will be set to 0.0.
#' @param cell_size Optionally specified cell size of output raster. Not used when base raster is specified.
#' @param base Optionally specified input base raster file. Not used when a cell size is specified.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords DataTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_vector_polygons_to_raster <- function(input, output, field="FID", nodata=TRUE, cell_size=NULL, base=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(field)) {
args <- paste(args, paste0("--field=", field))
}
if (nodata) {
args <- paste(args, "--nodata")
}
if (!is.null(cell_size)) {
args <- paste(args, paste0("--cell_size=", cell_size))
}
if (!missing(base)) {
args <- paste(args, paste0("--base=", wbt_file_path(base)))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "vector_polygons_to_raster"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
|
/scratch/gouwar.j/cran-all/cranData/whitebox/R/data_tools.R
|
#' @title Aggregate raster
#'
#' @description Aggregates a raster to a lower resolution.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param agg_factor Aggregation factor, in pixels.
#' @param type Statistic used to fill output pixels.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_aggregate_raster <- function(input, output, agg_factor=2, type="mean", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(agg_factor)) {
args <- paste(args, paste0("--agg_factor=", agg_factor))
}
if (!is.null(type)) {
args <- paste(args, paste0("--type=", type))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "aggregate_raster"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Block maximum gridding
#'
#' @description Creates a raster grid based on a set of vector points and assigns grid values using a block maximum scheme.
#'
#' @param input Input vector Points file.
#' @param field Input field name in attribute table.
#' @param use_z Use z-coordinate instead of field?.
#' @param output Output raster file.
#' @param cell_size Optionally specified cell size of output raster. Not used when base raster is specified.
#' @param base Optionally specified input base raster file. Not used when a cell size is specified.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_block_maximum_gridding <- function(input, field, output, use_z=FALSE, cell_size=NULL, base=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--field=", wbt_file_path(field)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (use_z) {
args <- paste(args, "--use_z")
}
if (!is.null(cell_size)) {
args <- paste(args, paste0("--cell_size=", cell_size))
}
if (!missing(base)) {
args <- paste(args, paste0("--base=", wbt_file_path(base)))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "block_maximum_gridding"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Block minimum gridding
#'
#' @description Creates a raster grid based on a set of vector points and assigns grid values using a block minimum scheme.
#'
#' @param input Input vector Points file.
#' @param field Input field name in attribute table.
#' @param use_z Use z-coordinate instead of field?.
#' @param output Output raster file.
#' @param cell_size Optionally specified cell size of output raster. Not used when base raster is specified.
#' @param base Optionally specified input base raster file. Not used when a cell size is specified.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_block_minimum_gridding <- function(input, field, output, use_z=FALSE, cell_size=NULL, base=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--field=", wbt_file_path(field)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (use_z) {
args <- paste(args, "--use_z")
}
if (!is.null(cell_size)) {
args <- paste(args, paste0("--cell_size=", cell_size))
}
if (!missing(base)) {
args <- paste(args, paste0("--base=", wbt_file_path(base)))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "block_minimum_gridding"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Centroid
#'
#' @description Calculates the centroid, or average location, of raster polygon objects.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param text_output Optional text output.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_centroid <- function(input, output, text_output=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (text_output) {
args <- paste(args, "--text_output")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "centroid"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Centroid vector
#'
#' @description Identifies the centroid point of a vector polyline or polygon feature or a group of vector points.
#'
#' @param input Input vector file path. See `wbt_file_path()` for details.
#' @param output Output vector file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_centroid_vector <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "centroid_vector"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Clump
#'
#' @description Groups cells that form discrete areas, assigning them unique identifiers.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param diag Flag indicating whether diagonal connections should be considered.
#' @param zero_back Flag indicating whether zero values should be treated as a background.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_clump <- function(input, output, diag=TRUE, zero_back=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (diag) {
args <- paste(args, "--diag")
}
if (zero_back) {
args <- paste(args, "--zero_back")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "clump"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Construct vector tin
#'
#' @description Creates a vector triangular irregular network (TIN) for a set of vector points.
#'
#' @param input Input vector points file.
#' @param field Input field name in attribute table.
#' @param use_z Use the 'z' dimension of the Shapefile's geometry instead of an attribute field?.
#' @param output Output vector polygon file.
#' @param max_triangle_edge_length Optional maximum triangle edge length; triangles larger than this size will not be gridded.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_construct_vector_tin <- function(input, output, field=NULL, use_z=FALSE, max_triangle_edge_length=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(field)) {
args <- paste(args, paste0("--field=", field))
}
if (use_z) {
args <- paste(args, "--use_z")
}
if (!is.null(max_triangle_edge_length)) {
args <- paste(args, paste0("--max_triangle_edge_length=", max_triangle_edge_length))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "construct_vector_tin"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Create hexagonal vector grid
#'
#' @description Creates a hexagonal vector grid.
#'
#' @param input Input base file.
#' @param output Output vector polygon file.
#' @param width The grid cell width.
#' @param orientation Grid Orientation, 'horizontal' or 'vertical'.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_create_hexagonal_vector_grid <- function(input, output, width, orientation="horizontal", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--width=", wbt_file_path(width)))
if (!is.null(orientation)) {
args <- paste(args, paste0("--orientation=", orientation))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "create_hexagonal_vector_grid"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Create plane
#'
#' @description Creates a raster image based on the equation for a simple plane.
#'
#' @param base Input base raster file.
#' @param output Output raster file.
#' @param gradient Slope gradient in degrees (-85.0 to 85.0).
#' @param aspect Aspect (direction) in degrees clockwise from north (0.0-360.0).
#' @param constant Constant value.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_create_plane <- function(base, output, gradient=15.0, aspect=90.0, constant=0.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--base=", wbt_file_path(base)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(gradient)) {
args <- paste(args, paste0("--gradient=", gradient))
}
if (!is.null(aspect)) {
args <- paste(args, paste0("--aspect=", aspect))
}
if (!is.null(constant)) {
args <- paste(args, paste0("--constant=", constant))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "create_plane"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Create rectangular vector grid
#'
#' @description Creates a rectangular vector grid.
#'
#' @param input Input base file.
#' @param output Output vector polygon file.
#' @param width The grid cell width.
#' @param height The grid cell height.
#' @param xorig The grid origin x-coordinate.
#' @param yorig The grid origin y-coordinate.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_create_rectangular_vector_grid <- function(input, output, width, height, xorig=0, yorig=0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--width=", wbt_file_path(width)))
args <- paste(args, paste0("--height=", wbt_file_path(height)))
if (!is.null(xorig)) {
args <- paste(args, paste0("--xorig=", xorig))
}
if (!is.null(yorig)) {
args <- paste(args, paste0("--yorig=", yorig))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "create_rectangular_vector_grid"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Dissolve
#'
#' @description Removes the interior, or shared, boundaries within a vector polygon coverage.
#'
#' @param input Input vector file path. See `wbt_file_path()` for details.
#' @param field Dissolve field attribute (optional).
#' @param output Output vector file.
#' @param snap Snap tolerance.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_dissolve <- function(input, output, field=NULL, snap=0.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(field)) {
args <- paste(args, paste0("--field=", field))
}
if (!is.null(snap)) {
args <- paste(args, paste0("--snap=", snap))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "dissolve"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Eliminate coincident points
#'
#' @description Removes any coincident, or nearly coincident, points from a vector points file.
#'
#' @param input Input vector file path. See `wbt_file_path()` for details.
#' @param output Output vector points file.
#' @param tolerance The distance tolerance for points.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_eliminate_coincident_points <- function(input, output, tolerance, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--tolerance=", wbt_file_path(tolerance)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "eliminate_coincident_points"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Extend vector lines
#'
#' @description Extends vector lines by a specified distance.
#'
#' @param input Input vector polyline file.
#' @param output Output vector polyline file.
#' @param dist The distance to extend.
#' @param extend Extend direction, 'both ends' (default), 'line start', 'line end'.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_extend_vector_lines <- function(input, output, dist, extend="both ends", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--dist=", wbt_file_path(dist)))
if (!is.null(extend)) {
args <- paste(args, paste0("--extend=", extend))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "extend_vector_lines"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Extract nodes
#'
#' @description Converts vector lines or polygons into vertex points.
#'
#' @param input Input vector lines or polygon file.
#' @param output Output vector points file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_extract_nodes <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "extract_nodes"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Extract raster values at points
#'
#' @description Extracts the values of raster(s) at vector point locations.
#'
#' @param inputs Input raster file paths, concatenated with `","` or `";"`. See `wbt_file_path()` for details.
#' @param points Input vector points file.
#' @param out_text Output point values as text? Otherwise, the only output is to to the points file's attribute table.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_extract_raster_values_at_points <- function(inputs, points, out_text=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--points=", wbt_file_path(points)))
if (out_text) {
args <- paste(args, "--out_text")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "extract_raster_values_at_points"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Filter raster features by area
#'
#' @description Removes small-area features from a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param threshold Remove features with fewer grid cells than this threshold value.
#' @param background Background value.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_filter_raster_features_by_area <- function(input, output, threshold, background="zero", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--threshold=", wbt_file_path(threshold)))
if (!is.null(background)) {
args <- paste(args, paste0("--background=", background))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "filter_raster_features_by_area"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Find lowest or highest points
#'
#' @description Locates the lowest and/or highest valued cells in a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output vector points file.
#' @param out_type Output type; one of 'area' (default) and 'volume'.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_find_lowest_or_highest_points <- function(input, output, out_type="lowest", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(out_type)) {
args <- paste(args, paste0("--out_type=", out_type))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "find_lowest_or_highest_points"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Heat map
#'
#' @description Calculates a heat map, or kernel density estimation (KDE), for an input point set.
#'
#' @param input Name of the input points shapefile.
#' @param weight_field Optional name of the attribute containing point weight.
#' @param output Name of the output raster image file.
#' @param bandwidth Bandwidth (metres).
#' @param kernel Kernel type; one of 'uniform', 'triangular', 'epanechnikov', 'quartic', 'triweight', 'tricube', 'gaussian', 'cosine', 'logistic', 'sigmoid', 'silverman'.
#' @param cell_size Optionally specified cell size of output raster, in metres. Not used when base raster is specified.
#' @param base Optionally specified input base raster file. Not used when a cell size is specified.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_heat_map <- function(input, output, weight_field=NULL, bandwidth="", kernel="quartic", cell_size="", base=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(weight_field)) {
args <- paste(args, paste0("--weight_field=", weight_field))
}
if (!is.null(bandwidth)) {
args <- paste(args, paste0("--bandwidth=", bandwidth))
}
if (!is.null(kernel)) {
args <- paste(args, paste0("--kernel=", kernel))
}
if (!is.null(cell_size)) {
args <- paste(args, paste0("--cell_size=", cell_size))
}
if (!missing(base)) {
args <- paste(args, paste0("--base=", wbt_file_path(base)))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "heat_map"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Idw interpolation
#'
#' @description Interpolates vector points into a raster surface using an inverse-distance weighted scheme.
#'
#' @param input Input vector Points file.
#' @param field Input field name in attribute table.
#' @param use_z Use z-coordinate instead of field?.
#' @param output Output raster file.
#' @param weight IDW weight value.
#' @param radius Search Radius in map units.
#' @param min_points Minimum number of points.
#' @param cell_size Optionally specified cell size of output raster. Not used when base raster is specified.
#' @param base Optionally specified input base raster file. Not used when a cell size is specified.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_idw_interpolation <- function(input, field, output, use_z=FALSE, weight=2.0, radius=NULL, min_points=NULL, cell_size=NULL, base=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--field=", wbt_file_path(field)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (use_z) {
args <- paste(args, "--use_z")
}
if (!is.null(weight)) {
args <- paste(args, paste0("--weight=", weight))
}
if (!is.null(radius)) {
args <- paste(args, paste0("--radius=", radius))
}
if (!is.null(min_points)) {
args <- paste(args, paste0("--min_points=", min_points))
}
if (!is.null(cell_size)) {
args <- paste(args, paste0("--cell_size=", cell_size))
}
if (!missing(base)) {
args <- paste(args, paste0("--base=", wbt_file_path(base)))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "idw_interpolation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Layer footprint
#'
#' @description Creates a vector polygon footprint of the area covered by a raster grid or vector layer.
#'
#' @param input Input raster or vector file.
#' @param output Output vector polygon file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_layer_footprint <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "layer_footprint"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Medoid
#'
#' @description Calculates the medoid for a series of vector features contained in a shapefile.
#'
#' @param input Input vector file path. See `wbt_file_path()` for details.
#' @param output Output vector file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_medoid <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "medoid"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Minimum bounding box
#'
#' @description Creates a vector minimum bounding rectangle around vector features.
#'
#' @param input Input vector file path. See `wbt_file_path()` for details.
#' @param output Output vector polygon file.
#' @param criterion Minimization criterion; options include 'area' (default), 'length', 'width', and 'perimeter'.
#' @param features Find the minimum bounding rectangles around each individual vector feature.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_minimum_bounding_box <- function(input, output, criterion="area", features=TRUE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(criterion)) {
args <- paste(args, paste0("--criterion=", criterion))
}
if (features) {
args <- paste(args, "--features")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "minimum_bounding_box"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Minimum bounding circle
#'
#' @description Delineates the minimum bounding circle (i.e. smallest enclosing circle) for a group of vectors.
#'
#' @param input Input vector file path. See `wbt_file_path()` for details.
#' @param output Output vector polygon file.
#' @param features Find the minimum bounding circle around each individual vector feature.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_minimum_bounding_circle <- function(input, output, features=TRUE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (features) {
args <- paste(args, "--features")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "minimum_bounding_circle"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Minimum bounding envelope
#'
#' @description Creates a vector axis-aligned minimum bounding rectangle (envelope) around vector features.
#'
#' @param input Input vector file path. See `wbt_file_path()` for details.
#' @param output Output vector polygon file.
#' @param features Find the minimum bounding envelop around each individual vector feature.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_minimum_bounding_envelope <- function(input, output, features=TRUE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (features) {
args <- paste(args, "--features")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "minimum_bounding_envelope"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Minimum convex hull
#'
#' @description Creates a vector convex polygon around vector features.
#'
#' @param input Input vector file path. See `wbt_file_path()` for details.
#' @param output Output vector polygon file.
#' @param features Find the hulls around each vector feature.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_minimum_convex_hull <- function(input, output, features=TRUE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (features) {
args <- paste(args, "--features")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "minimum_convex_hull"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Natural neighbour interpolation
#'
#' @description Creates a raster grid based on Sibson's natural neighbour method.
#'
#' @param input Input vector points file.
#' @param field Input field name in attribute table.
#' @param use_z Use the 'z' dimension of the Shapefile's geometry instead of an attribute field?.
#' @param output Output raster file.
#' @param cell_size Optionally specified cell size of output raster. Not used when base raster is specified.
#' @param base Optionally specified input base raster file. Not used when a cell size is specified.
#' @param clip Clip the data to the convex hull of the points?.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_natural_neighbour_interpolation <- function(input, output, field=NULL, use_z=FALSE, cell_size=NULL, base=NULL, clip=TRUE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(field)) {
args <- paste(args, paste0("--field=", field))
}
if (use_z) {
args <- paste(args, "--use_z")
}
if (!is.null(cell_size)) {
args <- paste(args, paste0("--cell_size=", cell_size))
}
if (!missing(base)) {
args <- paste(args, paste0("--base=", wbt_file_path(base)))
}
if (clip) {
args <- paste(args, "--clip")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "natural_neighbour_interpolation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Nearest neighbour gridding
#'
#' @description Creates a raster grid based on a set of vector points and assigns grid values using the nearest neighbour.
#'
#' @param input Input vector Points file.
#' @param field Input field name in attribute table.
#' @param use_z Use z-coordinate instead of field?.
#' @param output Output raster file.
#' @param cell_size Optionally specified cell size of output raster. Not used when base raster is specified.
#' @param base Optionally specified input base raster file. Not used when a cell size is specified.
#' @param max_dist Maximum search distance (optional).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_nearest_neighbour_gridding <- function(input, field, output, use_z=FALSE, cell_size=NULL, base=NULL, max_dist=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--field=", wbt_file_path(field)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (use_z) {
args <- paste(args, "--use_z")
}
if (!is.null(cell_size)) {
args <- paste(args, paste0("--cell_size=", cell_size))
}
if (!missing(base)) {
args <- paste(args, paste0("--base=", wbt_file_path(base)))
}
if (!is.null(max_dist)) {
args <- paste(args, paste0("--max_dist=", max_dist))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "nearest_neighbour_gridding"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Polygon area
#'
#' @description Calculates the area of vector polygons.
#'
#' @param input Input vector polygon file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_polygon_area <- function(input, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "polygon_area"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Polygon long axis
#'
#' @description Used to map the long axis of polygon features.
#'
#' @param input Input vector polygons file.
#' @param output Output vector polyline file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_polygon_long_axis <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "polygon_long_axis"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Polygon perimeter
#'
#' @description Calculates the perimeter of vector polygons.
#'
#' @param input Input vector polygon file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_polygon_perimeter <- function(input, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "polygon_perimeter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Polygon short axis
#'
#' @description Used to map the short axis of polygon features.
#'
#' @param input Input vector polygons file.
#' @param output Output vector polyline file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_polygon_short_axis <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "polygon_short_axis"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Radial basis function interpolation
#'
#' @description Interpolates vector points into a raster surface using a radial basis function scheme.
#'
#' @param input Input vector points file.
#' @param field Input field name in attribute table.
#' @param use_z Use z-coordinate instead of field?.
#' @param output Output raster file.
#' @param radius Search Radius (in map units).
#' @param min_points Minimum number of points.
#' @param func_type Radial basis function type; options are 'ThinPlateSpline' (default), 'PolyHarmonic', 'Gaussian', 'MultiQuadric', 'InverseMultiQuadric'.
#' @param poly_order Polynomial order; options are 'none' (default), 'constant', 'affine'.
#' @param weight Weight parameter used in basis function.
#' @param cell_size Optionally specified cell size of output raster. Not used when base raster is specified.
#' @param base Optionally specified input base raster file. Not used when a cell size is specified.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_radial_basis_function_interpolation <- function(input, field, output, use_z=FALSE, radius=NULL, min_points=NULL, func_type="ThinPlateSpline", poly_order="none", weight=0.1, cell_size=NULL, base=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--field=", wbt_file_path(field)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (use_z) {
args <- paste(args, "--use_z")
}
if (!is.null(radius)) {
args <- paste(args, paste0("--radius=", radius))
}
if (!is.null(min_points)) {
args <- paste(args, paste0("--min_points=", min_points))
}
if (!is.null(func_type)) {
args <- paste(args, paste0("--func_type=", func_type))
}
if (!is.null(poly_order)) {
args <- paste(args, paste0("--poly_order=", poly_order))
}
if (!is.null(weight)) {
args <- paste(args, paste0("--weight=", weight))
}
if (!is.null(cell_size)) {
args <- paste(args, paste0("--cell_size=", cell_size))
}
if (!missing(base)) {
args <- paste(args, paste0("--base=", wbt_file_path(base)))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "radial_basis_function_interpolation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Raster area
#'
#' @description Calculates the area of polygons or classes within a raster image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param out_text Would you like to output polygon areas to text?.
#' @param units Area units; options include 'grid cells' and 'map units'.
#' @param zero_back Flag indicating whether zero values should be treated as a background.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_raster_area <- function(input, output=NULL, out_text=FALSE, units="grid cells", zero_back=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (out_text) {
args <- paste(args, "--out_text")
}
if (!is.null(units)) {
args <- paste(args, paste0("--units=", units))
}
if (zero_back) {
args <- paste(args, "--zero_back")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "raster_area"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Raster cell assignment
#'
#' @description Assign row or column number to cells.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param assign Which variable would you like to assign to grid cells? Options include 'column', 'row', 'x', and 'y'.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_raster_cell_assignment <- function(input, output, assign="column", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(assign)) {
args <- paste(args, paste0("--assign=", assign))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "raster_cell_assignment"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Raster perimeter
#'
#' @description Calculates the perimeters of polygons or classes within a raster image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param out_text Would you like to output polygon areas to text?.
#' @param units Area units; options include 'grid cells' and 'map units'.
#' @param zero_back Flag indicating whether zero values should be treated as a background.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_raster_perimeter <- function(input, output=NULL, out_text=FALSE, units="grid cells", zero_back=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (out_text) {
args <- paste(args, "--out_text")
}
if (!is.null(units)) {
args <- paste(args, paste0("--units=", units))
}
if (zero_back) {
args <- paste(args, "--zero_back")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "raster_perimeter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Reclass
#'
#' @description Reclassifies the values in a raster image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param reclass_vals Reclassification triplet values (new value; from value; to less than), e.g. '0.0;0.0;1.0;1.0;1.0;2.0'.
#' @param assign_mode Optional Boolean flag indicating whether to operate in assign mode, reclass_vals values are interpreted as new value; old value pairs.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_reclass <- function(input, output, reclass_vals, assign_mode=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--reclass_vals=", wbt_file_path(reclass_vals)))
if (assign_mode) {
args <- paste(args, "--assign_mode")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "reclass"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Reclass equal interval
#'
#' @description Reclassifies the values in a raster image based on equal-ranges.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param interval Class interval size.
#' @param start_val Optional starting value (default is input minimum value).
#' @param end_val Optional ending value (default is input maximum value).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_reclass_equal_interval <- function(input, output, interval=10.0, start_val=NULL, end_val=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(interval)) {
args <- paste(args, paste0("--interval=", interval))
}
if (!is.null(start_val)) {
args <- paste(args, paste0("--start_val=", start_val))
}
if (!is.null(end_val)) {
args <- paste(args, paste0("--end_val=", end_val))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "reclass_equal_interval"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Reclass from file
#'
#' @description Reclassifies the values in a raster image using reclass ranges in a text file.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param reclass_file Input text file containing reclass ranges.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_reclass_from_file <- function(input, reclass_file, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--reclass_file=", wbt_file_path(reclass_file)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "reclass_from_file"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Smooth vectors
#'
#' @description Smooths a vector coverage of either a POLYLINE or POLYGON base ShapeType.
#'
#' @param input Input vector POLYLINE or POLYGON file.
#' @param output Output vector file.
#' @param filter The filter size, any odd integer greater than or equal to 3; default is 3.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_smooth_vectors <- function(input, output, filter=3, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filter)) {
args <- paste(args, paste0("--filter=", filter))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "smooth_vectors"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Split vector lines
#'
#' @description Used to split a vector line coverage into even-lengthed segments.
#'
#' @param input Name of the input lines shapefile.
#' @param output Name of the output lines shapefile.
#' @param length Maximum segment length (m).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_split_vector_lines <- function(input, output, length=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(length)) {
args <- paste(args, paste0("--length=", length))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "split_vector_lines"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Tin gridding
#'
#' @description Creates a raster grid based on a triangular irregular network (TIN) fitted to vector points.
#'
#' @param input Input vector points file.
#' @param field Input field name in attribute table.
#' @param use_z Use the 'z' dimension of the Shapefile's geometry instead of an attribute field?.
#' @param output Output raster file.
#' @param resolution Output raster's grid resolution.
#' @param base Optionally specified input base raster file. Not used when a cell size is specified.
#' @param max_triangle_edge_length Optional maximum triangle edge length; triangles larger than this size will not be gridded.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_tin_gridding <- function(input, output, field=NULL, use_z=FALSE, resolution=NULL, base=NULL, max_triangle_edge_length=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(field)) {
args <- paste(args, paste0("--field=", field))
}
if (use_z) {
args <- paste(args, "--use_z")
}
if (!is.null(resolution)) {
args <- paste(args, paste0("--resolution=", resolution))
}
if (!missing(base)) {
args <- paste(args, paste0("--base=", wbt_file_path(base)))
}
if (!is.null(max_triangle_edge_length)) {
args <- paste(args, paste0("--max_triangle_edge_length=", max_triangle_edge_length))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "tin_gridding"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Travelling salesman problem
#'
#' @description Finds approximate solutions to travelling salesman problems, the goal of which is to identify the shortest route connecting a set of locations.
#'
#' @param input Name of the input points shapefile.
#' @param output Name of the output lines shapefile.
#' @param duration Maximum duration, in seconds.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_travelling_salesman_problem <- function(input, output, duration=60, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(duration)) {
args <- paste(args, paste0("--duration=", duration))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "travelling_salesman_problem"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Vector hex binning
#'
#' @description Hex-bins a set of vector points.
#'
#' @param input Input base file.
#' @param output Output vector polygon file.
#' @param width The grid cell width.
#' @param orientation Grid Orientation, 'horizontal' or 'vertical'.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_vector_hex_binning <- function(input, output, width, orientation="horizontal", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--width=", wbt_file_path(width)))
if (!is.null(orientation)) {
args <- paste(args, paste0("--orientation=", orientation))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "vector_hex_binning"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Voronoi diagram
#'
#' @description Creates a vector Voronoi diagram for a set of vector points.
#'
#' @param input Input vector points file.
#' @param output Output vector polygon file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_voronoi_diagram <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "voronoi_diagram"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
|
/scratch/gouwar.j/cran-all/cranData/whitebox/R/gis_analysis.R
|
#' @title Buffer raster
#'
#' @description Maps a distance-based buffer around each non-background (non-zero/non-nodata) grid cell in an input image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param size Buffer size.
#' @param gridcells Optional flag to indicate that the 'size' threshold should be measured in grid cells instead of the default map units.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisDistanceTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_buffer_raster <- function(input, output, size, gridcells=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--size=", wbt_file_path(size)))
if (gridcells) {
args <- paste(args, "--gridcells")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "buffer_raster"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Cost allocation
#'
#' @description Identifies the source cell to which each grid cell is connected by a least-cost pathway in a cost-distance analysis.
#'
#' @param source Input source raster file.
#' @param backlink Input backlink raster file generated by the cost-distance tool.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisDistanceTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_cost_allocation <- function(source, backlink, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--source=", wbt_file_path(source)))
args <- paste(args, paste0("--backlink=", wbt_file_path(backlink)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "cost_allocation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Cost distance
#'
#' @description Performs cost-distance accumulation on a cost surface and a group of source cells.
#'
#' @param source Input source raster file.
#' @param cost Input cost (friction) raster file.
#' @param out_accum Output cost accumulation raster file.
#' @param out_backlink Output backlink raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisDistanceTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_cost_distance <- function(source, cost, out_accum, out_backlink, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--source=", wbt_file_path(source)))
args <- paste(args, paste0("--cost=", wbt_file_path(cost)))
args <- paste(args, paste0("--out_accum=", wbt_file_path(out_accum)))
args <- paste(args, paste0("--out_backlink=", wbt_file_path(out_backlink)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "cost_distance"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Cost pathway
#'
#' @description Performs cost-distance pathway analysis using a series of destination grid cells.
#'
#' @param destination Input destination raster file.
#' @param backlink Input backlink raster file generated by the cost-distance tool.
#' @param output Output cost pathway raster file.
#' @param zero_background Flag indicating whether zero values should be treated as a background.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisDistanceTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_cost_pathway <- function(destination, backlink, output, zero_background=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--destination=", wbt_file_path(destination)))
args <- paste(args, paste0("--backlink=", wbt_file_path(backlink)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (zero_background) {
args <- paste(args, "--zero_background")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "cost_pathway"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Euclidean allocation
#'
#' @description Assigns grid cells in the output raster the value of the nearest target cell in the input image, measured by the Shih and Wu (2004) Euclidean distance transform.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisDistanceTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_euclidean_allocation <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "euclidean_allocation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Euclidean distance
#'
#' @description Calculates the Shih and Wu (2004) Euclidean distance transform.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisDistanceTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_euclidean_distance <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "euclidean_distance"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
|
/scratch/gouwar.j/cran-all/cranData/whitebox/R/gis_analysis_distance.R
|
#' @title Average overlay
#'
#' @description Calculates the average for each grid cell from a group of raster images.
#'
#' @param inputs Input raster file paths, concatenated with `","` or `";"`. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_average_overlay <- function(inputs, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "average_overlay"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Clip
#'
#' @description Extract all the features, or parts of features, that overlap with the features of the clip vector.
#'
#' @param input Input vector file path. See `wbt_file_path()` for details.
#' @param clip Input clip polygon vector file.
#' @param output Output vector file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_clip <- function(input, clip, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--clip=", wbt_file_path(clip)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "clip"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Clip raster to polygon
#'
#' @description Clips a raster to a vector polygon.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param polygons Input vector polygons file.
#' @param output Output raster file.
#' @param maintain_dimensions Maintain input raster dimensions?.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_clip_raster_to_polygon <- function(input, polygons, output, maintain_dimensions=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--polygons=", wbt_file_path(polygons)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (maintain_dimensions) {
args <- paste(args, "--maintain_dimensions")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "clip_raster_to_polygon"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Count if
#'
#' @description Counts the number of occurrences of a specified value in a cell-stack of rasters.
#'
#' @param inputs Input raster file paths, concatenated with `","` or `";"`. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param value Search value (e.g. countif value = 5.0).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_count_if <- function(inputs, output, value, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--value=", wbt_file_path(value)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "count_if"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Difference
#'
#' @description Outputs the features that occur in one of the two vector inputs but not both, i.e. no overlapping features.
#'
#' @param input Input vector file path. See `wbt_file_path()` for details.
#' @param overlay Input overlay vector file.
#' @param output Output vector file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_difference <- function(input, overlay, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--overlay=", wbt_file_path(overlay)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "difference"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Erase
#'
#' @description Removes all the features, or parts of features, that overlap with the features of the erase vector polygon.
#'
#' @param input Input vector file path. See `wbt_file_path()` for details.
#' @param erase Input erase polygon vector file.
#' @param output Output vector file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_erase <- function(input, erase, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--erase=", wbt_file_path(erase)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "erase"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Erase polygon from raster
#'
#' @description Erases (cuts out) a vector polygon from a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param polygons Input vector polygons file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_erase_polygon_from_raster <- function(input, polygons, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--polygons=", wbt_file_path(polygons)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "erase_polygon_from_raster"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Highest position
#'
#' @description Identifies the stack position of the maximum value within a raster stack on a cell-by-cell basis.
#'
#' @param inputs Input raster file paths, concatenated with `","` or `";"`. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_highest_position <- function(inputs, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "highest_position"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Intersect
#'
#' @description Identifies the parts of features in common between two input vector layers.
#'
#' @param input Input vector file path. See `wbt_file_path()` for details.
#' @param overlay Input overlay vector file.
#' @param output Output vector file.
#' @param snap Snap tolerance.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_intersect <- function(input, overlay, output, snap=0.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--overlay=", wbt_file_path(overlay)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(snap)) {
args <- paste(args, paste0("--snap=", snap))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "intersect"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Line intersections
#'
#' @description Identifies points where the features of two vector line layers intersect.
#'
#' @param input1 Input vector polyline file.
#' @param input2 Input vector polyline file.
#' @param output Output vector point file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_line_intersections <- function(input1, input2, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "line_intersections"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lowest position
#'
#' @description Identifies the stack position of the minimum value within a raster stack on a cell-by-cell basis.
#'
#' @param inputs Input raster file paths, concatenated with `","` or `";"`. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lowest_position <- function(inputs, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lowest_position"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Max absolute overlay
#'
#' @description Evaluates the maximum absolute value for each grid cell from a stack of input rasters.
#'
#' @param inputs Input raster file paths, concatenated with `","` or `";"`. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_max_absolute_overlay <- function(inputs, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "max_absolute_overlay"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Max overlay
#'
#' @description Evaluates the maximum value for each grid cell from a stack of input rasters.
#'
#' @param inputs Input raster file paths, concatenated with `","` or `";"`. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_max_overlay <- function(inputs, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "max_overlay"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Merge line segments
#'
#' @description Merges vector line segments into larger features.
#'
#' @param input Input vector file path. See `wbt_file_path()` for details.
#' @param output Output vector file.
#' @param snap Snap tolerance.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_merge_line_segments <- function(input, output, snap=0.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(snap)) {
args <- paste(args, paste0("--snap=", snap))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "merge_line_segments"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Min absolute overlay
#'
#' @description Evaluates the minimum absolute value for each grid cell from a stack of input rasters.
#'
#' @param inputs Input raster file paths, concatenated with `","` or `";"`. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_min_absolute_overlay <- function(inputs, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "min_absolute_overlay"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Min overlay
#'
#' @description Evaluates the minimum value for each grid cell from a stack of input rasters.
#'
#' @param inputs Input raster file paths, concatenated with `","` or `";"`. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_min_overlay <- function(inputs, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "min_overlay"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Multiply overlay
#'
#' @description Calculates the sum for each grid cell from a group of raster images.
#'
#' @param inputs Input raster file paths, concatenated with `","` or `";"`. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_multiply_overlay <- function(inputs, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "multiply_overlay"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Percent equal to
#'
#' @description Calculates the percentage of a raster stack that have cell values equal to an input on a cell-by-cell basis.
#'
#' @param inputs Input raster file paths, concatenated with `","` or `";"`. See `wbt_file_path()` for details.
#' @param comparison Input comparison raster file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_percent_equal_to <- function(inputs, comparison, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--comparison=", wbt_file_path(comparison)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "percent_equal_to"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Percent greater than
#'
#' @description Calculates the percentage of a raster stack that have cell values greater than an input on a cell-by-cell basis.
#'
#' @param inputs Input raster file paths, concatenated with `","` or `";"`. See `wbt_file_path()` for details.
#' @param comparison Input comparison raster file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_percent_greater_than <- function(inputs, comparison, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--comparison=", wbt_file_path(comparison)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "percent_greater_than"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Percent less than
#'
#' @description Calculates the percentage of a raster stack that have cell values less than an input on a cell-by-cell basis.
#'
#' @param inputs Input raster file paths, concatenated with `","` or `";"`. See `wbt_file_path()` for details.
#' @param comparison Input comparison raster file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_percent_less_than <- function(inputs, comparison, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--comparison=", wbt_file_path(comparison)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "percent_less_than"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Pick from list
#'
#' @description Outputs the value from a raster stack specified by a position raster.
#'
#' @param inputs Input raster file paths, concatenated with `","` or `";"`. See `wbt_file_path()` for details.
#' @param pos_input Input position raster file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_pick_from_list <- function(inputs, pos_input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--pos_input=", wbt_file_path(pos_input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "pick_from_list"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Polygonize
#'
#' @description Creates a polygon layer from two or more intersecting line features contained in one or more input vector line files.
#'
#' @param inputs Input vector polyline file.
#' @param output Output vector polygon file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_polygonize <- function(inputs, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "polygonize"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Split with lines
#'
#' @description Splits the lines or polygons in one layer using the lines in another layer.
#'
#' @param input Input vector line or polygon file.
#' @param split Input vector polyline file.
#' @param output Output vector file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_split_with_lines <- function(input, split, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--split=", wbt_file_path(split)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "split_with_lines"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Sum overlay
#'
#' @description Calculates the sum for each grid cell from a group of raster images.
#'
#' @param inputs Input raster file paths, concatenated with `","` or `";"`. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_sum_overlay <- function(inputs, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "sum_overlay"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Symmetrical difference
#'
#' @description Outputs the features that occur in one of the two vector inputs but not both, i.e. no overlapping features.
#'
#' @param input Input vector file path. See `wbt_file_path()` for details.
#' @param overlay Input overlay vector file.
#' @param output Output vector file.
#' @param snap Snap tolerance.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_symmetrical_difference <- function(input, overlay, output, snap=0.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--overlay=", wbt_file_path(overlay)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(snap)) {
args <- paste(args, paste0("--snap=", snap))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "symmetrical_difference"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Union
#'
#' @description Splits vector layers at their overlaps, creating a layer containing all the portions from both input and overlay layers.
#'
#' @param input Input vector file path. See `wbt_file_path()` for details.
#' @param overlay Input overlay vector file.
#' @param output Output vector file.
#' @param snap Snap tolerance.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_union <- function(input, overlay, output, snap=0.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--overlay=", wbt_file_path(overlay)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(snap)) {
args <- paste(args, paste0("--snap=", snap))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "union"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Update nodata cells
#'
#' @description Replaces the NoData values in an input raster with the corresponding values contained in a second update layer.
#'
#' @param input1 Input raster file 1.
#' @param input2 Input raster file 2; update layer.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_update_nodata_cells <- function(input1, input2, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "update_nodata_cells"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Weighted overlay
#'
#' @description Performs a weighted sum on multiple input rasters after converting each image to a common scale. The tool performs a multi-criteria evaluation (MCE).
#'
#' @param factors Input factor raster files.
#' @param weights Weight values, contained in quotes and separated by commas or semicolons. Must have the same number as factors.
#' @param cost Boolean array indicating which factors are cost factors, contained in quotes and separated by commas or semicolons. Must have the same number as factors.
#' @param constraints Input constraints raster files.
#' @param output Output raster file.
#' @param scale_max Suitability scale maximum value (common values are 1.0, 100.0, and 255.0).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_weighted_overlay <- function(factors, weights, output, cost=NULL, constraints=NULL, scale_max=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--factors=", wbt_file_path(factors)))
args <- paste(args, paste0("--weights=", wbt_file_path(weights)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(cost)) {
args <- paste(args, paste0("--cost=", cost))
}
if (!is.null(constraints)) {
args <- paste(args, paste0("--constraints=", constraints))
}
if (!is.null(scale_max)) {
args <- paste(args, paste0("--scale_max=", scale_max))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "weighted_overlay"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Weighted sum
#'
#' @description Performs a weighted-sum overlay on multiple input raster images.
#'
#' @param inputs Input raster file paths, concatenated with `","` or `";"`. See `wbt_file_path()` for details.
#' @param weights Weight values, contained in quotes and separated by commas or semicolons.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisOverlayTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_weighted_sum <- function(inputs, weights, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--weights=", wbt_file_path(weights)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "weighted_sum"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
|
/scratch/gouwar.j/cran-all/cranData/whitebox/R/gis_analysis_overlay.R
|
#' @title Boundary shape complexity
#'
#' @description Calculates the complexity of the boundaries of raster polygons.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisPatchShapeTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_boundary_shape_complexity <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "boundary_shape_complexity"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Compactness ratio
#'
#' @description Calculates the compactness ratio (A/P), a measure of shape complexity, for vector polygons.
#'
#' @param input Input vector polygon file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisPatchShapeTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_compactness_ratio <- function(input, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "compactness_ratio"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Edge proportion
#'
#' @description Calculate the proportion of cells in a raster polygon that are edge cells.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param output_text flag indicating whether a text report should also be output.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisPatchShapeTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_edge_proportion <- function(input, output, output_text=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (output_text) {
args <- paste(args, "--output_text")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "edge_proportion"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Elongation ratio
#'
#' @description Calculates the elongation ratio for vector polygons.
#'
#' @param input Input vector polygon file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisPatchShapeTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_elongation_ratio <- function(input, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "elongation_ratio"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Find patch or class edge cells
#'
#' @description Finds all cells located on the edge of patch or class features.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisPatchShapeTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_find_patch_or_class_edge_cells <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "find_patch_or_class_edge_cells"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Hole proportion
#'
#' @description Calculates the proportion of the total area of a polygon's holes relative to the area of the polygon's hull.
#'
#' @param input Input vector polygon file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisPatchShapeTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_hole_proportion <- function(input, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "hole_proportion"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Linearity index
#'
#' @description Calculates the linearity index for vector polygons.
#'
#' @param input Input vector polygon file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisPatchShapeTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_linearity_index <- function(input, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "linearity_index"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Narrowness index
#'
#' @description Calculates the narrowness of raster polygons.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisPatchShapeTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_narrowness_index <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "narrowness_index"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Patch orientation
#'
#' @description Calculates the orientation of vector polygons.
#'
#' @param input Input vector polygon file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisPatchShapeTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_patch_orientation <- function(input, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "patch_orientation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Perimeter area ratio
#'
#' @description Calculates the perimeter-area ratio of vector polygons.
#'
#' @param input Input vector polygon file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisPatchShapeTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_perimeter_area_ratio <- function(input, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "perimeter_area_ratio"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Radius of gyration
#'
#' @description Calculates the distance of cells from their polygon's centroid.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param text_output Optional text output.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisPatchShapeTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_radius_of_gyration <- function(input, output, text_output=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (text_output) {
args <- paste(args, "--text_output")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "radius_of_gyration"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Related circumscribing circle
#'
#' @description Calculates the related circumscribing circle of vector polygons.
#'
#' @param input Input vector polygon file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisPatchShapeTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_related_circumscribing_circle <- function(input, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "related_circumscribing_circle"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Shape complexity index
#'
#' @description Calculates overall polygon shape complexity or irregularity.
#'
#' @param input Input vector polygon file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisPatchShapeTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_shape_complexity_index <- function(input, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "shape_complexity_index"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Shape complexity index raster
#'
#' @description Calculates the complexity of raster polygons or classes.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GISAnalysisPatchShapeTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_shape_complexity_index_raster <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "shape_complexity_index_raster"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
|
/scratch/gouwar.j/cran-all/cranData/whitebox/R/gis_analysis_patch_shape.R
|
#' @title Average flowpath slope
#'
#' @description Measures the average slope gradient from each grid cell to all upslope divide cells.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_average_flowpath_slope <- function(dem, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "average_flowpath_slope"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Average upslope flowpath length
#'
#' @description Measures the average length of all upslope flowpaths draining each grid cell.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_average_upslope_flowpath_length <- function(dem, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "average_upslope_flowpath_length"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Basins
#'
#' @description Identifies drainage basins that drain to the DEM edge.
#'
#' @param d8_pntr Input raster D8 pointer file.
#' @param output Output raster file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_basins <- function(d8_pntr, output, esri_pntr=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "basins"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Breach depressions
#'
#' @description Breaches all of the depressions in a DEM using Lindsay's (2016) algorithm. This should be preferred over depression filling in most cases.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param max_depth Optional maximum breach depth (default is Inf).
#' @param max_length Optional maximum breach channel length (in grid cells; default is Inf).
#' @param flat_increment Optional elevation increment applied to flat areas.
#' @param fill_pits Optional flag indicating whether to fill single-cell pits.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_breach_depressions <- function(dem, output, max_depth=NULL, max_length=NULL, flat_increment=NULL, fill_pits=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(max_depth)) {
args <- paste(args, paste0("--max_depth=", max_depth))
}
if (!is.null(max_length)) {
args <- paste(args, paste0("--max_length=", max_length))
}
if (!is.null(flat_increment)) {
args <- paste(args, paste0("--flat_increment=", flat_increment))
}
if (fill_pits) {
args <- paste(args, "--fill_pits")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "breach_depressions"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Breach depressions least cost
#'
#' @description Breaches the depressions in a DEM using a least-cost pathway method.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param dist Maximum search distance for breach paths in cells.
#' @param max_cost Optional maximum breach cost (default is Inf).
#' @param min_dist Optional flag indicating whether to minimize breach distances.
#' @param flat_increment Optional elevation increment applied to flat areas.
#' @param fill Optional flag indicating whether to fill any remaining unbreached depressions.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_breach_depressions_least_cost <- function(dem, output, dist, max_cost=NULL, min_dist=TRUE, flat_increment=NULL, fill=TRUE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--dist=", wbt_file_path(dist)))
if (!is.null(max_cost)) {
args <- paste(args, paste0("--max_cost=", max_cost))
}
if (min_dist) {
args <- paste(args, "--min_dist")
}
if (!is.null(flat_increment)) {
args <- paste(args, paste0("--flat_increment=", flat_increment))
}
if (fill) {
args <- paste(args, "--fill")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "breach_depressions_least_cost"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Breach single cell pits
#'
#' @description Removes single-cell pits from an input DEM by breaching.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_breach_single_cell_pits <- function(dem, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "breach_single_cell_pits"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Burn streams at roads
#'
#' @description Burns-in streams at the sites of road embankments.
#'
#' @param dem Input raster digital elevation model (DEM) file.
#' @param streams Input vector streams file.
#' @param roads Input vector roads file.
#' @param output Output raster file.
#' @param width Maximum road embankment width, in map units.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_burn_streams_at_roads <- function(dem, streams, roads, output, width=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--roads=", wbt_file_path(roads)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(width)) {
args <- paste(args, paste0("--width=", width))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "burn_streams_at_roads"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title D8 flow accumulation
#'
#' @description Calculates a D8 flow accumulation raster from an input DEM or flow pointer.
#'
#' @param input Input raster DEM or D8 pointer file.
#' @param output Output raster file.
#' @param out_type Output type; one of 'cells' (default), 'catchment area', and 'specific contributing area'.
#' @param log Optional flag to request the output be log-transformed.
#' @param clip Optional flag to request clipping the display max by 1 percent.
#' @param pntr Is the input raster a D8 flow pointer rather than a DEM?.
#' @param esri_pntr Input D8 pointer uses the ESRI style scheme.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_d8_flow_accumulation <- function(input, output, out_type="cells", log=FALSE, clip=FALSE, pntr=FALSE, esri_pntr=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(out_type)) {
args <- paste(args, paste0("--out_type=", out_type))
}
if (log) {
args <- paste(args, "--log")
}
if (clip) {
args <- paste(args, "--clip")
}
if (pntr) {
args <- paste(args, "--pntr")
}
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "d8_flow_accumulation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title D8 mass flux
#'
#' @description Performs a D8 mass flux calculation.
#'
#' @param dem Input raster DEM file.
#' @param loading Input loading raster file.
#' @param efficiency Input efficiency raster file.
#' @param absorption Input absorption raster file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_d8_mass_flux <- function(dem, loading, efficiency, absorption, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--loading=", wbt_file_path(loading)))
args <- paste(args, paste0("--efficiency=", wbt_file_path(efficiency)))
args <- paste(args, paste0("--absorption=", wbt_file_path(absorption)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "d8_mass_flux"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title D8 pointer
#'
#' @description Calculates a D8 flow pointer raster from an input DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_d8_pointer <- function(dem, output, esri_pntr=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "d8_pointer"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title D inf flow accumulation
#'
#' @description Calculates a D-infinity flow accumulation raster from an input DEM.
#'
#' @param input Input raster DEM or D-infinity pointer file.
#' @param output Output raster file.
#' @param out_type Output type; one of 'cells', 'sca' (default), and 'ca'.
#' @param threshold Optional convergence threshold parameter, in grid cells; default is infinity.
#' @param log Optional flag to request the output be log-transformed.
#' @param clip Optional flag to request clipping the display max by 1 percent.
#' @param pntr Is the input raster a D-infinity flow pointer rather than a DEM?.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_d_inf_flow_accumulation <- function(input, output, out_type="Specific Contributing Area", threshold=NULL, log=FALSE, clip=FALSE, pntr=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(out_type)) {
args <- paste(args, paste0("--out_type=", out_type))
}
if (!is.null(threshold)) {
args <- paste(args, paste0("--threshold=", threshold))
}
if (log) {
args <- paste(args, "--log")
}
if (clip) {
args <- paste(args, "--clip")
}
if (pntr) {
args <- paste(args, "--pntr")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "d_inf_flow_accumulation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title D inf mass flux
#'
#' @description Performs a D-infinity mass flux calculation.
#'
#' @param dem Input raster DEM file.
#' @param loading Input loading raster file.
#' @param efficiency Input efficiency raster file.
#' @param absorption Input absorption raster file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_d_inf_mass_flux <- function(dem, loading, efficiency, absorption, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--loading=", wbt_file_path(loading)))
args <- paste(args, paste0("--efficiency=", wbt_file_path(efficiency)))
args <- paste(args, paste0("--absorption=", wbt_file_path(absorption)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "d_inf_mass_flux"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title D inf pointer
#'
#' @description Calculates a D-infinity flow pointer (flow direction) raster from an input DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_d_inf_pointer <- function(dem, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "d_inf_pointer"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Depth in sink
#'
#' @description Measures the depth of sinks (depressions) in a DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param zero_background Flag indicating whether the background value of zero should be used.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_depth_in_sink <- function(dem, output, zero_background=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (zero_background) {
args <- paste(args, "--zero_background")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "depth_in_sink"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Depth to water
#'
#' @description This tool calculates cartographic depth-to-water (DTW) index.
#'
#' @param dem Name of the input raster DEM file.
#' @param streams Name of the input streams vector (optional).
#' @param lakes Name of the input lakes vector (optional).
#' @param output Name of the output raster image file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_depth_to_water <- function(dem, output, streams=NULL, lakes=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(streams)) {
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
}
if (!is.null(lakes)) {
args <- paste(args, paste0("--lakes=", wbt_file_path(lakes)))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "depth_to_water"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Downslope distance to stream
#'
#' @description Measures distance to the nearest downslope stream cell.
#'
#' @param dem Input raster DEM file.
#' @param streams Input raster streams file.
#' @param output Output raster file.
#' @param dinf Use the D-infinity flow algorithm instead of D8?.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_downslope_distance_to_stream <- function(dem, streams, output, dinf=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (dinf) {
args <- paste(args, "--dinf")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "downslope_distance_to_stream"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Downslope flowpath length
#'
#' @description Calculates the downslope flowpath length from each cell to basin outlet.
#'
#' @param d8_pntr Input D8 pointer raster file.
#' @param watersheds Optional input watershed raster file.
#' @param weights Optional input weights raster file.
#' @param output Output raster file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_downslope_flowpath_length <- function(d8_pntr, output, watersheds=NULL, weights=NULL, esri_pntr=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(watersheds)) {
args <- paste(args, paste0("--watersheds=", watersheds))
}
if (!is.null(weights)) {
args <- paste(args, paste0("--weights=", weights))
}
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "downslope_flowpath_length"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Edge contamination
#'
#' @description Identifies grid cells within an input DEM that may be impacted by edge contamination for hydrological applications.
#'
#' @param dem Name of the input DEM raster file; must be depressionless.
#' @param output Name of the output raster file.
#' @param flow_type Flow algorithm type, one of 'd8', 'mfd', or 'dinf'.
#' @param zfactor Optional multiplier for when the vertical and horizontal units are not the same.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_edge_contamination <- function(dem, output, flow_type="mfd", zfactor="", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(flow_type)) {
args <- paste(args, paste0("--flow_type=", flow_type))
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "edge_contamination"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Elevation above stream
#'
#' @description Calculates the elevation of cells above the nearest downslope stream cell.
#'
#' @param dem Input raster DEM file.
#' @param streams Input raster streams file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_elevation_above_stream <- function(dem, streams, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "elevation_above_stream"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Elevation above stream euclidean
#'
#' @description Calculates the elevation of cells above the nearest (Euclidean distance) stream cell.
#'
#' @param dem Input raster DEM file.
#' @param streams Input raster streams file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_elevation_above_stream_euclidean <- function(dem, streams, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "elevation_above_stream_euclidean"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Fd8 flow accumulation
#'
#' @description Calculates an FD8 flow accumulation raster from an input DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param out_type Output type; one of 'cells', 'specific contributing area' (default), and 'catchment area'.
#' @param exponent Optional exponent parameter; default is 1.1.
#' @param threshold Optional convergence threshold parameter, in grid cells; default is infinity.
#' @param log Optional flag to request the output be log-transformed.
#' @param clip Optional flag to request clipping the display max by 1 percent.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_fd8_flow_accumulation <- function(dem, output, out_type="specific contributing area", exponent=1.1, threshold=NULL, log=FALSE, clip=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(out_type)) {
args <- paste(args, paste0("--out_type=", out_type))
}
if (!is.null(exponent)) {
args <- paste(args, paste0("--exponent=", exponent))
}
if (!is.null(threshold)) {
args <- paste(args, paste0("--threshold=", threshold))
}
if (log) {
args <- paste(args, "--log")
}
if (clip) {
args <- paste(args, "--clip")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "fd8_flow_accumulation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Fd8 pointer
#'
#' @description Calculates an FD8 flow pointer raster from an input DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_fd8_pointer <- function(dem, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "fd8_pointer"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Fill burn
#'
#' @description Burns streams into a DEM using the FillBurn (Saunders, 1999) method.
#'
#' @param dem Input raster DEM file.
#' @param streams Input vector streams file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_fill_burn <- function(dem, streams, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "fill_burn"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Fill depressions
#'
#' @description Fills all of the depressions in a DEM. Depression breaching should be preferred in most cases.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param fix_flats Optional flag indicating whether flat areas should have a small gradient applied.
#' @param flat_increment Optional elevation increment applied to flat areas.
#' @param max_depth Optional maximum depression depth to fill.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_fill_depressions <- function(dem, output, fix_flats=TRUE, flat_increment=NULL, max_depth=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (fix_flats) {
args <- paste(args, "--fix_flats")
}
if (!is.null(flat_increment)) {
args <- paste(args, paste0("--flat_increment=", flat_increment))
}
if (!is.null(max_depth)) {
args <- paste(args, paste0("--max_depth=", max_depth))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "fill_depressions"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Fill depressions planchon and darboux
#'
#' @description Fills all of the depressions in a DEM using the Planchon and Darboux (2002) method.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param fix_flats Optional flag indicating whether flat areas should have a small gradient applied.
#' @param flat_increment Optional elevation increment applied to flat areas.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_fill_depressions_planchon_and_darboux <- function(dem, output, fix_flats=TRUE, flat_increment=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (fix_flats) {
args <- paste(args, "--fix_flats")
}
if (!is.null(flat_increment)) {
args <- paste(args, paste0("--flat_increment=", flat_increment))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "fill_depressions_planchon_and_darboux"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Fill depressions wang and liu
#'
#' @description Fills all of the depressions in a DEM using the Wang and Liu (2006) method. Depression breaching should be preferred in most cases.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param fix_flats Optional flag indicating whether flat areas should have a small gradient applied.
#' @param flat_increment Optional elevation increment applied to flat areas.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_fill_depressions_wang_and_liu <- function(dem, output, fix_flats=TRUE, flat_increment=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (fix_flats) {
args <- paste(args, "--fix_flats")
}
if (!is.null(flat_increment)) {
args <- paste(args, paste0("--flat_increment=", flat_increment))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "fill_depressions_wang_and_liu"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Fill single cell pits
#'
#' @description Raises pit cells to the elevation of their lowest neighbour.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_fill_single_cell_pits <- function(dem, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "fill_single_cell_pits"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Find no flow cells
#'
#' @description Finds grid cells with no downslope neighbours.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_find_no_flow_cells <- function(dem, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "find_no_flow_cells"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Find parallel flow
#'
#' @description Finds areas of parallel flow in D8 flow direction rasters.
#'
#' @param d8_pntr Input D8 pointer raster file.
#' @param streams Input raster streams file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_find_parallel_flow <- function(d8_pntr, streams, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "find_parallel_flow"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Flatten lakes
#'
#' @description Flattens lake polygons in a raster DEM.
#'
#' @param dem Input raster DEM file.
#' @param lakes Input lakes vector polygons file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_flatten_lakes <- function(dem, lakes, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--lakes=", wbt_file_path(lakes)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "flatten_lakes"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Flood order
#'
#' @description Assigns each DEM grid cell its order in the sequence of inundations that are encountered during a search starting from the edges, moving inward at increasing elevations.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_flood_order <- function(dem, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "flood_order"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Flow accumulation full workflow
#'
#' @description Resolves all of the depressions in a DEM, outputting a breached DEM, an aspect-aligned non-divergent flow pointer, and a flow accumulation raster.
#'
#' @param dem Input raster DEM file.
#' @param out_dem Output raster DEM file.
#' @param out_pntr Output raster flow pointer file.
#' @param out_accum Output raster flow accumulation file.
#' @param out_type Output type; one of 'cells', 'sca' (default), and 'ca'.
#' @param log Optional flag to request the output be log-transformed.
#' @param clip Optional flag to request clipping the display max by 1 percent.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_flow_accumulation_full_workflow <- function(dem, out_dem, out_pntr, out_accum, out_type="Specific Contributing Area", log=FALSE, clip=FALSE, esri_pntr=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--out_dem=", wbt_file_path(out_dem)))
args <- paste(args, paste0("--out_pntr=", wbt_file_path(out_pntr)))
args <- paste(args, paste0("--out_accum=", wbt_file_path(out_accum)))
if (!is.null(out_type)) {
args <- paste(args, paste0("--out_type=", out_type))
}
if (log) {
args <- paste(args, "--log")
}
if (clip) {
args <- paste(args, "--clip")
}
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "flow_accumulation_full_workflow"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Flow length diff
#'
#' @description Calculates the local maximum absolute difference in downslope flowpath length, useful in mapping drainage divides and ridges.
#'
#' @param d8_pntr Input D8 pointer raster file.
#' @param output Output raster file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_flow_length_diff <- function(d8_pntr, output, esri_pntr=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "flow_length_diff"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Hillslopes
#'
#' @description Identifies the individual hillslopes draining to each link in a stream network.
#'
#' @param d8_pntr Input raster D8 pointer file.
#' @param streams Input raster streams file.
#' @param output Output raster file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_hillslopes <- function(d8_pntr, streams, output, esri_pntr=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "hillslopes"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Hydrologic connectivity
#'
#' @description This tool evaluates hydrologic connectivity within a DEM.
#'
#' @param dem Name of the input DEM raster file; must be depressionless.
#' @param output1 Name of the output downslope unsaturated length (DUL) file.
#' @param output2 Name of the output upslope disconnected saturated area (UDSA) file.
#' @param exponent Optional exponent parameter; default is 1.0.
#' @param threshold Optional convergence threshold parameter, in grid cells; default is infinity.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_hydrologic_connectivity <- function(dem, output1, output2, exponent=1.0, threshold=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output1=", wbt_file_path(output1)))
args <- paste(args, paste0("--output2=", wbt_file_path(output2)))
if (!is.null(exponent)) {
args <- paste(args, paste0("--exponent=", exponent))
}
if (!is.null(threshold)) {
args <- paste(args, paste0("--threshold=", threshold))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "hydrologic_connectivity"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Impoundment size index
#'
#' @description Calculates the impoundment size resulting from damming a DEM.
#'
#' @param dem Input raster DEM file.
#' @param out_mean Output mean flooded depth file.
#' @param out_max Output maximum flooded depth file.
#' @param out_volume Output flooded volume file.
#' @param out_area Output flooded area file.
#' @param out_dam_height Output dam height file.
#' @param damlength Maximum length of the dam.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_impoundment_size_index <- function(dem, damlength, out_mean=NULL, out_max=NULL, out_volume=NULL, out_area=NULL, out_dam_height=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--damlength=", wbt_file_path(damlength)))
if (!is.null(out_mean)) {
args <- paste(args, paste0("--out_mean=", out_mean))
}
if (!is.null(out_max)) {
args <- paste(args, paste0("--out_max=", out_max))
}
if (!is.null(out_volume)) {
args <- paste(args, paste0("--out_volume=", out_volume))
}
if (!is.null(out_area)) {
args <- paste(args, paste0("--out_area=", out_area))
}
if (!is.null(out_dam_height)) {
args <- paste(args, paste0("--out_dam_height=", out_dam_height))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "impoundment_size_index"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Insert dams
#'
#' @description Calculates the impoundment size resulting from damming a DEM.
#'
#' @param dem Input raster DEM file.
#' @param dam_pts Input vector dam points file.
#' @param output Output file.
#' @param damlength Maximum length of the dam.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_insert_dams <- function(dem, dam_pts, output, damlength, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--dam_pts=", wbt_file_path(dam_pts)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--damlength=", wbt_file_path(damlength)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "insert_dams"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Isobasins
#'
#' @description Divides a landscape into nearly equal sized drainage basins (i.e. watersheds).
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param size Target basin size, in grid cells.
#' @param connections Output upstream-downstream flow connections among basins?.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_isobasins <- function(dem, output, size, connections=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--size=", wbt_file_path(size)))
if (connections) {
args <- paste(args, "--connections")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "isobasins"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Jenson snap pour points
#'
#' @description Moves outlet points used to specify points of interest in a watershedding operation to the nearest stream cell.
#'
#' @param pour_pts Input vector pour points (outlet) file.
#' @param streams Input raster streams file.
#' @param output Output vector file.
#' @param snap_dist Maximum snap distance in map units.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_jenson_snap_pour_points <- function(pour_pts, streams, output, snap_dist, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--pour_pts=", wbt_file_path(pour_pts)))
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--snap_dist=", wbt_file_path(snap_dist)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "jenson_snap_pour_points"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Longest flowpath
#'
#' @description Delineates the longest flowpaths for a group of subbasins or watersheds.
#'
#' @param dem Input raster DEM file.
#' @param basins Input raster basins file.
#' @param output Output vector file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_longest_flowpath <- function(dem, basins, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--basins=", wbt_file_path(basins)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "longest_flowpath"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Low points on headwater divides
#'
#' @description This tool locates saddle points along ridges within a digital elevation model (DEM).
#'
#' @param dem Name of the input DEM raster file.
#' @param streams Name of the input stream channel raster file.
#' @param output Name of the output vector file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_low_points_on_headwater_divides <- function(dem, streams, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "low_points_on_headwater_divides"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Max upslope flowpath length
#'
#' @description Measures the maximum length of all upslope flowpaths draining each grid cell.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_max_upslope_flowpath_length <- function(dem, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "max_upslope_flowpath_length"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Max upslope value
#'
#' @description Calculates the maximum upslope value from an input values raster along flowpaths.
#'
#' @param dem Input DEM; it must be depressionless.
#' @param values Name of the input values raster file.
#' @param output Name of the output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_max_upslope_value <- function(dem, values, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--values=", wbt_file_path(values)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "max_upslope_value"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Md inf flow accumulation
#'
#' @description Calculates an FD8 flow accumulation raster from an input DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param out_type Output type; one of 'cells', 'specific contributing area' (default), and 'catchment area'.
#' @param exponent Optional exponent parameter; default is 1.1.
#' @param threshold Optional convergence threshold parameter, in grid cells; default is infinity.
#' @param log Optional flag to request the output be log-transformed.
#' @param clip Optional flag to request clipping the display max by 1 percent.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_md_inf_flow_accumulation <- function(dem, output, out_type="specific contributing area", exponent=1.1, threshold=NULL, log=FALSE, clip=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(out_type)) {
args <- paste(args, paste0("--out_type=", out_type))
}
if (!is.null(exponent)) {
args <- paste(args, paste0("--exponent=", exponent))
}
if (!is.null(threshold)) {
args <- paste(args, paste0("--threshold=", threshold))
}
if (log) {
args <- paste(args, "--log")
}
if (clip) {
args <- paste(args, "--clip")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "md_inf_flow_accumulation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Num inflowing neighbours
#'
#' @description Computes the number of inflowing neighbours to each cell in an input DEM based on the D8 algorithm.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_num_inflowing_neighbours <- function(dem, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "num_inflowing_neighbours"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Qin flow accumulation
#'
#' @description Calculates Qin et al. (2007) flow accumulation.
#'
#' @param dem Name of the input DEM raster file; must be depressionless.
#' @param output Name of the output raster file.
#' @param out_type Output type; one of 'cells', 'specific contributing area' (default), and 'catchment area'.
#' @param exponent Optional upper-bound exponent parameter; default is 10.0.
#' @param max_slope Optional upper-bound slope parameter, in degrees (0-90); default is 45.0.
#' @param threshold Optional convergence threshold parameter, in grid cells; default is infinity.
#' @param log Log-transform the output values?.
#' @param clip Optional flag to request clipping the display max by 1 percent.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_qin_flow_accumulation <- function(dem, output, out_type="specific contributing area", exponent=10.0, max_slope=45.0, threshold=NULL, log=FALSE, clip=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(out_type)) {
args <- paste(args, paste0("--out_type=", out_type))
}
if (!is.null(exponent)) {
args <- paste(args, paste0("--exponent=", exponent))
}
if (!is.null(max_slope)) {
args <- paste(args, paste0("--max_slope=", max_slope))
}
if (!is.null(threshold)) {
args <- paste(args, paste0("--threshold=", threshold))
}
if (log) {
args <- paste(args, "--log")
}
if (clip) {
args <- paste(args, "--clip")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "qin_flow_accumulation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Quinn flow accumulation
#'
#' @description Calculates Quinn et al. (1995) flow accumulation.
#'
#' @param dem Name of the input DEM raster file; must be depressionless.
#' @param output Name of the output raster file.
#' @param out_type Output type; one of 'cells', 'specific contributing area' (default), and 'catchment area'.
#' @param exponent Optional exponent parameter; default is 1.0.
#' @param threshold Optional convergence threshold parameter, in grid cells; default is infinity.
#' @param log Log-transform the output values?.
#' @param clip Optional flag to request clipping the display max by 1 percent.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_quinn_flow_accumulation <- function(dem, output, out_type="specific contributing area", exponent=1.0, threshold=NULL, log=FALSE, clip=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(out_type)) {
args <- paste(args, paste0("--out_type=", out_type))
}
if (!is.null(exponent)) {
args <- paste(args, paste0("--exponent=", exponent))
}
if (!is.null(threshold)) {
args <- paste(args, paste0("--threshold=", threshold))
}
if (log) {
args <- paste(args, "--log")
}
if (clip) {
args <- paste(args, "--clip")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "quinn_flow_accumulation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Raise walls
#'
#' @description Raises walls in a DEM along a line or around a polygon, e.g. a watershed.
#'
#' @param input Input vector lines or polygons file.
#' @param breach Optional input vector breach lines.
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param height Wall height.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_raise_walls <- function(input, dem, output, breach=NULL, height=100.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(breach)) {
args <- paste(args, paste0("--breach=", breach))
}
if (!is.null(height)) {
args <- paste(args, paste0("--height=", height))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "raise_walls"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Rho8 flow accumulation
#'
#' @description Calculates Fairfield and Leymarie (1991) flow accumulation.
#'
#' @param input Input DEM or Rho8 pointer file; if a DEM is used, it must be depressionless.
#' @param output Name of the output raster file.
#' @param out_type Output type; one of 'cells', 'specific contributing area' (default), and 'catchment area'.
#' @param log Log-transform the output values?.
#' @param clip Optional flag to request clipping the display max by 1 percent.
#' @param pntr Is the input raster a Rho8 flow pointer rather than a DEM?.
#' @param esri_pntr Does the input Rho8 pointer use the ESRI style scheme?.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_rho8_flow_accumulation <- function(input, output, out_type="specific contributing area", log=FALSE, clip=FALSE, pntr=FALSE, esri_pntr=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(out_type)) {
args <- paste(args, paste0("--out_type=", out_type))
}
if (log) {
args <- paste(args, "--log")
}
if (clip) {
args <- paste(args, "--clip")
}
if (pntr) {
args <- paste(args, "--pntr")
}
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "rho8_flow_accumulation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Rho8 pointer
#'
#' @description Calculates a stochastic Rho8 flow pointer raster from an input DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_rho8_pointer <- function(dem, output, esri_pntr=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "rho8_pointer"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title River centerlines
#'
#' @description Maps river centerlines from an input water raster.
#'
#' @param input Name of the input raster image file.
#' @param output Name of the output vector lines file.
#' @param min_length Minimum line length, in grid cells.
#' @param radius Search radius for joining distant endnodes, in grid cells.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_river_centerlines <- function(input, output, min_length=3, radius=4, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(min_length)) {
args <- paste(args, paste0("--min_length=", min_length))
}
if (!is.null(radius)) {
args <- paste(args, paste0("--radius=", radius))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "river_centerlines"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Sink
#'
#' @description Identifies the depressions in a DEM, giving each feature a unique identifier.
#'
#' @param input Input raster DEM file.
#' @param output Output raster file.
#' @param zero_background Flag indicating whether a background value of zero should be used.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_sink <- function(input, output, zero_background=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (zero_background) {
args <- paste(args, "--zero_background")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "sink"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Snap pour points
#'
#' @description Moves outlet points used to specify points of interest in a watershedding operation to the cell with the highest flow accumulation in its neighbourhood.
#'
#' @param pour_pts Input vector pour points (outlet) file.
#' @param flow_accum Input raster D8 flow accumulation file.
#' @param output Output vector file.
#' @param snap_dist Maximum snap distance in map units.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_snap_pour_points <- function(pour_pts, flow_accum, output, snap_dist, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--pour_pts=", wbt_file_path(pour_pts)))
args <- paste(args, paste0("--flow_accum=", wbt_file_path(flow_accum)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--snap_dist=", wbt_file_path(snap_dist)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "snap_pour_points"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Stochastic depression analysis
#'
#' @description Performs a stochastic analysis of depressions within a DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output file.
#' @param rmse The DEM's root-mean-square-error (RMSE), in z units. This determines error magnitude.
#' @param range The error field's correlation length, in xy-units.
#' @param iterations The number of iterations.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_stochastic_depression_analysis <- function(dem, output, rmse, range, iterations=100, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--rmse=", wbt_file_path(rmse)))
args <- paste(args, paste0("--range=", wbt_file_path(range)))
if (!is.null(iterations)) {
args <- paste(args, paste0("--iterations=", iterations))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "stochastic_depression_analysis"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Strahler order basins
#'
#' @description Identifies Strahler-order basins from an input stream network.
#'
#' @param d8_pntr Input raster D8 pointer file.
#' @param streams Input raster streams file.
#' @param output Output raster file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_strahler_order_basins <- function(d8_pntr, streams, output, esri_pntr=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "strahler_order_basins"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Subbasins
#'
#' @description Identifies the catchments, or sub-basin, draining to each link in a stream network.
#'
#' @param d8_pntr Input D8 pointer raster file.
#' @param streams Input raster streams file.
#' @param output Output raster file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_subbasins <- function(d8_pntr, streams, output, esri_pntr=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "subbasins"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Trace downslope flowpaths
#'
#' @description Traces downslope flowpaths from one or more target sites (i.e. seed points).
#'
#' @param seed_pts Input vector seed points file.
#' @param d8_pntr Input D8 pointer raster file.
#' @param output Output raster file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param zero_background Flag indicating whether a background value of zero should be used.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_trace_downslope_flowpaths <- function(seed_pts, d8_pntr, output, esri_pntr=FALSE, zero_background=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--seed_pts=", wbt_file_path(seed_pts)))
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (zero_background) {
args <- paste(args, "--zero_background")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "trace_downslope_flowpaths"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Unnest basins
#'
#' @description Extract whole watersheds for a set of outlet points.
#'
#' @param d8_pntr Input D8 pointer raster file.
#' @param pour_pts Input vector pour points (outlet) file.
#' @param output Output raster file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_unnest_basins <- function(d8_pntr, pour_pts, output, esri_pntr=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--pour_pts=", wbt_file_path(pour_pts)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "unnest_basins"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Upslope depression storage
#'
#' @description Estimates the average upslope depression storage depth.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_upslope_depression_storage <- function(dem, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "upslope_depression_storage"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Watershed
#'
#' @description Identifies the watershed, or drainage basin, draining to a set of target cells.
#'
#' @param d8_pntr Input D8 pointer raster file.
#' @param pour_pts Input pour points (outlet) file.
#' @param output Output raster file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords HydrologicalAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_watershed <- function(d8_pntr, pour_pts, output, esri_pntr=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--pour_pts=", wbt_file_path(pour_pts)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "watershed"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
|
/scratch/gouwar.j/cran-all/cranData/whitebox/R/hydro_analysis.R
|
#' @title Change vector analysis
#'
#' @description Performs a change vector analysis on a two-date multi-spectral dataset.
#'
#' @param date1 Input raster files for the earlier date.
#' @param date2 Input raster files for the later date.
#' @param magnitude Output vector magnitude raster file.
#' @param direction Output vector Direction raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_change_vector_analysis <- function(date1, date2, magnitude, direction, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--date1=", wbt_file_path(date1)))
args <- paste(args, paste0("--date2=", wbt_file_path(date2)))
args <- paste(args, paste0("--magnitude=", wbt_file_path(magnitude)))
args <- paste(args, paste0("--direction=", wbt_file_path(direction)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "change_vector_analysis"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Closing
#'
#' @description A closing is a mathematical morphology operation involving an erosion (min filter) of a dilation (max filter) set.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param filterx Size of the filter kernel in the x-direction.
#' @param filtery Size of the filter kernel in the y-direction.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_closing <- function(input, output, filterx=11, filtery=11, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filterx)) {
args <- paste(args, paste0("--filterx=", filterx))
}
if (!is.null(filtery)) {
args <- paste(args, paste0("--filtery=", filtery))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "closing"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Create colour composite
#'
#' @description Creates a colour-composite image from three bands of multispectral imagery.
#'
#' @param red Input red band image file.
#' @param green Input green band image file.
#' @param blue Input blue band image file.
#' @param opacity Input opacity band image file (optional).
#' @param output Output colour composite file.
#' @param enhance Optional flag indicating whether a balance contrast enhancement is performed.
#' @param zeros Optional flag to indicate if zeros are nodata values.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_create_colour_composite <- function(red, green, blue, output, opacity=NULL, enhance=TRUE, zeros=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--red=", wbt_file_path(red)))
args <- paste(args, paste0("--green=", wbt_file_path(green)))
args <- paste(args, paste0("--blue=", wbt_file_path(blue)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(opacity)) {
args <- paste(args, paste0("--opacity=", opacity))
}
if (enhance) {
args <- paste(args, "--enhance")
}
if (zeros) {
args <- paste(args, "--zeros")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "create_colour_composite"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Flip image
#'
#' @description Reflects an image in the vertical or horizontal axis.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param direction Direction of reflection; options include 'v' (vertical), 'h' (horizontal), and 'b' (both).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_flip_image <- function(input, output, direction="vertical", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(direction)) {
args <- paste(args, paste0("--direction=", direction))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "flip_image"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Ihs to rgb
#'
#' @description Converts intensity, hue, and saturation (IHS) images into red, green, and blue (RGB) images.
#'
#' @param intensity Input intensity file.
#' @param hue Input hue file.
#' @param saturation Input saturation file.
#' @param red Output red band file. Optionally specified if colour-composite not specified.
#' @param green Output green band file. Optionally specified if colour-composite not specified.
#' @param blue Output blue band file. Optionally specified if colour-composite not specified.
#' @param output Output colour-composite file. Only used if individual bands are not specified.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_ihs_to_rgb <- function(intensity, hue, saturation, red=NULL, green=NULL, blue=NULL, output=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--intensity=", wbt_file_path(intensity)))
args <- paste(args, paste0("--hue=", wbt_file_path(hue)))
args <- paste(args, paste0("--saturation=", wbt_file_path(saturation)))
if (!is.null(red)) {
args <- paste(args, paste0("--red=", red))
}
if (!is.null(green)) {
args <- paste(args, paste0("--green=", green))
}
if (!is.null(blue)) {
args <- paste(args, paste0("--blue=", blue))
}
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "ihs_to_rgb"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Image slider
#'
#' @description This tool creates an image slider from two input images.
#'
#' @param input1 Name of the left input image file.
#' @param palette1 Left image palette; options are 'grey', 'atlas', 'high_relief', 'arid', 'soft', 'muted', 'purple', 'viridi', 'gn_yl', 'pi_y_g', 'bl_yl_rd', 'deep', and 'rgb'.
#' @param reverse1 Reverse left image palette?.
#' @param label1 Left image label (leave blank for none).
#' @param input2 Name of the right input image file.
#' @param palette2 Right image palette; options are 'grey', 'atlas', 'high_relief', 'arid', 'soft', 'muted', 'purple', 'viridi', 'gn_yl', 'pi_y_g', 'bl_yl_rd', 'deep', and 'rgb'.
#' @param reverse2 Reverse right image palette?.
#' @param label2 Right image label (leave blank for none).
#' @param output Name of the output HTML file (*.html).
#' @param height Image height, in pixels.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_image_slider <- function(input1, input2, output, palette1="grey", reverse1=FALSE, label1="", palette2="grey", reverse2=FALSE, label2="", height=600, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(palette1)) {
args <- paste(args, paste0("--palette1=", palette1))
}
if (reverse1) {
args <- paste(args, "--reverse1")
}
if (!is.null(label1)) {
args <- paste(args, paste0("--label1=", label1))
}
if (!is.null(palette2)) {
args <- paste(args, paste0("--palette2=", palette2))
}
if (reverse2) {
args <- paste(args, "--reverse2")
}
if (!is.null(label2)) {
args <- paste(args, paste0("--label2=", label2))
}
if (!is.null(height)) {
args <- paste(args, paste0("--height=", height))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "image_slider"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Image stack profile
#'
#' @description Plots an image stack profile (i.e. signature) for a set of points and multispectral images.
#'
#' @param inputs Input multispectral image files.
#' @param points Input vector points file.
#' @param output Output HTML file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_image_stack_profile <- function(inputs, points, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--points=", wbt_file_path(points)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "image_stack_profile"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Integral image
#'
#' @description Transforms an input image (summed area table) into its integral image equivalent.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_integral_image <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "integral_image"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Line thinning
#'
#' @description Performs line thinning a on Boolean raster image; intended to be used with the RemoveSpurs tool.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_line_thinning <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "line_thinning"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Mosaic
#'
#' @description Mosaics two or more images together.
#'
#' @param inputs Input raster file paths, concatenated with `","` or `";"`. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param method Resampling method; options include 'nn' (nearest neighbour), 'bilinear', and 'cc' (cubic convolution).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_mosaic <- function(output, inputs=NULL, method="nn", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(inputs)) {
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
}
if (!is.null(method)) {
args <- paste(args, paste0("--method=", method))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "mosaic"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Mosaic with feathering
#'
#' @description Mosaics two images together using a feathering technique in overlapping areas to reduce edge-effects.
#'
#' @param input1 Input raster file to modify.
#' @param input2 Input reference raster file.
#' @param output Output raster file.
#' @param method Resampling method; options include 'nn' (nearest neighbour), 'bilinear', and 'cc' (cubic convolution).
#' @param weight .
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_mosaic_with_feathering <- function(input1, input2, output, method="cc", weight=4.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(method)) {
args <- paste(args, paste0("--method=", method))
}
if (!is.null(weight)) {
args <- paste(args, paste0("--weight=", weight))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "mosaic_with_feathering"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Normalized difference index
#'
#' @description Calculate a normalized-difference index (NDI) from two bands of multispectral image data.
#'
#' @param input1 Input image 1 (e.g. near-infrared band).
#' @param input2 Input image 2 (e.g. red band).
#' @param output Output raster file.
#' @param clip Optional amount to clip the distribution tails by, in percent.
#' @param correction Optional adjustment value (e.g. 1, or 0.16 for the optimal soil adjusted vegetation index, OSAVI).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_normalized_difference_index <- function(input1, input2, output, clip=0.0, correction=0.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(clip)) {
args <- paste(args, paste0("--clip=", clip))
}
if (!is.null(correction)) {
args <- paste(args, paste0("--correction=", correction))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "normalized_difference_index"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Opening
#'
#' @description An opening is a mathematical morphology operation involving a dilation (max filter) of an erosion (min filter) set.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param filterx Size of the filter kernel in the x-direction.
#' @param filtery Size of the filter kernel in the y-direction.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_opening <- function(input, output, filterx=11, filtery=11, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filterx)) {
args <- paste(args, paste0("--filterx=", filterx))
}
if (!is.null(filtery)) {
args <- paste(args, paste0("--filtery=", filtery))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "opening"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Remove spurs
#'
#' @description Removes the spurs (pruning operation) from a Boolean line image; intended to be used on the output of the LineThinning tool.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param iterations Maximum number of iterations.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_remove_spurs <- function(input, output, iterations=10, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(iterations)) {
args <- paste(args, paste0("--iterations=", iterations))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "remove_spurs"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Resample
#'
#' @description Resamples one or more input images into a destination image.
#'
#' @param inputs Input raster file paths, concatenated with `","` or `";"`. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param cell_size Optionally specified cell size of output raster. Not used when base raster is specified.
#' @param base Optionally specified input base raster file. Not used when a cell size is specified.
#' @param method Resampling method; options include 'nn' (nearest neighbour), 'bilinear', and 'cc' (cubic convolution).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_resample <- function(inputs, output, cell_size=NULL, base=NULL, method="cc", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(cell_size)) {
args <- paste(args, paste0("--cell_size=", cell_size))
}
if (!missing(base)) {
args <- paste(args, paste0("--base=", wbt_file_path(base)))
}
if (!is.null(method)) {
args <- paste(args, paste0("--method=", method))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "resample"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Rgb to ihs
#'
#' @description Converts red, green, and blue (RGB) images into intensity, hue, and saturation (IHS) images.
#'
#' @param red Input red band image file. Optionally specified if colour-composite not specified.
#' @param green Input green band image file. Optionally specified if colour-composite not specified.
#' @param blue Input blue band image file. Optionally specified if colour-composite not specified.
#' @param composite Input colour-composite image file. Only used if individual bands are not specified.
#' @param intensity Output intensity raster file.
#' @param hue Output hue raster file.
#' @param saturation Output saturation raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_rgb_to_ihs <- function(intensity, hue, saturation, red=NULL, green=NULL, blue=NULL, composite=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--intensity=", wbt_file_path(intensity)))
args <- paste(args, paste0("--hue=", wbt_file_path(hue)))
args <- paste(args, paste0("--saturation=", wbt_file_path(saturation)))
if (!is.null(red)) {
args <- paste(args, paste0("--red=", red))
}
if (!is.null(green)) {
args <- paste(args, paste0("--green=", green))
}
if (!is.null(blue)) {
args <- paste(args, paste0("--blue=", blue))
}
if (!is.null(composite)) {
args <- paste(args, paste0("--composite=", composite))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "rgb_to_ihs"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Split colour composite
#'
#' @description Splits an RGB colour composite image into separate multispectral images.
#'
#' @param input Input colour composite image file.
#' @param red Output red band file.
#' @param green Output green band file.
#' @param blue Output blue band file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_split_colour_composite <- function(input, red=NULL, green=NULL, blue=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(red)) {
args <- paste(args, paste0("--red=", red))
}
if (!is.null(green)) {
args <- paste(args, paste0("--green=", green))
}
if (!is.null(blue)) {
args <- paste(args, paste0("--blue=", blue))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "split_colour_composite"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Thicken raster line
#'
#' @description Thickens single-cell wide lines within a raster image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_thicken_raster_line <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "thicken_raster_line"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Tophat transform
#'
#' @description Performs either a white or black top-hat transform on an input image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param filterx Size of the filter kernel in the x-direction.
#' @param filtery Size of the filter kernel in the y-direction.
#' @param variant Optional variant value. Options include 'white' and 'black'.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_tophat_transform <- function(input, output, filterx=11, filtery=11, variant="white", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filterx)) {
args <- paste(args, paste0("--filterx=", filterx))
}
if (!is.null(filtery)) {
args <- paste(args, paste0("--filtery=", filtery))
}
if (!is.null(variant)) {
args <- paste(args, paste0("--variant=", wbt_file_path(variant)))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "tophat_transform"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Write function memory insertion
#'
#' @description Performs a write function memory insertion for single-band multi-date change detection.
#'
#' @param input1 Input raster file associated with the first date.
#' @param input2 Input raster file associated with the second date.
#' @param input3 Optional input raster file associated with the third date.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_write_function_memory_insertion <- function(input1, input2, output, input3=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(input3)) {
args <- paste(args, paste0("--input3=", input3))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "write_function_memory_insertion"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
|
/scratch/gouwar.j/cran-all/cranData/whitebox/R/image_analysis.R
|
#' @title Evaluate training sites
#'
#' @description This tool can be used to inspect the overlap in spectral signatures of training sites for various classes.
#'
#' @param inputs Name of the input band images.
#' @param polys Name of the input training site polygons shapefile.
#' @param field Name of the attribute containing class name data.
#' @param output Name of the output report file (*.html).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsClassification
#'
#' @return Returns the tool text outputs.
#' @export
wbt_evaluate_training_sites <- function(inputs, polys, field, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--polys=", wbt_file_path(polys)))
args <- paste(args, paste0("--field=", wbt_file_path(field)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "evaluate_training_sites"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Generalize classified raster
#'
#' @description Generalizes a raster containing class or object features by removing small features.
#'
#' @param input Name of the input raster image file.
#' @param output Name of the output raster file.
#' @param min_size Minimum feature size, in grid cells.
#' @param method Grouping method; one of 'longest' (default), 'largest', and 'nearest'.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsClassification
#'
#' @return Returns the tool text outputs.
#' @export
wbt_generalize_classified_raster <- function(input, output, min_size=4, method="longest", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(min_size)) {
args <- paste(args, paste0("--min_size=", min_size))
}
if (!is.null(method)) {
args <- paste(args, paste0("--method=", method))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "generalize_classified_raster"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Generalize with similarity
#'
#' @description Generalizes a raster containing class or object features by removing small features using similarity criteria of neighbouring features.
#'
#' @param input Name of the input raster image file.
#' @param similarity Names of the input similarity images.
#' @param output Name of the output raster file.
#' @param min_size Minimum feature size, in grid cells.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsClassification
#'
#' @return Returns the tool text outputs.
#' @export
wbt_generalize_with_similarity <- function(input, similarity, output, min_size=4, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--similarity=", wbt_file_path(similarity)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(min_size)) {
args <- paste(args, paste0("--min_size=", min_size))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "generalize_with_similarity"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Image segmentation
#'
#' @description Performs a region-growing based segmentation on a set of multi-spectral images.
#'
#' @param inputs Names of the input band images.
#' @param output Name of the output raster file.
#' @param threshold Distance threshold, in z-scores.
#' @param steps Number of steps.
#' @param min_area Minimum object area, in grid cells (1-8).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsClassification
#'
#' @return Returns the tool text outputs.
#' @export
wbt_image_segmentation <- function(inputs, output, threshold=0.5, steps=10, min_area=4, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(threshold)) {
args <- paste(args, paste0("--threshold=", threshold))
}
if (!is.null(steps)) {
args <- paste(args, paste0("--steps=", steps))
}
if (!is.null(min_area)) {
args <- paste(args, paste0("--min_area=", min_area))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "image_segmentation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Min dist classification
#'
#' @description Performs a supervised minimum-distance classification using training site polygons and multi-spectral images.
#'
#' @param inputs Names of the input band images.
#' @param polys Name of the input training site polygons shapefile.
#' @param field Name of the attribute containing class name data.
#' @param output Name of the output raster file.
#' @param threshold Distance threshold, in z-scores; blank for none.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsClassification
#'
#' @return Returns the tool text outputs.
#' @export
wbt_min_dist_classification <- function(inputs, polys, field, output, threshold=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--polys=", wbt_file_path(polys)))
args <- paste(args, paste0("--field=", wbt_file_path(field)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(threshold)) {
args <- paste(args, paste0("--threshold=", threshold))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "min_dist_classification"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Parallelepiped classification
#'
#' @description Performs a supervised parallelepiped classification using training site polygons and multi-spectral images.
#'
#' @param inputs Name of the input band images.
#' @param polys Name of the input training site polygons shapefile.
#' @param field Name of the attribute containing class name data.
#' @param output Name of the output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsClassification
#'
#' @return Returns the tool text outputs.
#' @export
wbt_parallelepiped_classification <- function(inputs, polys, field, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--polys=", wbt_file_path(polys)))
args <- paste(args, paste0("--field=", wbt_file_path(field)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "parallelepiped_classification"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
|
/scratch/gouwar.j/cran-all/cranData/whitebox/R/image_analysis_classification.R
|
#' @title Balance contrast enhancement
#'
#' @description Performs a balance contrast enhancement on a colour-composite image of multispectral data.
#'
#' @param input Input colour composite image file.
#' @param output Output raster file.
#' @param band_mean Band mean value.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsImageEnhancement
#'
#' @return Returns the tool text outputs.
#' @export
wbt_balance_contrast_enhancement <- function(input, output, band_mean=100.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(band_mean)) {
args <- paste(args, paste0("--band_mean=", band_mean))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "balance_contrast_enhancement"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Correct vignetting
#'
#' @description Corrects the darkening of images towards corners.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param pp Input principal point file.
#' @param output Output raster file.
#' @param focal_length Camera focal length, in millimeters.
#' @param image_width Distance between photograph edges, in millimeters.
#' @param n The 'n' parameter.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsImageEnhancement
#'
#' @return Returns the tool text outputs.
#' @export
wbt_correct_vignetting <- function(input, pp, output, focal_length=304.8, image_width=228.6, n=4.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--pp=", wbt_file_path(pp)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(focal_length)) {
args <- paste(args, paste0("--focal_length=", focal_length))
}
if (!is.null(image_width)) {
args <- paste(args, paste0("--image_width=", image_width))
}
if (!is.null(n)) {
args <- paste(args, paste0("--n=", n))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "correct_vignetting"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Direct decorrelation stretch
#'
#' @description Performs a direct decorrelation stretch enhancement on a colour-composite image of multispectral data.
#'
#' @param input Input colour composite image file.
#' @param output Output raster file.
#' @param k Achromatic factor (k) ranges between 0 (no effect) and 1 (full saturation stretch), although typical values range from 0.3 to 0.7.
#' @param clip Optional percent to clip the upper tail by during the stretch.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsImageEnhancement
#'
#' @return Returns the tool text outputs.
#' @export
wbt_direct_decorrelation_stretch <- function(input, output, k=0.5, clip=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(k)) {
args <- paste(args, paste0("--k=", k))
}
if (!is.null(clip)) {
args <- paste(args, paste0("--clip=", clip))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "direct_decorrelation_stretch"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Gamma correction
#'
#' @description Performs a gamma correction on an input images.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param gamma Gamma value.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsImageEnhancement
#'
#' @return Returns the tool text outputs.
#' @export
wbt_gamma_correction <- function(input, output, gamma=0.5, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(gamma)) {
args <- paste(args, paste0("--gamma=", gamma))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "gamma_correction"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Gaussian contrast stretch
#'
#' @description Performs a Gaussian contrast stretch on input images.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param num_tones Number of tones in the output image.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsImageEnhancement
#'
#' @return Returns the tool text outputs.
#' @export
wbt_gaussian_contrast_stretch <- function(input, output, num_tones=256, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(num_tones)) {
args <- paste(args, paste0("--num_tones=", num_tones))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "gaussian_contrast_stretch"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Histogram equalization
#'
#' @description Performs a histogram equalization contrast enhancement on an image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param num_tones Number of tones in the output image.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsImageEnhancement
#'
#' @return Returns the tool text outputs.
#' @export
wbt_histogram_equalization <- function(input, output, num_tones=256, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(num_tones)) {
args <- paste(args, paste0("--num_tones=", num_tones))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "histogram_equalization"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Histogram matching
#'
#' @description Alters the statistical distribution of a raster image matching it to a specified PDF.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param histo_file Input reference probability distribution function (pdf) text file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsImageEnhancement
#'
#' @return Returns the tool text outputs.
#' @export
wbt_histogram_matching <- function(input, histo_file, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--histo_file=", wbt_file_path(histo_file)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "histogram_matching"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Histogram matching two images
#'
#' @description Alters the cumulative distribution function of a raster image to that of another image.
#'
#' @param input1 Input raster file to modify.
#' @param input2 Input reference raster file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsImageEnhancement
#'
#' @return Returns the tool text outputs.
#' @export
wbt_histogram_matching_two_images <- function(input1, input2, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "histogram_matching_two_images"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Min max contrast stretch
#'
#' @description Performs a min-max contrast stretch on an input greytone image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param min_val Lower tail clip value.
#' @param max_val Upper tail clip value.
#' @param num_tones Number of tones in the output image.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsImageEnhancement
#'
#' @return Returns the tool text outputs.
#' @export
wbt_min_max_contrast_stretch <- function(input, output, min_val, max_val, num_tones=256, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--min_val=", wbt_file_path(min_val)))
args <- paste(args, paste0("--max_val=", wbt_file_path(max_val)))
if (!is.null(num_tones)) {
args <- paste(args, paste0("--num_tones=", num_tones))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "min_max_contrast_stretch"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Panchromatic sharpening
#'
#' @description Increases the spatial resolution of image data by combining multispectral bands with panchromatic data.
#'
#' @param red Input red band image file. Optionally specified if colour-composite not specified.
#' @param green Input green band image file. Optionally specified if colour-composite not specified.
#' @param blue Input blue band image file. Optionally specified if colour-composite not specified.
#' @param composite Input colour-composite image file. Only used if individual bands are not specified.
#' @param pan Input panchromatic band file.
#' @param output Output colour composite file.
#' @param method Options include 'brovey' (default) and 'ihs'.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsImageEnhancement
#'
#' @return Returns the tool text outputs.
#' @export
wbt_panchromatic_sharpening <- function(pan, output, red=NULL, green=NULL, blue=NULL, composite=NULL, method="brovey", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--pan=", wbt_file_path(pan)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(red)) {
args <- paste(args, paste0("--red=", red))
}
if (!is.null(green)) {
args <- paste(args, paste0("--green=", green))
}
if (!is.null(blue)) {
args <- paste(args, paste0("--blue=", blue))
}
if (!is.null(composite)) {
args <- paste(args, paste0("--composite=", composite))
}
if (!is.null(method)) {
args <- paste(args, paste0("--method=", method))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "panchromatic_sharpening"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Percentage contrast stretch
#'
#' @description Performs a percentage linear contrast stretch on input images.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param clip Optional amount to clip the distribution tails by, in percent.
#' @param tail Specified which tails to clip; options include 'upper', 'lower', and 'both' (default is 'both').
#' @param num_tones Number of tones in the output image.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsImageEnhancement
#'
#' @return Returns the tool text outputs.
#' @export
wbt_percentage_contrast_stretch <- function(input, output, clip=1.0, tail="both", num_tones=256, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(clip)) {
args <- paste(args, paste0("--clip=", clip))
}
if (!is.null(tail)) {
args <- paste(args, paste0("--tail=", tail))
}
if (!is.null(num_tones)) {
args <- paste(args, paste0("--num_tones=", num_tones))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "percentage_contrast_stretch"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Piecewise contrast stretch
#'
#' @description Performs a piecewise contrast stretch on an input image.
#'
#' @param input Name of the input raster image file.
#' @param output Name of the output raster image file.
#' @param FUN Piecewise break-points e.g. '(50, 0.1); (150, 0.8); (255; 1.0).
#' @param greytones Number of greytones in the output image.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsImageEnhancement
#'
#' @return Returns the tool text outputs.
#' @export
wbt_piecewise_contrast_stretch <- function(input, output, FUN="", greytones=1024, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(FUN)) {
args <- paste(args, paste0("--FUN=", FUN))
}
if (!is.null(greytones)) {
args <- paste(args, paste0("--greytones=", greytones))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "piecewise_contrast_stretch"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Sigmoidal contrast stretch
#'
#' @description Performs a sigmoidal contrast stretch on input images.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param cutoff Cutoff value between 0.0 and 0.95.
#' @param gain Gain value.
#' @param num_tones Number of tones in the output image.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsImageEnhancement
#'
#' @return Returns the tool text outputs.
#' @export
wbt_sigmoidal_contrast_stretch <- function(input, output, cutoff=0.0, gain=1.0, num_tones=256, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(cutoff)) {
args <- paste(args, paste0("--cutoff=", cutoff))
}
if (!is.null(gain)) {
args <- paste(args, paste0("--gain=", gain))
}
if (!is.null(num_tones)) {
args <- paste(args, paste0("--num_tones=", num_tones))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "sigmoidal_contrast_stretch"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Standard deviation contrast stretch
#'
#' @description Performs a standard-deviation contrast stretch on input images.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param stdev Standard deviation clip value.
#' @param num_tones Number of tones in the output image.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsImageEnhancement
#'
#' @return Returns the tool text outputs.
#' @export
wbt_standard_deviation_contrast_stretch <- function(input, output, stdev=2.0, num_tones=256, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(stdev)) {
args <- paste(args, paste0("--stdev=", stdev))
}
if (!is.null(num_tones)) {
args <- paste(args, paste0("--num_tones=", num_tones))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "standard_deviation_contrast_stretch"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
|
/scratch/gouwar.j/cran-all/cranData/whitebox/R/image_analysis_enhancement.R
|
#' @title Adaptive filter
#'
#' @description Performs an adaptive filter on an image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param filterx Size of the filter kernel in the x-direction.
#' @param filtery Size of the filter kernel in the y-direction.
#' @param threshold Difference from mean threshold, in standard deviations.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_adaptive_filter <- function(input, output, filterx=11, filtery=11, threshold=2.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filterx)) {
args <- paste(args, paste0("--filterx=", filterx))
}
if (!is.null(filtery)) {
args <- paste(args, paste0("--filtery=", filtery))
}
if (!is.null(threshold)) {
args <- paste(args, paste0("--threshold=", threshold))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "adaptive_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Bilateral filter
#'
#' @description A bilateral filter is an edge-preserving smoothing filter introduced by Tomasi and Manduchi (1998).
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param sigma_dist Standard deviation in distance in pixels.
#' @param sigma_int Standard deviation in intensity in pixels.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_bilateral_filter <- function(input, output, sigma_dist=0.75, sigma_int=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(sigma_dist)) {
args <- paste(args, paste0("--sigma_dist=", sigma_dist))
}
if (!is.null(sigma_int)) {
args <- paste(args, paste0("--sigma_int=", sigma_int))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "bilateral_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Canny edge detection
#'
#' @description This tool performs a Canny edge-detection filter on an input image.
#'
#' @param input Name of the input raster image file.
#' @param output Name of the output raster image file.
#' @param sigma Sigma value used in Gaussian filtering, default = 0.5.
#' @param low Low threshold, default = 0.05.
#' @param high High threshold, default = 0.15.
#' @param add_back Add the edge cells back to the input image.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_canny_edge_detection <- function(input, output, sigma=0.5, low=0.05, high=0.15, add_back=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(sigma)) {
args <- paste(args, paste0("--sigma=", sigma))
}
if (!is.null(low)) {
args <- paste(args, paste0("--low=", low))
}
if (!is.null(high)) {
args <- paste(args, paste0("--high=", high))
}
if (add_back) {
args <- paste(args, "--add_back")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "canny_edge_detection"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Conservative smoothing filter
#'
#' @description Performs a conservative-smoothing filter on an image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param filterx Size of the filter kernel in the x-direction.
#' @param filtery Size of the filter kernel in the y-direction.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_conservative_smoothing_filter <- function(input, output, filterx=3, filtery=3, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filterx)) {
args <- paste(args, paste0("--filterx=", filterx))
}
if (!is.null(filtery)) {
args <- paste(args, paste0("--filtery=", filtery))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "conservative_smoothing_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Corner detection
#'
#' @description Identifies corner patterns in boolean images using hit-and-miss pattern matching.
#'
#' @param input Input boolean image.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_corner_detection <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "corner_detection"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Diff of gaussian filter
#'
#' @description Performs a Difference of Gaussian (DoG) filter on an image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param sigma1 Standard deviation distance in pixels.
#' @param sigma2 Standard deviation distance in pixels.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_diff_of_gaussian_filter <- function(input, output, sigma1=2.0, sigma2=4.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(sigma1)) {
args <- paste(args, paste0("--sigma1=", sigma1))
}
if (!is.null(sigma2)) {
args <- paste(args, paste0("--sigma2=", sigma2))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "diff_of_gaussian_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Diversity filter
#'
#' @description Assigns each cell in the output grid the number of different values in a moving window centred on each grid cell in the input raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param filterx Size of the filter kernel in the x-direction.
#' @param filtery Size of the filter kernel in the y-direction.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_diversity_filter <- function(input, output, filterx=11, filtery=11, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filterx)) {
args <- paste(args, paste0("--filterx=", filterx))
}
if (!is.null(filtery)) {
args <- paste(args, paste0("--filtery=", filtery))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "diversity_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Edge preserving mean filter
#'
#' @description Performs a simple edge-preserving mean filter on an input image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param filter Size of the filter kernel.
#' @param threshold Maximum difference in values.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_edge_preserving_mean_filter <- function(input, output, threshold, filter=11, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--threshold=", wbt_file_path(threshold)))
if (!is.null(filter)) {
args <- paste(args, paste0("--filter=", filter))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "edge_preserving_mean_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Emboss filter
#'
#' @description Performs an emboss filter on an image, similar to a hillshade operation.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param direction Direction of reflection; options include 'n', 's', 'e', 'w', 'ne', 'se', 'nw', 'sw'.
#' @param clip Optional amount to clip the distribution tails by, in percent.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_emboss_filter <- function(input, output, direction="n", clip=0.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(direction)) {
args <- paste(args, paste0("--direction=", direction))
}
if (!is.null(clip)) {
args <- paste(args, paste0("--clip=", clip))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "emboss_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Fast almost gaussian filter
#'
#' @description Performs a fast approximate Gaussian filter on an image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param sigma Standard deviation distance in pixels.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_fast_almost_gaussian_filter <- function(input, output, sigma=1.8, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(sigma)) {
args <- paste(args, paste0("--sigma=", sigma))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "fast_almost_gaussian_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Gaussian filter
#'
#' @description Performs a Gaussian filter on an image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param sigma Standard deviation distance in pixels.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_gaussian_filter <- function(input, output, sigma=0.75, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(sigma)) {
args <- paste(args, paste0("--sigma=", sigma))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "gaussian_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title High pass bilateral filter
#'
#' @description Performs a high-pass bilateral filter, by differencing an input image by the bilateral filter by Tomasi and Manduchi (1998).
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param sigma_dist Standard deviation in distance in pixels.
#' @param sigma_int Standard deviation in intensity in pixels.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_high_pass_bilateral_filter <- function(input, output, sigma_dist=0.75, sigma_int=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(sigma_dist)) {
args <- paste(args, paste0("--sigma_dist=", sigma_dist))
}
if (!is.null(sigma_int)) {
args <- paste(args, paste0("--sigma_int=", sigma_int))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "high_pass_bilateral_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title High pass filter
#'
#' @description Performs a high-pass filter on an input image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param filterx Size of the filter kernel in the x-direction.
#' @param filtery Size of the filter kernel in the y-direction.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_high_pass_filter <- function(input, output, filterx=11, filtery=11, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filterx)) {
args <- paste(args, paste0("--filterx=", filterx))
}
if (!is.null(filtery)) {
args <- paste(args, paste0("--filtery=", filtery))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "high_pass_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title High pass median filter
#'
#' @description Performs a high pass median filter on an input image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param filterx Size of the filter kernel in the x-direction.
#' @param filtery Size of the filter kernel in the y-direction.
#' @param sig_digits Number of significant digits.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_high_pass_median_filter <- function(input, output, filterx=11, filtery=11, sig_digits=2, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filterx)) {
args <- paste(args, paste0("--filterx=", filterx))
}
if (!is.null(filtery)) {
args <- paste(args, paste0("--filtery=", filtery))
}
if (!is.null(sig_digits)) {
args <- paste(args, paste0("--sig_digits=", sig_digits))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "high_pass_median_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title K nearest mean filter
#'
#' @description A k-nearest mean filter is a type of edge-preserving smoothing filter.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param filterx Size of the filter kernel in the x-direction.
#' @param filtery Size of the filter kernel in the y-direction.
#' @param k k-value in pixels; this is the number of nearest-valued neighbours to use.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_k_nearest_mean_filter <- function(input, output, filterx=11, filtery=11, k=5, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filterx)) {
args <- paste(args, paste0("--filterx=", filterx))
}
if (!is.null(filtery)) {
args <- paste(args, paste0("--filtery=", filtery))
}
if (!is.null(k)) {
args <- paste(args, paste0("--k=", k))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "k_nearest_mean_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Laplacian filter
#'
#' @description Performs a Laplacian filter on an image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param variant Optional variant value. Options include 3x3(1), 3x3(2), 3x3(3), 3x3(4), 5x5(1), and 5x5(2) (default is 3x3(1)).
#' @param clip Optional amount to clip the distribution tails by, in percent.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_laplacian_filter <- function(input, output, variant="3x3(1)", clip=0.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(variant)) {
args <- paste(args, paste0("--variant=", wbt_file_path(variant)))
}
if (!is.null(clip)) {
args <- paste(args, paste0("--clip=", clip))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "laplacian_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Laplacian of gaussian filter
#'
#' @description Performs a Laplacian-of-Gaussian (LoG) filter on an image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param sigma Standard deviation in pixels.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_laplacian_of_gaussian_filter <- function(input, output, sigma=0.75, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(sigma)) {
args <- paste(args, paste0("--sigma=", sigma))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "laplacian_of_gaussian_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lee sigma filter
#'
#' @description Performs a Lee (Sigma) smoothing filter on an image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param filterx Size of the filter kernel in the x-direction.
#' @param filtery Size of the filter kernel in the y-direction.
#' @param sigma Sigma value should be related to the standard deviation of the distribution of image speckle noise.
#' @param m M-threshold value the minimum allowable number of pixels within the intensity range.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lee_sigma_filter <- function(input, output, filterx=11, filtery=11, sigma=10.0, m=5.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filterx)) {
args <- paste(args, paste0("--filterx=", filterx))
}
if (!is.null(filtery)) {
args <- paste(args, paste0("--filtery=", filtery))
}
if (!is.null(sigma)) {
args <- paste(args, paste0("--sigma=", sigma))
}
if (!is.null(m)) {
args <- paste(args, paste0("--m=", m))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lee_sigma_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Line detection filter
#'
#' @description Performs a line-detection filter on an image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param variant Optional variant value. Options include 'v' (vertical), 'h' (horizontal), '45', and '135' (default is 'v').
#' @param absvals Optional flag indicating whether outputs should be absolute values.
#' @param clip Optional amount to clip the distribution tails by, in percent.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_line_detection_filter <- function(input, output, variant="vertical", absvals=FALSE, clip=0.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(variant)) {
args <- paste(args, paste0("--variant=", wbt_file_path(variant)))
}
if (absvals) {
args <- paste(args, "--absvals")
}
if (!is.null(clip)) {
args <- paste(args, paste0("--clip=", clip))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "line_detection_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Majority filter
#'
#' @description Assigns each cell in the output grid the most frequently occurring value (mode) in a moving window centred on each grid cell in the input raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param filterx Size of the filter kernel in the x-direction.
#' @param filtery Size of the filter kernel in the y-direction.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_majority_filter <- function(input, output, filterx=11, filtery=11, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filterx)) {
args <- paste(args, paste0("--filterx=", filterx))
}
if (!is.null(filtery)) {
args <- paste(args, paste0("--filtery=", filtery))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "majority_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Maximum filter
#'
#' @description Assigns each cell in the output grid the maximum value in a moving window centred on each grid cell in the input raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param filterx Size of the filter kernel in the x-direction.
#' @param filtery Size of the filter kernel in the y-direction.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_maximum_filter <- function(input, output, filterx=11, filtery=11, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filterx)) {
args <- paste(args, paste0("--filterx=", filterx))
}
if (!is.null(filtery)) {
args <- paste(args, paste0("--filtery=", filtery))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "maximum_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Mean filter
#'
#' @description Performs a mean filter (low-pass filter) on an input image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param filterx Size of the filter kernel in the x-direction.
#' @param filtery Size of the filter kernel in the y-direction.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_mean_filter <- function(input, output, filterx=3, filtery=3, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filterx)) {
args <- paste(args, paste0("--filterx=", filterx))
}
if (!is.null(filtery)) {
args <- paste(args, paste0("--filtery=", filtery))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "mean_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Median filter
#'
#' @description Performs a median filter on an input image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param filterx Size of the filter kernel in the x-direction.
#' @param filtery Size of the filter kernel in the y-direction.
#' @param sig_digits Number of significant digits.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_median_filter <- function(input, output, filterx=11, filtery=11, sig_digits=2, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filterx)) {
args <- paste(args, paste0("--filterx=", filterx))
}
if (!is.null(filtery)) {
args <- paste(args, paste0("--filtery=", filtery))
}
if (!is.null(sig_digits)) {
args <- paste(args, paste0("--sig_digits=", sig_digits))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "median_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Minimum filter
#'
#' @description Assigns each cell in the output grid the minimum value in a moving window centred on each grid cell in the input raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param filterx Size of the filter kernel in the x-direction.
#' @param filtery Size of the filter kernel in the y-direction.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_minimum_filter <- function(input, output, filterx=11, filtery=11, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filterx)) {
args <- paste(args, paste0("--filterx=", filterx))
}
if (!is.null(filtery)) {
args <- paste(args, paste0("--filtery=", filtery))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "minimum_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Olympic filter
#'
#' @description Performs an olympic smoothing filter on an image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param filterx Size of the filter kernel in the x-direction.
#' @param filtery Size of the filter kernel in the y-direction.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_olympic_filter <- function(input, output, filterx=11, filtery=11, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filterx)) {
args <- paste(args, paste0("--filterx=", filterx))
}
if (!is.null(filtery)) {
args <- paste(args, paste0("--filtery=", filtery))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "olympic_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Percentile filter
#'
#' @description Performs a percentile filter on an input image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param filterx Size of the filter kernel in the x-direction.
#' @param filtery Size of the filter kernel in the y-direction.
#' @param sig_digits Number of significant digits.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_percentile_filter <- function(input, output, filterx=11, filtery=11, sig_digits=2, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filterx)) {
args <- paste(args, paste0("--filterx=", filterx))
}
if (!is.null(filtery)) {
args <- paste(args, paste0("--filtery=", filtery))
}
if (!is.null(sig_digits)) {
args <- paste(args, paste0("--sig_digits=", sig_digits))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "percentile_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Prewitt filter
#'
#' @description Performs a Prewitt edge-detection filter on an image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param clip Optional amount to clip the distribution tails by, in percent.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_prewitt_filter <- function(input, output, clip=0.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(clip)) {
args <- paste(args, paste0("--clip=", clip))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "prewitt_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Range filter
#'
#' @description Assigns each cell in the output grid the range of values in a moving window centred on each grid cell in the input raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param filterx Size of the filter kernel in the x-direction.
#' @param filtery Size of the filter kernel in the y-direction.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_range_filter <- function(input, output, filterx=11, filtery=11, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filterx)) {
args <- paste(args, paste0("--filterx=", filterx))
}
if (!is.null(filtery)) {
args <- paste(args, paste0("--filtery=", filtery))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "range_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Roberts cross filter
#'
#' @description Performs a Robert's cross edge-detection filter on an image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param clip Optional amount to clip the distribution tails by, in percent.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_roberts_cross_filter <- function(input, output, clip=0.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(clip)) {
args <- paste(args, paste0("--clip=", clip))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "roberts_cross_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Scharr filter
#'
#' @description Performs a Scharr edge-detection filter on an image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param clip Optional amount to clip the distribution tails by, in percent.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_scharr_filter <- function(input, output, clip=0.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(clip)) {
args <- paste(args, paste0("--clip=", clip))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "scharr_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Sobel filter
#'
#' @description Performs a Sobel edge-detection filter on an image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param variant Optional variant value. Options include 3x3 and 5x5 (default is 3x3).
#' @param clip Optional amount to clip the distribution tails by, in percent (default is 0.0).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_sobel_filter <- function(input, output, variant="3x3", clip=0.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(variant)) {
args <- paste(args, paste0("--variant=", wbt_file_path(variant)))
}
if (!is.null(clip)) {
args <- paste(args, paste0("--clip=", clip))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "sobel_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Standard deviation filter
#'
#' @description Assigns each cell in the output grid the standard deviation of values in a moving window centred on each grid cell in the input raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param filterx Size of the filter kernel in the x-direction.
#' @param filtery Size of the filter kernel in the y-direction.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_standard_deviation_filter <- function(input, output, filterx=11, filtery=11, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filterx)) {
args <- paste(args, paste0("--filterx=", filterx))
}
if (!is.null(filtery)) {
args <- paste(args, paste0("--filtery=", filtery))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "standard_deviation_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Total filter
#'
#' @description Performs a total filter on an input image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param filterx Size of the filter kernel in the x-direction.
#' @param filtery Size of the filter kernel in the y-direction.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_total_filter <- function(input, output, filterx=11, filtery=11, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filterx)) {
args <- paste(args, paste0("--filterx=", filterx))
}
if (!is.null(filtery)) {
args <- paste(args, paste0("--filtery=", filtery))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "total_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Unsharp masking
#'
#' @description An image sharpening technique that enhances edges.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param sigma Standard deviation distance in pixels.
#' @param amount A percentage and controls the magnitude of each overshoot.
#' @param threshold Controls the minimal brightness change that will be sharpened.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_unsharp_masking <- function(input, output, sigma=0.75, amount=100.0, threshold=0.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(sigma)) {
args <- paste(args, paste0("--sigma=", sigma))
}
if (!is.null(amount)) {
args <- paste(args, paste0("--amount=", amount))
}
if (!is.null(threshold)) {
args <- paste(args, paste0("--threshold=", threshold))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "unsharp_masking"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title User ined weights filter
#'
#' @description Performs a user-defined weights filter on an image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param weights Input weights file.
#' @param output Output raster file.
#' @param center Kernel center cell; options include 'center', 'upper-left', 'upper-right', 'lower-left', 'lower-right'.
#' @param normalize Normalize kernel weights? This can reduce edge effects and lessen the impact of data gaps (nodata) but is not suited when the kernel weights sum to zero.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords ImageProcessingToolsFilters
#'
#' @return Returns the tool text outputs.
#' @export
wbt_user_defined_weights_filter <- function(input, weights, output, center="center", normalize=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--weights=", wbt_file_path(weights)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(center)) {
args <- paste(args, paste0("--center=", center))
}
if (normalize) {
args <- paste(args, "--normalize")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "user_defined_weights_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
|
/scratch/gouwar.j/cran-all/cranData/whitebox/R/image_analysis_filters.R
|
#' @title Ascii to las
#'
#' @description Converts one or more ASCII files containing LiDAR points into LAS files.
#'
#' @param inputs Input LiDAR ASCII files (.csv).
#' @param pattern Input field pattern.
#' @param proj Well-known-text string or EPSG code describing projection.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_ascii_to_las <- function(inputs, pattern, proj=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--pattern=", wbt_file_path(pattern)))
if (!is.null(proj)) {
args <- paste(args, paste0("--proj=", proj))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "ascii_to_las"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Classify buildings in lidar
#'
#' @description Reclassifies a LiDAR points that lie within vector building footprints.
#'
#' @param input Input LiDAR file.
#' @param buildings Input vector polygons file.
#' @param output Output LiDAR file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_classify_buildings_in_lidar <- function(input, buildings, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--buildings=", wbt_file_path(buildings)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "classify_buildings_in_lidar"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Classify lidar
#'
#' @description Classify points within a LiDAR point cloud based on point properties.
#'
#' @param input Name of the input LiDAR points.
#' @param output Name of the output LiDAR points.
#' @param radius Search distance used in neighbourhood search (metres).
#' @param grd_threshold Ground threshold (metres).
#' @param oto_threshold Off-terrain object threshold (metres).
#' @param planarity_threshold Planarity threshold (0-1).
#' @param linearity_threshold Linearity threshold (0-1).
#' @param iterations Number of iterations.
#' @param facade_threshold Facade threshold (metres).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_classify_lidar <- function(input, output=NULL, radius=1.5, grd_threshold=0.1, oto_threshold=2.0, planarity_threshold=0.85, linearity_threshold=0.70, iterations=30, facade_threshold=0.5, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!is.null(radius)) {
args <- paste(args, paste0("--radius=", radius))
}
if (!is.null(grd_threshold)) {
args <- paste(args, paste0("--grd_threshold=", grd_threshold))
}
if (!is.null(oto_threshold)) {
args <- paste(args, paste0("--oto_threshold=", oto_threshold))
}
if (!is.null(planarity_threshold)) {
args <- paste(args, paste0("--planarity_threshold=", planarity_threshold))
}
if (!is.null(linearity_threshold)) {
args <- paste(args, paste0("--linearity_threshold=", linearity_threshold))
}
if (!is.null(iterations)) {
args <- paste(args, paste0("--iterations=", iterations))
}
if (!is.null(facade_threshold)) {
args <- paste(args, paste0("--facade_threshold=", facade_threshold))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "classify_lidar"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Classify overlap points
#'
#' @description Classifies or filters LAS points in regions of overlapping flight lines.
#'
#' @param input Input LiDAR file.
#' @param output Output LiDAR file.
#' @param resolution The size of the square area used to evaluate nearby points in the LiDAR data.
#' @param criterion Criterion used to identify overlapping points; options are 'max scan angle', 'not min point source ID', 'not min time', 'multiple point source IDs'.
#' @param filter Filter out points from overlapping flightlines? If false, overlaps will simply be classified.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_classify_overlap_points <- function(input, output, resolution=2.0, criterion="max scan angle", filter=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(resolution)) {
args <- paste(args, paste0("--resolution=", resolution))
}
if (!is.null(criterion)) {
args <- paste(args, paste0("--criterion=", criterion))
}
if (filter) {
args <- paste(args, "--filter")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "classify_overlap_points"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Clip lidar to polygon
#'
#' @description Clips a LiDAR point cloud to a vector polygon or polygons.
#'
#' @param input Input LiDAR file.
#' @param polygons Input vector polygons file.
#' @param output Output LiDAR file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_clip_lidar_to_polygon <- function(input, polygons, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--polygons=", wbt_file_path(polygons)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "clip_lidar_to_polygon"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Colourize based on class
#'
#' @description Sets the RGB values of a LiDAR point cloud based on the point classification values.
#'
#' @param input Name of the input LiDAR points.
#' @param output Name of the output LiDAR points.
#' @param intensity_blending Intensity blending amount (0-100 percent).
#' @param clr_str Colour values, e.g. 2: (184, 167, 108); 5: #9ab86c.
#' @param use_unique_clrs_for_buildings Use unique colours for each building?.
#' @param radius Search distance used in neighbourhood search.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_colourize_based_on_class <- function(input, output=NULL, intensity_blending=50.0, clr_str="", use_unique_clrs_for_buildings=FALSE, radius="", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!is.null(intensity_blending)) {
args <- paste(args, paste0("--intensity_blending=", intensity_blending))
}
if (!is.null(clr_str)) {
args <- paste(args, paste0("--clr_str=", clr_str))
}
if (use_unique_clrs_for_buildings) {
args <- paste(args, "--use_unique_clrs_for_buildings")
}
if (!is.null(radius)) {
args <- paste(args, paste0("--radius=", radius))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "colourize_based_on_class"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Colourize based on point returns
#'
#' @description Sets the RGB values of a LiDAR point cloud based on the point returns.
#'
#' @param input Name of the input LiDAR points.
#' @param output Name of the output LiDAR points.
#' @param intensity_blending Intensity blending amount (0-100 percent).
#' @param only Only return colour, e.g. (230,214,170), #e6d6aa, or 0xe6d6aa.
#' @param first First return colour, e.g. (230,214,170), #e6d6aa, or 0xe6d6aa.
#' @param intermediate Intermediate return colour, e.g. (230,214,170), #e6d6aa, or 0xe6d6aa.
#' @param last Last return colour, e.g. (230,214,170), #e6d6aa, or 0xe6d6aa.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_colourize_based_on_point_returns <- function(input, output=NULL, intensity_blending=50.0, only="(230,214,170)", first="(0,140,0)", intermediate="(255,0,255)", last="(0,0,255)", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!is.null(intensity_blending)) {
args <- paste(args, paste0("--intensity_blending=", intensity_blending))
}
if (!is.null(only)) {
args <- paste(args, paste0("--only=", only))
}
args <- paste(args, paste0("--214=", wbt_file_path(214)))
if (!is.null(first)) {
args <- paste(args, paste0("--first=", first))
}
args <- paste(args, paste0("--140=", wbt_file_path(140)))
if (!is.null(intermediate)) {
args <- paste(args, paste0("--intermediate=", intermediate))
}
args <- paste(args, paste0("--0=", wbt_file_path(0)))
if (!is.null(last)) {
args <- paste(args, paste0("--last=", last))
}
args <- paste(args, paste0("--0=", wbt_file_path(0)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "colourize_based_on_point_returns"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Erase polygon from lidar
#'
#' @description Erases (cuts out) a vector polygon or polygons from a LiDAR point cloud.
#'
#' @param input Input LiDAR file.
#' @param polygons Input vector polygons file.
#' @param output Output LiDAR file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_erase_polygon_from_lidar <- function(input, polygons, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--polygons=", wbt_file_path(polygons)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "erase_polygon_from_lidar"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Filter lidar
#'
#' @description Filters points within a LiDAR point cloud based on point properties.
#'
#' @param input Name of the input LiDAR points.
#' @param output Name of the output LiDAR points.
#' @param statement Filter statement e.g. x < 5000.0 && y > 100.0 && is_late && !is_noise. This statement must be a valid Rust statement.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_filter_lidar <- function(input, output=NULL, statement="", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!is.null(statement)) {
args <- paste(args, paste0("--statement=", statement))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "filter_lidar"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Filter lidar classes
#'
#' @description Removes points in a LAS file with certain specified class values.
#'
#' @param input Input LiDAR file.
#' @param output Output LiDAR file.
#' @param exclude_cls Optional exclude classes from interpolation; Valid class values range from 0 to 18, based on LAS specifications. Example, --exclude_cls='3,4,5,6,7,18'.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_filter_lidar_classes <- function(input, output, exclude_cls=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(exclude_cls)) {
args <- paste(args, paste0("--exclude_cls=", exclude_cls))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "filter_lidar_classes"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Filter lidar scan angles
#'
#' @description Removes points in a LAS file with scan angles greater than a threshold.
#'
#' @param input Input LiDAR file.
#' @param output Output LiDAR file.
#' @param threshold Scan angle threshold.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_filter_lidar_scan_angles <- function(input, output, threshold, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--threshold=", wbt_file_path(threshold)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "filter_lidar_scan_angles"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Find flightline edge points
#'
#' @description Identifies points along a flightline's edge in a LAS file.
#'
#' @param input Input LiDAR file.
#' @param output Output file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_find_flightline_edge_points <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "find_flightline_edge_points"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Flightline overlap
#'
#' @description Reads a LiDAR (LAS) point file and outputs a raster containing the number of overlapping flight-lines in each grid cell.
#'
#' @param input Input LiDAR file.
#' @param output Output file.
#' @param resolution Output raster's grid resolution.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_flightline_overlap <- function(input, output=NULL, resolution=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!is.null(resolution)) {
args <- paste(args, paste0("--resolution=", resolution))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "flightline_overlap"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Height above ground
#'
#' @description Normalizes a LiDAR point cloud, providing the height above the nearest ground-classified point.
#'
#' @param input Input LiDAR file (including extension).
#' @param output Output lidar file (including extension).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_height_above_ground <- function(input, output=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "height_above_ground"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Individual tree detection
#'
#' @description Identifies points in a LiDAR point cloud that are associated with the tops of individual trees.
#'
#' @param input Name of the input LiDAR file.
#' @param output Name of the output vector points file.
#' @param min_search_radius Minimum search radius (m).
#' @param min_height Minimum height (m).
#' @param max_search_radius Maximum search radius (m).
#' @param max_height Maximum height (m).
#' @param only_use_veg Only use veg. class points?.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_individual_tree_detection <- function(input, output=NULL, min_search_radius=1.0, min_height=0.0, max_search_radius="", max_height="", only_use_veg=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!is.null(min_search_radius)) {
args <- paste(args, paste0("--min_search_radius=", min_search_radius))
}
if (!is.null(min_height)) {
args <- paste(args, paste0("--min_height=", min_height))
}
if (!is.null(max_search_radius)) {
args <- paste(args, paste0("--max_search_radius=", max_search_radius))
}
if (!is.null(max_height)) {
args <- paste(args, paste0("--max_height=", max_height))
}
if (only_use_veg) {
args <- paste(args, "--only_use_veg")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "individual_tree_detection"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Las to ascii
#'
#' @description Converts one or more LAS files into ASCII text files.
#'
#' @param inputs Input LiDAR files.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_las_to_ascii <- function(inputs, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "las_to_ascii"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Las to laz
#'
#' @description This tool converts one or more LAS files into the LAZ format.
#'
#' @param input Name of the input LAS files (leave blank to use all LAS files in WorkingDirectory.
#' @param output Output LAZ file (including extension).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_las_to_laz <- function(input, output=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "las_to_laz"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Las to multipoint shapefile
#'
#' @description Converts one or more LAS files into MultipointZ vector Shapefiles. When the input parameter is not specified, the tool grids all LAS files contained within the working directory.
#'
#' @param input Input LiDAR file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_las_to_multipoint_shapefile <- function(input, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "las_to_multipoint_shapefile"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Las to shapefile
#'
#' @description Converts one or more LAS files into a vector Shapefile of POINT ShapeType.
#'
#' @param input Input LiDAR file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_las_to_shapefile <- function(input, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "las_to_shapefile"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Las to zlidar
#'
#' @description Converts one or more LAS files into the zlidar compressed LiDAR data format.
#'
#' @param inputs Input LAS files.
#' @param outdir Output directory into which zlidar files are created. If unspecified, it is assumed to be the same as the inputs.
#' @param compress Compression method, including 'brotli' and 'deflate'.
#' @param level Compression level (1-9).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_las_to_zlidar <- function(inputs=NULL, outdir=NULL, compress="brotli", level=5, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
if (!is.null(inputs)) {
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
}
if (!is.null(outdir)) {
args <- paste(args, paste0("--outdir=", outdir))
}
if (!is.null(compress)) {
args <- paste(args, paste0("--compress=", compress))
}
if (!is.null(level)) {
args <- paste(args, paste0("--level=", level))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "las_to_zlidar"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Laz to las
#'
#' @description This tool converts one or more LAZ files into the LAS format.
#'
#' @param input Name of the input LAZ files (leave blank to use all LAZ files in WorkingDirectory.
#' @param output Output LAS file (including extension).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_laz_to_las <- function(input, output=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "laz_to_las"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar block maximum
#'
#' @description Creates a block-maximum raster from an input LAS file. When the input/output parameters are not specified, the tool grids all LAS files contained within the working directory.
#'
#' @param input Input LiDAR file.
#' @param output Output file.
#' @param resolution Output raster's grid resolution.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_block_maximum <- function(input, output=NULL, resolution=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!is.null(resolution)) {
args <- paste(args, paste0("--resolution=", resolution))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_block_maximum"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar block minimum
#'
#' @description Creates a block-minimum raster from an input LAS file. When the input/output parameters are not specified, the tool grids all LAS files contained within the working directory.
#'
#' @param input Input LiDAR file.
#' @param output Output file.
#' @param resolution Output raster's grid resolution.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_block_minimum <- function(input, output=NULL, resolution=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!is.null(resolution)) {
args <- paste(args, paste0("--resolution=", resolution))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_block_minimum"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar classify subset
#'
#' @description Classifies the values in one LiDAR point cloud that correspond with points in a subset cloud.
#'
#' @param base Input base LiDAR file.
#' @param subset Input subset LiDAR file.
#' @param output Output LiDAR file.
#' @param subset_class Subset point class value (must be 0-18; see LAS specifications).
#' @param nonsubset_class Non-subset point class value (must be 0-18; see LAS specifications).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_classify_subset <- function(base, subset, output, subset_class, nonsubset_class=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--base=", wbt_file_path(base)))
args <- paste(args, paste0("--subset=", wbt_file_path(subset)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--subset_class=", wbt_file_path(subset_class)))
if (!is.null(nonsubset_class)) {
args <- paste(args, paste0("--nonsubset_class=", nonsubset_class))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_classify_subset"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar colourize
#'
#' @description Adds the red-green-blue colour fields of a LiDAR (LAS) file based on an input image.
#'
#' @param in_lidar Input LiDAR file.
#' @param in_image Input colour image file.
#' @param output Output LiDAR file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_colourize <- function(in_lidar, in_image, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--in_lidar=", wbt_file_path(in_lidar)))
args <- paste(args, paste0("--in_image=", wbt_file_path(in_image)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_colourize"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar contour
#'
#' @description This tool creates a vector contour coverage from an input LiDAR point file.
#'
#' @param input Name of the input LiDAR points.
#' @param output Name of the output vector lines file.
#' @param interval Contour interval.
#' @param base Base contour.
#' @param smooth Smoothing filter size (in num. points), e.g. 3, 5, 7, 9, 11.
#' @param parameter Interpolation parameter; options are 'elevation' (default), 'intensity', 'user_data'.
#' @param returns Point return types to include; options are 'all' (default), 'last', 'first'.
#' @param exclude_cls Optional exclude classes from interpolation; Valid class values range from 0 to 18, based on LAS specifications. Example, --exclude_cls='3,4,5,6,7,18'.
#' @param minz Optional minimum elevation for inclusion in interpolation.
#' @param maxz Optional maximum elevation for inclusion in interpolation.
#' @param max_triangle_edge_length Optional maximum triangle edge length; triangles larger than this size will not be gridded.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_contour <- function(input, output=NULL, interval=10.0, base=0.0, smooth=5, parameter="elevation", returns="all", exclude_cls=NULL, minz=NULL, maxz=NULL, max_triangle_edge_length=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!is.null(interval)) {
args <- paste(args, paste0("--interval=", interval))
}
if (!is.null(base)) {
args <- paste(args, paste0("--base=", base))
}
if (!is.null(smooth)) {
args <- paste(args, paste0("--smooth=", smooth))
}
if (!is.null(parameter)) {
args <- paste(args, paste0("--parameter=", parameter))
}
if (!is.null(returns)) {
args <- paste(args, paste0("--returns=", returns))
}
if (!is.null(exclude_cls)) {
args <- paste(args, paste0("--exclude_cls=", exclude_cls))
}
if (!is.null(minz)) {
args <- paste(args, paste0("--minz=", minz))
}
if (!is.null(maxz)) {
args <- paste(args, paste0("--maxz=", maxz))
}
if (!is.null(max_triangle_edge_length)) {
args <- paste(args, paste0("--max_triangle_edge_length=", max_triangle_edge_length))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_contour"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar digital surface model
#'
#' @description Creates a top-surface digital surface model (DSM) from a LiDAR point cloud.
#'
#' @param input Input LiDAR file (including extension).
#' @param output Output raster file (including extension).
#' @param resolution Output raster's grid resolution.
#' @param radius Search Radius.
#' @param minz Optional minimum elevation for inclusion in interpolation.
#' @param maxz Optional maximum elevation for inclusion in interpolation.
#' @param max_triangle_edge_length Optional maximum triangle edge length; triangles larger than this size will not be gridded.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_digital_surface_model <- function(input, output=NULL, resolution=1.0, radius=0.5, minz=NULL, maxz=NULL, max_triangle_edge_length=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!is.null(resolution)) {
args <- paste(args, paste0("--resolution=", resolution))
}
if (!is.null(radius)) {
args <- paste(args, paste0("--radius=", radius))
}
if (!is.null(minz)) {
args <- paste(args, paste0("--minz=", minz))
}
if (!is.null(maxz)) {
args <- paste(args, paste0("--maxz=", maxz))
}
if (!is.null(max_triangle_edge_length)) {
args <- paste(args, paste0("--max_triangle_edge_length=", max_triangle_edge_length))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_digital_surface_model"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar eigenvalue features
#'
#' @description Calculate eigenvalue-based metrics from a LiDAR point cloud.
#'
#' @param input Name of the input LiDAR points.
#' @param num_neighbours Number of neighbours used in search.
#' @param radius Search distance used in neighbourhood search.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_eigenvalue_features <- function(input, num_neighbours=NULL, radius=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(num_neighbours)) {
args <- paste(args, paste0("--num_neighbours=", num_neighbours))
}
if (!is.null(radius)) {
args <- paste(args, paste0("--radius=", radius))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_eigenvalue_features"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar elevation slice
#'
#' @description Outputs all of the points within a LiDAR (LAS) point file that lie between a specified elevation range.
#'
#' @param input Input LiDAR file.
#' @param output Output LiDAR file.
#' @param minz Minimum elevation value (optional).
#' @param maxz Maximum elevation value (optional).
#' @param cls Optional boolean flag indicating whether points outside the range should be retained in output but reclassified.
#' @param inclassval Optional parameter specifying the class value assigned to points within the slice.
#' @param outclassval Optional parameter specifying the class value assigned to points within the slice.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_elevation_slice <- function(input, output, minz=NULL, maxz=NULL, cls=FALSE, inclassval=2, outclassval=1, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(minz)) {
args <- paste(args, paste0("--minz=", minz))
}
if (!is.null(maxz)) {
args <- paste(args, paste0("--maxz=", maxz))
}
if (cls) {
args <- paste(args, "--cls")
}
if (!is.null(inclassval)) {
args <- paste(args, paste0("--inclassval=", inclassval))
}
if (!is.null(outclassval)) {
args <- paste(args, paste0("--outclassval=", outclassval))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_elevation_slice"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar ground point filter
#'
#' @description Identifies ground points within LiDAR dataset using a slope-based method.
#'
#' @param input Input LiDAR file.
#' @param output Output LiDAR file.
#' @param radius Search Radius.
#' @param min_neighbours The minimum number of neighbouring points within search areas. If fewer points than this threshold are identified during the fixed-radius search, a subsequent kNN search is performed to identify the k number of neighbours.
#' @param slope_threshold Maximum inter-point slope to be considered an off-terrain point.
#' @param height_threshold Inter-point height difference to be considered an off-terrain point.
#' @param classify Classify points as ground (2) or off-ground (1).
#' @param slope_norm Perform initial ground slope normalization?.
#' @param height_above_ground Transform output to height above average ground elevation?.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_ground_point_filter <- function(input, output, radius=2.0, min_neighbours=0, slope_threshold=45.0, height_threshold=1.0, classify=TRUE, slope_norm=TRUE, height_above_ground=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(radius)) {
args <- paste(args, paste0("--radius=", radius))
}
if (!is.null(min_neighbours)) {
args <- paste(args, paste0("--min_neighbours=", min_neighbours))
}
if (!is.null(slope_threshold)) {
args <- paste(args, paste0("--slope_threshold=", slope_threshold))
}
if (!is.null(height_threshold)) {
args <- paste(args, paste0("--height_threshold=", height_threshold))
}
if (classify) {
args <- paste(args, "--classify")
}
if (slope_norm) {
args <- paste(args, "--slope_norm")
}
if (height_above_ground) {
args <- paste(args, "--height_above_ground")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_ground_point_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar hex binning
#'
#' @description Hex-bins a set of LiDAR points.
#'
#' @param input Input base file.
#' @param output Output vector polygon file.
#' @param width The grid cell width.
#' @param orientation Grid Orientation, 'horizontal' or 'vertical'.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_hex_binning <- function(input, output, width, orientation="horizontal", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--width=", wbt_file_path(width)))
if (!is.null(orientation)) {
args <- paste(args, paste0("--orientation=", orientation))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_hex_binning"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar hillshade
#'
#' @description Calculates a hillshade value for points within a LAS file and stores these data in the RGB field.
#'
#' @param input Input LiDAR file.
#' @param output Output file.
#' @param azimuth Illumination source azimuth in degrees.
#' @param altitude Illumination source altitude in degrees.
#' @param radius Search Radius.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_hillshade <- function(input, output, azimuth=315.0, altitude=30.0, radius=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(azimuth)) {
args <- paste(args, paste0("--azimuth=", azimuth))
}
if (!is.null(altitude)) {
args <- paste(args, paste0("--altitude=", altitude))
}
if (!is.null(radius)) {
args <- paste(args, paste0("--radius=", radius))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_hillshade"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar histogram
#'
#' @description Creates a histogram of LiDAR data.
#'
#' @param input Input LiDAR file.
#' @param output Output HTML file (default name will be based on input file if unspecified).
#' @param parameter Parameter; options are 'elevation' (default), 'intensity', 'scan angle', 'class', 'time'.
#' @param clip Amount to clip distribution tails (in percent).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_histogram <- function(input, output, parameter="elevation", clip=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(parameter)) {
args <- paste(args, paste0("--parameter=", parameter))
}
if (!is.null(clip)) {
args <- paste(args, paste0("--clip=", clip))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_histogram"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar idw interpolation
#'
#' @description Interpolates LAS files using an inverse-distance weighted (IDW) scheme. When the input/output parameters are not specified, the tool interpolates all LAS files contained within the working directory.
#'
#' @param input Input LiDAR file (including extension).
#' @param output Output raster file (including extension).
#' @param parameter Interpolation parameter; options are 'elevation' (default), 'intensity', 'class', 'return_number', 'number_of_returns', 'scan angle', 'rgb', 'user data'.
#' @param returns Point return types to include; options are 'all' (default), 'last', 'first'.
#' @param resolution Output raster's grid resolution.
#' @param weight IDW weight value.
#' @param radius Search Radius.
#' @param exclude_cls Optional exclude classes from interpolation; Valid class values range from 0 to 18, based on LAS specifications. Example, --exclude_cls='3,4,5,6,7,18'.
#' @param minz Optional minimum elevation for inclusion in interpolation.
#' @param maxz Optional maximum elevation for inclusion in interpolation.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_idw_interpolation <- function(input, output=NULL, parameter="elevation", returns="all", resolution=1.0, weight=1.0, radius=2.5, exclude_cls=NULL, minz=NULL, maxz=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!is.null(parameter)) {
args <- paste(args, paste0("--parameter=", parameter))
}
if (!is.null(returns)) {
args <- paste(args, paste0("--returns=", returns))
}
if (!is.null(resolution)) {
args <- paste(args, paste0("--resolution=", resolution))
}
if (!is.null(weight)) {
args <- paste(args, paste0("--weight=", weight))
}
if (!is.null(radius)) {
args <- paste(args, paste0("--radius=", radius))
}
if (!is.null(exclude_cls)) {
args <- paste(args, paste0("--exclude_cls=", exclude_cls))
}
if (!is.null(minz)) {
args <- paste(args, paste0("--minz=", minz))
}
if (!is.null(maxz)) {
args <- paste(args, paste0("--maxz=", maxz))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_idw_interpolation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar info
#'
#' @description Prints information about a LiDAR (LAS) dataset, including header, point return frequency, and classification data and information about the variable length records (VLRs) and geokeys.
#'
#' @param input Input LiDAR file.
#' @param output Output HTML file for summary report.
#' @param density Flag indicating whether or not to calculate the average point density and nominal point spacing.
#' @param vlr Flag indicating whether or not to print the variable length records (VLRs).
#' @param geokeys Flag indicating whether or not to print the geokeys.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_info <- function(input, output, density=TRUE, vlr=TRUE, geokeys=TRUE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (density) {
args <- paste(args, "--density")
}
if (vlr) {
args <- paste(args, "--vlr")
}
if (geokeys) {
args <- paste(args, "--geokeys")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_info"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar join
#'
#' @description Joins multiple LiDAR (LAS) files into a single LAS file.
#'
#' @param inputs Input LiDAR files.
#' @param output Output LiDAR file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_join <- function(inputs, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_join"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar kappa index
#'
#' @description Performs a kappa index of agreement (KIA) analysis on the classifications of two LAS files.
#'
#' @param input1 Input LiDAR classification file.
#' @param input2 Input LiDAR reference file.
#' @param output Output HTML file.
#' @param class_accuracy Output classification accuracy raster file.
#' @param resolution Output raster's grid resolution.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_kappa_index <- function(input1, input2, output, class_accuracy, resolution=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--class_accuracy=", wbt_file_path(class_accuracy)))
if (!is.null(resolution)) {
args <- paste(args, paste0("--resolution=", resolution))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_kappa_index"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar nearest neighbour gridding
#'
#' @description Grids LiDAR files using nearest-neighbour scheme. When the input/output parameters are not specified, the tool grids all LAS files contained within the working directory.
#'
#' @param input Input LiDAR file (including extension).
#' @param output Output raster file (including extension).
#' @param parameter Interpolation parameter; options are 'elevation' (default), 'intensity', 'class', 'return_number', 'number_of_returns', 'scan angle', 'rgb', 'user data', 'time'.
#' @param returns Point return types to include; options are 'all' (default), 'last', 'first'.
#' @param resolution Output raster's grid resolution.
#' @param radius Search Radius.
#' @param exclude_cls Optional exclude classes from interpolation; Valid class values range from 0 to 18, based on LAS specifications. Example, --exclude_cls='3,4,5,6,7,18'.
#' @param minz Optional minimum elevation for inclusion in interpolation.
#' @param maxz Optional maximum elevation for inclusion in interpolation.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_nearest_neighbour_gridding <- function(input, output=NULL, parameter="elevation", returns="all", resolution=1.0, radius=2.5, exclude_cls=NULL, minz=NULL, maxz=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!is.null(parameter)) {
args <- paste(args, paste0("--parameter=", parameter))
}
if (!is.null(returns)) {
args <- paste(args, paste0("--returns=", returns))
}
if (!is.null(resolution)) {
args <- paste(args, paste0("--resolution=", resolution))
}
if (!is.null(radius)) {
args <- paste(args, paste0("--radius=", radius))
}
if (!is.null(exclude_cls)) {
args <- paste(args, paste0("--exclude_cls=", exclude_cls))
}
if (!is.null(minz)) {
args <- paste(args, paste0("--minz=", minz))
}
if (!is.null(maxz)) {
args <- paste(args, paste0("--maxz=", maxz))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_nearest_neighbour_gridding"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar point density
#'
#' @description Calculates the spatial pattern of point density for a LiDAR data set. When the input/output parameters are not specified, the tool grids all LAS files contained within the working directory.
#'
#' @param input Input LiDAR file (including extension).
#' @param output Output raster file (including extension).
#' @param returns Point return types to include; options are 'all' (default), 'last', 'first'.
#' @param resolution Output raster's grid resolution.
#' @param radius Search radius.
#' @param exclude_cls Optional exclude classes from interpolation; Valid class values range from 0 to 18, based on LAS specifications. Example, --exclude_cls='3,4,5,6,7,18'.
#' @param minz Optional minimum elevation for inclusion in interpolation.
#' @param maxz Optional maximum elevation for inclusion in interpolation.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_point_density <- function(input, output=NULL, returns="all", resolution=1.0, radius=2.5, exclude_cls=NULL, minz=NULL, maxz=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!is.null(returns)) {
args <- paste(args, paste0("--returns=", returns))
}
if (!is.null(resolution)) {
args <- paste(args, paste0("--resolution=", resolution))
}
if (!is.null(radius)) {
args <- paste(args, paste0("--radius=", radius))
}
if (!is.null(exclude_cls)) {
args <- paste(args, paste0("--exclude_cls=", exclude_cls))
}
if (!is.null(minz)) {
args <- paste(args, paste0("--minz=", minz))
}
if (!is.null(maxz)) {
args <- paste(args, paste0("--maxz=", maxz))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_point_density"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar point return analysis
#'
#' @description This tool performs a quality control check on the return values of points in a LiDAR file.
#'
#' @param input Name of the input LiDAR points.
#' @param output Name of the output LiDAR points.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_point_return_analysis <- function(input, output=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_point_return_analysis"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar point stats
#'
#' @description Creates several rasters summarizing the distribution of LAS point data. When the input/output parameters are not specified, the tool works on all LAS files contained within the working directory.
#'
#' @param input Input LiDAR file.
#' @param resolution Output raster's grid resolution.
#' @param num_points Flag indicating whether or not to output the number of points (returns) raster.
#' @param num_pulses Flag indicating whether or not to output the number of pulses raster.
#' @param avg_points_per_pulse Flag indicating whether or not to output the average number of points (returns) per pulse raster.
#' @param z_range Flag indicating whether or not to output the elevation range raster.
#' @param intensity_range Flag indicating whether or not to output the intensity range raster.
#' @param predom_class Flag indicating whether or not to output the predominant classification raster.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_point_stats <- function(input, resolution=1.0, num_points=TRUE, num_pulses=FALSE, avg_points_per_pulse=TRUE, z_range=FALSE, intensity_range=FALSE, predom_class=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(resolution)) {
args <- paste(args, paste0("--resolution=", resolution))
}
if (num_points) {
args <- paste(args, "--num_points")
}
if (num_pulses) {
args <- paste(args, "--num_pulses")
}
if (avg_points_per_pulse) {
args <- paste(args, "--avg_points_per_pulse")
}
if (z_range) {
args <- paste(args, "--z_range")
}
if (intensity_range) {
args <- paste(args, "--intensity_range")
}
if (predom_class) {
args <- paste(args, "--predom_class")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_point_stats"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar ransac planes
#'
#' @description Performs a RANSAC analysis to identify points within a LiDAR point cloud that belong to linear planes.
#'
#' @param input Input LiDAR file.
#' @param output Output LiDAR file.
#' @param radius Search Radius.
#' @param num_iter Number of iterations.
#' @param num_samples Number of sample points on which to build the model.
#' @param threshold Threshold used to determine inlier points.
#' @param model_size Acceptable model size.
#' @param max_slope Maximum planar slope.
#' @param classify Classify points as ground (2) or off-ground (1).
#' @param last_returns Only include last- and only-return points.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_ransac_planes <- function(input, output, radius=2.0, num_iter=50, num_samples=5, threshold=0.35, model_size=8, max_slope=80.0, classify=FALSE, last_returns=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(radius)) {
args <- paste(args, paste0("--radius=", radius))
}
if (!is.null(num_iter)) {
args <- paste(args, paste0("--num_iter=", num_iter))
}
if (!is.null(num_samples)) {
args <- paste(args, paste0("--num_samples=", num_samples))
}
if (!is.null(threshold)) {
args <- paste(args, paste0("--threshold=", threshold))
}
if (!is.null(model_size)) {
args <- paste(args, paste0("--model_size=", model_size))
}
if (!is.null(max_slope)) {
args <- paste(args, paste0("--max_slope=", max_slope))
}
if (classify) {
args <- paste(args, "--classify")
}
if (last_returns) {
args <- paste(args, "--last_returns")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_ransac_planes"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar rbf interpolation
#'
#' @description Interpolates LAS files using a radial basis function (RBF) scheme. When the input/output parameters are not specified, the tool interpolates all LAS files contained within the working directory.
#'
#' @param input Input LiDAR file (including extension).
#' @param output Output raster file (including extension).
#' @param parameter Interpolation parameter; options are 'elevation' (default), 'intensity', 'class', 'return_number', 'number_of_returns', 'scan angle', 'rgb', 'user data'.
#' @param returns Point return types to include; options are 'all' (default), 'last', 'first'.
#' @param resolution Output raster's grid resolution.
#' @param num_points Number of points.
#' @param exclude_cls Optional exclude classes from interpolation; Valid class values range from 0 to 18, based on LAS specifications. Example, --exclude_cls='3,4,5,6,7,18'.
#' @param minz Optional minimum elevation for inclusion in interpolation.
#' @param maxz Optional maximum elevation for inclusion in interpolation.
#' @param func_type Radial basis function type; options are 'ThinPlateSpline' (default), 'PolyHarmonic', 'Gaussian', 'MultiQuadric', 'InverseMultiQuadric'.
#' @param poly_order Polynomial order; options are 'none' (default), 'constant', 'affine'.
#' @param weight Weight parameter used in basis function.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_rbf_interpolation <- function(input, output=NULL, parameter="elevation", returns="all", resolution=1.0, num_points=20, exclude_cls=NULL, minz=NULL, maxz=NULL, func_type="ThinPlateSpline", poly_order="none", weight=5, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!is.null(parameter)) {
args <- paste(args, paste0("--parameter=", parameter))
}
if (!is.null(returns)) {
args <- paste(args, paste0("--returns=", returns))
}
if (!is.null(resolution)) {
args <- paste(args, paste0("--resolution=", resolution))
}
if (!is.null(num_points)) {
args <- paste(args, paste0("--num_points=", num_points))
}
if (!is.null(exclude_cls)) {
args <- paste(args, paste0("--exclude_cls=", exclude_cls))
}
if (!is.null(minz)) {
args <- paste(args, paste0("--minz=", minz))
}
if (!is.null(maxz)) {
args <- paste(args, paste0("--maxz=", maxz))
}
if (!is.null(func_type)) {
args <- paste(args, paste0("--func_type=", func_type))
}
if (!is.null(poly_order)) {
args <- paste(args, paste0("--poly_order=", poly_order))
}
if (!is.null(weight)) {
args <- paste(args, paste0("--weight=", weight))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_rbf_interpolation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar remove duplicates
#'
#' @description Removes duplicate points from a LiDAR data set.
#'
#' @param input Input LiDAR file.
#' @param output Output LiDAR file.
#' @param include_z Include z-values in point comparison?.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_remove_duplicates <- function(input, output, include_z=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (include_z) {
args <- paste(args, "--include_z")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_remove_duplicates"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar remove outliers
#'
#' @description Removes outliers (high and low points) in a LiDAR point cloud.
#'
#' @param input Input LiDAR file.
#' @param output Output LiDAR file.
#' @param radius Search Radius.
#' @param elev_diff Max. elevation difference.
#' @param use_median Optional flag indicating whether to use the difference from median elevation rather than mean.
#' @param classify Classify points as ground (2) or off-ground (1).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_remove_outliers <- function(input, output, radius=2.0, elev_diff=50.0, use_median=FALSE, classify=TRUE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(radius)) {
args <- paste(args, paste0("--radius=", radius))
}
if (!is.null(elev_diff)) {
args <- paste(args, paste0("--elev_diff=", elev_diff))
}
if (use_median) {
args <- paste(args, "--use_median")
}
if (classify) {
args <- paste(args, "--classify")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_remove_outliers"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar rooftop analysis
#'
#' @description Identifies roof segments in a LiDAR point cloud.
#'
#' @param input Input LiDAR file.
#' @param buildings Input vector build footprint polygons file.
#' @param output Output vector polygon file.
#' @param radius Search Radius.
#' @param num_iter Number of iterations.
#' @param num_samples Number of sample points on which to build the model.
#' @param threshold Threshold used to determine inlier points (in elevation units).
#' @param model_size Acceptable model size, in points.
#' @param max_slope Maximum planar slope, in degrees.
#' @param norm_diff Maximum difference in normal vectors, in degrees.
#' @param azimuth Illumination source azimuth, in degrees.
#' @param altitude Illumination source altitude in degrees.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_rooftop_analysis <- function(buildings, output, input=NULL, radius=2.0, num_iter=50, num_samples=10, threshold=0.15, model_size=15, max_slope=65.0, norm_diff=10.0, azimuth=180.0, altitude=30.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--buildings=", wbt_file_path(buildings)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(input)) {
args <- paste(args, paste0("--input=", input))
}
if (!is.null(radius)) {
args <- paste(args, paste0("--radius=", radius))
}
if (!is.null(num_iter)) {
args <- paste(args, paste0("--num_iter=", num_iter))
}
if (!is.null(num_samples)) {
args <- paste(args, paste0("--num_samples=", num_samples))
}
if (!is.null(threshold)) {
args <- paste(args, paste0("--threshold=", threshold))
}
if (!is.null(model_size)) {
args <- paste(args, paste0("--model_size=", model_size))
}
if (!is.null(max_slope)) {
args <- paste(args, paste0("--max_slope=", max_slope))
}
if (!is.null(norm_diff)) {
args <- paste(args, paste0("--norm_diff=", norm_diff))
}
if (!is.null(azimuth)) {
args <- paste(args, paste0("--azimuth=", azimuth))
}
if (!is.null(altitude)) {
args <- paste(args, paste0("--altitude=", altitude))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_rooftop_analysis"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar segmentation
#'
#' @description Segments a LiDAR point cloud based on differences in the orientation of fitted planar surfaces and point proximity.
#'
#' @param input Input LiDAR file.
#' @param output Output LiDAR file.
#' @param radius Search Radius.
#' @param num_iter Number of iterations.
#' @param num_samples Number of sample points on which to build the model.
#' @param threshold Threshold used to determine inlier points.
#' @param model_size Acceptable model size.
#' @param max_slope Maximum planar slope.
#' @param norm_diff Maximum difference in normal vectors, in degrees.
#' @param maxzdiff Maximum difference in elevation (z units) between neighbouring points of the same segment.
#' @param classes Segments don't cross class boundaries.
#' @param ground Classify the largest segment as ground points?.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_segmentation <- function(input, output, radius=2.0, num_iter=50, num_samples=10, threshold=0.15, model_size=15, max_slope=80.0, norm_diff=10.0, maxzdiff=1.0, classes=FALSE, ground=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(radius)) {
args <- paste(args, paste0("--radius=", radius))
}
if (!is.null(num_iter)) {
args <- paste(args, paste0("--num_iter=", num_iter))
}
if (!is.null(num_samples)) {
args <- paste(args, paste0("--num_samples=", num_samples))
}
if (!is.null(threshold)) {
args <- paste(args, paste0("--threshold=", threshold))
}
if (!is.null(model_size)) {
args <- paste(args, paste0("--model_size=", model_size))
}
if (!is.null(max_slope)) {
args <- paste(args, paste0("--max_slope=", max_slope))
}
if (!is.null(norm_diff)) {
args <- paste(args, paste0("--norm_diff=", norm_diff))
}
if (!is.null(maxzdiff)) {
args <- paste(args, paste0("--maxzdiff=", maxzdiff))
}
if (classes) {
args <- paste(args, "--classes")
}
if (ground) {
args <- paste(args, "--ground")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_segmentation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar segmentation based filter
#'
#' @description Identifies ground points within LiDAR point clouds using a segmentation based approach.
#'
#' @param input Input LiDAR file.
#' @param output Output file.
#' @param radius Search Radius.
#' @param norm_diff Maximum difference in normal vectors, in degrees.
#' @param maxzdiff Maximum difference in elevation (z units) between neighbouring points of the same segment.
#' @param classify Classify points as ground (2) or off-ground (1).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_segmentation_based_filter <- function(input, output, radius=5.0, norm_diff=2.0, maxzdiff=1.0, classify=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(radius)) {
args <- paste(args, paste0("--radius=", radius))
}
if (!is.null(norm_diff)) {
args <- paste(args, paste0("--norm_diff=", norm_diff))
}
if (!is.null(maxzdiff)) {
args <- paste(args, paste0("--maxzdiff=", maxzdiff))
}
if (classify) {
args <- paste(args, "--classify")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_segmentation_based_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar shift
#'
#' @description Shifts the x,y,z coordinates of a LiDAR file.
#'
#' @param input Name of the input LiDAR points.
#' @param output Name of the output LiDAR points.
#' @param x_shift x-shift value, blank for none.
#' @param y_shift y-shift value, blank for none.
#' @param z_shift z-shift value, blank for none.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_shift <- function(input, output, x_shift="", y_shift="", z_shift="", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(x_shift)) {
args <- paste(args, paste0("--x_shift=", x_shift))
}
if (!is.null(y_shift)) {
args <- paste(args, paste0("--y_shift=", y_shift))
}
if (!is.null(z_shift)) {
args <- paste(args, paste0("--z_shift=", z_shift))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_shift"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar sibson interpolation
#'
#' @description This tool interpolates one or more LiDAR tiles using Sibson's natural neighbour method.
#'
#' @param input Name of the input LiDAR points (leave blank to use all files in WorkingDirectory.
#' @param output Output raster file (including extension).
#' @param parameter Interpolation parameter; options are 'elevation' (default), 'intensity', 'class', 'return_number', 'number_of_returns', 'scan angle', 'user_data'.
#' @param returns Point return types to include; options are 'all' (default), 'last', 'first'.
#' @param resolution Output raster's grid resolution.
#' @param exclude_cls Optional exclude classes from interpolation; Valid class values range from 0 to 18, based on LAS specifications. Example, --exclude_cls='3,4,5,6,7,18'.
#' @param minz Optional minimum elevation for inclusion in interpolation.
#' @param maxz Optional maximum elevation for inclusion in interpolation.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_sibson_interpolation <- function(input, output=NULL, parameter="elevation", returns="all", resolution=1.0, exclude_cls=NULL, minz=NULL, maxz=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!is.null(parameter)) {
args <- paste(args, paste0("--parameter=", parameter))
}
if (!is.null(returns)) {
args <- paste(args, paste0("--returns=", returns))
}
if (!is.null(resolution)) {
args <- paste(args, paste0("--resolution=", resolution))
}
if (!is.null(exclude_cls)) {
args <- paste(args, paste0("--exclude_cls=", exclude_cls))
}
if (!is.null(minz)) {
args <- paste(args, paste0("--minz=", minz))
}
if (!is.null(maxz)) {
args <- paste(args, paste0("--maxz=", maxz))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_sibson_interpolation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar sort by time
#'
#' @description This tool sorts the points in a LiDAR file by the GPS time.
#'
#' @param input Name of the input LiDAR points.
#' @param output Name of the output LiDAR points.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_sort_by_time <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_sort_by_time"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar thin
#'
#' @description Thins a LiDAR point cloud, reducing point density.
#'
#' @param input Input LiDAR file.
#' @param output Output LiDAR file.
#' @param resolution The size of the square area used to evaluate nearby points in the LiDAR data.
#' @param method Point selection method; options are 'first', 'last', 'lowest' (default), 'highest', 'nearest'.
#' @param save_filtered Save filtered points to separate file?.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_thin <- function(input, output, resolution=2.0, method="lowest", save_filtered=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(resolution)) {
args <- paste(args, paste0("--resolution=", resolution))
}
if (!is.null(method)) {
args <- paste(args, paste0("--method=", method))
}
if (save_filtered) {
args <- paste(args, "--save_filtered")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_thin"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar thin high density
#'
#' @description Thins points from high density areas within a LiDAR point cloud.
#'
#' @param input Input LiDAR file.
#' @param output Output LiDAR file.
#' @param resolution Output raster's grid resolution.
#' @param density Max. point density (points / m^3).
#' @param save_filtered Save filtered points to separate file?.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_thin_high_density <- function(input, output, density, resolution=1.0, save_filtered=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--density=", wbt_file_path(density)))
if (!is.null(resolution)) {
args <- paste(args, paste0("--resolution=", resolution))
}
if (save_filtered) {
args <- paste(args, "--save_filtered")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_thin_high_density"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar tile
#'
#' @description Tiles a LiDAR LAS file into multiple LAS files.
#'
#' @param input Input LiDAR file.
#' @param width Width of tiles in the X dimension; default 1000.0.
#' @param height Height of tiles in the Y dimension.
#' @param origin_x Origin point X coordinate for tile grid.
#' @param origin_y Origin point Y coordinate for tile grid.
#' @param min_points Minimum number of points contained in a tile for it to be saved.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_tile <- function(input, width=1000.0, height=1000.0, origin_x=0.0, origin_y=0.0, min_points=2, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(width)) {
args <- paste(args, paste0("--width=", width))
}
if (!is.null(height)) {
args <- paste(args, paste0("--height=", height))
}
if (!is.null(origin_x)) {
args <- paste(args, paste0("--origin_x=", origin_x))
}
if (!is.null(origin_y)) {
args <- paste(args, paste0("--origin_y=", origin_y))
}
if (!is.null(min_points)) {
args <- paste(args, paste0("--min_points=", min_points))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_tile"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar tile footprint
#'
#' @description Creates a vector polygon of the convex hull of a LiDAR point cloud. When the input/output parameters are not specified, the tool works with all LAS files contained within the working directory.
#'
#' @param input Input LiDAR file.
#' @param output Output vector polygon file.
#' @param hull Identify the convex hull around points.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_tile_footprint <- function(input, output, hull=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (hull) {
args <- paste(args, "--hull")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_tile_footprint"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar tin gridding
#'
#' @description Creates a raster grid based on a Delaunay triangular irregular network (TIN) fitted to LiDAR points.
#'
#' @param input Input LiDAR file (including extension).
#' @param output Output raster file (including extension).
#' @param parameter Interpolation parameter; options are 'elevation' (default), 'intensity', 'class', 'return_number', 'number_of_returns', 'scan angle', 'rgb', 'user data'.
#' @param returns Point return types to include; options are 'all' (default), 'last', 'first'.
#' @param resolution Output raster's grid resolution.
#' @param exclude_cls Optional exclude classes from interpolation; Valid class values range from 0 to 18, based on LAS specifications. Example, --exclude_cls='3,4,5,6,7,18'.
#' @param minz Optional minimum elevation for inclusion in interpolation.
#' @param maxz Optional maximum elevation for inclusion in interpolation.
#' @param max_triangle_edge_length Optional maximum triangle edge length; triangles larger than this size will not be gridded.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_tin_gridding <- function(input, output=NULL, parameter="elevation", returns="all", resolution=1.0, exclude_cls="7,18", minz=NULL, maxz=NULL, max_triangle_edge_length=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!is.null(parameter)) {
args <- paste(args, paste0("--parameter=", parameter))
}
if (!is.null(returns)) {
args <- paste(args, paste0("--returns=", returns))
}
if (!is.null(resolution)) {
args <- paste(args, paste0("--resolution=", resolution))
}
if (!is.null(exclude_cls)) {
args <- paste(args, paste0("--exclude_cls=", exclude_cls))
}
if (!is.null(minz)) {
args <- paste(args, paste0("--minz=", minz))
}
if (!is.null(maxz)) {
args <- paste(args, paste0("--maxz=", maxz))
}
if (!is.null(max_triangle_edge_length)) {
args <- paste(args, paste0("--max_triangle_edge_length=", max_triangle_edge_length))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_tin_gridding"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Lidar tophat transform
#'
#' @description Performs a white top-hat transform on a Lidar dataset; as an estimate of height above ground, this is useful for modelling the vegetation canopy.
#'
#' @param input Input LiDAR file.
#' @param output Output LiDAR file.
#' @param radius Search Radius.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_lidar_tophat_transform <- function(input, output, radius=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(radius)) {
args <- paste(args, paste0("--radius=", radius))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "lidar_tophat_transform"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Modify lidar
#'
#' @description Modify points within a LiDAR point cloud based on point properties.
#'
#' @param input Name of the input LiDAR points.
#' @param output Name of the output LiDAR points.
#' @param statement Modify statement e.g. x += 5000.0.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_modify_lidar <- function(input, output=NULL, statement="", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!is.null(statement)) {
args <- paste(args, paste0("--statement=", statement))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "modify_lidar"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Normal vectors
#'
#' @description Calculates normal vectors for points within a LAS file and stores these data (XYZ vector components) in the RGB field.
#'
#' @param input Input LiDAR file.
#' @param output Output LiDAR file.
#' @param radius Search Radius.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_normal_vectors <- function(input, output, radius=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(radius)) {
args <- paste(args, paste0("--radius=", radius))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "normal_vectors"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Normalize lidar
#'
#' @description Normalizes a LiDAR point cloud.
#'
#' @param input Name of the input LiDAR file.
#' @param output Name of the output LiDAR file.
#' @param dtm Name of the input digital terrain model (DTM) raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_normalize_lidar <- function(input, output, dtm, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--dtm=", wbt_file_path(dtm)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "normalize_lidar"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Recover flightline info
#'
#' @description Associates LiDAR points by their flightlines.
#'
#' @param input Name of the input LiDAR points.
#' @param output Name of the output LiDAR points.
#' @param max_time_diff Maximum in-flightline time difference (seconds).
#' @param pt_src_id Add flightline information to the point source ID.
#' @param user_data Add flightline information to the user data.
#' @param rgb Add flightline information to the RGB colour data.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_recover_flightline_info <- function(input, output, max_time_diff=5.0, pt_src_id=FALSE, user_data=FALSE, rgb=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(max_time_diff)) {
args <- paste(args, paste0("--max_time_diff=", max_time_diff))
}
if (pt_src_id) {
args <- paste(args, "--pt_src_id")
}
if (user_data) {
args <- paste(args, "--user_data")
}
if (rgb) {
args <- paste(args, "--rgb")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "recover_flightline_info"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Select tiles by polygon
#'
#' @description Copies LiDAR tiles overlapping with a polygon into an output directory.
#'
#' @param indir Input LAS file source directory.
#' @param outdir Output directory into which LAS files within the polygon are copied.
#' @param polygons Input vector polygons file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_select_tiles_by_polygon <- function(indir, outdir, polygons, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--indir=", wbt_file_path(indir)))
args <- paste(args, paste0("--outdir=", wbt_file_path(outdir)))
args <- paste(args, paste0("--polygons=", wbt_file_path(polygons)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "select_tiles_by_polygon"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Sort lidar
#'
#' @description Sorts LiDAR points based on their properties.
#'
#' @param input Name of the input LiDAR points.
#' @param output Name of the output LiDAR points.
#' @param criteria Sort criteria e.g. 'x 50.0, y 50.0, z'; criteria may include x, y, z, intensity, class, user_data, point_source_id, and scan_angle.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_sort_lidar <- function(input, output=NULL, criteria="", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!is.null(criteria)) {
args <- paste(args, paste0("--criteria=", criteria))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "sort_lidar"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Split lidar
#'
#' @description Splits LiDAR points up into a series of new files based on their properties.
#'
#' @param input Name of the input LiDAR points.
#' @param criterion Criterion on which to base the split of the input file. Options include 'num_pts, 'x', 'y', 'z', intensity, 'class', 'user_data', 'point_source_id', 'scan_angle', 'time'.
#' @param interval Interval.
#' @param min_pts Minimum number of points in an output file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_split_lidar <- function(input, criterion="num_pts", interval="", min_pts=5, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(criterion)) {
args <- paste(args, paste0("--criterion=", criterion))
}
if (!is.null(interval)) {
args <- paste(args, paste0("--interval=", interval))
}
if (!is.null(min_pts)) {
args <- paste(args, paste0("--min_pts=", min_pts))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "split_lidar"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Zlidar to las
#'
#' @description Converts one or more zlidar files into the LAS data format.
#'
#' @param inputs Input ZLidar files.
#' @param outdir Output directory into which zlidar files are created. If unspecified, it is assumed to be the same as the inputs.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords LiDARTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_zlidar_to_las <- function(inputs=NULL, outdir=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
if (!is.null(inputs)) {
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
}
if (!is.null(outdir)) {
args <- paste(args, paste0("--outdir=", outdir))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "zlidar_to_las"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
|
/scratch/gouwar.j/cran-all/cranData/whitebox/R/lidar_analysis.R
|
#' @title Dbscan
#'
#' @description Performs a DBSCAN-based unsupervised clustering operation.
#'
#' @param inputs Names of the input rasters.
#' @param scaling Scaling method for predictors. Options include 'None', 'Normalize', and 'Standardize'.
#' @param output Name of the output raster file.
#' @param search_dist Search-distance parameter.
#' @param min_points Minimum point density needed to define 'core' point in cluster.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MachineLearning
#'
#' @return Returns the tool text outputs.
#' @export
wbt_dbscan <- function(inputs, output, scaling="Normalize", search_dist=0.01, min_points=5, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(scaling)) {
args <- paste(args, paste0("--scaling=", scaling))
}
if (!is.null(search_dist)) {
args <- paste(args, paste0("--search_dist=", search_dist))
}
if (!is.null(min_points)) {
args <- paste(args, paste0("--min_points=", min_points))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "dbscan"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title K means clustering
#'
#' @description Performs a k-means clustering operation on a multi-spectral dataset.
#'
#' @param inputs Input raster file paths, concatenated with `","` or `";"`. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param out_html Output HTML report file.
#' @param classes Number of classes.
#' @param max_iterations Maximum number of iterations.
#' @param class_change Minimum percent of cells changed between iterations before completion.
#' @param initialize How to initialize cluster centres?.
#' @param min_class_size Minimum class size, in pixels.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MachineLearning
#'
#' @return Returns the tool text outputs.
#' @export
wbt_k_means_clustering <- function(inputs, output, classes, out_html=NULL, max_iterations=10, class_change=2.0, initialize="diagonal", min_class_size=10, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--classes=", wbt_file_path(classes)))
if (!is.null(out_html)) {
args <- paste(args, paste0("--out_html=", out_html))
}
if (!is.null(max_iterations)) {
args <- paste(args, paste0("--max_iterations=", max_iterations))
}
if (!is.null(class_change)) {
args <- paste(args, paste0("--class_change=", class_change))
}
if (!is.null(initialize)) {
args <- paste(args, paste0("--initialize=", initialize))
}
if (!is.null(min_class_size)) {
args <- paste(args, paste0("--min_class_size=", min_class_size))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "k_means_clustering"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Knn classification
#'
#' @description Performs a supervised k-nearest neighbour classification using training site polygons/points and predictor rasters.
#'
#' @param inputs Names of the input predictor rasters.
#' @param scaling Scaling method for predictors. Options include 'None', 'Normalize', and 'Standardize'.
#' @param training Name of the input training site polygons/points shapefile.
#' @param field Name of the attribute containing class name data.
#' @param output Name of the output raster file.
#' @param k k-parameter, which determines the number of nearest neighbours used.
#' @param clip Perform training data clipping to remove outlier pixels?.
#' @param test_proportion The proportion of the dataset to include in the test split; default is 0.2.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MachineLearning
#'
#' @return Returns the tool text outputs.
#' @export
wbt_knn_classification <- function(inputs, training, field, scaling="Normalize", output=NULL, k=5, clip=TRUE, test_proportion=0.2, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--training=", wbt_file_path(training)))
args <- paste(args, paste0("--field=", wbt_file_path(field)))
if (!is.null(scaling)) {
args <- paste(args, paste0("--scaling=", scaling))
}
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!is.null(k)) {
args <- paste(args, paste0("--k=", k))
}
if (clip) {
args <- paste(args, "--clip")
}
if (!is.null(test_proportion)) {
args <- paste(args, paste0("--test_proportion=", test_proportion))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "knn_classification"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Knn regression
#'
#' @description Performs a supervised k-nearest neighbour regression using training site points and predictor rasters.
#'
#' @param inputs Names of the input predictor rasters.
#' @param scaling Scaling method for predictors. Options include 'None', 'Normalize', and 'Standardize'.
#' @param training Name of the input training site points Shapefile.
#' @param field Name of the attribute containing response variable name data.
#' @param output Name of the output raster file.
#' @param k k-parameter, which determines the number of nearest neighbours used.
#' @param weight Use distance weighting?.
#' @param test_proportion The proportion of the dataset to include in the test split; default is 0.2.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MachineLearning
#'
#' @return Returns the tool text outputs.
#' @export
wbt_knn_regression <- function(inputs, training, field, scaling="Normalize", output=NULL, k=5, weight=TRUE, test_proportion=0.2, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--training=", wbt_file_path(training)))
args <- paste(args, paste0("--field=", wbt_file_path(field)))
if (!is.null(scaling)) {
args <- paste(args, paste0("--scaling=", scaling))
}
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!is.null(k)) {
args <- paste(args, paste0("--k=", k))
}
if (weight) {
args <- paste(args, "--weight")
}
if (!is.null(test_proportion)) {
args <- paste(args, paste0("--test_proportion=", test_proportion))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "knn_regression"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Logistic regression
#'
#' @description Performs a logistic regression analysis using training site polygons/points and predictor rasters.
#'
#' @param inputs Names of the input predictor rasters.
#' @param scaling Scaling method for predictors. Options include 'None', 'Normalize', and 'Standardize'.
#' @param training Name of the input training site polygons/points shapefile.
#' @param field Name of the attribute containing class data.
#' @param output Name of the output raster file.
#' @param test_proportion The proportion of the dataset to include in the test split; default is 0.2.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MachineLearning
#'
#' @return Returns the tool text outputs.
#' @export
wbt_logistic_regression <- function(inputs, training, field, scaling="Normalize", output=NULL, test_proportion=0.2, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--training=", wbt_file_path(training)))
args <- paste(args, paste0("--field=", wbt_file_path(field)))
if (!is.null(scaling)) {
args <- paste(args, paste0("--scaling=", scaling))
}
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!is.null(test_proportion)) {
args <- paste(args, paste0("--test_proportion=", test_proportion))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "logistic_regression"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Modified k means clustering
#'
#' @description Performs a modified k-means clustering operation on a multi-spectral dataset.
#'
#' @param inputs Input raster file paths, concatenated with `","` or `";"`. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param out_html Output HTML report file.
#' @param start_clusters Initial number of clusters.
#' @param merge_dist Cluster merger distance.
#' @param max_iterations Maximum number of iterations.
#' @param class_change Minimum percent of cells changed between iterations before completion.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MachineLearning
#'
#' @return Returns the tool text outputs.
#' @export
wbt_modified_k_means_clustering <- function(inputs, output, out_html=NULL, start_clusters=1000, merge_dist=NULL, max_iterations=10, class_change=2.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(out_html)) {
args <- paste(args, paste0("--out_html=", out_html))
}
if (!is.null(start_clusters)) {
args <- paste(args, paste0("--start_clusters=", start_clusters))
}
if (!is.null(merge_dist)) {
args <- paste(args, paste0("--merge_dist=", merge_dist))
}
if (!is.null(max_iterations)) {
args <- paste(args, paste0("--max_iterations=", max_iterations))
}
if (!is.null(class_change)) {
args <- paste(args, paste0("--class_change=", class_change))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "modified_k_means_clustering"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Random forest classification
#'
#' @description Performs a supervised random forest classification using training site polygons/points and predictor rasters.
#'
#' @param inputs Names of the input predictor rasters.
#' @param training Name of the input training site polygons/points shapefile.
#' @param field Name of the attribute containing class data.
#' @param output Name of the output raster file.
#' @param split_criterion Split criterion to use when building a tree. Options include 'Gini', 'Entropy', and 'ClassificationError'.
#' @param n_trees The number of trees in the forest.
#' @param min_samples_leaf The minimum number of samples required to be at a leaf node.
#' @param min_samples_split The minimum number of samples required to split an internal node.
#' @param test_proportion The proportion of the dataset to include in the test split; default is 0.2.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MachineLearning
#'
#' @return Returns the tool text outputs.
#' @export
wbt_random_forest_classification <- function(inputs, training, field, output=NULL, split_criterion="Gini", n_trees=500, min_samples_leaf=1, min_samples_split=2, test_proportion=0.2, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--training=", wbt_file_path(training)))
args <- paste(args, paste0("--field=", wbt_file_path(field)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!is.null(split_criterion)) {
args <- paste(args, paste0("--split_criterion=", split_criterion))
}
if (!is.null(n_trees)) {
args <- paste(args, paste0("--n_trees=", n_trees))
}
if (!is.null(min_samples_leaf)) {
args <- paste(args, paste0("--min_samples_leaf=", min_samples_leaf))
}
if (!is.null(min_samples_split)) {
args <- paste(args, paste0("--min_samples_split=", min_samples_split))
}
if (!is.null(test_proportion)) {
args <- paste(args, paste0("--test_proportion=", test_proportion))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "random_forest_classification"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Random forest regression
#'
#' @description Performs a random forest regression analysis using training site data and predictor rasters.
#'
#' @param inputs Names of the input predictor rasters.
#' @param training Name of the input training site points shapefile.
#' @param field Name of the attribute containing response variable name data.
#' @param output Name of the output raster file. This parameter is optional. When unspecified, the tool will only build the model. When specified, the tool will use the built model and predictor rasters to perform a spatial prediction.
#' @param n_trees The number of trees in the forest.
#' @param min_samples_leaf The minimum number of samples required to be at a leaf node.
#' @param min_samples_split The minimum number of samples required to split an internal node.
#' @param test_proportion The proportion of the dataset to include in the test split; default is 0.2.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MachineLearning
#'
#' @return Returns the tool text outputs.
#' @export
wbt_random_forest_regression <- function(inputs, training, field, output=NULL, n_trees=100, min_samples_leaf=1, min_samples_split=2, test_proportion=0.2, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--training=", wbt_file_path(training)))
args <- paste(args, paste0("--field=", wbt_file_path(field)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!is.null(n_trees)) {
args <- paste(args, paste0("--n_trees=", n_trees))
}
if (!is.null(min_samples_leaf)) {
args <- paste(args, paste0("--min_samples_leaf=", min_samples_leaf))
}
if (!is.null(min_samples_split)) {
args <- paste(args, paste0("--min_samples_split=", min_samples_split))
}
if (!is.null(test_proportion)) {
args <- paste(args, paste0("--test_proportion=", test_proportion))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "random_forest_regression"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Svm classification
#'
#' @description Performs an SVM binary classification using training site polygons/points and multiple input images.
#'
#' @param inputs Names of the input predictor rasters.
#' @param scaling Scaling method for predictors. Options include 'None', 'Normalize', and 'Standardize'.
#' @param training Name of the input training site polygons/points Shapefile.
#' @param field Name of the attribute containing class data.
#' @param output Name of the output raster file.
#' @param c c-value, the regularization parameter.
#' @param gamma Gamma parameter used in setting the RBF (Gaussian) kernel function.
#' @param tolerance The tolerance parameter used in determining the stopping condition.
#' @param test_proportion The proportion of the dataset to include in the test split; default is 0.2.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MachineLearning
#'
#' @return Returns the tool text outputs.
#' @export
wbt_svm_classification <- function(inputs, training, field, scaling="Normalize", output=NULL, c=200.0, gamma=50.0, tolerance=0.1, test_proportion=0.2, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--training=", wbt_file_path(training)))
args <- paste(args, paste0("--field=", wbt_file_path(field)))
if (!is.null(scaling)) {
args <- paste(args, paste0("--scaling=", scaling))
}
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!is.null(c)) {
args <- paste(args, paste0("--c=", c))
}
if (!is.null(gamma)) {
args <- paste(args, paste0("--gamma=", gamma))
}
if (!is.null(tolerance)) {
args <- paste(args, paste0("--tolerance=", tolerance))
}
if (!is.null(test_proportion)) {
args <- paste(args, paste0("--test_proportion=", test_proportion))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "svm_classification"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Svm regression
#'
#' @description Performs a supervised SVM regression analysis using training site points and predictor rasters.
#'
#' @param inputs Names of the input predictor rasters.
#' @param scaling Scaling method for predictors. Options include 'None', 'Normalize', and 'Standardize'.
#' @param training Name of the input training site points Shapefile.
#' @param field Name of the attribute containing class data.
#' @param output Name of the output raster file.
#' @param c c-value, the regularization parameter.
#' @param eps Epsilon in the epsilon-SVR model.
#' @param gamma Gamma parameter used in setting the RBF (Gaussian) kernel function.
#' @param test_proportion The proportion of the dataset to include in the test split; default is 0.2.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MachineLearning
#'
#' @return Returns the tool text outputs.
#' @export
wbt_svm_regression <- function(inputs, training, field, scaling="Normalize", output=NULL, c=50.0, eps=10.0, gamma=0.5, test_proportion=0.2, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--training=", wbt_file_path(training)))
args <- paste(args, paste0("--field=", wbt_file_path(field)))
if (!is.null(scaling)) {
args <- paste(args, paste0("--scaling=", scaling))
}
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!is.null(c)) {
args <- paste(args, paste0("--c=", c))
}
if (!is.null(eps)) {
args <- paste(args, paste0("--eps=", eps))
}
if (!is.null(gamma)) {
args <- paste(args, paste0("--gamma=", gamma))
}
if (!is.null(test_proportion)) {
args <- paste(args, paste0("--test_proportion=", test_proportion))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "svm_regression"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
|
/scratch/gouwar.j/cran-all/cranData/whitebox/R/machine_learning.R
|
#' @title And
#'
#' @description Performs a logical AND operator on two Boolean raster images.
#'
#' @param input1 Input raster file path. See `wbt_file_path()` for details.
#' @param input2 Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_and <- function(input1, input2, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "and"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Not
#'
#' @description Performs a logical NOT operator on two Boolean raster images.
#'
#' @param input1 Input raster file path. See `wbt_file_path()` for details.
#' @param input2 Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_not <- function(input1, input2, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "not"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Or
#'
#' @description Performs a logical OR operator on two Boolean raster images.
#'
#' @param input1 Input raster file path. See `wbt_file_path()` for details.
#' @param input2 Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_or <- function(input1, input2, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "or"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Absolute value
#'
#' @description Calculates the absolute value of every cell in a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_absolute_value <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "absolute_value"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Add
#'
#' @description Performs an addition operation on two rasters or a raster and a constant value.
#'
#' @param input1 Input raster file or constant value.
#' @param input2 Input raster file or constant value.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_add <- function(input1, input2, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "add"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Anova
#'
#' @description Performs an analysis of variance (ANOVA) test on a raster dataset.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param features Feature definition (or class) raster.
#' @param output Output HTML file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_anova <- function(input, features, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--features=", wbt_file_path(features)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "anova"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Arc cos
#'
#' @description Returns the inverse cosine (arccos) of each values in a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_arc_cos <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "arc_cos"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Arc sin
#'
#' @description Returns the inverse sine (arcsin) of each values in a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_arc_sin <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "arc_sin"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Arc tan
#'
#' @description Returns the inverse tangent (arctan) of each values in a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_arc_tan <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "arc_tan"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Arcosh
#'
#' @description Returns the inverse hyperbolic cosine (arcosh) of each values in a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_arcosh <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "arcosh"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Arsinh
#'
#' @description Returns the inverse hyperbolic sine (arsinh) of each values in a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_arsinh <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "arsinh"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Artanh
#'
#' @description Returns the inverse hyperbolic tangent (arctanh) of each values in a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_artanh <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "artanh"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Atan2
#'
#' @description Returns the 2-argument inverse tangent (atan2).
#'
#' @param input_y Input y raster file or constant value (rise).
#' @param input_x Input x raster file or constant value (run).
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_atan2 <- function(input_y, input_x, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input_y=", wbt_file_path(input_y)))
args <- paste(args, paste0("--input_x=", wbt_file_path(input_x)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "atan2"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Attribute correlation
#'
#' @description Performs a correlation analysis on attribute fields from a vector database.
#'
#' @param input Input vector file path. See `wbt_file_path()` for details.
#' @param output Output HTML file (default name will be based on input file if unspecified).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_attribute_correlation <- function(input, output=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "attribute_correlation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Attribute correlation neighbourhood analysis
#'
#' @description Performs a correlation on two input vector attributes within a neighbourhood search windows.
#'
#' @param input Input vector file path. See `wbt_file_path()` for details.
#' @param field1 First input field name (dependent variable) in attribute table.
#' @param field2 Second input field name (independent variable) in attribute table.
#' @param radius Search Radius (in map units).
#' @param min_points Minimum number of points.
#' @param stat Correlation type; one of 'pearson' (default) and 'spearman'.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_attribute_correlation_neighbourhood_analysis <- function(input, field1, field2, radius=NULL, min_points=NULL, stat="pearson", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--field1=", wbt_file_path(field1)))
args <- paste(args, paste0("--field2=", wbt_file_path(field2)))
if (!is.null(radius)) {
args <- paste(args, paste0("--radius=", radius))
}
if (!is.null(min_points)) {
args <- paste(args, paste0("--min_points=", min_points))
}
if (!is.null(stat)) {
args <- paste(args, paste0("--stat=", stat))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "attribute_correlation_neighbourhood_analysis"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Attribute histogram
#'
#' @description Creates a histogram for the field values of a vector's attribute table.
#'
#' @param input Input vector file path. See `wbt_file_path()` for details.
#' @param field Input field name in attribute table.
#' @param output Output HTML file (default name will be based on input file if unspecified).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_attribute_histogram <- function(input, field, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--field=", wbt_file_path(field)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "attribute_histogram"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Attribute scattergram
#'
#' @description Creates a scattergram for two field values of a vector's attribute table.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param fieldx Input field name in attribute table for the x-axis.
#' @param fieldy Input field name in attribute table for the y-axis.
#' @param output Output HTML file (default name will be based on input file if unspecified).
#' @param trendline Draw the trendline.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_attribute_scattergram <- function(input, fieldx, fieldy, output, trendline=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--fieldx=", wbt_file_path(fieldx)))
args <- paste(args, paste0("--fieldy=", wbt_file_path(fieldy)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (trendline) {
args <- paste(args, "--trendline")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "attribute_scattergram"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Ceil
#'
#' @description Returns the smallest (closest to negative infinity) value that is greater than or equal to the values in a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_ceil <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "ceil"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Conditional evaluation
#'
#' @description Performs a conditional evaluation (if-then-else) operation on a raster.
#'
#' @param input Name of the input raster file.
#' @param statement Conditional statement e.g. value > 35.0. This statement must be a valid Rust statement.
#' @param true Value where condition evaluates TRUE (input raster or constant value).
#' @param false Value where condition evaluates FALSE (input raster or constant value).
#' @param output Name of the output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_conditional_evaluation <- function(input, output, statement="", true=NULL, false=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(statement)) {
args <- paste(args, paste0("--statement=", statement))
}
if (!is.null(true)) {
args <- paste(args, paste0("--true=", true))
}
if (!is.null(false)) {
args <- paste(args, paste0("--false=", false))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "conditional_evaluation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Conditioned latin hypercube
#'
#' @description Implements conditioned Latin Hypercube sampling.
#'
#' @param inputs Name of the input raster file.
#' @param output Output shapefile.
#' @param samples Number of sample sites returned.
#' @param iterations Maximum iterations (if stopping criteria not reached).
#' @param seed Seed for RNG consistency.
#' @param prob Probability of random resample or resampling worst strata between `[0,1]`.
#' @param threshold Objective function values below the theshold stop the resampling iterations.
#' @param temp Initial annealing temperature between `[0,1]`.
#' @param temp_decay Annealing temperature decay proportion between `[0,1]`. Reduce temperature by this proportion each annealing cycle.
#' @param cycle Number of iterations before decaying annealing temperature.
#' @param average Weight the continuous objective funtion by the 1/N contributing strata.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_conditioned_latin_hypercube <- function(inputs, output, samples=500, iterations=25000, seed=NULL, prob=0.5, threshold=NULL, temp=1.0, temp_decay=0.05, cycle=10, average=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(samples)) {
args <- paste(args, paste0("--samples=", samples))
}
if (!is.null(iterations)) {
args <- paste(args, paste0("--iterations=", iterations))
}
if (!is.null(seed)) {
args <- paste(args, paste0("--seed=", seed))
}
if (!is.null(prob)) {
args <- paste(args, paste0("--prob=", prob))
}
if (!is.null(threshold)) {
args <- paste(args, paste0("--threshold=", threshold))
}
if (!is.null(temp)) {
args <- paste(args, paste0("--temp=", temp))
}
if (!is.null(temp_decay)) {
args <- paste(args, paste0("--temp_decay=", temp_decay))
}
if (!is.null(cycle)) {
args <- paste(args, paste0("--cycle=", cycle))
}
if (average) {
args <- paste(args, "--average")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "conditioned_latin_hypercube"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Cos
#'
#' @description Returns the cosine (cos) of each values in a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_cos <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "cos"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Cosh
#'
#' @description Returns the hyperbolic cosine (cosh) of each values in a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_cosh <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "cosh"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Crispness index
#'
#' @description Calculates the Crispness Index, which is used to quantify how crisp (or conversely how fuzzy) a probability image is.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Optional output html file (default name will be based on input file if unspecified).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_crispness_index <- function(input, output=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "crispness_index"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Cross tabulation
#'
#' @description Performs a cross-tabulation on two categorical images.
#'
#' @param input1 Input raster file 1.
#' @param input2 Input raster file 1.
#' @param output Output HTML file (default name will be based on input file if unspecified).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_cross_tabulation <- function(input1, input2, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "cross_tabulation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Cumulative distribution
#'
#' @description Converts a raster image to its cumulative distribution function.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_cumulative_distribution <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "cumulative_distribution"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Decrement
#'
#' @description Decreases the values of each grid cell in an input raster by 1.0 (see also InPlaceSubtract).
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_decrement <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "decrement"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Divide
#'
#' @description Performs a division operation on two rasters or a raster and a constant value.
#'
#' @param input1 Input raster file or constant value.
#' @param input2 Input raster file or constant value.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_divide <- function(input1, input2, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "divide"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Equal to
#'
#' @description Performs a equal-to comparison operation on two rasters or a raster and a constant value.
#'
#' @param input1 Input raster file or constant value.
#' @param input2 Input raster file or constant value.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_equal_to <- function(input1, input2, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "equal_to"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Exp
#'
#' @description Returns the exponential (base e) of values in a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_exp <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "exp"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Exp2
#'
#' @description Returns the exponential (base 2) of values in a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_exp2 <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "exp2"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Floor
#'
#' @description Returns the largest (closest to positive infinity) value that is less than or equal to the values in a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_floor <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "floor"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Greater than
#'
#' @description Performs a greater-than comparison operation on two rasters or a raster and a constant value.
#'
#' @param input1 Input raster file or constant value.
#' @param input2 Input raster file or constant value.
#' @param output Output raster file.
#' @param incl_equals Perform a greater-than-or-equal-to operation.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_greater_than <- function(input1, input2, output, incl_equals=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (incl_equals) {
args <- paste(args, "--incl_equals")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "greater_than"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Image autocorrelation
#'
#' @description Performs Moran's I analysis on two or more input images.
#'
#' @param inputs Input raster file paths, concatenated with `","` or `";"`. See `wbt_file_path()` for details.
#' @param contiguity Contiguity type.
#' @param output Output HTML file (default name will be based on input file if unspecified).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_image_autocorrelation <- function(inputs, output, contiguity="Rook", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(contiguity)) {
args <- paste(args, paste0("--contiguity=", contiguity))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "image_autocorrelation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Image correlation
#'
#' @description Performs image correlation on two or more input images.
#'
#' @param inputs Input raster file paths, concatenated with `","` or `";"`. See `wbt_file_path()` for details.
#' @param output Output HTML file (default name will be based on input file if unspecified).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_image_correlation <- function(inputs, output=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "image_correlation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Image correlation neighbourhood analysis
#'
#' @description Performs image correlation on two input images neighbourhood search windows.
#'
#' @param input1 Input raster file path. See `wbt_file_path()` for details.
#' @param input2 Input raster file path. See `wbt_file_path()` for details.
#' @param output1 Output correlation (r-value or rho) raster file.
#' @param output2 Output significance (p-value) raster file.
#' @param filter Size of the filter kernel.
#' @param stat Correlation type; one of 'pearson' (default) and 'spearman'.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_image_correlation_neighbourhood_analysis <- function(input1, input2, output1, output2, filter=11, stat="pearson", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output1=", wbt_file_path(output1)))
args <- paste(args, paste0("--output2=", wbt_file_path(output2)))
if (!is.null(filter)) {
args <- paste(args, paste0("--filter=", filter))
}
if (!is.null(stat)) {
args <- paste(args, paste0("--stat=", stat))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "image_correlation_neighbourhood_analysis"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Image regression
#'
#' @description Performs image regression analysis on two input images.
#'
#' @param input1 Input raster file (independent variable, X).
#' @param input2 Input raster file (dependent variable, Y).
#' @param output Output HTML file for regression summary report.
#' @param out_residuals Output raster regression residual file.
#' @param standardize Optional flag indicating whether to standardize the residuals map.
#' @param scattergram Optional flag indicating whether to output a scattergram.
#' @param num_samples Number of samples used to create scattergram.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_image_regression <- function(input1, input2, output, out_residuals=NULL, standardize=FALSE, scattergram=FALSE, num_samples=1000, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(out_residuals)) {
args <- paste(args, paste0("--out_residuals=", out_residuals))
}
if (standardize) {
args <- paste(args, "--standardize")
}
if (scattergram) {
args <- paste(args, "--scattergram")
}
if (!is.null(num_samples)) {
args <- paste(args, paste0("--num_samples=", num_samples))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "image_regression"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title In place add
#'
#' @description Performs an in-place addition operation (input1 += input2).
#'
#' @param input1 Input raster file path. See `wbt_file_path()` for details.
#' @param input2 Input raster file or constant value.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_in_place_add <- function(input1, input2, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "in_place_add"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title In place divide
#'
#' @description Performs an in-place division operation (input1 /= input2).
#'
#' @param input1 Input raster file path. See `wbt_file_path()` for details.
#' @param input2 Input raster file or constant value.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_in_place_divide <- function(input1, input2, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "in_place_divide"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title In place multiply
#'
#' @description Performs an in-place multiplication operation (input1 *= input2).
#'
#' @param input1 Input raster file path. See `wbt_file_path()` for details.
#' @param input2 Input raster file or constant value.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_in_place_multiply <- function(input1, input2, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "in_place_multiply"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title In place subtract
#'
#' @description Performs an in-place subtraction operation (input1 -= input2).
#'
#' @param input1 Input raster file path. See `wbt_file_path()` for details.
#' @param input2 Input raster file or constant value.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_in_place_subtract <- function(input1, input2, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "in_place_subtract"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Increment
#'
#' @description Increases the values of each grid cell in an input raster by 1.0. (see also InPlaceAdd).
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_increment <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "increment"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Integer division
#'
#' @description Performs an integer division operation on two rasters or a raster and a constant value.
#'
#' @param input1 Input raster file or constant value.
#' @param input2 Input raster file or constant value.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_integer_division <- function(input1, input2, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "integer_division"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Inverse principal component analysis
#'
#' @description This tool performs an inverse principal component analysis on a series of input component images.
#'
#' @param inputs Name of the input PCA component images.
#' @param report Name of the PCA report file (*.html).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_inverse_principal_component_analysis <- function(inputs, report, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--report=", wbt_file_path(report)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "inverse_principal_component_analysis"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Is no data
#'
#' @description Identifies NoData valued pixels in an image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_is_no_data <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "is_no_data"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Kappa index
#'
#' @description Performs a kappa index of agreement (KIA) analysis on two categorical raster files.
#'
#' @param input1 Input classification raster file.
#' @param input2 Input reference raster file.
#' @param output Output HTML file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_kappa_index <- function(input1, input2, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "kappa_index"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Ks test for normality
#'
#' @description Evaluates whether the values in a raster are normally distributed.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output HTML file.
#' @param num_samples Number of samples. Leave blank to use whole image.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_ks_test_for_normality <- function(input, output, num_samples=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(num_samples)) {
args <- paste(args, paste0("--num_samples=", num_samples))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "ks_test_for_normality"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Less than
#'
#' @description Performs a less-than comparison operation on two rasters or a raster and a constant value.
#'
#' @param input1 Input raster file or constant value.
#' @param input2 Input raster file or constant value.
#' @param output Output raster file.
#' @param incl_equals Perform a less-than-or-equal-to operation.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_less_than <- function(input1, input2, output, incl_equals=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (incl_equals) {
args <- paste(args, "--incl_equals")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "less_than"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title List unique values
#'
#' @description Lists the unique values contained in a field within a vector's attribute table.
#'
#' @param input Input vector file path. See `wbt_file_path()` for details.
#' @param field Input field name in attribute table.
#' @param output Output HTML file (default name will be based on input file if unspecified).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_list_unique_values <- function(input, field, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--field=", wbt_file_path(field)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "list_unique_values"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title List unique values raster
#'
#' @description Lists the unique values contained in a field within a vector's attribute table.
#'
#' @param input Input vector file path. See `wbt_file_path()` for details.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_list_unique_values_raster <- function(input, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "list_unique_values_raster"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Ln
#'
#' @description Returns the natural logarithm of values in a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_ln <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "ln"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Log10
#'
#' @description Returns the base-10 logarithm of values in a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_log10 <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "log10"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Log2
#'
#' @description Returns the base-2 logarithm of values in a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_log2 <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "log2"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Max
#'
#' @description Performs a MAX operation on two rasters or a raster and a constant value.
#'
#' @param input1 Input raster file or constant value.
#' @param input2 Input raster file or constant value.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_max <- function(input1, input2, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "max"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Min
#'
#' @description Performs a MIN operation on two rasters or a raster and a constant value.
#'
#' @param input1 Input raster file or constant value.
#' @param input2 Input raster file or constant value.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_min <- function(input1, input2, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "min"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Modulo
#'
#' @description Performs a modulo operation on two rasters or a raster and a constant value.
#'
#' @param input1 Input raster file or constant value.
#' @param input2 Input raster file or constant value.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_modulo <- function(input1, input2, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "modulo"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Multiply
#'
#' @description Performs a multiplication operation on two rasters or a raster and a constant value.
#'
#' @param input1 Input raster file or constant value.
#' @param input2 Input raster file or constant value.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_multiply <- function(input1, input2, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "multiply"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Negate
#'
#' @description Changes the sign of values in a raster or the 0-1 values of a Boolean raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_negate <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "negate"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Not equal to
#'
#' @description Performs a not-equal-to comparison operation on two rasters or a raster and a constant value.
#'
#' @param input1 Input raster file or constant value.
#' @param input2 Input raster file or constant value.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_not_equal_to <- function(input1, input2, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "not_equal_to"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Paired sample t test
#'
#' @description Performs a 2-sample K-S test for significant differences on two input rasters.
#'
#' @param input1 First input raster file.
#' @param input2 Second input raster file.
#' @param output Output HTML file.
#' @param num_samples Number of samples. Leave blank to use whole image.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_paired_sample_t_test <- function(input1, input2, output, num_samples=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(num_samples)) {
args <- paste(args, paste0("--num_samples=", num_samples))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "paired_sample_t_test"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Phi coefficient
#'
#' @description This tool performs a binary classification accuracy assessment.
#'
#' @param input1 Name of the first input raster image file.
#' @param input2 Name of the second input raster image file.
#' @param output Name of the output HTML file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_phi_coefficient <- function(input1, input2, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "phi_coefficient"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Power
#'
#' @description Raises the values in grid cells of one rasters, or a constant value, by values in another raster or constant value.
#'
#' @param input1 Input raster file or constant value.
#' @param input2 Input raster file or constant value.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_power <- function(input1, input2, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "power"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Principal component analysis
#'
#' @description Performs a principal component analysis (PCA) on a multi-spectral dataset.
#'
#' @param inputs Input raster file paths, concatenated with `","` or `";"`. See `wbt_file_path()` for details.
#' @param output Output HTML report file.
#' @param num_comp Number of component images to output; <= to num. input images.
#' @param standardized Perform standardized PCA?.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_principal_component_analysis <- function(inputs, output, num_comp=NULL, standardized=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(num_comp)) {
args <- paste(args, paste0("--num_comp=", num_comp))
}
if (standardized) {
args <- paste(args, "--standardized")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "principal_component_analysis"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Quantiles
#'
#' @description Transforms raster values into quantiles.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param num_quantiles Number of quantiles.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_quantiles <- function(input, output, num_quantiles=5, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(num_quantiles)) {
args <- paste(args, paste0("--num_quantiles=", num_quantiles))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "quantiles"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Random field
#'
#' @description Creates an image containing random values.
#'
#' @param base Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_random_field <- function(base, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--base=", wbt_file_path(base)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "random_field"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Random sample
#'
#' @description Creates an image containing randomly located sample grid cells with unique IDs.
#'
#' @param base Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param num_samples Number of samples.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_random_sample <- function(base, output, num_samples=1000, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--base=", wbt_file_path(base)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(num_samples)) {
args <- paste(args, paste0("--num_samples=", num_samples))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "random_sample"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Raster calculator
#'
#' @description Performs a complex mathematical operations on one or more input raster images on a cell-to-cell basis.
#'
#' @param statement Statement e.g. cos("raster1") * 35.0 + "raster2". This statement must be a valid Rust statement.
#' @param output Name of the output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_raster_calculator <- function(output, statement="", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(statement)) {
args <- paste(args, paste0("--statement=", statement))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "raster_calculator"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Raster histogram
#'
#' @description Creates a histogram from raster values.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output HTML file (default name will be based on input file if unspecified).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_raster_histogram <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "raster_histogram"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Raster summary stats
#'
#' @description Measures a rasters min, max, average, standard deviation, num. non-nodata cells, and total.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_raster_summary_stats <- function(input, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "raster_summary_stats"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Reciprocal
#'
#' @description Returns the reciprocal (i.e. 1 / z) of values in a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_reciprocal <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "reciprocal"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Rescale value range
#'
#' @description Performs a min-max contrast stretch on an input greytone image.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param out_min_val New minimum value in output image.
#' @param out_max_val New maximum value in output image.
#' @param clip_min Optional lower tail clip value.
#' @param clip_max Optional upper tail clip value.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_rescale_value_range <- function(input, output, out_min_val, out_max_val, clip_min=NULL, clip_max=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--out_min_val=", wbt_file_path(out_min_val)))
args <- paste(args, paste0("--out_max_val=", wbt_file_path(out_max_val)))
if (!is.null(clip_min)) {
args <- paste(args, paste0("--clip_min=", clip_min))
}
if (!is.null(clip_max)) {
args <- paste(args, paste0("--clip_max=", clip_max))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "rescale_value_range"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Root mean square error
#'
#' @description Calculates the RMSE and other accuracy statistics.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param base Input base raster file used for comparison.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_root_mean_square_error <- function(input, base, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--base=", wbt_file_path(base)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "root_mean_square_error"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Round
#'
#' @description Rounds the values in an input raster to the nearest integer value.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_round <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "round"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Sin
#'
#' @description Returns the sine (sin) of each values in a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_sin <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "sin"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Sinh
#'
#' @description Returns the hyperbolic sine (sinh) of each values in a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_sinh <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "sinh"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Square
#'
#' @description Squares the values in a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_square <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "square"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Square root
#'
#' @description Returns the square root of the values in a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_square_root <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "square_root"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Subtract
#'
#' @description Performs a differencing operation on two rasters or a raster and a constant value.
#'
#' @param input1 Input raster file or constant value.
#' @param input2 Input raster file or constant value.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_subtract <- function(input1, input2, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "subtract"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Tan
#'
#' @description Returns the tangent (tan) of each values in a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_tan <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "tan"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Tanh
#'
#' @description Returns the hyperbolic tangent (tanh) of each values in a raster.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_tanh <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "tanh"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title To degrees
#'
#' @description Converts a raster from radians to degrees.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_to_degrees <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "to_degrees"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title To radians
#'
#' @description Converts a raster from degrees to radians.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_to_radians <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "to_radians"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Trend surface
#'
#' @description Estimates the trend surface of an input raster file.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param order Polynomial order (1 to 10).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_trend_surface <- function(input, output, order=1, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(order)) {
args <- paste(args, paste0("--order=", order))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "trend_surface"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Trend surface vector points
#'
#' @description Estimates a trend surface from vector points.
#'
#' @param input Input vector Points file.
#' @param field Input field name in attribute table.
#' @param output Output raster file.
#' @param order Polynomial order (1 to 10).
#' @param cell_size Optionally specified cell size of output raster. Not used when base raster is specified.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_trend_surface_vector_points <- function(input, field, output, cell_size, order=1, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--field=", wbt_file_path(field)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--cell_size=", wbt_file_path(cell_size)))
if (!is.null(order)) {
args <- paste(args, paste0("--order=", order))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "trend_surface_vector_points"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Truncate
#'
#' @description Truncates the values in a raster to the desired number of decimal places.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param num_decimals Number of decimals left after truncation (default is zero).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_truncate <- function(input, output, num_decimals=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(num_decimals)) {
args <- paste(args, paste0("--num_decimals=", num_decimals))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "truncate"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Turning bands simulation
#'
#' @description Creates an image containing random values based on a turning-bands simulation.
#'
#' @param base Input base raster file.
#' @param output Output file.
#' @param range The field's range, in xy-units, related to the extent of spatial autocorrelation.
#' @param iterations The number of iterations.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_turning_bands_simulation <- function(base, output, range, iterations=1000, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--base=", wbt_file_path(base)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--range=", wbt_file_path(range)))
if (!is.null(iterations)) {
args <- paste(args, paste0("--iterations=", iterations))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "turning_bands_simulation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Two sample ks test
#'
#' @description Performs a 2-sample K-S test for significant differences on two input rasters.
#'
#' @param input1 First input raster file.
#' @param input2 Second input raster file.
#' @param output Output HTML file.
#' @param num_samples Number of samples. Leave blank to use whole image.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_two_sample_ks_test <- function(input1, input2, output, num_samples=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(num_samples)) {
args <- paste(args, paste0("--num_samples=", num_samples))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "two_sample_ks_test"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Wilcoxon signed rank test
#'
#' @description Performs a 2-sample K-S test for significant differences on two input rasters.
#'
#' @param input1 First input raster file.
#' @param input2 Second input raster file.
#' @param output Output HTML file.
#' @param num_samples Number of samples. Leave blank to use whole image.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_wilcoxon_signed_rank_test <- function(input1, input2, output, num_samples=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(num_samples)) {
args <- paste(args, paste0("--num_samples=", num_samples))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "wilcoxon_signed_rank_test"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Xor
#'
#' @description Performs a logical XOR operator on two Boolean raster images.
#'
#' @param input1 Input raster file path. See `wbt_file_path()` for details.
#' @param input2 Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_xor <- function(input1, input2, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input1=", wbt_file_path(input1)))
args <- paste(args, paste0("--input2=", wbt_file_path(input2)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "xor"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Z scores
#'
#' @description Standardizes the values in an input raster by converting to z-scores.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_z_scores <- function(input, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "z_scores"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Zonal statistics
#'
#' @description Extracts descriptive statistics for a group of patches in a raster.
#'
#' @param input Input data raster file.
#' @param features Input feature definition raster file.
#' @param output Output raster file.
#' @param stat Statistic to extract, including 'mean', 'median', 'minimum', 'maximum', 'range', 'standard deviation', and 'total'.
#' @param out_table Output HTML Table file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords MathandStatsTools
#'
#' @return Returns the tool text outputs.
#' @export
wbt_zonal_statistics <- function(input, features, output=NULL, stat="mean", out_table=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--features=", wbt_file_path(features)))
if (!is.null(output)) {
args <- paste(args, paste0("--output=", wbt_file_path(output)))
}
if (!is.null(stat)) {
args <- paste(args, paste0("--stat=", stat))
}
if (!is.null(out_table)) {
args <- paste(args, paste0("--out_table=", out_table))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "zonal_statistics"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
|
/scratch/gouwar.j/cran-all/cranData/whitebox/R/math_stat_analysis.R
|
#' @title Reconcile multiple headers
#'
#' @description This tool adjusts the crop yield values for data sets collected with multiple headers or combines.
#'
#' @param input Name of the input points shapefile.
#' @param region_field Name of the attribute containing region data.
#' @param yield_field Name of the attribute containing yield data.
#' @param output Name of the output points shapefile.
#' @param radius Optional search radius, in metres. Only specify this value if you want to calculate locally normalized yield.
#' @param min_yield Minimum yield value in output.
#' @param max_yield Maximum yield value in output.
#' @param mean_tonnage Use this optional parameter to force the output to have a certain overall average tonnage.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords PrecisionAgriculture
#'
#' @return Returns the tool text outputs.
#' @export
wbt_reconcile_multiple_headers <- function(input, region_field, yield_field, output, radius=NULL, min_yield=NULL, max_yield=NULL, mean_tonnage=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--region_field=", wbt_file_path(region_field)))
args <- paste(args, paste0("--yield_field=", wbt_file_path(yield_field)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(radius)) {
args <- paste(args, paste0("--radius=", radius))
}
if (!is.null(min_yield)) {
args <- paste(args, paste0("--min_yield=", min_yield))
}
if (!is.null(max_yield)) {
args <- paste(args, paste0("--max_yield=", max_yield))
}
if (!is.null(mean_tonnage)) {
args <- paste(args, paste0("--mean_tonnage=", mean_tonnage))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "reconcile_multiple_headers"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Recreate pass lines
#'
#' @description This tool can be used to approximate the harvester pass lines from yield points.
#'
#' @param input Name of the input points shapefile.
#' @param yield_field_name Name of the attribute containing yield data.
#' @param output_lines Name of the output pass lines shapefile.
#' @param output_points Name of the output points shapefile.
#' @param max_change_in_heading Max change in heading.
#' @param ignore_zeros Ignore zero-valued yield points?.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords PrecisionAgriculture
#'
#' @return Returns the tool text outputs.
#' @export
wbt_recreate_pass_lines <- function(input, yield_field_name, output_lines, output_points, max_change_in_heading=25.0, ignore_zeros=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--yield_field_name=", wbt_file_path(yield_field_name)))
args <- paste(args, paste0("--output_lines=", wbt_file_path(output_lines)))
args <- paste(args, paste0("--output_points=", wbt_file_path(output_points)))
if (!is.null(max_change_in_heading)) {
args <- paste(args, paste0("--max_change_in_heading=", max_change_in_heading))
}
if (ignore_zeros) {
args <- paste(args, "--ignore_zeros")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "recreate_pass_lines"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Remove field edge points
#'
#' @description This tool can be used to remove, or flag, most of the points along the edges from a crop yield data set.
#'
#' @param input Name of the input points shapefile.
#' @param output Name of the output points shapefile.
#' @param dist Average distance between passes, in meters.
#' @param max_change_in_heading Max change in heading.
#' @param flag_edges Don't remove edge points, just flag them in the attribute table?.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords PrecisionAgriculture
#'
#' @return Returns the tool text outputs.
#' @export
wbt_remove_field_edge_points <- function(input, output, dist=NULL, max_change_in_heading=25.0, flag_edges=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(dist)) {
args <- paste(args, paste0("--dist=", dist))
}
if (!is.null(max_change_in_heading)) {
args <- paste(args, paste0("--max_change_in_heading=", max_change_in_heading))
}
if (flag_edges) {
args <- paste(args, "--flag_edges")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "remove_field_edge_points"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Yield filter
#'
#' @description Filters crop yield values of point data derived from combine harvester yield monitors.
#'
#' @param input Name of the input points shapefile.
#' @param yield_field Name of the attribute containing yield data.
#' @param pass_field Name of the attribute containing pass line ID.
#' @param output Name of the output points shapefile.
#' @param width Pass swath width (m).
#' @param z_score_threshold Z-score threshold value (default=2.5).
#' @param min_yield Minimum yield value in output.
#' @param max_yield Maximum yield value in output.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords PrecisionAgriculture
#'
#' @return Returns the tool text outputs.
#' @export
wbt_yield_filter <- function(input, yield_field, pass_field, output, width=6.096, z_score_threshold=2.5, min_yield=0.0, max_yield=99999.9, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--yield_field=", wbt_file_path(yield_field)))
args <- paste(args, paste0("--pass_field=", wbt_file_path(pass_field)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(width)) {
args <- paste(args, paste0("--width=", width))
}
if (!is.null(z_score_threshold)) {
args <- paste(args, paste0("--z_score_threshold=", z_score_threshold))
}
if (!is.null(min_yield)) {
args <- paste(args, paste0("--min_yield=", min_yield))
}
if (!is.null(max_yield)) {
args <- paste(args, paste0("--max_yield=", max_yield))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "yield_filter"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Yield map
#'
#' @description This tool can be used to create a segmented-vector polygon yield map from a set of harvester points.
#'
#' @param input Name of the input points shapefile.
#' @param pass_field_name Name of the attribute containing pass line ID.
#' @param output Name of the output polygon shapefile.
#' @param width Pass swath width (m).
#' @param max_change_in_heading Max change in heading.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords PrecisionAgriculture
#'
#' @return Returns the tool text outputs.
#' @export
wbt_yield_map <- function(input, pass_field_name, output, width=6.096, max_change_in_heading=25.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--pass_field_name=", wbt_file_path(pass_field_name)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(width)) {
args <- paste(args, paste0("--width=", width))
}
if (!is.null(max_change_in_heading)) {
args <- paste(args, paste0("--max_change_in_heading=", max_change_in_heading))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "yield_map"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Yield normalization
#'
#' @description This tool can be used to normalize the yield points for a field.
#'
#' @param input Name of the input points shapefile.
#' @param yield_field Name of the attribute containing yield data.
#' @param output Name of the output points shapefile.
#' @param standardize Should the yield values be standardized (converted to z-scores) rather than normalized?.
#' @param radius Optional search radius, in metres. Only specify this value if you want to calculate locally normalized yield.
#' @param min_yield Minimum yield value in output.
#' @param max_yield Maximum yield value in output.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords PrecisionAgriculture
#'
#' @return Returns the tool text outputs.
#' @export
wbt_yield_normalization <- function(input, yield_field, output, standardize=FALSE, radius=NULL, min_yield=0.0, max_yield=99999.9, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--yield_field=", wbt_file_path(yield_field)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (standardize) {
args <- paste(args, "--standardize")
}
if (!is.null(radius)) {
args <- paste(args, paste0("--radius=", radius))
}
if (!is.null(min_yield)) {
args <- paste(args, paste0("--min_yield=", min_yield))
}
if (!is.null(max_yield)) {
args <- paste(args, paste0("--max_yield=", max_yield))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "yield_normalization"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
|
/scratch/gouwar.j/cran-all/cranData/whitebox/R/precision_agriculture.R
|
#' @title Distance to outlet
#'
#' @description Calculates the distance of stream grid cells to the channel network outlet cell.
#'
#' @param d8_pntr Input raster D8 pointer file.
#' @param streams Input raster streams file.
#' @param output Output raster file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param zero_background Flag indicating whether a background value of zero should be used.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords StreamNetworkAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_distance_to_outlet <- function(d8_pntr, streams, output, esri_pntr=FALSE, zero_background=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (zero_background) {
args <- paste(args, "--zero_background")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "distance_to_outlet"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Extract streams
#'
#' @description Extracts stream grid cells from a flow accumulation raster.
#'
#' @param flow_accum Input raster D8 flow accumulation file.
#' @param output Output raster file.
#' @param threshold Threshold in flow accumulation values for channelization.
#' @param zero_background Flag indicating whether a background value of zero should be used.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords StreamNetworkAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_extract_streams <- function(flow_accum, output, threshold, zero_background=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--flow_accum=", wbt_file_path(flow_accum)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--threshold=", wbt_file_path(threshold)))
if (zero_background) {
args <- paste(args, "--zero_background")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "extract_streams"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Extract valleys
#'
#' @description Identifies potential valley bottom grid cells based on local topolography alone.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param variant Options include 'LQ' (lower quartile), 'JandR' (Johnston and Rosenfeld), and 'PandD' (Peucker and Douglas); default is 'LQ'.
#' @param line_thin Optional flag indicating whether post-processing line-thinning should be performed.
#' @param filter Optional argument (only used when variant='lq') providing the filter size, in grid cells, used for lq-filtering (default is 5).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords StreamNetworkAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_extract_valleys <- function(dem, output, variant="LQ", line_thin=TRUE, filter=5, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(variant)) {
args <- paste(args, paste0("--variant=", wbt_file_path(variant)))
}
if (line_thin) {
args <- paste(args, "--line_thin")
}
if (!is.null(filter)) {
args <- paste(args, paste0("--filter=", filter))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "extract_valleys"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Farthest channel head
#'
#' @description Calculates the distance to the furthest upstream channel head for each stream cell.
#'
#' @param d8_pntr Input raster D8 pointer file.
#' @param streams Input raster streams file.
#' @param output Output raster file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param zero_background Flag indicating whether a background value of zero should be used.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords StreamNetworkAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_farthest_channel_head <- function(d8_pntr, streams, output, esri_pntr=FALSE, zero_background=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (zero_background) {
args <- paste(args, "--zero_background")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "farthest_channel_head"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Find main stem
#'
#' @description Finds the main stem, based on stream lengths, of each stream network.
#'
#' @param d8_pntr Input raster D8 pointer file.
#' @param streams Input raster streams file.
#' @param output Output raster file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param zero_background Flag indicating whether a background value of zero should be used.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords StreamNetworkAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_find_main_stem <- function(d8_pntr, streams, output, esri_pntr=FALSE, zero_background=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (zero_background) {
args <- paste(args, "--zero_background")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "find_main_stem"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Hack stream order
#'
#' @description Assigns the Hack stream order to each tributary in a stream network.
#'
#' @param d8_pntr Input raster D8 pointer file.
#' @param streams Input raster streams file.
#' @param output Output raster file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param zero_background Flag indicating whether a background value of zero should be used.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords StreamNetworkAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_hack_stream_order <- function(d8_pntr, streams, output, esri_pntr=FALSE, zero_background=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (zero_background) {
args <- paste(args, "--zero_background")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "hack_stream_order"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Horton stream order
#'
#' @description Assigns the Horton stream order to each tributary in a stream network.
#'
#' @param d8_pntr Input raster D8 pointer file.
#' @param streams Input raster streams file.
#' @param output Output raster file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param zero_background Flag indicating whether a background value of zero should be used.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords StreamNetworkAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_horton_stream_order <- function(d8_pntr, streams, output, esri_pntr=FALSE, zero_background=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (zero_background) {
args <- paste(args, "--zero_background")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "horton_stream_order"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Length of upstream channels
#'
#' @description Calculates the total length of channels upstream.
#'
#' @param d8_pntr Input raster D8 pointer file.
#' @param streams Input raster streams file.
#' @param output Output raster file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param zero_background Flag indicating whether a background value of zero should be used.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords StreamNetworkAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_length_of_upstream_channels <- function(d8_pntr, streams, output, esri_pntr=FALSE, zero_background=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (zero_background) {
args <- paste(args, "--zero_background")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "length_of_upstream_channels"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Long profile
#'
#' @description Plots the stream longitudinal profiles for one or more rivers.
#'
#' @param d8_pntr Input raster D8 pointer file.
#' @param streams Input raster streams file.
#' @param dem Input raster DEM file.
#' @param output Output HTML file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords StreamNetworkAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_long_profile <- function(d8_pntr, streams, dem, output, esri_pntr=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "long_profile"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Long profile from points
#'
#' @description Plots the longitudinal profiles from flow-paths initiating from a set of vector points.
#'
#' @param d8_pntr Input raster D8 pointer file.
#' @param points Input vector points file.
#' @param dem Input raster DEM file.
#' @param output Output HTML file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords StreamNetworkAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_long_profile_from_points <- function(d8_pntr, points, dem, output, esri_pntr=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--points=", wbt_file_path(points)))
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "long_profile_from_points"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Raster streams to vector
#'
#' @description Converts a raster stream file into a vector file.
#'
#' @param streams Input raster streams file.
#' @param d8_pntr Input raster D8 pointer file.
#' @param output Output vector file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords StreamNetworkAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_raster_streams_to_vector <- function(streams, d8_pntr, output, esri_pntr=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "raster_streams_to_vector"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Rasterize streams
#'
#' @description Rasterizes vector streams based on Lindsay (2016) method.
#'
#' @param streams Input vector streams file.
#' @param base Input base raster file.
#' @param output Output raster file.
#' @param nodata Use NoData value for background?.
#' @param feature_id Use feature number as output value?.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords StreamNetworkAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_rasterize_streams <- function(streams, base, output, nodata=TRUE, feature_id=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--base=", wbt_file_path(base)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (nodata) {
args <- paste(args, "--nodata")
}
if (feature_id) {
args <- paste(args, "--feature_id")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "rasterize_streams"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Remove short streams
#'
#' @description Removes short first-order streams from a stream network.
#'
#' @param d8_pntr Input raster D8 pointer file.
#' @param streams Input raster streams file.
#' @param output Output raster file.
#' @param min_length Minimum tributary length (in map units) used for network pruning.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords StreamNetworkAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_remove_short_streams <- function(d8_pntr, streams, output, min_length, esri_pntr=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--min_length=", wbt_file_path(min_length)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "remove_short_streams"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Repair stream vector topology
#'
#' @description This tool resolves topological errors and inconsistencies associated with digitized vector streams.
#'
#' @param input Name of the input lines vector file.
#' @param output Name of the output lines vector file.
#' @param dist Snap distance, in xy units (metres).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords StreamNetworkAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_repair_stream_vector_topology <- function(input, output, dist="", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(dist)) {
args <- paste(args, paste0("--dist=", dist))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "repair_stream_vector_topology"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Shreve stream magnitude
#'
#' @description Assigns the Shreve stream magnitude to each link in a stream network.
#'
#' @param d8_pntr Input raster D8 pointer file.
#' @param streams Input raster streams file.
#' @param output Output raster file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param zero_background Flag indicating whether a background value of zero should be used.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords StreamNetworkAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_shreve_stream_magnitude <- function(d8_pntr, streams, output, esri_pntr=FALSE, zero_background=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (zero_background) {
args <- paste(args, "--zero_background")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "shreve_stream_magnitude"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Strahler stream order
#'
#' @description Assigns the Strahler stream order to each link in a stream network.
#'
#' @param d8_pntr Input raster D8 pointer file.
#' @param streams Input raster streams file.
#' @param output Output raster file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param zero_background Flag indicating whether a background value of zero should be used.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords StreamNetworkAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_strahler_stream_order <- function(d8_pntr, streams, output, esri_pntr=FALSE, zero_background=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (zero_background) {
args <- paste(args, "--zero_background")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "strahler_stream_order"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Stream link class
#'
#' @description Identifies the exterior/interior links and nodes in a stream network.
#'
#' @param d8_pntr Input raster D8 pointer file.
#' @param streams Input raster streams file.
#' @param output Output raster file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param zero_background Flag indicating whether a background value of zero should be used.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords StreamNetworkAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_stream_link_class <- function(d8_pntr, streams, output, esri_pntr=FALSE, zero_background=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (zero_background) {
args <- paste(args, "--zero_background")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "stream_link_class"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Stream link identifier
#'
#' @description Assigns a unique identifier to each link in a stream network.
#'
#' @param d8_pntr Input raster D8 pointer file.
#' @param streams Input raster streams file.
#' @param output Output raster file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param zero_background Flag indicating whether a background value of zero should be used.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords StreamNetworkAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_stream_link_identifier <- function(d8_pntr, streams, output, esri_pntr=FALSE, zero_background=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (zero_background) {
args <- paste(args, "--zero_background")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "stream_link_identifier"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Stream link length
#'
#' @description Estimates the length of each link (or tributary) in a stream network.
#'
#' @param d8_pntr Input raster D8 pointer file.
#' @param linkid Input raster streams link ID (or tributary ID) file.
#' @param output Output raster file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param zero_background Flag indicating whether a background value of zero should be used.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords StreamNetworkAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_stream_link_length <- function(d8_pntr, linkid, output, esri_pntr=FALSE, zero_background=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--linkid=", wbt_file_path(linkid)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (zero_background) {
args <- paste(args, "--zero_background")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "stream_link_length"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Stream link slope
#'
#' @description Estimates the average slope of each link (or tributary) in a stream network.
#'
#' @param d8_pntr Input raster D8 pointer file.
#' @param linkid Input raster streams link ID (or tributary ID) file.
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param zero_background Flag indicating whether a background value of zero should be used.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords StreamNetworkAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_stream_link_slope <- function(d8_pntr, linkid, dem, output, esri_pntr=FALSE, zero_background=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--linkid=", wbt_file_path(linkid)))
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (zero_background) {
args <- paste(args, "--zero_background")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "stream_link_slope"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Stream slope continuous
#'
#' @description Estimates the slope of each grid cell in a stream network.
#'
#' @param d8_pntr Input raster D8 pointer file.
#' @param streams Input raster streams file.
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param zero_background Flag indicating whether a background value of zero should be used.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords StreamNetworkAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_stream_slope_continuous <- function(d8_pntr, streams, dem, output, esri_pntr=FALSE, zero_background=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (zero_background) {
args <- paste(args, "--zero_background")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "stream_slope_continuous"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Topological stream order
#'
#' @description Assigns each link in a stream network its topological order.
#'
#' @param d8_pntr Input raster D8 pointer file.
#' @param streams Input raster streams file.
#' @param output Output raster file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param zero_background Flag indicating whether a background value of zero should be used.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords StreamNetworkAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_topological_stream_order <- function(d8_pntr, streams, output, esri_pntr=FALSE, zero_background=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (zero_background) {
args <- paste(args, "--zero_background")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "topological_stream_order"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Tributary identifier
#'
#' @description Assigns a unique identifier to each tributary in a stream network.
#'
#' @param d8_pntr Input raster D8 pointer file.
#' @param streams Input raster streams file.
#' @param output Output raster file.
#' @param esri_pntr D8 pointer uses the ESRI style scheme.
#' @param zero_background Flag indicating whether a background value of zero should be used.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords StreamNetworkAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_tributary_identifier <- function(d8_pntr, streams, output, esri_pntr=FALSE, zero_background=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--d8_pntr=", wbt_file_path(d8_pntr)))
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (esri_pntr) {
args <- paste(args, "--esri_pntr")
}
if (zero_background) {
args <- paste(args, "--zero_background")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "tributary_identifier"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Vector stream network analysis
#'
#' @description This tool performs common stream network analysis operations on an input vector stream file.
#'
#' @param streams Name of the input streams vector file.
#' @param dem Name of the input DEM raster file.
#' @param output Name of the output lines shapefile.
#' @param cutting_height Maximum ridge-cutting height (z units).
#' @param snap Snap distance, in xy units (metres).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords StreamNetworkAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_vector_stream_network_analysis <- function(streams, dem, output, cutting_height=10.0, snap=0.1, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--streams=", wbt_file_path(streams)))
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(cutting_height)) {
args <- paste(args, paste0("--cutting_height=", cutting_height))
}
if (!is.null(snap)) {
args <- paste(args, paste0("--snap=", snap))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "vector_stream_network_analysis"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
|
/scratch/gouwar.j/cran-all/cranData/whitebox/R/stream_network_analysis.R
|
#' @title Accumulation curvature
#'
#' @description This tool calculates accumulation curvature from an input DEM.
#'
#' @param dem Name of the input raster DEM file.
#' @param output Name of the output raster image file.
#' @param log Display output values using a log-scale.
#' @param zfactor Z conversion factor.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_accumulation_curvature <- function(dem, output, log=FALSE, zfactor=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (log) {
args <- paste(args, "--log")
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "accumulation_curvature"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Aspect
#'
#' @description Calculates an aspect raster from an input DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param zfactor Optional multiplier for when the vertical and horizontal units are not the same.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_aspect <- function(dem, output, zfactor=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "aspect"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Assess route
#'
#' @description This tool assesses a route for slope, elevation, and visibility variation.
#'
#' @param routes Name of the input routes vector file.
#' @param dem Name of the input DEM raster file.
#' @param output Name of the output lines shapefile.
#' @param length Maximum segment length (m).
#' @param dist Search distance, in grid cells, used in visibility analysis.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_assess_route <- function(routes, dem, output, length="", dist=20, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--routes=", wbt_file_path(routes)))
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(length)) {
args <- paste(args, paste0("--length=", length))
}
if (!is.null(dist)) {
args <- paste(args, paste0("--dist=", dist))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "assess_route"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Average normal vector angular deviation
#'
#' @description Calculates the circular variance of aspect at a scale for a DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param filter Size of the filter kernel.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_average_normal_vector_angular_deviation <- function(dem, output, filter=11, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filter)) {
args <- paste(args, paste0("--filter=", filter))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "average_normal_vector_angular_deviation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Breakline mapping
#'
#' @description This tool maps breaklines from an input DEM.
#'
#' @param dem Name of the input raster image file.
#' @param output Name of the output vector lines file.
#' @param threshold Threshold value (0 - infinity but typcially 1 to 5 works well).
#' @param min_length Minimum line length, in grid cells.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_breakline_mapping <- function(dem, output, threshold=2.0, min_length=3, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(threshold)) {
args <- paste(args, paste0("--threshold=", threshold))
}
if (!is.null(min_length)) {
args <- paste(args, paste0("--min_length=", min_length))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "breakline_mapping"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Circular variance of aspect
#'
#' @description Calculates the circular variance of aspect at a scale for a DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param filter Size of the filter kernel.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_circular_variance_of_aspect <- function(dem, output, filter=11, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filter)) {
args <- paste(args, paste0("--filter=", filter))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "circular_variance_of_aspect"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Contours from points
#'
#' @description Creates a contour coverage from a set of input points.
#'
#' @param input Input vector points file.
#' @param field Input field name in attribute table.
#' @param use_z Use the 'z' dimension of the Shapefile's geometry instead of an attribute field?.
#' @param output Output vector lines file.
#' @param max_triangle_edge_length Optional maximum triangle edge length; triangles larger than this size will not be gridded.
#' @param interval Contour interval.
#' @param base Base contour height.
#' @param smooth Smoothing filter size (in num. points), e.g. 3, 5, 7, 9, 11.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_contours_from_points <- function(input, output, field=NULL, use_z=FALSE, max_triangle_edge_length=NULL, interval=10.0, base=0.0, smooth=5, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(field)) {
args <- paste(args, paste0("--field=", field))
}
if (use_z) {
args <- paste(args, "--use_z")
}
if (!is.null(max_triangle_edge_length)) {
args <- paste(args, paste0("--max_triangle_edge_length=", max_triangle_edge_length))
}
if (!is.null(interval)) {
args <- paste(args, paste0("--interval=", interval))
}
if (!is.null(base)) {
args <- paste(args, paste0("--base=", base))
}
if (!is.null(smooth)) {
args <- paste(args, paste0("--smooth=", smooth))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "contours_from_points"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Contours from raster
#'
#' @description Derives a vector contour coverage from a raster surface.
#'
#' @param input Input surface raster file.
#' @param output Output vector contour file.
#' @param interval Contour interval.
#' @param base Base contour height.
#' @param smooth Smoothing filter size (in num. points), e.g. 3, 5, 7, 9, 11.
#' @param tolerance Tolerance factor, in degrees (0-45); determines generalization level.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_contours_from_raster <- function(input, output, interval=10.0, base=0.0, smooth=9, tolerance=10.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(interval)) {
args <- paste(args, paste0("--interval=", interval))
}
if (!is.null(base)) {
args <- paste(args, paste0("--base=", base))
}
if (!is.null(smooth)) {
args <- paste(args, paste0("--smooth=", smooth))
}
if (!is.null(tolerance)) {
args <- paste(args, paste0("--tolerance=", tolerance))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "contours_from_raster"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Curvedness
#'
#' @description This tool calculates curvedness from an input DEM.
#'
#' @param dem Name of the input raster DEM file.
#' @param output Name of the output raster image file.
#' @param log Display output values using a log-scale.
#' @param zfactor Z conversion factor.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_curvedness <- function(dem, output, log=FALSE, zfactor=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (log) {
args <- paste(args, "--log")
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "curvedness"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Dem void filling
#'
#' @description This tool can be used to fill the void areas of a DEM using another fill DEM data set.
#'
#' @param dem Name of the input raster DEM file, containing the void areas.
#' @param fill Name of the input fill DEM file, containing the values used to fill the void areas in the other DEM.
#' @param output Name of the output void-filled DEM file.
#' @param mean_plane_dist Distance to void edge at which the mean-plane value is used as an offset, measured in grid cells.
#' @param edge_treatment How should void-edge cells be treated? Options include 'use DEM' (default), 'use Fill', 'average'.
#' @param weight_value Weight value used for IDW interpolation (default is 2.0).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_dem_void_filling <- function(dem, fill, output, mean_plane_dist=20, edge_treatment="use DEM", weight_value=2.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--fill=", wbt_file_path(fill)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(mean_plane_dist)) {
args <- paste(args, paste0("--mean_plane_dist=", mean_plane_dist))
}
if (!is.null(edge_treatment)) {
args <- paste(args, paste0("--edge_treatment=", edge_treatment))
}
if (!is.null(weight_value)) {
args <- paste(args, paste0("--weight_value=", weight_value))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "dem_void_filling"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Dev from mean elev
#'
#' @description Calculates deviation from mean elevation.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param filterx Size of the filter kernel in the x-direction.
#' @param filtery Size of the filter kernel in the y-direction.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_dev_from_mean_elev <- function(dem, output, filterx=11, filtery=11, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filterx)) {
args <- paste(args, paste0("--filterx=", filterx))
}
if (!is.null(filtery)) {
args <- paste(args, paste0("--filtery=", filtery))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "dev_from_mean_elev"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Diff from mean elev
#'
#' @description Calculates difference from mean elevation (equivalent to a high-pass filter).
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param filterx Size of the filter kernel in the x-direction.
#' @param filtery Size of the filter kernel in the y-direction.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_diff_from_mean_elev <- function(dem, output, filterx=11, filtery=11, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filterx)) {
args <- paste(args, paste0("--filterx=", filterx))
}
if (!is.null(filtery)) {
args <- paste(args, paste0("--filtery=", filtery))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "diff_from_mean_elev"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Difference curvature
#'
#' @description This tool calculates difference curvature from an input DEM.
#'
#' @param dem Name of the input raster DEM file.
#' @param output Name of the output raster image file.
#' @param log Display output values using a log-scale.
#' @param zfactor Z conversion factor.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_difference_curvature <- function(dem, output, log=FALSE, zfactor=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (log) {
args <- paste(args, "--log")
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "difference_curvature"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Directional relief
#'
#' @description Calculates relief for cells in an input DEM for a specified direction.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param azimuth Wind azimuth in degrees.
#' @param max_dist Optional maximum search distance (unspecified if none; in xy units).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_directional_relief <- function(dem, output, azimuth=0.0, max_dist=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(azimuth)) {
args <- paste(args, paste0("--azimuth=", azimuth))
}
if (!is.null(max_dist)) {
args <- paste(args, paste0("--max_dist=", max_dist))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "directional_relief"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Downslope index
#'
#' @description Calculates the Hjerdt et al. (2004) downslope index.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param drop Vertical drop value (default is 2.0).
#' @param out_type Output type, options include 'tangent', 'degrees', 'radians', 'distance' (default is 'tangent').
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_downslope_index <- function(dem, output, drop=2.0, out_type="tangent", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(drop)) {
args <- paste(args, paste0("--drop=", drop))
}
if (!is.null(out_type)) {
args <- paste(args, paste0("--out_type=", out_type))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "downslope_index"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Edge density
#'
#' @description Calculates the density of edges, or breaks-in-slope within DEMs.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param filter Size of the filter kernel.
#' @param norm_diff Maximum difference in normal vectors, in degrees.
#' @param zfactor Optional multiplier for when the vertical and horizontal units are not the same.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_edge_density <- function(dem, output, filter=11, norm_diff=5.0, zfactor=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filter)) {
args <- paste(args, paste0("--filter=", filter))
}
if (!is.null(norm_diff)) {
args <- paste(args, paste0("--norm_diff=", norm_diff))
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "edge_density"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Elev above pit
#'
#' @description Calculate the elevation of each grid cell above the nearest downstream pit cell or grid edge cell.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_elev_above_pit <- function(dem, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "elev_above_pit"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Elev percentile
#'
#' @description Calculates the elevation percentile raster from a DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param filterx Size of the filter kernel in the x-direction.
#' @param filtery Size of the filter kernel in the y-direction.
#' @param sig_digits Number of significant digits.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_elev_percentile <- function(dem, output, filterx=11, filtery=11, sig_digits=2, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filterx)) {
args <- paste(args, paste0("--filterx=", filterx))
}
if (!is.null(filtery)) {
args <- paste(args, paste0("--filtery=", filtery))
}
if (!is.null(sig_digits)) {
args <- paste(args, paste0("--sig_digits=", sig_digits))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "elev_percentile"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Elev relative to min max
#'
#' @description Calculates the elevation of a location relative to the minimum and maximum elevations in a DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_elev_relative_to_min_max <- function(dem, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "elev_relative_to_min_max"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Elev relative to watershed min max
#'
#' @description Calculates the elevation of a location relative to the minimum and maximum elevations in a watershed.
#'
#' @param dem Input raster DEM file.
#' @param watersheds Input raster watersheds file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_elev_relative_to_watershed_min_max <- function(dem, watersheds, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--watersheds=", wbt_file_path(watersheds)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "elev_relative_to_watershed_min_max"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Embankment mapping
#'
#' @description Maps and/or removes road embankments from an input fine-resolution DEM.
#'
#' @param dem Input raster DEM file.
#' @param road_vec Input vector polygons file.
#' @param output Output raster file.
#' @param search_dist Search distance used to reposition transportation vectors onto road embankments (in map units).
#' @param min_road_width Minimum road width; this is the width of the paved road surface (in map units).
#' @param typical_width Typical embankment width; this is the maximum width of an embankment with roadside ditches (in map units).
#' @param max_height Typical embankment maximum height; this is the height a typical embankment with roadside ditches (in map units).
#' @param max_width Maximum embankment width, typically where embankments traverse steep-sided valleys (in map units).
#' @param max_increment Maximum upwards increment between neighbouring cells on an embankment (in elevation units).
#' @param spillout_slope Spillout slope (in degrees).
#' @param remove_embankments Optional flag indicating whether to output a DEM with embankments removed (true) or an embankment raster map (false).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_embankment_mapping <- function(dem, road_vec, output, search_dist=2.5, min_road_width=6.0, typical_width=30.0, max_height=2.0, max_width=60.0, max_increment=0.05, spillout_slope=4.0, remove_embankments=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--road_vec=", wbt_file_path(road_vec)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(search_dist)) {
args <- paste(args, paste0("--search_dist=", search_dist))
}
if (!is.null(min_road_width)) {
args <- paste(args, paste0("--min_road_width=", min_road_width))
}
if (!is.null(typical_width)) {
args <- paste(args, paste0("--typical_width=", typical_width))
}
if (!is.null(max_height)) {
args <- paste(args, paste0("--max_height=", max_height))
}
if (!is.null(max_width)) {
args <- paste(args, paste0("--max_width=", max_width))
}
if (!is.null(max_increment)) {
args <- paste(args, paste0("--max_increment=", max_increment))
}
if (!is.null(spillout_slope)) {
args <- paste(args, paste0("--spillout_slope=", spillout_slope))
}
if (remove_embankments) {
args <- paste(args, "--remove_embankments")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "embankment_mapping"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Exposure towards wind flux
#'
#' @description Evaluates hydrologic connectivity within a DEM.
#'
#' @param dem Name of the input DEM raster file.
#' @param output Name of the output raster file.
#' @param azimuth Wind azimuth, in degrees.
#' @param max_dist Optional maximum search distance. Minimum value is 5 x cell size.
#' @param zfactor Optional multiplier for when the vertical and horizontal units are not the same.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_exposure_towards_wind_flux <- function(dem, output, azimuth="", max_dist="", zfactor="", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(azimuth)) {
args <- paste(args, paste0("--azimuth=", azimuth))
}
if (!is.null(max_dist)) {
args <- paste(args, paste0("--max_dist=", max_dist))
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "exposure_towards_wind_flux"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Feature preserving smoothing
#'
#' @description Reduces short-scale variation in an input DEM using a modified Sun et al. (2007) algorithm.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param filter Size of the filter kernel.
#' @param norm_diff Maximum difference in normal vectors, in degrees.
#' @param num_iter Number of iterations.
#' @param max_diff Maximum allowable absolute elevation change (optional).
#' @param zfactor Optional multiplier for when the vertical and horizontal units are not the same.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_feature_preserving_smoothing <- function(dem, output, filter=11, norm_diff=15.0, num_iter=3, max_diff=0.5, zfactor=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filter)) {
args <- paste(args, paste0("--filter=", filter))
}
if (!is.null(norm_diff)) {
args <- paste(args, paste0("--norm_diff=", norm_diff))
}
if (!is.null(num_iter)) {
args <- paste(args, paste0("--num_iter=", num_iter))
}
if (!is.null(max_diff)) {
args <- paste(args, paste0("--max_diff=", max_diff))
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "feature_preserving_smoothing"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Fetch analysis
#'
#' @description Performs an analysis of fetch or upwind distance to an obstacle.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param azimuth Wind azimuth in degrees in degrees.
#' @param hgt_inc Height increment value.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_fetch_analysis <- function(dem, output, azimuth=0.0, hgt_inc=0.05, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(azimuth)) {
args <- paste(args, paste0("--azimuth=", azimuth))
}
if (!is.null(hgt_inc)) {
args <- paste(args, paste0("--hgt_inc=", hgt_inc))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "fetch_analysis"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Fill missing data
#'
#' @description Fills NoData holes in a DEM.
#'
#' @param input Input raster file path. See `wbt_file_path()` for details.
#' @param output Output raster file.
#' @param filter Filter size (cells).
#' @param weight IDW weight value.
#' @param no_edges Optional flag indicating whether to exclude NoData cells in edge regions.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_fill_missing_data <- function(input, output, filter=11, weight=2.0, no_edges=TRUE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filter)) {
args <- paste(args, paste0("--filter=", filter))
}
if (!is.null(weight)) {
args <- paste(args, paste0("--weight=", weight))
}
if (no_edges) {
args <- paste(args, "--no_edges")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "fill_missing_data"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Find ridges
#'
#' @description Identifies potential ridge and peak grid cells.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param line_thin Optional flag indicating whether post-processing line-thinning should be performed.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_find_ridges <- function(dem, output, line_thin=TRUE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (line_thin) {
args <- paste(args, "--line_thin")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "find_ridges"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Gaussian curvature
#'
#' @description Calculates a mean curvature raster from an input DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param log Display output values using a log-scale.
#' @param zfactor Optional multiplier for when the vertical and horizontal units are not the same.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_gaussian_curvature <- function(dem, output, log=FALSE, zfactor=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (log) {
args <- paste(args, "--log")
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "gaussian_curvature"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Gaussian scale space
#'
#' @description Uses the fast Gaussian approximation algorithm to produce scaled land-surface parameter measurements from an input DEM.
#'
#' @param dem Name of the input DEM raster file.
#' @param points Name of the input vector points shapefile.
#' @param output Name of the output land-surface parameter raster file.
#' @param output_zscore Name of the output z-score raster file.
#' @param output_scale Name of the output scale raster file.
#' @param sigma Initial sigma value (cells).
#' @param step Step size as any positive non-zero integer.
#' @param num_steps Number of steps.
#' @param lsp Output land-surface parameter; one of 'AnisotropyLTP', 'Aspect', 'DiffMeanElev', 'Eastness', 'Elevation', 'Hillshade', 'MeanCurvature', 'Northness', 'PlanCurvature', 'ProfileCurvature', 'Ruggedness', 'Slope', 'TanCurvature', 'TotalCurvature'.
#' @param z_factor Optional multiplier for when the vertical and horizontal units are not the same.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_gaussian_scale_space <- function(dem, output, output_zscore, output_scale, points=NULL, sigma=0.5, step=0.5, num_steps=10, lsp="Slope", z_factor=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--output_zscore=", wbt_file_path(output_zscore)))
args <- paste(args, paste0("--output_scale=", wbt_file_path(output_scale)))
if (!is.null(points)) {
args <- paste(args, paste0("--points=", points))
}
if (!is.null(sigma)) {
args <- paste(args, paste0("--sigma=", sigma))
}
if (!is.null(step)) {
args <- paste(args, paste0("--step=", step))
}
if (!is.null(num_steps)) {
args <- paste(args, paste0("--num_steps=", num_steps))
}
if (!is.null(lsp)) {
args <- paste(args, paste0("--lsp=", lsp))
}
if (!is.null(z_factor)) {
args <- paste(args, paste0("--z_factor=", z_factor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "gaussian_scale_space"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Generating function
#'
#' @description This tool calculates generating function from an input DEM.
#'
#' @param dem Name of the input raster DEM file.
#' @param output Name of the output raster image file.
#' @param log Display output values using a log-scale.
#' @param zfactor Z conversion factor.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_generating_function <- function(dem, output, log=FALSE, zfactor=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (log) {
args <- paste(args, "--log")
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "generating_function"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Geomorphons
#'
#' @description Computes geomorphon patterns.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param search Look up distance (in cells).
#' @param threshold Flatness threshold for the classification function (in degrees).
#' @param fdist Distance (in cells) to begin reducing the flatness threshold to avoid problems with pseudo-flat lines-of-sight.
#' @param skip Distance (in cells) to begin calculating lines-of-sight.
#' @param forms Classify geomorphons into 10 common land morphologies, else output ternary pattern.
#' @param residuals Convert elevation to residuals of a linear model.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_geomorphons <- function(dem, output, search=50, threshold=0.0, fdist=0, skip=0, forms=TRUE, residuals=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(search)) {
args <- paste(args, paste0("--search=", search))
}
if (!is.null(threshold)) {
args <- paste(args, paste0("--threshold=", threshold))
}
if (!is.null(fdist)) {
args <- paste(args, paste0("--fdist=", fdist))
}
if (!is.null(skip)) {
args <- paste(args, paste0("--skip=", skip))
}
if (forms) {
args <- paste(args, "--forms")
}
if (residuals) {
args <- paste(args, "--residuals")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "geomorphons"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Hillshade
#'
#' @description Calculates a hillshade raster from an input DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param azimuth Illumination source azimuth in degrees.
#' @param altitude Illumination source altitude in degrees.
#' @param zfactor Optional multiplier for when the vertical and horizontal units are not the same.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_hillshade <- function(dem, output, azimuth=315.0, altitude=30.0, zfactor=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(azimuth)) {
args <- paste(args, paste0("--azimuth=", azimuth))
}
if (!is.null(altitude)) {
args <- paste(args, paste0("--altitude=", altitude))
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "hillshade"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Horizon angle
#'
#' @description Calculates horizon angle (maximum upwind slope) for each grid cell in an input DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param azimuth Azimuth, in degrees.
#' @param max_dist Optional maximum search distance (unspecified if none; in xy units). Minimum value is 5 x cell size.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_horizon_angle <- function(dem, output, azimuth=0.0, max_dist=100.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(azimuth)) {
args <- paste(args, paste0("--azimuth=", azimuth))
}
if (!is.null(max_dist)) {
args <- paste(args, paste0("--max_dist=", max_dist))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "horizon_angle"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Horizontal excess curvature
#'
#' @description This tool calculates horizontal excess curvature from an input DEM.
#'
#' @param dem Name of the input raster DEM file.
#' @param output Name of the output raster image file.
#' @param log Display output values using a log-scale.
#' @param zfactor Z conversion factor.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_horizontal_excess_curvature <- function(dem, output, log=FALSE, zfactor=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (log) {
args <- paste(args, "--log")
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "horizontal_excess_curvature"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Hypsometric analysis
#'
#' @description Calculates a hypsometric curve for one or more DEMs.
#'
#' @param inputs Input DEM files.
#' @param watershed Input watershed files (optional).
#' @param output Output HTML file (default name will be based on input file if unspecified).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_hypsometric_analysis <- function(inputs, output, watershed=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(watershed)) {
args <- paste(args, paste0("--watershed=", watershed))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "hypsometric_analysis"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Hypsometrically tinted hillshade
#'
#' @description Creates an colour shaded relief image from an input DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param altitude Illumination source altitude in degrees.
#' @param hs_weight Weight given to hillshade relative to relief (0.0-1.0).
#' @param brightness Brightness factor (0.0-1.0).
#' @param atmospheric Atmospheric effects weight (0.0-1.0).
#' @param palette Options include 'atlas', 'high_relief', 'arid', 'soft', 'muted', 'purple', 'viridis', 'gn_yl', 'pi_y_g', 'bl_yl_rd', and 'deep'.
#' @param reverse Optional flag indicating whether to use reverse the palette.
#' @param zfactor Optional multiplier for when the vertical and horizontal units are not the same.
#' @param full_mode Optional flag indicating whether to use full 360-degrees of illumination sources.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_hypsometrically_tinted_hillshade <- function(dem, output, altitude=45.0, hs_weight=0.5, brightness=0.5, atmospheric=0.0, palette="atlas", reverse=FALSE, zfactor=NULL, full_mode=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(altitude)) {
args <- paste(args, paste0("--altitude=", altitude))
}
if (!is.null(hs_weight)) {
args <- paste(args, paste0("--hs_weight=", hs_weight))
}
if (!is.null(brightness)) {
args <- paste(args, paste0("--brightness=", brightness))
}
if (!is.null(atmospheric)) {
args <- paste(args, paste0("--atmospheric=", atmospheric))
}
if (!is.null(palette)) {
args <- paste(args, paste0("--palette=", palette))
}
if (reverse) {
args <- paste(args, "--reverse")
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (full_mode) {
args <- paste(args, "--full_mode")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "hypsometrically_tinted_hillshade"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Local hypsometric analysis
#'
#' @description This tool calculates a local, neighbourhood-based hypsometric integral raster.
#'
#' @param input Name of the input raster DEM file.
#' @param out_mag Name of the openness output raster file.
#' @param out_scale Name of the openness output raster file.
#' @param min_scale Minimum search neighbourhood radius in grid cells.
#' @param step Step size as any positive non-zero integer.
#' @param num_steps Number of steps.
#' @param step_nonlinearity Step nonlinearity factor (1.0-2.0 is typical).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_local_hypsometric_analysis <- function(input, out_mag, out_scale, min_scale=4, step=1, num_steps=10, step_nonlinearity=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--out_mag=", wbt_file_path(out_mag)))
args <- paste(args, paste0("--out_scale=", wbt_file_path(out_scale)))
if (!is.null(min_scale)) {
args <- paste(args, paste0("--min_scale=", min_scale))
}
if (!is.null(step)) {
args <- paste(args, paste0("--step=", step))
}
if (!is.null(num_steps)) {
args <- paste(args, paste0("--num_steps=", num_steps))
}
if (!is.null(step_nonlinearity)) {
args <- paste(args, paste0("--step_nonlinearity=", step_nonlinearity))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "local_hypsometric_analysis"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Local quadratic regression
#'
#' @description An implementation of the constrained quadratic regression algorithm using a flexible window size described in Wood (1996).
#'
#' @param dem Name of the input DEM raster file.
#' @param output Name of the output raster file.
#' @param filter Edge length of the filter kernel.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_local_quadratic_regression <- function(dem, output, filter=3, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filter)) {
args <- paste(args, paste0("--filter=", filter))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "local_quadratic_regression"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Map off terrain objects
#'
#' @description Maps off-terrain objects in a digital elevation model (DEM).
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param max_slope Maximum inter-cell absolute slope.
#' @param min_size Minimum feature size, in grid cells.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_map_off_terrain_objects <- function(dem, output, max_slope=40.0, min_size=1, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(max_slope)) {
args <- paste(args, paste0("--max_slope=", max_slope))
}
if (!is.null(min_size)) {
args <- paste(args, paste0("--min_size=", min_size))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "map_off_terrain_objects"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Max anisotropy dev
#'
#' @description Calculates the maximum anisotropy (directionality) in elevation deviation over a range of spatial scales.
#'
#' @param dem Input raster DEM file.
#' @param out_mag Output raster DEVmax magnitude file.
#' @param out_scale Output raster DEVmax scale file.
#' @param min_scale Minimum search neighbourhood radius in grid cells.
#' @param max_scale Maximum search neighbourhood radius in grid cells.
#' @param step Step size as any positive non-zero integer.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_max_anisotropy_dev <- function(dem, out_mag, out_scale, max_scale, min_scale=3, step=2, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--out_mag=", wbt_file_path(out_mag)))
args <- paste(args, paste0("--out_scale=", wbt_file_path(out_scale)))
args <- paste(args, paste0("--max_scale=", wbt_file_path(max_scale)))
if (!is.null(min_scale)) {
args <- paste(args, paste0("--min_scale=", min_scale))
}
if (!is.null(step)) {
args <- paste(args, paste0("--step=", step))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "max_anisotropy_dev"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Max anisotropy dev signature
#'
#' @description Calculates the anisotropy in deviation from mean for points over a range of spatial scales.
#'
#' @param dem Input raster DEM file.
#' @param points Input vector points file.
#' @param output Output HTML file.
#' @param min_scale Minimum search neighbourhood radius in grid cells.
#' @param max_scale Maximum search neighbourhood radius in grid cells.
#' @param step Step size as any positive non-zero integer.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_max_anisotropy_dev_signature <- function(dem, points, output, max_scale, min_scale=1, step=1, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--points=", wbt_file_path(points)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--max_scale=", wbt_file_path(max_scale)))
if (!is.null(min_scale)) {
args <- paste(args, paste0("--min_scale=", min_scale))
}
if (!is.null(step)) {
args <- paste(args, paste0("--step=", step))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "max_anisotropy_dev_signature"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Max branch length
#'
#' @description Lindsay and Seibert's (2013) branch length index is used to map drainage divides or ridge lines.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param log Optional flag to request the output be log-transformed.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_max_branch_length <- function(dem, output, log=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (log) {
args <- paste(args, "--log")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "max_branch_length"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Max difference from mean
#'
#' @description Calculates the maximum difference from mean elevation over a range of spatial scales.
#'
#' @param dem Input raster DEM file.
#' @param out_mag Output raster DIFFmax magnitude file.
#' @param out_scale Output raster DIFFmax scale file.
#' @param min_scale Minimum search neighbourhood radius in grid cells.
#' @param max_scale Maximum search neighbourhood radius in grid cells.
#' @param step Step size as any positive non-zero integer.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_max_difference_from_mean <- function(dem, out_mag, out_scale, min_scale, max_scale, step=1, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--out_mag=", wbt_file_path(out_mag)))
args <- paste(args, paste0("--out_scale=", wbt_file_path(out_scale)))
args <- paste(args, paste0("--min_scale=", wbt_file_path(min_scale)))
args <- paste(args, paste0("--max_scale=", wbt_file_path(max_scale)))
if (!is.null(step)) {
args <- paste(args, paste0("--step=", step))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "max_difference_from_mean"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Max downslope elev change
#'
#' @description Calculates the maximum downslope change in elevation between a grid cell and its eight downslope neighbors.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_max_downslope_elev_change <- function(dem, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "max_downslope_elev_change"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Max elev dev signature
#'
#' @description Calculates the maximum elevation deviation over a range of spatial scales and for a set of points.
#'
#' @param dem Input raster DEM file.
#' @param points Input vector points file.
#' @param output Output HTML file.
#' @param min_scale Minimum search neighbourhood radius in grid cells.
#' @param max_scale Maximum search neighbourhood radius in grid cells.
#' @param step Step size as any positive non-zero integer.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_max_elev_dev_signature <- function(dem, points, output, min_scale, max_scale, step=10, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--points=", wbt_file_path(points)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--min_scale=", wbt_file_path(min_scale)))
args <- paste(args, paste0("--max_scale=", wbt_file_path(max_scale)))
if (!is.null(step)) {
args <- paste(args, paste0("--step=", step))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "max_elev_dev_signature"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Max elevation deviation
#'
#' @description Calculates the maximum elevation deviation over a range of spatial scales.
#'
#' @param dem Input raster DEM file.
#' @param out_mag Output raster DEVmax magnitude file.
#' @param out_scale Output raster DEVmax scale file.
#' @param min_scale Minimum search neighbourhood radius in grid cells.
#' @param max_scale Maximum search neighbourhood radius in grid cells.
#' @param step Step size as any positive non-zero integer.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_max_elevation_deviation <- function(dem, out_mag, out_scale, min_scale, max_scale, step=1, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--out_mag=", wbt_file_path(out_mag)))
args <- paste(args, paste0("--out_scale=", wbt_file_path(out_scale)))
args <- paste(args, paste0("--min_scale=", wbt_file_path(min_scale)))
args <- paste(args, paste0("--max_scale=", wbt_file_path(max_scale)))
if (!is.null(step)) {
args <- paste(args, paste0("--step=", step))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "max_elevation_deviation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Max upslope elev change
#'
#' @description Calculates the maximum upslope change in elevation between a grid cell and its eight downslope neighbors.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_max_upslope_elev_change <- function(dem, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "max_upslope_elev_change"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Maximal curvature
#'
#' @description Calculates a mean curvature raster from an input DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param log Display output values using a log-scale.
#' @param zfactor Optional multiplier for when the vertical and horizontal units are not the same.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_maximal_curvature <- function(dem, output, log=FALSE, zfactor=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (log) {
args <- paste(args, "--log")
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "maximal_curvature"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Mean curvature
#'
#' @description Calculates a mean curvature raster from an input DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param log Display output values using a log-scale.
#' @param zfactor Optional multiplier for when the vertical and horizontal units are not the same.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_mean_curvature <- function(dem, output, log=FALSE, zfactor=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (log) {
args <- paste(args, "--log")
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "mean_curvature"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Min downslope elev change
#'
#' @description Calculates the minimum downslope change in elevation between a grid cell and its eight downslope neighbors.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_min_downslope_elev_change <- function(dem, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "min_downslope_elev_change"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Minimal curvature
#'
#' @description Calculates a mean curvature raster from an input DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param log Display output values using a log-scale.
#' @param zfactor Optional multiplier for when the vertical and horizontal units are not the same.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_minimal_curvature <- function(dem, output, log=FALSE, zfactor=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (log) {
args <- paste(args, "--log")
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "minimal_curvature"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Multidirectional hillshade
#'
#' @description Calculates a multi-direction hillshade raster from an input DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param altitude Illumination source altitude in degrees.
#' @param zfactor Optional multiplier for when the vertical and horizontal units are not the same.
#' @param full_mode Optional flag indicating whether to use full 360-degrees of illumination sources.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_multidirectional_hillshade <- function(dem, output, altitude=45.0, zfactor=NULL, full_mode=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(altitude)) {
args <- paste(args, paste0("--altitude=", altitude))
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (full_mode) {
args <- paste(args, "--full_mode")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "multidirectional_hillshade"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Multiscale curvatures
#'
#' @description This tool calculates several multiscale curvatures and curvature-based indices from an input DEM.
#'
#' @param dem Name of the input raster DEM file.
#' @param curv_type Curvature type.
#' @param out_mag Output raster magnitude file.
#' @param out_scale Output raster scale file.
#' @param min_scale Minimum search neighbourhood radius in grid cells.
#' @param step Step size as any positive non-zero integer.
#' @param num_steps Number of steps.
#' @param step_nonlinearity Step nonlinearity factor (1.0-2.0 is typical).
#' @param log Display output values using a log-scale.
#' @param standardize Should each scale be standardized to z-scores?.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_multiscale_curvatures <- function(dem, out_mag, curv_type="ProfileCurv", out_scale=NULL, min_scale=0, step=1, num_steps=1, step_nonlinearity=1.0, log=TRUE, standardize=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--out_mag=", wbt_file_path(out_mag)))
if (!is.null(curv_type)) {
args <- paste(args, paste0("--curv_type=", curv_type))
}
if (!is.null(out_scale)) {
args <- paste(args, paste0("--out_scale=", out_scale))
}
if (!is.null(min_scale)) {
args <- paste(args, paste0("--min_scale=", min_scale))
}
if (!is.null(step)) {
args <- paste(args, paste0("--step=", step))
}
if (!is.null(num_steps)) {
args <- paste(args, paste0("--num_steps=", num_steps))
}
if (!is.null(step_nonlinearity)) {
args <- paste(args, paste0("--step_nonlinearity=", step_nonlinearity))
}
if (log) {
args <- paste(args, "--log")
}
if (standardize) {
args <- paste(args, "--standardize")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "multiscale_curvatures"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Multiscale elevation percentile
#'
#' @description Calculates surface roughness over a range of spatial scales.
#'
#' @param dem Input raster DEM file.
#' @param out_mag Output raster roughness magnitude file.
#' @param out_scale Output raster roughness scale file.
#' @param sig_digits Number of significant digits.
#' @param min_scale Minimum search neighbourhood radius in grid cells.
#' @param step Step size as any positive non-zero integer.
#' @param num_steps Number of steps.
#' @param step_nonlinearity Step nonlinearity factor (1.0-2.0 is typical).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_multiscale_elevation_percentile <- function(dem, out_mag, out_scale, sig_digits=3, min_scale=4, step=1, num_steps=10, step_nonlinearity=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--out_mag=", wbt_file_path(out_mag)))
args <- paste(args, paste0("--out_scale=", wbt_file_path(out_scale)))
if (!is.null(sig_digits)) {
args <- paste(args, paste0("--sig_digits=", sig_digits))
}
if (!is.null(min_scale)) {
args <- paste(args, paste0("--min_scale=", min_scale))
}
if (!is.null(step)) {
args <- paste(args, paste0("--step=", step))
}
if (!is.null(num_steps)) {
args <- paste(args, paste0("--num_steps=", num_steps))
}
if (!is.null(step_nonlinearity)) {
args <- paste(args, paste0("--step_nonlinearity=", step_nonlinearity))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "multiscale_elevation_percentile"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Multiscale roughness
#'
#' @description Calculates surface roughness over a range of spatial scales.
#'
#' @param dem Input raster DEM file.
#' @param out_mag Output raster roughness magnitude file.
#' @param out_scale Output raster roughness scale file.
#' @param min_scale Minimum search neighbourhood radius in grid cells.
#' @param max_scale Maximum search neighbourhood radius in grid cells.
#' @param step Step size as any positive non-zero integer.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_multiscale_roughness <- function(dem, out_mag, out_scale, max_scale, min_scale=1, step=1, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--out_mag=", wbt_file_path(out_mag)))
args <- paste(args, paste0("--out_scale=", wbt_file_path(out_scale)))
args <- paste(args, paste0("--max_scale=", wbt_file_path(max_scale)))
if (!is.null(min_scale)) {
args <- paste(args, paste0("--min_scale=", min_scale))
}
if (!is.null(step)) {
args <- paste(args, paste0("--step=", step))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "multiscale_roughness"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Multiscale roughness signature
#'
#' @description Calculates the surface roughness for points over a range of spatial scales.
#'
#' @param dem Input raster DEM file.
#' @param points Input vector points file.
#' @param output Output HTML file.
#' @param min_scale Minimum search neighbourhood radius in grid cells.
#' @param max_scale Maximum search neighbourhood radius in grid cells.
#' @param step Step size as any positive non-zero integer.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_multiscale_roughness_signature <- function(dem, points, output, max_scale, min_scale=1, step=1, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--points=", wbt_file_path(points)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--max_scale=", wbt_file_path(max_scale)))
if (!is.null(min_scale)) {
args <- paste(args, paste0("--min_scale=", min_scale))
}
if (!is.null(step)) {
args <- paste(args, paste0("--step=", step))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "multiscale_roughness_signature"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Multiscale std dev normals
#'
#' @description Calculates surface roughness over a range of spatial scales.
#'
#' @param dem Input raster DEM file.
#' @param out_mag Output raster roughness magnitude file.
#' @param out_scale Output raster roughness scale file.
#' @param min_scale Minimum search neighbourhood radius in grid cells.
#' @param step Step size as any positive non-zero integer.
#' @param num_steps Number of steps.
#' @param step_nonlinearity Step nonlinearity factor (1.0-2.0 is typical).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_multiscale_std_dev_normals <- function(dem, out_mag, out_scale, min_scale=1, step=1, num_steps=10, step_nonlinearity=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--out_mag=", wbt_file_path(out_mag)))
args <- paste(args, paste0("--out_scale=", wbt_file_path(out_scale)))
if (!is.null(min_scale)) {
args <- paste(args, paste0("--min_scale=", min_scale))
}
if (!is.null(step)) {
args <- paste(args, paste0("--step=", step))
}
if (!is.null(num_steps)) {
args <- paste(args, paste0("--num_steps=", num_steps))
}
if (!is.null(step_nonlinearity)) {
args <- paste(args, paste0("--step_nonlinearity=", step_nonlinearity))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "multiscale_std_dev_normals"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Multiscale std dev normals signature
#'
#' @description Calculates the surface roughness for points over a range of spatial scales.
#'
#' @param dem Input raster DEM file.
#' @param points Input vector points file.
#' @param output Output HTML file.
#' @param min_scale Minimum search neighbourhood radius in grid cells.
#' @param step Step size as any positive non-zero integer.
#' @param num_steps Number of steps.
#' @param step_nonlinearity Step nonlinearity factor (1.0-2.0 is typical).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_multiscale_std_dev_normals_signature <- function(dem, points, output, min_scale=1, step=1, num_steps=10, step_nonlinearity=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--points=", wbt_file_path(points)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(min_scale)) {
args <- paste(args, paste0("--min_scale=", min_scale))
}
if (!is.null(step)) {
args <- paste(args, paste0("--step=", step))
}
if (!is.null(num_steps)) {
args <- paste(args, paste0("--num_steps=", num_steps))
}
if (!is.null(step_nonlinearity)) {
args <- paste(args, paste0("--step_nonlinearity=", step_nonlinearity))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "multiscale_std_dev_normals_signature"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Multiscale topographic position image
#'
#' @description Creates a multiscale topographic position image from three DEVmax rasters of differing spatial scale ranges.
#'
#' @param local Input local-scale topographic position (DEVmax) raster file.
#' @param meso Input meso-scale topographic position (DEVmax) raster file.
#' @param broad Input broad-scale topographic position (DEVmax) raster file.
#' @param hillshade Input optional hillshade raster file. Note: a multi-directional (360-degree option) hillshade tends to work best in this application.
#' @param output Output raster file.
#' @param lightness Image lightness value (default is 1.2).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_multiscale_topographic_position_image <- function(local, meso, broad, output, hillshade=NULL, lightness=1.2, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--local=", wbt_file_path(local)))
args <- paste(args, paste0("--meso=", wbt_file_path(meso)))
args <- paste(args, paste0("--broad=", wbt_file_path(broad)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(hillshade)) {
args <- paste(args, paste0("--hillshade=", hillshade))
}
if (!is.null(lightness)) {
args <- paste(args, paste0("--lightness=", lightness))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "multiscale_topographic_position_image"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Num downslope neighbours
#'
#' @description Calculates the number of downslope neighbours to each grid cell in a DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_num_downslope_neighbours <- function(dem, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "num_downslope_neighbours"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Num upslope neighbours
#'
#' @description Calculates the number of upslope neighbours to each grid cell in a DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_num_upslope_neighbours <- function(dem, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "num_upslope_neighbours"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Openness
#'
#' @description This tool calculates the topographic openness index from an input DEM.
#'
#' @param input Name of the input raster DEM file.
#' @param pos_output Name of the positive openness output raster file.
#' @param neg_output Name of the negative openness output raster file.
#' @param dist Search distance, in grid cells.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_openness <- function(input, pos_output, neg_output, dist=20, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--pos_output=", wbt_file_path(pos_output)))
args <- paste(args, paste0("--neg_output=", wbt_file_path(neg_output)))
if (!is.null(dist)) {
args <- paste(args, paste0("--dist=", dist))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "openness"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Pennock landform class
#'
#' @description Classifies hillslope zones based on slope, profile curvature, and plan curvature.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param slope Slope threshold value, in degrees (default is 3.0).
#' @param prof Profile curvature threshold value (default is 0.1).
#' @param plan Plan curvature threshold value (default is 0.0).
#' @param zfactor Optional multiplier for when the vertical and horizontal units are not the same.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_pennock_landform_class <- function(dem, output, slope=3.0, prof=0.1, plan=0.0, zfactor=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(slope)) {
args <- paste(args, paste0("--slope=", slope))
}
if (!is.null(prof)) {
args <- paste(args, paste0("--prof=", prof))
}
if (!is.null(plan)) {
args <- paste(args, paste0("--plan=", plan))
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "pennock_landform_class"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Percent elev range
#'
#' @description Calculates percent of elevation range from a DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param filterx Size of the filter kernel in the x-direction.
#' @param filtery Size of the filter kernel in the y-direction.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_percent_elev_range <- function(dem, output, filterx=3, filtery=3, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filterx)) {
args <- paste(args, paste0("--filterx=", filterx))
}
if (!is.null(filtery)) {
args <- paste(args, paste0("--filtery=", filtery))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "percent_elev_range"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Plan curvature
#'
#' @description Calculates a plan (contour) curvature raster from an input DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param log Display output values using a log-scale.
#' @param zfactor Optional multiplier for when the vertical and horizontal units are not the same.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_plan_curvature <- function(dem, output, log=FALSE, zfactor=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (log) {
args <- paste(args, "--log")
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "plan_curvature"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Profile
#'
#' @description Plots profiles from digital surface models.
#'
#' @param lines Input vector line file.
#' @param surface Input raster surface file.
#' @param output Output HTML file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_profile <- function(lines, surface, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--lines=", wbt_file_path(lines)))
args <- paste(args, paste0("--surface=", wbt_file_path(surface)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "profile"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Profile curvature
#'
#' @description Calculates a profile curvature raster from an input DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param log Display output values using a log-scale.
#' @param zfactor Optional multiplier for when the vertical and horizontal units are not the same.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_profile_curvature <- function(dem, output, log=FALSE, zfactor=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (log) {
args <- paste(args, "--log")
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "profile_curvature"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Relative aspect
#'
#' @description Calculates relative aspect (relative to a user-specified direction) from an input DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param azimuth Illumination source azimuth.
#' @param zfactor Optional multiplier for when the vertical and horizontal units are not the same.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_relative_aspect <- function(dem, output, azimuth=0.0, zfactor=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(azimuth)) {
args <- paste(args, paste0("--azimuth=", azimuth))
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "relative_aspect"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Relative topographic position
#'
#' @description Calculates the relative topographic position index from a DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param filterx Size of the filter kernel in the x-direction.
#' @param filtery Size of the filter kernel in the y-direction.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_relative_topographic_position <- function(dem, output, filterx=11, filtery=11, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filterx)) {
args <- paste(args, paste0("--filterx=", filterx))
}
if (!is.null(filtery)) {
args <- paste(args, paste0("--filtery=", filtery))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "relative_topographic_position"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Remove off terrain objects
#'
#' @description Removes off-terrain objects from a raster digital elevation model (DEM).
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param filter Filter size (cells).
#' @param slope Slope threshold value.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_remove_off_terrain_objects <- function(dem, output, filter=11, slope=15.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filter)) {
args <- paste(args, paste0("--filter=", filter))
}
if (!is.null(slope)) {
args <- paste(args, paste0("--slope=", slope))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "remove_off_terrain_objects"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Ring curvature
#'
#' @description This tool calculates ring curvature from an input DEM.
#'
#' @param dem Name of the input raster DEM file.
#' @param output Name of the output raster image file.
#' @param log Display output values using a log-scale.
#' @param zfactor Z conversion factor.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_ring_curvature <- function(dem, output, log=FALSE, zfactor=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (log) {
args <- paste(args, "--log")
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "ring_curvature"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Rotor
#'
#' @description This tool calculates rotor from an input DEM.
#'
#' @param dem Name of the input raster DEM file.
#' @param output Name of the output raster image file.
#' @param log Display output values using a log-scale.
#' @param zfactor Z conversion factor.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_rotor <- function(dem, output, log=FALSE, zfactor=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (log) {
args <- paste(args, "--log")
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "rotor"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Ruggedness index
#'
#' @description Calculates the Riley et al.'s (1999) terrain ruggedness index from an input DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_ruggedness_index <- function(dem, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "ruggedness_index"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Sediment transport index
#'
#' @description Calculates the sediment transport index.
#'
#' @param sca Input raster specific contributing area (SCA) file.
#' @param slope Input raster slope file.
#' @param output Output raster file.
#' @param sca_exponent SCA exponent value.
#' @param slope_exponent Slope exponent value.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_sediment_transport_index <- function(sca, slope, output, sca_exponent=0.4, slope_exponent=1.3, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--sca=", wbt_file_path(sca)))
args <- paste(args, paste0("--slope=", wbt_file_path(slope)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(sca_exponent)) {
args <- paste(args, paste0("--sca_exponent=", sca_exponent))
}
if (!is.null(slope_exponent)) {
args <- paste(args, paste0("--slope_exponent=", slope_exponent))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "sediment_transport_index"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Shadow animation
#'
#' @description This tool creates an animated GIF of shadows based on an input DEM.
#'
#' @param input Name of the input digital surface model (DSM) raster file.
#' @param palette DSM image palette; options are 'atlas', 'high_relief', 'arid', 'soft', 'muted', 'light_quant', 'purple', 'viridis', 'gn_yl', 'pi_y_g', 'bl_yl_rd', 'deep', and 'none'.
#' @param output Name of the output HTML file (*.html).
#' @param max_dist Optional maximum search distance, in xy units. Minimum value is 5 x cell size.
#' @param date Date in format DD/MM/YYYY.
#' @param interval Time interval, in minutes (1-60).
#' @param location Location, defined as Lat/Long/UTC-offset (e.g. 43.5448/-80.2482/-4).
#' @param height Image height, in pixels.
#' @param delay GIF time delay in milliseconds.
#' @param label Label text (leave blank for none).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_shadow_animation <- function(input, output, palette="atlas", max_dist="", date="21/06/2021", interval=15, location="43.5448/-80.2482/-4", height=600, delay=250, label="", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(palette)) {
args <- paste(args, paste0("--palette=", palette))
}
if (!is.null(max_dist)) {
args <- paste(args, paste0("--max_dist=", max_dist))
}
if (!is.null(date)) {
args <- paste(args, paste0("--date=", date))
}
if (!is.null(interval)) {
args <- paste(args, paste0("--interval=", interval))
}
if (!is.null(location)) {
args <- paste(args, paste0("--location=", location))
}
if (!is.null(height)) {
args <- paste(args, paste0("--height=", height))
}
if (!is.null(delay)) {
args <- paste(args, paste0("--delay=", delay))
}
if (!is.null(label)) {
args <- paste(args, paste0("--label=", label))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "shadow_animation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Shadow image
#'
#' @description This tool creates a raster of shadow areas based on an input DEM.
#'
#' @param input Name of the input digital surface model (DSM) raster file.
#' @param palette DSM image palette; options are 'atlas', 'high_relief', 'arid', 'soft', 'muted', 'light_quant', 'purple', 'viridi', 'gn_yl', 'pi_y_g', 'bl_yl_rd', 'deep', and 'none'.
#' @param output Name of the output raster file.
#' @param max_dist Optional maximum search distance, in xy unites. Minimum value is 5 x cell size.
#' @param date Date in format DD/MM/YYYY.
#' @param time Time in format HH::MM, e.g. 03:15AM or 14:30.
#' @param location Location, defined as Lat/Long/UTC-offset (e.g. 43.5448/-80.2482/-4).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_shadow_image <- function(input, output, palette="soft", max_dist="", date="21/06/2021", time="13:00", location="43.5448/-80.2482/-4", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(palette)) {
args <- paste(args, paste0("--palette=", palette))
}
if (!is.null(max_dist)) {
args <- paste(args, paste0("--max_dist=", max_dist))
}
if (!is.null(date)) {
args <- paste(args, paste0("--date=", date))
}
if (!is.null(time)) {
args <- paste(args, paste0("--time=", time))
}
if (!is.null(location)) {
args <- paste(args, paste0("--location=", location))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "shadow_image"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Shape index
#'
#' @description This tool calculates the shape index from an input DEM.
#'
#' @param dem Name of the input raster DEM file.
#' @param output Name of the output raster image file.
#' @param zfactor Z conversion factor.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_shape_index <- function(dem, output, zfactor=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "shape_index"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Slope
#'
#' @description Calculates a slope raster from an input DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param zfactor Optional multiplier for when the vertical and horizontal units are not the same.
#' @param units Units of output raster; options include 'degrees', 'radians', 'percent'.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_slope <- function(dem, output, zfactor=NULL, units="degrees", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!is.null(units)) {
args <- paste(args, paste0("--units=", units))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "slope"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Slope vs aspect plot
#'
#' @description This tool creates a slope-aspect relation plot from an input DEM.
#'
#' @param input Name of the input raster image file.
#' @param output Name of the output report file (*.html).
#' @param bin_size Aspect bin size, in degrees.
#' @param min_slope Minimum slope, in degrees.
#' @param zfactor Z conversion factor.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_slope_vs_aspect_plot <- function(input, output, bin_size=2.0, min_slope=0.1, zfactor=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(bin_size)) {
args <- paste(args, paste0("--bin_size=", bin_size))
}
if (!is.null(min_slope)) {
args <- paste(args, paste0("--min_slope=", min_slope))
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "slope_vs_aspect_plot"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Slope vs elevation plot
#'
#' @description Creates a slope vs. elevation plot for one or more DEMs.
#'
#' @param inputs Input DEM files.
#' @param watershed Input watershed files (optional).
#' @param output Output HTML file (default name will be based on input file if unspecified).
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_slope_vs_elevation_plot <- function(inputs, output, watershed=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--inputs=", wbt_file_path(inputs)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(watershed)) {
args <- paste(args, paste0("--watershed=", watershed))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "slope_vs_elevation_plot"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Smooth vegetation residual
#'
#' @description This tool can smooth the residual roughness due to vegetation cover in LiDAR DEMs.
#'
#' @param input Name of the input digital elevation model (DEM) raster file.
#' @param output Name of the output raster file.
#' @param max_scale Maximum search neighbourhood radius in grid cells.
#' @param dev_threshold DEVmax Threshold.
#' @param scale_threshold DEVmax scale threshold.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_smooth_vegetation_residual <- function(input, output, max_scale=30, dev_threshold=1.0, scale_threshold=5, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(max_scale)) {
args <- paste(args, paste0("--max_scale=", max_scale))
}
if (!is.null(dev_threshold)) {
args <- paste(args, paste0("--dev_threshold=", dev_threshold))
}
if (!is.null(scale_threshold)) {
args <- paste(args, paste0("--scale_threshold=", scale_threshold))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "smooth_vegetation_residual"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Spherical std dev of normals
#'
#' @description Calculates the spherical standard deviation of surface normals for a DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param filter Size of the filter kernel.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_spherical_std_dev_of_normals <- function(dem, output, filter=11, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(filter)) {
args <- paste(args, paste0("--filter=", filter))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "spherical_std_dev_of_normals"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Standard deviation of slope
#'
#' @description Calculates the standard deviation of slope from an input DEM.
#'
#' @param input Input raster DEM file.
#' @param output Output raster DEM file.
#' @param zfactor Optional multiplier for when the vertical and horizontal units are not the same.
#' @param filterx Size of the filter kernel in the x-direction.
#' @param filtery Size of the filter kernel in the y-direction.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_standard_deviation_of_slope <- function(input, output, zfactor=NULL, filterx=11, filtery=11, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!is.null(filterx)) {
args <- paste(args, paste0("--filterx=", filterx))
}
if (!is.null(filtery)) {
args <- paste(args, paste0("--filtery=", filtery))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "standard_deviation_of_slope"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Stream power index
#'
#' @description Calculates the relative stream power index.
#'
#' @param sca Input raster specific contributing area (SCA) file.
#' @param slope Input raster slope file.
#' @param output Output raster file.
#' @param exponent SCA exponent value.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_stream_power_index <- function(sca, slope, output, exponent=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--sca=", wbt_file_path(sca)))
args <- paste(args, paste0("--slope=", wbt_file_path(slope)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(exponent)) {
args <- paste(args, paste0("--exponent=", exponent))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "stream_power_index"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Surface area ratio
#'
#' @description Calculates a the surface area ratio of each grid cell in an input DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_surface_area_ratio <- function(dem, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "surface_area_ratio"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Tangential curvature
#'
#' @description Calculates a tangential curvature raster from an input DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param log Display output values using a log-scale.
#' @param zfactor Optional multiplier for when the vertical and horizontal units are not the same.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_tangential_curvature <- function(dem, output, log=FALSE, zfactor=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (log) {
args <- paste(args, "--log")
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "tangential_curvature"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Time in daylight
#'
#' @description Calculates the proportion of time a location is not within an area of shadow.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param az_fraction Azimuth fraction in degrees.
#' @param max_dist Optional maximum search distance. Minimum value is 5 x cell size.
#' @param lat Centre point latitude.
#' @param long Centre point longitude.
#' @param utc_offset UTC time offset, in hours (e.g. -04:00, +06:00).
#' @param start_day Start day of the year (1-365).
#' @param end_day End day of the year (1-365).
#' @param start_time Starting hour to track shadows (e.g. 5, 5:00, 05:00:00). Assumes 24-hour time: HH:MM:SS. 'sunrise' is also a valid time.
#' @param end_time Ending hour to track shadows (e.g. 21, 21:00, 21:00:00). Assumes 24-hour time: HH:MM:SS. 'sunset' is also a valid time.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_time_in_daylight <- function(dem, output, lat, long, az_fraction=10.0, max_dist=100.0, utc_offset="00:00", start_day=1, end_day=365, start_time="00:00:00", end_time="23:59:59", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
args <- paste(args, paste0("--lat=", wbt_file_path(lat)))
args <- paste(args, paste0("--long=", wbt_file_path(long)))
if (!is.null(az_fraction)) {
args <- paste(args, paste0("--az_fraction=", az_fraction))
}
if (!is.null(max_dist)) {
args <- paste(args, paste0("--max_dist=", max_dist))
}
if (!is.null(utc_offset)) {
args <- paste(args, paste0("--utc_offset=", utc_offset))
}
if (!is.null(start_day)) {
args <- paste(args, paste0("--start_day=", start_day))
}
if (!is.null(end_day)) {
args <- paste(args, paste0("--end_day=", end_day))
}
if (!is.null(start_time)) {
args <- paste(args, paste0("--start_time=", start_time))
}
if (!is.null(end_time)) {
args <- paste(args, paste0("--end_time=", end_time))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "time_in_daylight"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Topo render
#'
#' @description This tool creates a pseudo-3D rendering from an input DEM, for the purpose of effective topographic visualization.
#'
#' @param dem Name of the input digital elevation model (DEM) raster file.
#' @param output Name of the output raster file.
#' @param palette Palette name; options are 'atlas', 'high_relief', 'arid', 'soft', 'earthtones', 'muted', 'light_quant', 'purple', 'viridi', 'gn_yl', 'pi_y_g', 'bl_yl_rd', 'deep', 'imhof', and 'white'.
#' @param rev_palette Reverse the palette?.
#' @param az Light source azimuth direction (degrees, 0-360).
#' @param alt Light source altitude (degrees, 0-90).
#' @param background_hgt_offset Offset height of background, in z-units.
#' @param polygon Clipping polygon vector file (optional).
#' @param background_clr Background red-green-blue (RGB) or red-green-blue-alpha (RGBA) colour, e.g. '`[255, 255, 245]`', '`[255, 255, 245, 200]`'.
#' @param attenuation Attenuation parameter. Range is 0-4. Zero means no attenuation.
#' @param ambient_light Ambient light parameter. Range is 0.0-0.7. Zero means no ambient light.
#' @param z_factor Elevation multiplier, or a vertical exageration.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_topo_render <- function(dem, output, palette="soft", rev_palette=FALSE, az=315.0, alt=30.0, background_hgt_offset=10.0, polygon=NULL, background_clr="[255, 255, 255]", attenuation=0.6, ambient_light=0.2, z_factor=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(palette)) {
args <- paste(args, paste0("--palette=", palette))
}
if (rev_palette) {
args <- paste(args, "--rev_palette")
}
if (!is.null(az)) {
args <- paste(args, paste0("--az=", az))
}
if (!is.null(alt)) {
args <- paste(args, paste0("--alt=", alt))
}
if (!is.null(background_hgt_offset)) {
args <- paste(args, paste0("--background_hgt_offset=", background_hgt_offset))
}
if (!is.null(polygon)) {
args <- paste(args, paste0("--polygon=", polygon))
}
if (!is.null(background_clr)) {
args <- paste(args, paste0("--background_clr=", background_clr))
}
args <- paste(args, paste0("--255=", wbt_file_path(255)))
if (!is.null(attenuation)) {
args <- paste(args, paste0("--attenuation=", attenuation))
}
if (!is.null(ambient_light)) {
args <- paste(args, paste0("--ambient_light=", ambient_light))
}
if (!is.null(z_factor)) {
args <- paste(args, paste0("--z_factor=", z_factor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "topo_render"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Topographic position animation
#'
#' @description This tool creates an animated GIF of multi-scale local topographic position (elevation deviation).
#'
#' @param input Name of the input digital elevation model (DEM) raster file.
#' @param palette Image palette; options are 'bl_yl_rd', 'bl_w_rd', 'purple', 'gn_yl', 'pi_y_g', and 'viridis'.
#' @param output Name of the output HTML file (*.html).
#' @param min_scale Minimum search neighbourhood radius in grid cells.
#' @param num_steps Number of steps.
#' @param step_nonlinearity Step nonlinearity factor (1.0-2.0 is typical).
#' @param height Image height, in pixels.
#' @param delay GIF time delay in milliseconds.
#' @param label Label text (leave blank for none).
#' @param dev_max Do you want to use DEVmax instead of DEV for measuring local topographic position?.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_topographic_position_animation <- function(input, output, palette="bl_yl_rd", min_scale=1, num_steps=100, step_nonlinearity=1.5, height=600, delay=250, label="", dev_max=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--input=", wbt_file_path(input)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(palette)) {
args <- paste(args, paste0("--palette=", palette))
}
if (!is.null(min_scale)) {
args <- paste(args, paste0("--min_scale=", min_scale))
}
if (!is.null(num_steps)) {
args <- paste(args, paste0("--num_steps=", num_steps))
}
if (!is.null(step_nonlinearity)) {
args <- paste(args, paste0("--step_nonlinearity=", step_nonlinearity))
}
if (!is.null(height)) {
args <- paste(args, paste0("--height=", height))
}
if (!is.null(delay)) {
args <- paste(args, paste0("--delay=", delay))
}
if (!is.null(label)) {
args <- paste(args, paste0("--label=", label))
}
if (dev_max) {
args <- paste(args, "--dev_max")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "topographic_position_animation"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Total curvature
#'
#' @description Calculates a total curvature raster from an input DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param log Display output values using a log-scale.
#' @param zfactor Optional multiplier for when the vertical and horizontal units are not the same.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_total_curvature <- function(dem, output, log=FALSE, zfactor=NULL, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (log) {
args <- paste(args, "--log")
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "total_curvature"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Unsphericity
#'
#' @description This tool calculates the unsphericity curvature from an input DEM.
#'
#' @param dem Name of the input raster DEM file.
#' @param output Name of the output raster image file.
#' @param log Display output values using a log-scale.
#' @param zfactor Z conversion factor.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_unsphericity <- function(dem, output, log=FALSE, zfactor=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (log) {
args <- paste(args, "--log")
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "unsphericity"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Vertical excess curvature
#'
#' @description This tool calculates vertical excess curvature from an input DEM.
#'
#' @param dem Name of the input raster DEM file.
#' @param output Name of the output raster image file.
#' @param log Display output values using a log-scale.
#' @param zfactor Z conversion factor.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_vertical_excess_curvature <- function(dem, output, log=FALSE, zfactor=1.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (log) {
args <- paste(args, "--log")
}
if (!is.null(zfactor)) {
args <- paste(args, paste0("--zfactor=", zfactor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "vertical_excess_curvature"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Viewshed
#'
#' @description Identifies the viewshed for a point or set of points.
#'
#' @param dem Input raster DEM file.
#' @param stations Input viewing station vector file.
#' @param output Output raster file.
#' @param height Viewing station height, in z units.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_viewshed <- function(dem, stations, output, height=2.0, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--stations=", wbt_file_path(stations)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(height)) {
args <- paste(args, paste0("--height=", height))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "viewshed"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Visibility index
#'
#' @description Estimates the relative visibility of sites in a DEM.
#'
#' @param dem Input raster DEM file.
#' @param output Output raster file.
#' @param height Viewing station height, in z units.
#' @param res_factor The resolution factor determines the density of measured viewsheds.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_visibility_index <- function(dem, output, height=2.0, res_factor=2, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--dem=", wbt_file_path(dem)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!is.null(height)) {
args <- paste(args, paste0("--height=", height))
}
if (!is.null(res_factor)) {
args <- paste(args, paste0("--res_factor=", res_factor))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "visibility_index"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Wetness index
#'
#' @description Calculates the topographic wetness index, Ln(A / tan(slope)).
#'
#' @param sca Input raster specific contributing area (SCA) file.
#' @param slope Input raster slope file (in degrees).
#' @param output Output raster file.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords GeomorphometricAnalysis
#'
#' @return Returns the tool text outputs.
#' @export
wbt_wetness_index <- function(sca, slope, output, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
args <- paste(args, paste0("--sca=", wbt_file_path(sca)))
args <- paste(args, paste0("--slope=", wbt_file_path(slope)))
args <- paste(args, paste0("--output=", wbt_file_path(output)))
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "wetness_index"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
|
/scratch/gouwar.j/cran-all/cranData/whitebox/R/terrain_analysis.R
|
#' Run WhiteboxTools by Tool Name
#'
#' You are required to specify all required arguments as either paths to files, or R object types that can be associated with a file.
#'
#' Supports SpatRaster / RasterLayer input / output. Arguments are transformed from their source class and passed to WhiteboxTools executable as standard character string arguments involving file paths.
#'
#' To print help for any tool, see `wbt_tool_help()`
#'
#' @param result an S3 object of class `wbt_result` to use to supply input arguments, may be _missing_ such that first argument is `tool_name`
#' @param tool_name character. name of the tool to run. Or a tool/function name (i.e. a symbol) that is non-standard evaluated as a character.
#' @param ... arguments to tool
#' @param crs character Optional: a WKT Coordinate Reference System string, or other identifier such as EPSG code or PROJ string
#' @param verbose_mode passed to `wbt_run_tool()`
#' @param command_only Return command that would be run with `system()`? Default: `FALSE`
#' @details `tool_name` may be specified with or without quotes or `wbt_` prefix. e.g. `"wbt_slope"`, `wbt_slope`, `slope`, and `"slope"` are identical.
#'
#' @seealso [wbt_tool_help()]
#' @keywords General
#' @return a list with class `"wbt_result"` containing elements:
#' * `tool` - the tool name
#' * `args` - arguments passed to executable
#' * `stdout` - console output (result of `wbt_run_tool()`)
#' * `crs` - Coordinate Reference System string (WKT or PROJ)
#' * `result` - any 'result' parameters (`--output`) that can be converted to R objects after run. A list of RasterLayer or character. May be a `try-error` if arguments are specified incorrectly.
#' * `history` - history of 'result' when `wbt_result` was passed as input, most recent output at end
#'
#' @export
wbt <- function(result,
tool_name,
...,
crs = NULL,
verbose_mode = FALSE,
command_only = FALSE) {
if (missing(result) || is.null(result)) {
wbt.missing(
result = NULL,
tool_name = gsub("[^A-Za-z_]", "", wbt_internal_tool_name(deparse(
substitute(tool_name)
))),
...,
crs = crs,
verbose_mode = verbose_mode,
command_only = command_only
)
} else UseMethod("wbt")
}
# constructors for wbt_result and wbt_error_result
# TODO: think about result class structure
.wbt_result_class <- function(tool_name, args, stdout, crs, result) {
structure(
list(
tool = tool_name,
args = args,
stdout = stdout,
crs = crs,
result = result
), class = "wbt_result")
}
wbt_error_result <- function(tool_name, args, crs, message) {
errm <- try(stop(), silent = TRUE)
errm[1] <- message
.wbt_result_class(
tool_name = tool_name,
args = args,
stdout = NULL,
crs = crs,
result = errm
)
}
#' @export
print.wbt_result <- function(x, ...) {
cat(paste0('<wbt_result>\n'))
n <- length(x$history)
showargs <- trimws(strsplit(x$args, "--")[[1]])
showargs <- paste0(showargs[nchar(showargs) > 1], "'")
showargs <- paste0(gsub('=', "\t: '", showargs), collapse = '\n')
if (length(showargs) >= 1 && nchar(showargs) > 1) {
cat(paste0('--- PARAMETERS (', x$tool,') ---\n', showargs),"\n")
} else {
cat(paste0('No parameters (', x$tool,')\n'))
}
if (length(x$result) > 0) {
if (is.null(names(x$result))) {
if (inherits(x$result, 'try-error')) {
cat("\n",attr(x$result, "tool"), x$result[1], "\n")
}
} else {
if (length(x$result) > 0) {
cat("--- RESULT ---\n")
}
sapply(names(x$result), function(y) {
resy <- x$result[[y]]
classy <- class(resy)
cat(paste0("$", y,"\n"))
if (is.character(resy)) {
if (file.exists(resy)) {
cat(' File result: ', resy,
paste0('exists (Last modified: ', as.character(file.mtime(resy)), ')\n'))
} else {
# TODO: are all output arguments "character" reasonably to be construed as files?
cat(' ', shQuote(resy), ' [file path does not exist]\n')
}
} else {
# show() for RasterLayer, SpatRaster outputs
print(x$result[[y]])
}
})
}
} else {
cat(paste0(' NULL result'))
}
if (n > 1) {
cat(paste0("--- HISTORY ---\n"))
cat(paste0("Prior results (n=", n - 1, ") for:"),
paste0(sapply(x$history[1:(length(x$history) - 1)], function(y)
if (!is.null(y$tool))
return(y$tool)),
collapse = ", "), "\n -",
paste0(sapply(x$history[1:(length(x$history) - 1)], function(y)
if (!is.null(y$tool))
return(paste0(y$tool," (", paste0(names(y$result), collapse = ", "), "<",
paste0(sapply(y$result, class), collapse = ", "), ">)"))),
collapse = "\n - "))
}
cat("\n")
}
#' @export
#' @rdname wbt
wbt.wbt_result <- function(result, tool_name, ..., crs = NULL, verbose_mode = FALSE, command_only = FALSE) {
# process user input
userargs <- list(...)
# get tool parameters and clean tool name
prm <- .get_tool_params(tool_name)
tool_name <- unique(prm$tool_name)[1]
userargs <- .process_tool_params(tool_name = tool_name,
userargs = userargs,
result = result,
prm = prm)
yrg <- try(.process_user_args(userargs), silent = TRUE)
if (inherits(yrg, 'try-error')) {
message(yrg)
message("Failed to process user arguments, this should not happen; returning NULL")
return(NULL)
}
# handle CRS propagation
crs <- ifelse(is.null(result$crs), "", result$crs)
# TODO: carry over other arguments?
# add prior call in history
res <- .wbt(tool_name, yrg, prm, crs = crs, verbose_mode = verbose_mode, command_only = command_only)
if (inherits(res, 'wbt_result')) {
res$history <- c(result$history, list(res))
}
res
}
#' @description `wbt_result()`: return a combined list of results from either the history of a `wbt_result` (if present and `history=TRUE`), or the result of a `wbt_result`
#' @param result an object of class `wbt_result`
#' @param i Optional index of result list element to return as result. Default is whole list.
#' @param history Default: `TRUE` returns a list of all history results
#' @param attribute Default: `"output"`
#' @return list of result in `attribute` if `"history"` is present, otherwise the result in `attribute`. If `i` is specified, just the `i`th element of the list.
#' @export
#' @rdname wbt
wbt_result <- function(result, i = NULL, history = TRUE, attribute = "output") {
UseMethod("wbt_result")
}
#' @export
wbt_result.wbt_result <- function(result, i = NULL, history = TRUE, attribute = "output") {
# if there is $history present, by default return a list of all the results
if (!is.null(result[["history"]]) && history) {
res <- sapply(result[["history"]], function(x) x$result[[attribute]])
} else {
res <- result$result[[attribute]]
}
# get the last result as stored in $result
if (is.null(i)) {
return(res)
}
if (i < 0 || i > length(res)) {
stop(sprintf("result list index %s is out of bounds", i), call. = FALSE)
}
.subset2(res, i)
}
#' @export
as.data.frame.wbt_result <- function(x, ...) {
outputlist <- wbt_result(x)
cbind(as.data.frame(unclass(x)[c("tool", "args", "stdout", "crs")],
...)[rep(1, length(outputlist)),],
data.frame(output = I(outputlist)))
}
#' @export
#' @rdname wbt
wbt.character <- function(result, tool_name, ..., crs = NULL, verbose_mode = FALSE, command_only = FALSE) {
# process user input
userargs <- list(...)
if (!missing(tool_name) && !is.null(tool_name)) {
warning("wbt.character uses first argument (`result`) as tool_name, `tool_name` ignored", call. = FALSE)
}
tool_name <- gsub(" ", "", result, fixed = TRUE)
# get tool parameters and clean tool name
prm <- .get_tool_params(tool_name)
tool_name <- unique(prm$tool_name)[1]
userargs <- .process_tool_params(tool_name = tool_name,
userargs = userargs,
prm = prm)
# get input CRS; argument takes precedence
if (missing(crs) || is.null(crs) || crs == "") {
# is_input is derived from the -i flag which is only defined for --input
# we want to check multiple inputs too, these have a numeric suffix e.g --input2
ldx <- prm$is_input | grepl("^input[1-9]+", prm$argument_name)
crs <- .process_crs(userargs[names(userargs) %in% prm$argument_name[ldx]])
}
# process user input (convert complex object -> character arguments)
yrg <- try(.process_user_args(userargs), silent = TRUE)
if (inherits(yrg, 'try-error')) {
message(yrg)
message("Failed to process user arguments, this should not happen; returning NULL")
return(NULL)
}
res <- .wbt(tool_name, yrg, prm, crs = crs, verbose_mode = verbose_mode, command_only = command_only)
if (inherits(res, 'wbt_result')) {
res$history <- list(res)
}
res
}
# support for using exported function names directly as input
#' @export
#' @rdname wbt
wbt.function <- function(result, tool_name, ..., crs = NULL, verbose_mode = FALSE, command_only = FALSE ) {
tool_name <- deparse(substitute(result))
if (is.character(tool_name)) {
wbt.character(result = tool_name, tool_name = NULL, ..., crs = crs,
verbose_mode = verbose_mode, command_only = command_only)
}
}
# start a toolchain with a call where result is missing or tool_name specified as result
#' @export
#' @rdname wbt
wbt.missing <- function(result, tool_name, ..., crs = NULL, verbose_mode = FALSE, command_only = FALSE) {
if (is.character(tool_name)) {
wbt.character(tool_name, result, ..., crs = crs, verbose_mode = verbose_mode, command_only = command_only)
}
}
.process_crs <- function(inputargs) {
# support raster inputs in the following formats
pkgin <- sapply(inputargs, function(x) {
if (inherits(x, 'SpatRaster')) return("terra")
if (inherits(x, 'SpatVector')) return("terra")
if (inherits(x, 'sf')) return("sf")
if (inherits(x, 'sfc')) return("sf")
if (inherits(x, 'RasterLayer')) return("raster")
if (inherits(x, 'RasterStack')) return("raster")
if (inherits(x, 'RasterBrick')) return("raster")
""
})
# requireNamespace("terra") for terra and/or raster as needed
pkgreq <- sapply(unique(pkgin[nchar(pkgin) > 0]),
requireNamespace, quietly = TRUE)
if (any(!pkgreq)) {
stop("package ", pkgin[!pkgreq], " is required", call. = FALSE)
}
if (!all(pkgin == pkgin[1])) {
# if (pkgin[1] != "")
# message("NOTE: Input spatial object classes do not match.")
}
crsin <- lapply(seq_along(inputargs), function(i) {
x <- inputargs[[i]]
if (pkgin[i] == "terra") {
x2 <- try(as.character(terra::crs(x)), silent = FALSE)
} else if (pkgin[i] == "sf") {
x2 <- try(as.character(sf::st_crs(x)), silent = FALSE)
} else {
x2 <- try(if (inherits(x, 'RasterLayer')) raster::wkt(raster::crs(x)))
}
if (is.null(x2) || inherits(x2, 'try-error')) {
return("")
}
x2
})
if (length(crsin) > 0) {
crsmatch <- do.call('c', lapply(crsin, function(x) x == crsin[[1]]))
if (length(crsmatch) == 0 || !all(crsmatch) || any(is.na(crsmatch))) {
message("NOTE: Input CRS do not match.")
}
# take first input CRS
res <- crsin[[1]]
attr(res, 'package') <- pkgin[1]
} else {
res <- ""
attr(res, 'package') <- ""
}
# record package used to create the object for use in output
res
}
.process_user_args <- function(userargs) {
# handle rasters so if given a raster as input, the filename is used as input
# if a .tif file is returned as output, then the output is a RasterLayer and so on
yrg <- lapply(names(userargs), function(argname) {
x <- userargs[[argname]]
# sfc/sp support
if (inherits(x, 'sfc') || inherits(x, 'Spatial')) {
if (requireNamespace("sf")) {
x <- sf::st_as_sf(x)
}
}
# raster rasterlayer support
if (inherits(x, c('RasterLayer', 'RasterStack', 'RasterBrick'))) {
if (requireNamespace("raster")) {
res <- try(raster::filename(x))
attr(res, "package") <- "raster"
return(res)
}
# terra spatraster support
} else if (inherits(x, 'SpatRaster')) {
if (requireNamespace("terra")) {
res <- try(terra::sources(x)$source, silent = TRUE)
if (inherits(res, 'try-error')) {
x <- wbt_source(x)
res2 <- attr(x, 'wbt_dsn')
}
if (is.null(res2)) {
message(res[1])
} else res <- res2
attr(res, "package") <- "terra"
return(res)
}
# vector data support
} else if (inherits(x, c('SpatVector', 'SpatVectorProxy', 'sf'))) {
src <- attr(x, 'wbt_dsn')
if (is.null(src)) {
x <- wbt_source(x)
src <- attr(x, 'wbt_dsn')
}
if (!is.null(src) && file.exists(src)) {
if (inherits(x, c('SpatVector', 'SpatVectorProxy'))) {
attr(src, "package") <- "terra"
} else if (inherits(x, 'sf')) {
attr(src, "package") <- "sf"
}
return(src)
} else {
stop("load/initialize SpatVector/sf objects with wbt_source()", call. = FALSE)
}
} else if (inherits(x, 'try-error')) {
return(.warninput(paste0("NOTE: try-error result cannot be used as `", argname,"`")))
} else if (!class(x)[1] %in% c("numeric", "integer", "character", "logical")) {
return(.warninput(
paste0('argument type (',
paste0(class(x), collapse = ", "),
') is not supported at this time')
))
} else {
# allowed inputs "numeric", "integer", "character", "logical"
# shell quote all character (safer if paths contain parentheses)
# convert all numeric to numeric (handles scientific notation)
switch(class(x),
# "character" = shQuote(x),
"numeric" = as.numeric(x),
x)
}
})
names(yrg) <- names(userargs)
# handle try errors by treating them as if the arguments were not supplied
yrg <- lapply(yrg, function(y) {
if (inherits(y, 'try-error')) {
message(y[1])
return(NULL)
}
return(y)
})
yrg[!sapply(yrg, is.null)]
}
# used to put notes into try-errors about user input; things that normally might cause fatal errors
.warninput <- function(x) {
res <- try(stop(), silent = TRUE)
if (!is.null(x))
res[1] <- paste0(x, collapse = "\n")
res
}
.get_tool_params <- function(tool_name) {
try({
wbttoolparameters <- get('wbttoolparameters')
}, silent = TRUE)
# remove underscores and other possible prefixes
tool_name <- gsub("_", "", wbt_internal_tool_name(tool_name))
# return subset by tool_name
res <- wbttoolparameters[which(toupper(wbttoolparameters$tool_name) %in% toupper(tool_name)), ]
if (nrow(res) == 0) {
extra <- ''
if (trimws(tool_name) != '') {
tn <- unique(wbttoolparameters$tool_name)
guess <- grep(paste0(".*", tolower(tool_name), ".*"), tolower(tn), ignore.case = TRUE)
# guess <- pmatch(tolower(tool_name), tolower(tn), duplicates.ok = TRUE)
if (length(guess) > 0) {
extra <- paste0(", perhaps you meant one of: ", paste0(shQuote(tn[guess]), collapse = ", " ))
}
}
warning("Parameters for tool_name='", tool_name, "' not found", extra, call. = FALSE)
}
res
}
.process_tool_params <- function(tool_name,
userargs,
result = NULL,
prm = .get_tool_params(tool_name)) {
# take output from result to augment as first input if not specified
inputprm <- prm$argument_name[prm$is_input][1]
if (length(inputprm) && !inputprm %in% names(userargs)) {
#TODO: multi output? is this robust
newinput <- character(0)
if (!is.null(result)) {
newinput <- result$result
if (!inherits(newinput, 'try-error')) {
newinput <- newinput$output
}
} else if ("input" %in% names(userargs)) {
newinput <- userargs$input
}
if (length(newinput) > 0) {
# re-arrange and re-name user "input" arg if necessary
userargs <- c(list(input = newinput), userargs[names(userargs) != "input"])
names(userargs)[1] <- inputprm
}
}
userargs
}
.wbt_args <- function(tool_name, args, params = .get_tool_params(tool_name), crs = NULL) {
# match tool_name and params options for helpful errors
newpkg <- unique(do.call('c', lapply(args, attr, 'package')))[1]
# construct arg string --param1=value1 --param2=value2
newargs <- paste(paste0("--", names(args), "=", as.character(args)), collapse = " ")
reqparams <- sapply(params$argument_name[!params$optional], function(x) any(sapply(x, function(y) grepl(y, newargs))))
# at least one required param is missing or a bad parameter is specified
chkprm <- !names(args) %in% params$argument_name
if (sum(as.numeric(reqparams)) < length(params$argument_name[!params$optional]) || any(chkprm)) {
# if (wbt_verbose()) {
# user specified a bad parameter
invalid <- character()
if (any(chkprm)) {
message("Error: invalid parameter", ifelse(sum(chkprm) > 1, "s", ""),
" '", paste0(names(args)[chkprm], collapse = "', '"), "'\n")
invalid <- names(args)[chkprm]
}
# inform of required args
message("Required arguments:")
reqprm <- params$argument_name[!params$optional][!reqparams]
ismissing <- ifelse(!reqparams, " [ ] ", " [*] ")
for (i in seq_along(reqparams)) {
message("-", ismissing[i], params$argument_name[!params$optional][i], " -- ", params$description[!params$optional][i])
}
message("")
# inform of optional args
optparams <- !params$argument_name[params$optional] %in% names(args)
ismissing <- ifelse(optparams, " [ ] ", " [*] ")
if (any(optparams)) {
message("Optional arguments:")
for (i in seq_along(optparams)) {
message("-", ismissing[i], params$argument_name[params$optional][i], " -- ", params$description[params$optional][i])
}
}
# }
if (length(invalid) > 0) {
invalid <- paste(paste0(shQuote(invalid), collapse = ", "), "invalid")
}
if (length(reqprm) > 0) {
reqprm <- paste(paste0(shQuote(reqprm), collapse = ", "), "required")
}
errres <- .warninput(paste0("ERROR: ",
paste0(c(invalid, reqprm),
collapse = "; ")))
attr(errres, 'tool') <- tool_name
attr(errres, 'args') <- newargs
return(errres)
}
attr(newargs, 'package') <- newpkg
newargs
}
# processing of output files -> R objects
.wbt_process_output <- function(args, crs = NULL, pkg = NULL) {
if (is.null(pkg)) {
pkg <- ""
}
lapply(args[names(args) %in% "output"], function(x) {
# TODO: user defined file patterns and customizable methods
# https://jblindsay.github.io/wbt_book/supported_formats.html
# support for GeoTIFF
if (!is.na(x) & (endsWith(x, ".tif") | endsWith(x, ".tiff"))) {
wdp <- file.path(wbt_wd(), x)
# check working directory if set
if (file.exists(wdp)) {
x <- wdp
}
# default value is original value
y <- x
# support for the raster v.s. terra v.s. ? package via attribute passed with crs or prior result
israster <- attr(crs, 'package')
if (length(israster) == 0) israster <- pkg
if (israster %in% "raster") {
if (requireNamespace('raster')) {
y <- suppressWarnings(try(raster::raster(x)))
if (!inherits(y, 'try-error')) {
if (length(crs) == 0) {
crs <- ""
}
# propagate wbt_result CRS if the result has none
if (is.na(as.character(raster::crs(y))) && !is.na(crs)) {
raster::crs(y) <- ifelse(!is.character(crs), "", crs)
}
}
y
}
# for other cases, use terra
} else if (israster %in% "terra") {
if (requireNamespace('terra')) {
y <- suppressWarnings(try(terra::rast(x)))
if (!inherits(y, 'try-error')) {
terra::crs(y) <- ifelse(!is.character(crs), "", crs)
}
}
}
##
## TODO: LAS object from lidR package support?
#
# } else if (!is.na(x) & endsWith(x, ".las")) {
# if (requireNamespace('lidR')) {
# # TODO: support additional arguments to readLAS()?
# try(lidR::readLAS(x))
# }
##
return(y)
} else if (!is.na(x) && endsWith(x, ".shp")) {
if (requireNamespace('terra')) {
return(try(terra::vect(x, crs = ifelse(!is.character(crs), "", crs), proxy = TRUE)))
}
} else {
return(x)
}
})
}
.wbt <- function(tool_name,
args,
params = .get_tool_params(tool_name),
crs = NULL,
verbose_mode = FALSE,
command_only = FALSE) {
# process and check user arguments
newargs <- .wbt_args(tool_name = tool_name, args = args, params = params, crs = crs)
if (inherits(newargs, 'try-error')) {
return(invisible(.wbt_result_class(tool_name = tool_name,
args = attr(newargs, 'args'),
stdout = NULL,
crs = crs,
result = newargs)))
}
# pass through wbt_run_tool
console <- try(wbt_run_tool(tool_name = tool_name,
args = newargs,
verbose_mode = verbose_mode,
command_only = command_only
), silent = TRUE)
if (command_only) {
return(console[1])
}
if (inherits(console, 'try-error')) {
return(invisible(.wbt_result_class(tool_name = tool_name,
args = newargs,
stdout = console[1], # return the error message, and a try-error in result
crs = crs,
result = .warninput(c("ERROR: Tool execution failed", console[1]))
)))
}
# if tool runs without needing "output" specified
# assume it modifies the file specified as the first input
if (!"output" %in% names(args)) {
# TODO: does this need further generalization/use of tool parameter LUT?
args[["output"]] <- args[[grep("dem|input", names(args))[1]]]
}
return(invisible(
.wbt_result_class(
tool_name = tool_name,
args = newargs,
stdout = console,
crs = crs,
result = .wbt_process_output(args, crs, pkg = attr(newargs, 'package'))
)
))
}
|
/scratch/gouwar.j/cran-all/cranData/whitebox/R/wbt-method.R
|
#' Initialize 'WhiteboxTools'
#'
#' `wbt_init()`: Check if a suitable 'WhiteboxTools' executable is present. Search default path in package directory or set it manually with `exe_path`.
#'
#' @param exe_path Default `exe_path` is result of `wbt_exe_path()` which checks a few user-settable options before defaulting to the package installation directory sub-directory "WBT". May be overridden if a custom path is needed.
#' @param ... additional arguments to `wbt_options()`
#' @param check_version Check version of 'WhiteboxTools' installed against version R package was built for? Default: `TRUE`
#'
#' @return `wbt_init()`: logical; `TRUE` if binary file is found at `exe_path`
#' @export
#' @keywords General
#' @seealso [install_whitebox()] [whitebox]
#' @examples
#' \dontrun{
#' ## wbt_init():
#'
#' # set path to binary as an argument
#' # wbt_init(exe_path = "not/a/valid/path/whitebox_tools.exe")
#' }
wbt_init <- function(exe_path = wbt_exe_path(shell_quote = FALSE),
...,
check_version = TRUE) {
# optional parameters specified by ...
initargs <- list(...)
wd <- initargs[["wd"]]
verbose <- initargs[["verbose"]]
compress_rasters <- initargs[["compress_rasters"]]
if (!is.character(exe_path) || length(exe_path) != 1) {
stop("exe_path must be a character vector with length 1", call. = FALSE)
}
exe_path <- path.expand(exe_path)
# if exe_path is not NULL and file exists, and value differs from the wbt_exe_path() result
if ((!is.null(exe_path) &&
file.exists(exe_path) &&
exe_path != wbt_exe_path(shell_quote = FALSE)) ||
!is.null(wd) ||
!is.null(verbose) ||
!is.null(compress_rasters)) {
if (!is.null(wd) && length(wd) > 0 && (is.na(wd) || wd == "")) {
.wbt_wd_unset()
}
# set the path with wbt_options
wbt_options(exe_path = exe_path, ...)
}
# check whether path exists (using new options)
res1 <- check_whitebox_binary()
# success? binary found matches path the user (may have) set, return TRUE
new_exe_path <- wbt_exe_path(shell_quote = FALSE)
res2 <- new_exe_path == exe_path
# if the wbt_exe_path() output doesnt match user input
if (!res2) {
if (wbt_verbose()) {
message("WhiteboxTools Executable Path (whitebox.exe_path) reverted to:\n\t", new_exe_path)
}
}
if (check_version) {
# check version info, provide ONE message per session if mismatched
exv <- try(wbt_version(extract = TRUE), silent = TRUE)
if (is.na(exv)) {
exv <- "<NA>"
}
pkv <- try(attr(whitebox::wbttools, 'version'), silent = TRUE)
if (is.na(pkv)) {
pkv <- "<NA>"
}
if (!inherits(exv, 'try-error') && !inherits(pkv, 'try-error')) {
if (isTRUE(exv != pkv)) {
warned <- try(get("whitebox.warned_version_difference",
envir = whitebox::whitebox.env),
silent = TRUE)
if (inherits(warned, 'try-error')) {
warned <- FALSE
}
if (wbt_verbose() && isFALSE(warned)) {
message("NOTE: Installed WhiteboxTools version (", exv,
") is ", ifelse(exv > pkv, "newer", "older"),
" than the package data (", pkv, ").")
try(assign("whitebox.warned_version_difference",
value = TRUE,
envir = whitebox::whitebox.env),
silent = TRUE)
}
}
}
}
return(invisible(res1 && res2))
}
#' @description `wbt_options()`: Get/set package options
#'
#' - **`whitebox.exe_path`** - character. Path to executable file. The default value is the package installation directory, subdirectory `"WBT"`, followed by `whitebox_tools.exe` or `whitebox_tools`. Set the `whitebox.exe_path` option using `wbt_init()` `exe_path` argument
#'
#' - **`whitebox.wd`** - character. Path to WhiteboxTools working directory. Used as `--wd` argument for tools that support it when `wd` is not specified elsewhere.
#'
#' - **`whitebox.verbose`** - logical. Should standard output from calls to executable be `cat()` out for readability? When `whitebox.verbose=FALSE` no output is produced. Set the value of `whitebox.verbose` with `wbt_verbose()` `verbose` argument. Default is result of `interactive()` if R package options are unset.
#'
#' - **`whitebox.compress_rasters`** - logical. Should raster output from WhiteboxTools be compressed? Default: `NULL` uses existing WhiteboxTools settings. Set the value of `whitebox.compress_rasters` with `wbt_compress_rasters()` `compress_rasters` argument.
#'
#' - **`whitebox.max_procs`** - integer. Maximum number of processes for tools that run in parallel or partially parallelize. Default: `-1` uses all of the available cores.
#'
#' @return `wbt_options()`: an invisible list containing current `whitebox.exe_path`, `whitebox.verbose`, `whitebox.compress_rasters`, and `whitebox.max_procs` options
#' @rdname wbt_init
#' @export
#' @keywords General
#' @examples
#' \dontrun{
#'
#' ## wbt_options():
#'
#' # set multiple options (e.g. exe_path and verbose) with wbt_options()
#' wbt_options(exe_path = "not/a/valid/path/whitebox_tools.exe", verbose = TRUE)
#'
#' }
wbt_options <- function(exe_path = NULL,
wd = NULL,
verbose = NULL,
compress_rasters = NULL,
max_procs = NULL) {
# get the system value
syswbt <- Sys.getenv("R_WHITEBOX_EXE_PATH")
syswd <- Sys.getenv("R_WHITEBOX_WD")
sysvrb <- Sys.getenv("R_WHITEBOX_VERBOSE")
syscpr <- Sys.getenv("R_WHITEBOX_COMPRESS_RASTERS")
sysmxp <- Sys.getenv("R_WHITEBOX_MAX_PROCS")
# check user input, set package options
if (!is.null(exe_path)) {
if (file.exists(exe_path)) exe_path <- path.expand(exe_path)
options(whitebox.exe_path = exe_path)
}
if (!is.null(wd)) {
# preserve attributes if any on wd
if (dir.exists(wd)) wd[1] <- path.expand(wd)
options(whitebox.wd = wd)
}
if (!is.null(verbose)) {
options(whitebox.verbose = verbose)
}
if (!is.null(compress_rasters)) {
options(whitebox.compress_rasters = compress_rasters)
}
if (!is.null(max_procs)) {
options(whitebox.max_procs = max_procs)
}
invisible(list(
whitebox.exe_path = ifelse(nchar(syswbt) == 0,
getOption("whitebox.exe_path",
default = wbt_exe_path(shell_quote = FALSE)),
syswbt),
whitebox.wd = ifelse(nchar(syswd) == 0,
getOption("whitebox.wd",
default = ""),
syswd),
whitebox.verbose = ifelse(nchar(sysvrb) == 0,
getOption("whitebox.verbose",
default = ""),
sysvrb),
whitebox.compress_rasters = ifelse(nchar(syscpr) == 0,
as.logical(getOption("whitebox.compress_rasters",
default = NA)),
syscpr),
whitebox.max_proc = ifelse(nchar(sysmxp) == 0,
as.integer(getOption("whitebox.max_proc",
default = -1)),
sysmxp)
))
}
#' @description `wbt_exe_path()`: Get the file path of the 'WhiteboxTools' executable.
#'
#' @details `wbt_exe_path()`: Checks system environment variable `R_WHITEBOX_EXE_PATH` and package option `whitebox.exe_path`. Set your desired path with either `Sys.setenv(R_WHITEBOX_EXE_PATH = "C:/path/to/whitebox_tools.exe")` or `options(whitebox.exe_path = "C:/path/to/whitebox_tools.exe")`. The default, backwards-compatible path is returned by `wbt_default_path()`
#'
#' @param exe_path Optional: User-supplied path to 'WhiteboxTools' executable. Default: `NULL`
#' @param shell_quote Return `shQuote()` result?
#'
#' @return Returns the file path of 'WhiteboxTools' executable.
#' @export
#' @keywords General
#' @rdname wbt_init
#' @examples
#' \dontrun{
#' wbt_exe_path()
#' }
wbt_exe_path <- function(exe_path = NULL, shell_quote = TRUE) {
syswbt <- Sys.getenv("R_WHITEBOX_EXE_PATH")
pkgwbt <- getOption("whitebox.exe_path")
defwbt <- wbt_default_path()
pthwbt <- Sys.which(basename(defwbt))
if (!is.null(exe_path) && file.exists(exe_path)) {
# user specified as argument
res <- exe_path
} else if (!is.null(syswbt) && file.exists(syswbt)) {
# user specified as system option
res <- syswbt
} else if (!is.null(pkgwbt) && file.exists(pkgwbt)) {
# user specified as package option
res <- pkgwbt
} else if (!is.na(pthwbt) && pthwbt != "" && file.exists(pthwbt)) {
# whitebox_tools is on PATH
res <- pthwbt
} else {
res <- defwbt
}
if (shell_quote) {
return(shQuote(res))
}
res
}
#' @description `wbt_runner_path()`: Get the file path of the 'WhiteboxTools Runner' executable.
#'
#' @details `wbt_runner_path()`: Returns a path to 'WhiteboxTools Runner' including a platform-specific executable (with or without .exe extension)
#' @export
#' @keywords General
#' @rdname wbt_init
wbt_runner_path <- function(shell_quote = TRUE) {
bn <- "whitebox_runner"
os <- Sys.info()["sysname"]
if (os == "Windows") {
bn <- "whitebox_runner.exe"
}
res <- file.path(dirname(wbt_exe_path(shell_quote = FALSE)), bn)
if (shell_quote) {
return(shQuote(res))
}
res
}
#' @title Launch 'WhiteboxTools Runner' GUI
#' @description `wbt_launch_runner()`: Launch the 'WhiteboxTools Runner' GUI at `wbt_runner_path()`
#' @param clear_app_state Clear application state memory? Default: `FALSE`
#' @details Opens the 'WhiteboxTools Runner' GUI included with WhiteboxTools Open Core v2.3.0 or higher.
#' @seealso [wbt_runner_path()]
#' @export
#' @keywords General
#' @rdname wbt_launch_runner
wbt_launch_runner <- function(clear_app_state = FALSE) {
system(paste0(wbt_runner_path(), ifelse(clear_app_state, "--clear_app_state", "")))
}
#' @description `wbt_default_path()`: Get the default file path of the 'WhiteboxTools' executable.
#'
#' @details `wbt_default_path()`: Returns a path to 'WhiteboxTools' executable including a platform-specific executable (with or without .exe extension)
#' @export
#' @keywords General
#' @rdname wbt_init
wbt_default_path <- function() {
exe <- "whitebox_tools"
# system specific executable filename
os <- Sys.info()["sysname"]
if (os == "Windows") {
exe <- "whitebox_tools.exe"
}
file.path(wbt_data_dir(), "WBT", exe)
}
#' @description `wbt_data_dir()`: Get the directory where 'WhiteboxTools' data are stored.
#'
#' @details `wbt_data_dir()`: Uses platform-specific user data directory from `tools::R_user_dir(package = "whitebox", which = "data")` on R 4.0+. On R<4 returns the original default `find.package("whitebox")`.
#' @export
#' @keywords General
#' @rdname wbt_init
wbt_data_dir <- function() {
if (R.version$major >= 4) {
tools::R_user_dir(package = "whitebox", which = "data")
} else {
# backwards compatible path
find.package("whitebox")
}
}
#' @description `wbt_wd()`: Get or set the 'WhiteboxTools' working directory. Default: `""` (unset) is your R working directory if no other options are set.
#'
#' @param wd character; Default: `NULL`; if set the package option `whitebox.wd` is set specified path (if directory exists)
#'
#' @return `wbt_wd()`: character; when working directory is unset, will not add `--wd=` arguments to calls and should be the same as using `getwd()`. See Details.
#'
#' @details `wbt_wd()`: Before you set the working directory in a session the default output will be in your current R working directory unless otherwise specified. You can change working directory at any time by setting the `wd` argument to `wbt_wd()` and running a tool. Note that once you have set a working directory, the directory needs to be set somewhere to "replace" the old value; just dropping the flag will not change the working directory back to the R working directory. To "unset" the option in the R package you can use `wbt_wd("")` which removes the `--wd` flag from commands and sets the `working_directory` value in the WhiteboxTools _settings.json_ to `""`.
#' @rdname wbt_init
#' @export
#' @keywords General
#' @examples
#' \dontrun{
#'
#' ## wbt_wd():
#'
#' # no working directory set
#' wbt_wd(wd = "")
#'
#' # set WBT working directory to R working directory
#' wbt_wd(wd = getwd())
#' }
wbt_wd <- function(wd = NULL) {
if (length(wd) > 0 && (is.na(wd) || wd == "")) {
.wbt_wd_unset()
}
if (is.character(wd)) {
# if character input, set the package option "wd"
wbt_options(wd = wd)
}
# system environment var takes precedence
syswd <- Sys.getenv("R_WHITEBOX_WD")
if (nchar(syswd) > 0 && dir.exists(syswd)) {
return(syswd)
}
# package option checked next; if missing default is getwd() (unspecified should be same as getwd())
res <- getOption("whitebox.wd")
# an empty string silently stays an empty string
if (is.null(res) || nchar(res) == 0) {
res <- ""
# otherwise, if the option is invalid directory message
} else if (!is.null(res) && !dir.exists(res)) {
message("Invalid path for `whitebox.wd`: directory does not exist.\nDefaulting to \"\"")
res <- ""
}
invisible(res)
}
.wbt_wd_unset <- function() {
# this doesnt actually set the value ""
# - try(wbt_system_call(paste0("--wd=", shQuote(""))), silent = TRUE)
try({
f <- file.path(dirname(wbt_exe_path(shell_quote = FALSE)), "settings.json")
x <- readLines(f, warn = FALSE)
x[grepl('^ *"working_directory": .*$', x)] <- ' "working_directory": "",'
writeLines(x, f)
})
}
#' @description `wbt_verbose()`: Check verbose options for 'WhiteboxTools'
#'
#' @param verbose logical. Default: `NULL`; if `TRUE` or `FALSE`, set the package option `whitebox.verbose` to specified value. Tool verbosity settings can be overridden in any `wbt_*()` function call by passing the `verbose_mode` argument directly.
#'
#' @return `wbt_verbose()`: logical; returns the result of option `"whitebox.verbose_mode"`, if unset defaults to result of `interactive()`.
#' @rdname wbt_init
#' @export
#' @keywords General
#' @examples
#' \dontrun{
#'
#' ## wbt_verbose():
#'
#' wbt_verbose(verbose = TRUE)
#' }
wbt_verbose <- function(verbose = NULL) {
# NA is treated NULL (no effect)
if (length(verbose) != 1 || is.na(verbose)) {
verbose <- NULL
}
# system environment var takes precedence
sysverbose <- Sys.getenv("R_WHITEBOX_VERBOSE", unset = "")
if (sysverbose == "all") {
# wbt_verbose always return logical, "all" is a flavor of true
return(TRUE)
} else if (sysverbose != "") {
# take up to first 5 characters, uppercase eval/parse/convert to logical
# this should also allow for 0/1 to be specified and converted as needed to logical
sysverbose <- as.logical(eval(parse(text = toupper(substr(sysverbose, 0, 5)))))
}
# if logical system env var, use that
if (is.logical(sysverbose) && !is.na(sysverbose)) {
return(sysverbose)
}
# if logical input, set the package option "verbose"
if (is.logical(verbose) || (!is.null(verbose) && verbose == "all")) {
wbt_options(verbose = verbose)
}
# package option subsequently, default true for interactive use
res <- as.logical(getOption("whitebox.verbose", default = interactive()))
if (is.na(res) || (!is.null(verbose) && verbose == "all")) {
res <- TRUE
} else if (is.na(res) || !is.logical(res)) {
message('Invalid value for whitebox.verbose, defaulting to interactive()')
res <- interactive()
}
invisible(res)
}
#' @description `wbt_compress_rasters()`: Check raster compression option for 'WhiteboxTools'. Default behavior is based on WhiteboxTools settings.json, package options (if set). Raster compression settings can be overridden in any `wbt_*()` function call by passing the `compress_rasters` argument directly.
#'
#' @param compress_rasters logical. Default: `NULL`; if `TRUE` or `FALSE`, set the package option `whitebox.compress_rasters` to specified value.
#'
#' @return `wbt_compress_rasters()`: logical; returns the result of option `"whitebox.compress_rasters"`, if unset defaults to `NA`.
#' @rdname wbt_init
#' @export
#' @keywords General
#' @examples
#' \dontrun{
#'
#' ## wbt_compress_rasters():
#'
#' wbt_compress_rasters(compress_rasters = TRUE)
#' }
wbt_compress_rasters <- function(compress_rasters = NULL) {
# NA is treated NULL (no effect)
if (length(compress_rasters) != 1 || is.na(compress_rasters)) {
compress_rasters <- NULL
}
# system environment var takes precedence
syscompress <- Sys.getenv("R_WHITEBOX_COMPRESS_RASTERS", unset = NA)
if (!is.na(syscompress)) {
# take up to first 5 characters, uppercase eval/parse/convert to logical
# this should also allow for 0/1 to be specified and converted as needed to logical
syscompress <- as.logical(eval(parse(
text = toupper(substr(syscompress, 0, 5))
)))
}
# if logical system env var, use that
if (is.logical(syscompress) && !is.na(syscompress)) {
return(syscompress)
}
# if logical input, set the package option "compress_rasters"
if (is.logical(compress_rasters)) {
wbt_options(compress_rasters = compress_rasters)
}
# package option subsequently, default FALSE
res <- as.logical(getOption("whitebox.compress_rasters", default = NA))
if (is.na(res) || !is.logical(res)) {
res <- NA
}
invisible(res)
}
#' @description `wbt_max_procs()`: Check maximum number of processes for for tools that run in parallel or partially parallelize. Default: `-1` uses all of the available cores.
#'
#' @param max_procs Default: `NULL`; if integer, set the package option `whitebox.max_procs` to specified value
#'
#' @return `wbt_max_procs()`: integer; defaults to `NA_integer_`
#' @rdname wbt_init
#' @export
#' @keywords General
#' @examples
#' \dontrun{
#'
#' ## wbt_max_procs():
#'
#' wbt_max_procs(max_procs = 2)
#' }
wbt_max_procs <- function(max_procs = NULL) {
# NA is treated NULL (no effect)
if (length(max_procs) != 1 || is.na(max_procs)) {
max_procs <- NULL
}
# system environment var takes precedence
sysmax_procs <- Sys.getenv("R_WHITEBOX_MAX_PROCS", unset = NA)
if (!is.na(sysmax_procs)) {
sysmax_procs <- as.integer(sysmax_procs)
}
# if integer system env var, use that
if (is.integer(sysmax_procs) && !is.na(sysmax_procs)) {
return(sysmax_procs)
}
# if integer input, set the package option "max_procs"
if (is.numeric(max_procs)) {
wbt_options(max_procs = as.integer(max_procs))
}
# package option subsequently, default FALSE
res <- as.integer(getOption("whitebox.max_procs", default = NA_integer_))
if (!is.integer(res)) {
res <- NA_integer_
}
invisible(res)
}
#' @export
#' @keywords General
#' @rdname install_whitebox
wbt_install <- function(pkg_dir = wbt_data_dir(), platform = NULL, force = FALSE, remove = FALSE) {
stopifnot(is.logical(force))
stopifnot(is.logical(remove))
stopifnot(length(pkg_dir) == 1)
stopifnot(is.character(pkg_dir))
pkg_dir <- normalizePath(pkg_dir, "/", FALSE)
if (!is.na(remove) && remove) {
unlink(list.files(file.path(pkg_dir, "WBT"), recursive = TRUE, full.names = TRUE), force = force, recursive = TRUE)
}
# Check for binary file in 'WBT' directory
exe_path <- wbt_default_path()
os <- Sys.info()["sysname"]
.unsupported <- function(){
message("Sorry, whitebox download from https://www.whiteboxgeo.com/download-whiteboxtools/ is unsupported for your operating system!\n")
message("Pre-built binaries are available only for 64-bit Windows, Mac OS Intel and Linux (compiled w/ Ubuntu 20.04).")
message("See: https://www.whiteboxgeo.com/download-whiteboxtools/ \n")
message("You can follow the instructions at https://github.com/jblindsay/whitebox-tools to use cargo to build the Rust library from source.\n")
message(paste0("If you have WhiteboxTools installed already, run `wbt_init(exe_path=...)`': \n",
"\twbt_init(exe_path='/home/user/path/to/whitebox_tools')\n"))
}
# if not in package directory, and user has not specified a path
if (!file.exists(exe_path) || pkg_dir != wbt_default_path() || force) {
# install_whitebox/wbt_install is 64-bit only
if (.Machine$sizeof.pointer != 8) {
return(invisible(.unsupported()))
}
if (missing(platform) || is.null(platform)) {
if (os == "Linux") {
url <- "https://www.whiteboxgeo.com/WBT_Linux/WhiteboxTools_linux_amd64.zip"
} else if (os == "Windows") {
url <- "https://www.whiteboxgeo.com/WBT_Windows/WhiteboxTools_win_amd64.zip"
} else if (os == "Darwin") {
suffix <- "amd64"
if (Sys.info()["machine"] == "arm64") {
suffix <- "m_series"
}
url <- paste0("https://www.whiteboxgeo.com/WBT_Darwin/WhiteboxTools_darwin_", suffix , ".zip")
} else {
return(invisible(.unsupported()))
}
} else {
# supports alternative platforms/filenames
# e.g. linux_musl, darwin_m_series
url <- paste0("https://www.whiteboxgeo.com/WBT_",
os, "/WhiteboxTools_",
platform, ".zip")
}
filename <- basename(url)
cat("Performing one-time download of WhiteboxTools binary from\n")
cat("\t", url, "\n")
cat("(This could take a few minutes, please be patient...)\n")
# path for downloaded zip file;
# remove downloaded zip file when exiting function
exe_zip <- file.path(pkg_dir, filename)
on.exit(unlink(exe_zip), add = TRUE)
if (!dir.exists(pkg_dir)) {
dir.create(pkg_dir, recursive = TRUE)
}
# this fails on some platforms and with certain URLs
# tried curl::curl_download, httr::GET, and other download.file method options for libcurl
# logic from xfun::download_file used for tinytex::install_tinytex()
if (getOption("timeout") == 60L) {
opts = options(timeout = 3600)
on.exit(options(opts), add = TRUE)
}
res <- -1
for (method in c(if (os == "Windows") "internal", "libcurl", "auto")) {
if (!inherits(try({
res <- utils::download.file(url, exe_zip, method = method)
}, silent = TRUE), "try-error") && res == 0)
break
}
if (res != 0) {
message("Unable to download by any method! Try downloading ZIP manually from https://www.whiteboxgeo.com/download-whiteboxtools/. Installation involves just extracting to your desired directory. Set path to binary with wbt_init(exe_path = '/path/to/whitebox_tools')")
return(invisible(NULL))
}
# unzip to either whitebox package or user specified folder
utils::unzip(exe_zip, exdir = pkg_dir)
# subfolder WBT/whitebox_tools
exe_path_out <- file.path(pkg_dir, "WBT", basename(exe_path))
Sys.chmod(exe_path_out, '755')
Sys.chmod(file.path(dirname(exe_path_out), basename(wbt_runner_path(shell_quote = FALSE))), '755')
# if (os == "Windows") {
# utils::unzip(exe_zip, exdir = pkg_dir)
# } else {
# utils::untar(exe_zip, exdir = pkg_dir)
# }
# if we can find the file where we extracted it, let the user know
if (file.exists(exe_path_out)) {
cat("WhiteboxTools binary is located here: ", exe_path_out, "\n")
cat("You can now start using whitebox\n")
cat(" library(whitebox)\n")
cat(" wbt_version()\n")
# call wbt_init (sets package option)
wbt_init(exe_path = exe_path_out, wd = "")
}
} else if (!force) {
cat("WhiteboxTools binary is located here: ", exe_path, "\n")
}
# return installed path
if (check_whitebox_binary()) {
return(invisible(wbt_exe_path(shell_quote = FALSE)))
}
invisible(NULL)
}
# many packages provide an "install_*" method; alias wbt_install mirrors the wbt_ prefix for most operations. Documentation refers to install_whitebox()
#' Download and Install 'WhiteboxTools'
#'
#' This function downloads the 'WhiteboxTools' binary if needed. Pre-compiled binaries are
#' only available for download for 64-bit Linux (default compiled with glibc on Ubuntu 22.04;
#' use `platform="linux_musl"` for musl/earlier versions of glibc), Windows and Mac OS (ARM and
#' Intel) platforms. If you need WhiteboxTools for another platform follow the instructions to
#' build from source: \url{https://github.com/jblindsay/whitebox-tools}
#'
#' 'WhiteboxTools' and all of its extensions can be uninstalled by passing the `remove=TRUE` argument.
#'
#' @param pkg_dir default install path is to whitebox package "WBT" folder
#' @param platform character. Optional: suffix used for alternate platform names. On Linux, you can choose `"linux_amd64"` (default; Linux) or `"linux_musl"` for older glibc versions. On macOS Darwin you can choose `"darwin_amd64"` (default; macOS) or `"darwin_m_series"` for Apple M series hardware. Note that for `wbt_install_extension()` on the Apple M series use `"MacOS_ARM"`. Only one Windows binary is available: `"win_amd64"` (default; Windows).
#' @param force logical. Force install? Default `FALSE`. When `remove=TRUE` passed to `unlink()` to change permissions to allow removal of files/directories.
#' @param remove logical. Remove contents of "WBT" folder from `pkg_dir`? Default: `FALSE`
#' @return Prints out the location of the WhiteboxTools binary, if found. `NULL` otherwise.
#' @aliases wbt_install
#' @examples
#' \dontrun{
#' install_whitebox()
#' }
#' @export
#' @keywords General
install_whitebox <- function(pkg_dir = wbt_data_dir(), platform = NULL, force = FALSE, remove = FALSE) {
wbt_install(pkg_dir = pkg_dir, platform = platform, force = force, remove = remove)
}
#' @param extension Extension name
#' @param destdir Directory to create `/plugins/` directory for extracting extensions
#' @export
#' @keywords General
#' @rdname install_whitebox
#' @importFrom utils unzip
wbt_install_extension <- function(extension = c(
"GeneralToolsetExtension",
"AgricultureToolset",
"DemAndSpatialHydrologyToolset",
"LidarAndRemoteSensingToolset"
),
platform = NULL,
destdir = dirname(wbt_exe_path(shell_quote = FALSE))) {
extension <- match.arg(extension, c(
"GeneralToolsetExtension",
"AgricultureToolset",
"DemAndSpatialHydrologyToolset",
"LidarAndRemoteSensingToolset"
), several.ok = TRUE)
sn <- Sys.info()[["sysname"]]
fn <- tempfile(extension, fileext = ".zip")
if (missing(platform) || is.null(platform)) {
sufx <- switch(sn,
"Windows" = "win",
"Linux" = "linux",
"Darwin" = switch(Sys.info()[["machine"]],
arm64 = "MacOS_ARM",
"MacOS_Intel"))
} else {
# non-default options include: linux_musl, MacOS_ARM
sufx <- platform
}
if (sn == "Darwin" && Sys.info()["machine"] == "arm64") {
suffix <- "MacOS_ARM"
}
# GTE
if ("GeneralToolsetExtension" %in% extension) {
url <- sprintf("https://www.whiteboxgeo.com/GTE_%s/%s_%s.zip", sn, "GeneralToolsetExtension", sufx)
fn <- "GeneralToolsetExtension.zip"
} else {
url <- sprintf("https://www.whiteboxgeo.com/%s/%s_%s.zip", extension, extension, sufx)
}
ed <- file.path(destdir, "plugins")
download.file(url, destfile = fn, mode = "wb")
unzip(fn, exdir = ed, junkpaths = TRUE)
Sys.chmod(list.files(ed, full.names = TRUE), mode = '0755')
invisible(unlink(fn))
}
#' Activate 'WhiteboxTools' Extensions
#'
#' @param email Email Address
#' @param activation_key Activation Key
#' @param seat Seat Number (Default `1`)
#' @param destdir Directory containing `whitebox_tools` and `/plugins/` folder.
#'
#' @return `0` for success (invisibly). Try-error on error.
#' @export
#' @keywords General
wbt_activate <- function(email, activation_key, seat = 1,
destdir = dirname(wbt_exe_path(shell_quote = FALSE))) {
exeactivate <- ifelse(Sys.info()[["sysname"]] == "Windows",
"register_license.exe", "register_license")
input <- c("register", email, seat, activation_key, "y", "N")
invisible(try(system(file.path(destdir, "plugins", exeactivate), input = input)))
}
#' Help description for 'WhiteboxTools'
#'
#' @return Returns the help description for 'WhiteboxTools' as an R character vector.
#' @export
#' @keywords General
#'
#' @examples
#' \dontrun{
#' wbt_help()
#' }
wbt_help <- function() {
ret <- wbt_system_call("--help")
if (wbt_verbose()) {
cat(ret, sep = "\n")
}
invisible(ret)
}
#' License information for 'WhiteboxTools'
#'
#' @return Returns the license information for WhiteboxTools as an R character vector.
#' @export
#' @keywords General
#'
#' @examples
#' \dontrun{
#' wbt_license()
#' }
wbt_license <- function() {
ret <- wbt_system_call("--license")
if (wbt_verbose()) {
cat(ret, sep = "\n")
}
invisible(ret)
}
#' Version information for 'WhiteboxTools'
#'
#' @param extract Extract semantic version number from first line of result? Default: `FALSE`
#'
#' @return Returns the version information for 'WhiteboxTools' as an R character vector.
#' @export
#' @keywords General
#' @examples
#' \dontrun{
#' wbt_version()
#' }
wbt_version <- function(extract = FALSE) {
ret <- wbt_system_call("--version", check_version = FALSE)
if (extract) {
return(gsub(".*\\bv([0-9\\.]+)\\b.*", "\\1", ret[1]))
}
if (wbt_verbose()) {
cat(ret, sep = "\n")
}
invisible(ret)
}
#' All available tools in 'WhiteboxTools'
#'
#' @param keywords Keywords may be used to search available tools. Default `"''"` returns all available tools.
#'
#' @return Return all available tools in WhiteboxTools that contain the keywords.
#' @export
#' @keywords General
#'
#' @examples
#' \dontrun{
#' wbt_list_tools("lidar")
#' }
wbt_list_tools <- function(keywords = "''") {
ret <- wbt_system_call(paste("--listtools", keywords))
ret <- ret[ret != ""]
if (wbt_verbose()) {
cat(ret, sep = "\n")
}
invisible(ret)
}
#' The toolbox for a specific tool in WhiteboxTools
#'
#' Retrieve the toolbox for a specific tool.
#'
#' @param tool_name The name of the tool.
#' @details Leaving `tool_name` as default `NULL` returns results for all tools, but does not work on Windows.
#' @return Returns the toolbox for a specific tool.
#' @export
#' @keywords General
#'
#' @examples
#' \dontrun{
#' wbt_toolbox("breach_depressions")
#' }
wbt_toolbox <- function(tool_name = NULL) {
ret <- wbt_system_call(paste0("--toolbox", ifelse(!is.null(tool_name),
paste0("=", tool_name), ""))
)
# , command_only = TRUE)
# TODO: shell problems; fix null tool_name not working on windows
# system(paste(wbt_exe_path(shell_quote = TRUE), '--toolbox'), intern = TRUE)
# thread 'main' panicked at 'Unrecognized tool name C:\PROGRA~1\UNIVER~1.0_W\WBT\WHITEB~1.EXE.', src\main.rs:72:21 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
if (wbt_verbose()) {
cat(ret, sep = "\n")
}
invisible(ret)
}
#' Help description for a specific tool in 'WhiteboxTools'
#'
#' Retrieves the help description for a specific tool.
#'
#' @param tool_name The name of the tool.
#'
#' @return Returns the help description for a specific tool.
#' @details Leaving `tool_name` as default `NULL` returns results for all tools, but does not work on Windows.
#' @export
#' @keywords General
#'
#' @examples
#' \dontrun{
#' wbt_tool_help("lidar_info")
#' }
wbt_tool_help <- function(tool_name = NULL) {
ret <- wbt_system_call(paste0("--toolhelp",
ifelse(!is.null(tool_name),
paste0("=", tool_name), "")))
if (wbt_verbose()) {
cat(ret, sep = "\n")
}
invisible(ret)
}
#' Tool parameter descriptions for a specific tool in 'WhiteboxTools'
#'
#' Retrieves the tool parameter descriptions for a specific tool.
#'
#' @param tool_name The name of the tool.
#' @param quiet Prevent tool output being printed. Default: `FALSE`
#'
#' @details `quiet` argument can be set to `TRUE` to allow for "quiet" internal use within other functions.
#'
#' @return Returns the tool parameter descriptions for a specific tool.
#' @export
#' @keywords General
#'
#' @examples
#' \dontrun{
#' wbt_tool_parameters("lidar_info")
#' }
wbt_tool_parameters <- function(tool_name, quiet = FALSE) {
ret <- wbt_system_call(paste0("--toolparameters=", tool_name))
if (wbt_verbose() && !quiet) {
cat(ret, sep = "\n")
}
invisible(ret)
}
#' Source code for a specific tool in 'WhiteboxTools'
#'
#' Opens a web browser to view the source code for a specific tool on the projects source code repository.
#' @param tool_name Name of the tool.
#' @param viewer Show source code in browser? default: `TRUE`
#' @return Returns a GitHub URL to view the source code of the tool.
#' @export
#' @keywords General
#'
#' @examples
#' \dontrun{
#' wbt_view_code("breach_depressions")
#' }
#' @importFrom utils browseURL
wbt_view_code <- function(tool_name, viewer = FALSE) {
ret <- wbt_system_call(paste0("--viewcode=", tool_name))
if (viewer) {
utils::browseURL(ret)
}
if (wbt_verbose()) {
cat(ret, sep = "\n")
}
invisible(ret)
}
#' Run a tool in 'WhiteboxTools' by name
#'
#' Runs a tool and specifies tool arguments. If the prefix "whitebox::" or "wbt_" is in `tool_name` it is removed to match the definitions in `wbt_list_tools()`
#'
#' @param tool_name The name of the tool to run.
#' @param args Tool arguments.
#' @param verbose_mode Verbose mode. Without this flag, tool outputs will not be printed.
#' @param command_only Return command that would be run with `system()`? Default: `FALSE`
#'
#' @return Returns the (character) output of the tool.
#' @export
#' @keywords General
#' @seealso \link{wbt_list_tools}
#' @examples
#' \dontrun{
#' tool_name <- "breach_depressions"
#' dem <- system.file("extdata", "DEM.tif", package="whitebox")
#' output <- "./output.tif"
#' arg1 <- paste0("--dem=", dem)
#' arg2 <- paste0("--output=", output)
#' args <- paste(arg1, arg2)
#' wbt_run_tool(tool_name, args)
#' }
wbt_run_tool <- function(tool_name, args, verbose_mode = FALSE, command_only = FALSE) {
if (length(tool_name) > 1) {
# take last tool_name in case of vector length >1
# e.g. whitebox::wbt_tool_name match.call() output
tool_name <- tool_name[length(tool_name)]
}
# build the call with wbt_system_call()
ret <- wbt_system_call(paste(args, "-v"),
tool_name = tool_name,
command_only = command_only)
if (command_only) {
return(ret)
}
# identify any warning messages in output
warn.idx1 <- grep("\\*{82}", ret)
warn.idx2 <- grep("warning\\:", ret, ignore.case = TRUE)
# produce a custom error message for tools to indicate it did not run
if (length(ret) == 0 || all(nchar(ret) == 0) || !is.null(attr(ret, 'status'))) {
ret <- paste(tool_name, "-", "Elapsed Time: NA [did not run]")
} else if (wbt_verbose() && length(warn.idx2) > 0) {
# show all output from first warning indicator to last, and find elapsed time
cat(ret[min(c(warn.idx1, warn.idx2)):max(c(warn.idx1, warn.idx2))], sep = "\n")
# supports warning messages all on one line, or multi-line
# at end of processing, surrounded by "*"x82
mx <- length(ret)
if (length(warn.idx1) > 0) {
mx <- warn.idx1[1] - 1
}
ret <- paste(tool_name, "-", ret[mx])
} else if (wbt_options()$whitebox.verbose == "all") {
# in "all" mode the full output is shown
cat(ret, sep = "\n")
ret <- paste(tool_name, "-", ret[length(ret)])
} else if (is.null(verbose_mode) || !verbose_mode) {
ret <- paste(tool_name, "-", ret[length(ret)])
}
if (wbt_verbose()) {
cat(ret, sep = "\n")
}
invisible(ret)
}
# sanitize tool names from user input and R methods (function names, case variants etc)
wbt_internal_tool_name <- function(tool_name) {
gsub("^(.)|_(.)", "\\U\\1\\2", gsub("^(whitebox::)?(wbt_)?", "", tool_name), perl = TRUE)
}
wbt_match_tool_name <- function(tool_name, result = c('tool_name', 'function_name')) {
wbttools <- NULL
load(system.file("data/wbttools.rda", package = "whitebox"))
result <- match.arg(result, choices = c('tool_name', 'function_name'), several.ok = TRUE)
idx <- match(tolower(wbttools$tool_name), tolower(gsub("[ _]", "", tool_name)))
wbttools[idx[which(!is.na(idx))], result, drop = FALSE]
}
#' Wrapper method for `system()` calls of `whitebox_tools`
#'
#' @param argstring Concatenated string of parameters passed in tool command.
#' @param tool_name 'WhiteboxTools' tool name
#' @param command_only Return command only?
#' @param ignore.stderr Ignore system() stderr output?
#' @param shell_quote Should the executable path part of the command be quoted?
#' @param check_version Should the version of 'WhiteboxTools' installed be checked against the version the package was built with?
#' @param ... Additional arguments are passed to `wbt_init()`
#' @keywords internal
#' @noRd
wbt_system_call <- function(argstring,
tool_name = NULL,
command_only = FALSE,
ignore.stderr = FALSE,
shell_quote = TRUE,
check_version = TRUE,
...) {
wbt_init(..., check_version = check_version)
wbt_exe <- wbt_exe_path(shell_quote = shell_quote)
args2 <- argstring
# messages about misspecified arguments (e.g. tool_name to wbt_tool_help())
if (length(args2) > 1) {
message("NOTE: Argument string has length greater than 1; using first value")
args2 <- args2[1]
}
# messages about tool_name >1
if (length(tool_name) > 1) {
message("NOTE: tool_name argument has length greater than 1; using first name")
tool_name <- tool_name[1]
}
# if working directory is not specified in the argstring, then pull the package option
if (!grepl("--wd=", args2)) {
userwd <- wbt_wd()
if (nchar(userwd) > 0) {
argstring <- paste0(argstring, " --wd=", shQuote(userwd))
}
# don't add the --wd= argument if the system/package option is unset (value == "")
}
# if compression is not specified in the argstring, then pull the package option
if (!grepl("--compress_rasters", args2)) {
crflag <- wbt_compress_rasters()
if (!is.na(crflag) && is.logical(crflag)) {
argstring <- paste0(argstring, " --compress_rasters=", crflag)
# add the --compress_rasters flag if needed
}
}
# if compression is not specified in the argstring, then pull the package option
if (!grepl("--max_procs", args2)) {
mxpflag <- wbt_max_procs()
if (!is.na(mxpflag) && is.integer(mxpflag)) {
argstring <- paste0(argstring, " --max_procs=", mxpflag)
# add the --max_procs flag if needed
}
}
# allow tool_name to be specified for --run= argument only via tool_name
if (!is.null(tool_name) && tool_name != "") {
tool_name <- wbt_internal_tool_name(tool_name)
args2 <- paste0("--run=", tool_name, " ", argstring)
# TODO: QC on arguments based on supplied tool name and related metadata
} else {
tool_name <- ""
}
exeargs <- trimws(paste(wbt_exe, args2))
# support command_only argument
if (command_only) {
return(exeargs)
}
stopmsg <- paste0("\nError running WhiteboxTools",
ifelse(tool_name != "", paste0(" (", tool_name, ")"), ""), "\n",
" whitebox.exe_path: ", wbt_exe, "; File exists? ",
file.exists(wbt_exe_path(shell_quote = FALSE)),
"\n Arguments: ", args2)
ret <- try(suppressWarnings(
system(exeargs, intern = TRUE, ignore.stderr = ignore.stderr, ignore.stdout = FALSE)
), silent = TRUE)
if (!is.null(attr(ret, "status"))) {
message(stopmsg, "\n")
message("System command had status ", attr(ret, "status"))
if (length(ret) > 0 && nchar(ret[1]) > 0) {
message(paste0(ret, collapse = "\n"))
}
}
invisible(ret)
}
# support for path expansion in input/output file arguments
#' Prepare File Paths for WhiteboxTools Commands
#'
#' Performs path expansion with `path.expand()` and shell quotes with `shQuote()` the input paths.
#'
#' @details If an input vector contains `";"` or `","` this is considered, path expansion is performed on the substrings. If the input vector has length greater than `1`, the vector is concatenated with `","` or `";"` to create a single output string.
#'
#' @param x character or `terra` object. Vector of file paths or strings of file paths for passing as arguments to WhiteboxTools. If the object is of class `SpatRaster`, `SpatRasterCollection`, `SpatVector` or `SpatVectorProxy` the sources are extracted with `terra::sources()`
#'
#' @param shell_quote logical. Shell quotes around result? Default: `TRUE`
#' @param delimiter character. Either `","` (default) or `";"` allowed by WhiteboxTools.
#' @param check_exists logical. Check if file(s) in x exist? Useful for input values. Default: `FALSE`
#'
#' @return character. Length 1. A safe input string for use in WhiteboxTools commands, with paths expanded and concatenated, if necessary, and optionally shell quoted.
#' @export
#'
#' @keywords General
#'
#' @examples
#'
#' wbt_file_path("./abc.tif")
#'
#' wbt_file_path("./abc.tif;./def.tif")
#'
#' wbt_file_path("./abc.tif,./def.tif")
#'
#' wbt_file_path(c("./abc.tif", "./def.tif"))
#'
#' wbt_file_path("~/abc.tif", shell_quote = FALSE)
#'
#' wbt_file_path(c("~/abc.tif", "~/def.tif"))
#'
wbt_file_path <- function(x, shell_quote = TRUE, delimiter = ",", check_exists = FALSE) {
if (inherits(x, c("RasterLayer", "RasterStack"))) {
if (requireNamespace("terra")) {
x <- terra::rast(x)
}
}
if (inherits(x, c('SpatRaster','SpatRasterCollection',
'SpatVector', 'SpatVectorProxy'))) {
if (requireNamespace("terra")) {
x2 <- paste0(terra::sources(x), collapse = delimiter)
if (nchar(x2) == 0) {
stop("The supplied 'terra' object for `", as.character(substitute(x)),"` is not backed by a file. Try loading the object directly from the source file with `terra::rast()` or `terra::vect()`. Various raster formats and ESRI Shapefile are supported. See <https://www.whiteboxgeo.com/manual/wbt_book/supported_formats.html> for details.", call. = FALSE)
}
x <- x2
}
}
delimiter <- match.arg(trimws(delimiter), c(",", ";"))
x <- path.expand(strsplit(
paste0(as.character(x), collapse = ","), ";|,"
)[[1]])
if (check_exists) {
y <- !file.exists(x)
if (any(y)) {
stop(sprintf("File%s not found: %s",
ifelse(sum(y) > 1, "s",""),
paste0(x[y], collapse = ", ")),
call. = FALSE)
}
}
x <- paste0(x, collapse = delimiter)
if (shell_quote) shQuote(x) else x
}
#' Convenience method for path to sample DEM
#'
#' Get a file path to DEM.tif stored in extdata subfolder of whitebox package installation directory. If needed, download the TIFF file from GitHub.
#'
#' @param destfile Path to target location of sample data. Will be downloaded if does not exist. Defaults to file path of extdata subfolder of whitebox package installation directory.
#' @param ... additional arguments to download.file()
#'
#' @return character.
#' @export
#' @keywords General datasets
#'
#' @examples
#'
#' if (check_whitebox_binary()) {
#' wbt_slope(sample_dem_data(), output = "slope.tif")
#' }
#' unlink(c('slope.tif', 'settings.json'))
#' @importFrom utils download.file
sample_dem_data <- function(destfile = file.path(system.file('extdata', package="whitebox"), 'DEM.tif'), ...) {
if (missing(destfile)) {
fp <- system.file("extdata/DEM.tif", package = "whitebox")[1]
} else {
if (!file.exists(destfile)) {
fp <- ""
} else {
fp <- destfile
}
}
if (fp == "") {
try(download.file("https://github.com/opengeos/whiteboxR/raw/master/inst/extdata/DEM.tif",
destfile = destfile,
mode = "wb", ...))
if (missing(destfile)) {
fp <- system.file("extdata/DEM.tif", package = "whitebox")[1]
} else {
if (file.exists(destfile)) {
fp <- destfile
}
}
}
fp
}
#' Convenience method for setting RUST_BACKTRACE options for debugging
#'
#' @param RUST_BACKTRACE One of `"0"`, `"1"`, `"full"`, Logical values are converted to integer and then character.
#'
#' @return value of system environment variable `RUST_BACKTRACE`
#' @export
#' @keywords General
#' @examples
#' \dontrun{
#' wbt_rust_backtrace(TRUE)
#' }
wbt_rust_backtrace <- function(RUST_BACKTRACE = c("0", "1", "full")) {
if (is.logical(RUST_BACKTRACE)) {
RUST_BACKTRACE <- as.integer(RUST_BACKTRACE)
}
Sys.setenv(RUST_BACKTRACE = match.arg(as.character(RUST_BACKTRACE)[1],
choices = c("0", "1", "full")))
invisible(Sys.getenv("RUST_BACKTRACE", unset = "0"))
}
|
/scratch/gouwar.j/cran-all/cranData/whitebox/R/wbt.R
|
#' Initialize an R object containing spatial data for use by WhiteboxTools
#'
#' @param x A terra SpatVector or sf object, or a path to a file that can be read as a SpatVectorProxy
#' @param dsn Data source path / file name
#' @param layer Data layer
#' @param force Force write of vector data to file? Default: FALSE (only write if file does not exist)
#' @param ... Additional arguments passed to `terra::writeVector()` or `sf::st_write()`
#' @param verbose Print information about data source and contents?
#' @return An R object with attributes `wbt_dsn` and `wbt_layer` set as needed to support reading and writing R objects from file by WhiteboxTools.
#' @keywords General
#' @export
wbt_source <- function(x,
dsn = NULL,
layer = NULL,
force = FALSE,
verbose = wbt_verbose(),
...) {
if (!requireNamespace("terra")) {
stop("package `terra` is required to convert vector sources to `wbt()`-compatible SpatVectorProxy", call. = FALSE)
}
if (is.character(x)) {
if (file.exists(x)) {
# convert to shapefile if needed
if (!grepl("\\.shp$", x)) {
xp <- paste0(basename(x), "_", basename(tempfile()), ".shp")
fp <- file.path(tempdir(), xp)
if (!requireNamespace("terra")) {
stop("package `terra` is required to convert non-Shapefile vector sources to Shapefile")
}
x2 <- terra::vect(x)
if (terra::writeVector(x2, fp)) {
x <- fp
} else {
stop("Failed to convert `x` (", x, ") to Shapefile.")
}
}
# a SpatVectorProxy allows us to get some basic info without loading the whole file
x <- terra::vect(x, proxy = TRUE)
attr(x, 'wbt_dsn') <- terra::sources(x)
attr(x, 'wbt_layer') <- layer
return(x)
}
}
# NULL dsn (TODO: GDAL-supported dsn not supported by WBT)
if (is.null(dsn)) {
# if (gpkg) {
# # default geopackage file paths
# dsn <- wbt_geopackage()
# layer <- wbt_geopackage_layer()
# } else {
# only supported vector format is the ESRI Shapefile.
# TODO: dbf limitations? use alternate wbt/gdal common format?
if (!is.null(layer)) {
bn <- layer
} else bn <- "file"
wd <- wbt_wd()
if (wd == "")
wd <- getwd()
ext <- ".shp"
if (inherits(x, 'SpatRaster') ||
inherits(x, 'RasterLayer') ||
inherits(x, 'RasterStack') ||
inherits(x, 'RasterBrick')) {
ext <- ".tif"
}
dsn <- tempfile(pattern = bn, tmpdir = wd, fileext = ext)
# }
}
if (!file.exists(dsn) || force) {
# convert less common types to core types
if (inherits(x, 'sfc') || inherits(x, 'Spatial')) {
x <- sf::st_as_sf(x)
}
# write to file/db
if (inherits(x, 'SpatVector')) {
terra::writeVector(x, filename = dsn, layer = layer, ...)
} else if (inherits(x, 'sf')) {
sf::st_write(x, dsn = dsn, layer = layer, quiet = !verbose, ...)
} else if (inherits(x, 'SpatRaster')) {
terra::writeRaster(x, filename = dsn)
}
}
# set attributes
# TODO: support for DBIConnection as dsn?
if (file.exists(dsn)) {
# TODO: check layer exists in DSN?
if (!is.null(layer)) {
# ...
}
# TODO: check file metadata/extent/CRS/etc?
attr(x, 'wbt_dsn') <- dsn
attr(x, 'wbt_layer') <- layer
}
x
}
# draft, non-exported functions for generating paths/layers in a "scratch" geopackage
wbt_geopackage <- function(wd = wbt_wd(),
gpkg = "Default.gpkg") {
if (wd == "")
wd <- getwd()
file.path(wd, gpkg)
}
wbt_geopackage_layer <- function(layer = NULL) {
basename(tempfile(pattern = "layer"))
}
wbt_add2 <- function(input1,
input2,
output,
wd = getOption("whitebox.wd", getwd()),
verbose_mode = wbt_verbose(),
compress_rasters = wbt_compress_rasters(),
...) {
wbt(
"add",
input1 = input1,
input2 = input2,
output = output,
# wd = wd,
# verbose_mode = verbose_mode,
# compress_rasters = compress_rasters,
...
)
}
|
/scratch/gouwar.j/cran-all/cranData/whitebox/R/wbt_source.R
|
#' @aliases whitebox-package whitebox whitebox.env
#' @export whitebox.env
#' @keywords internal
#' @section Package options:
#'
#' - **`whitebox.exe_path`** - character. Path to executable file. The default value is the package installation directory, subdirectory `"WBT"`, followed by `whitebox_tools.exe` or `whitebox_tools`. Set the `whitebox.exe_path` option using `wbt_init()` `exe_path` argument
#'
#' - **`whitebox.wd`** - character. Path to WhiteboxTools working directory. Used as `--wd` argument for tools that support it when `wd` is not specified elsewhere. Note that once you have set a working directory, the directory needs to be reset to "replace" the old value; just dropping the flag will not change the working directory back to your original R working directory. To "unset" the option in the R package you can use `wbt_wd("")` which is equivalent to `wbt_wd(getwd())`. The WhiteboxTools settings and the package settings will be updated to reflect the directory change after running the next tool and the `--wd` flag will be dropped from system calls.
#'
#' - **`whitebox.verbose`** - logical. Should standard output from calls to executable be `cat()` out for readability? Default is result of `interactive()`. Individual tools may have `verbose_mode` setting that produce only single-line output when `FALSE`. These argument values are left as the defaults defined in the package documentation for that function. When `whitebox.verbose=FALSE` no output is produced. Set the value of `whitebox.verbose` with `wbt_verbose()` `verbose` argument.
#'
#' - **`whitebox.compress_rasters`** - logical. Should raster output from WhiteboxTools be compressed? Default: `FALSE`. Set the value of `whitebox.compress_rasters` with `wbt_compress_rasters()` `compress_rasters` argument.
#'
#' - **`whitebox.max_procs`** - integer. Maximum number of processes for tools that run in parallel or partially parallelize. Default: `-1` uses all of the available cores.
#'
#' The package options can be overridden with system environment variables: `R_WHITEBOX_EXE_PATH`, `R_WHITEBOX_WD`, `R_WHITEBOX_VERBOSE`, `R_WHITEBOX_COMPRESS_RASTERS` and `R_WHITEBOX_MAX_PROCS`.
#'
#' @seealso [wbt_init()], [wbt_options()], [install_whitebox()]
"_PACKAGE"
# whitebox package environment
whitebox.env <- new.env()
#' 'WhiteboxTools' Tool List
#'
#' This data set is a `data.frame` containing tools by name and associated R function name
#' @name wbttools
#' @docType data
#' @keywords General datasets
#' @section Variables:
#' - `"tool_name"` - 'WhiteboxTools' tool name
#' - `"function_name"` - R function name
#' - `"toolbox_name"` - 'WhiteboxTools' toolbox name
#' - `"label"` - 'WhiteboxTools' tool label
#' - `"description"` - Brief description
#' - `"github"` - Link to related code on 'GitHub'
#' - `"book"` - Link to 'WhiteboxTools' Manual
#' - `"is_extension"` - Tool is part of 'General Toolset Extension' (GTE), as opposed to the "open core"
#' @source [WhiteboxTools](https://github.com/jblindsay/whitebox-tools/releases/)
#' @seealso [wbttoolparameters] [wbt_list_tools()]
#' @keywords datasets
"wbttools"
#' 'WhiteboxTools' Tool Parameters
#'
#' This data set is a `data.frame` containing tool parameters and associated metadata
#'
#' @seealso [wbttools] [wbt_tool_parameters()]
#'
#' @name wbttoolparameters
#' @docType data
#' @keywords General datasets
#' @section Variables:
#' - `"function_name"` - R function name
#' - `"tool_name"` - 'WhiteboxTools' tool name
#' - `"name"` - parameter name
#' - `"flags"` - flags used to specify parameter on command line; comma separated
#' - `"description"` - parameter description
#' - `"parameter_class"` - parameter type
#' - `"parameter_detail"` - parameter details; character: data type followed by colon and more specifics, For OptionList possible values, comma-separated (if defined)
#' - `"default_value"` - parameter default value, if any
#' - `"optional"` - parameter "optional" flag; note that some combination of optional parameters may be required for certain conditions
#' - `"label"` - labels for selected subset of `"flags"` **used as R function argument names** for `wbt_` functions
#' - `"is_input"` - logical. Classification of 'input' parameters
#' - `"is_output"` - logical. Classification of 'output' parameters
#' @source [WhiteboxTools](https://github.com/jblindsay/whitebox-tools/releases/)
#' @keywords datasets
"wbttoolparameters"
# The following block is used by usethis to automatically manage
# roxygen namespace tags. Modify with care!
## usethis namespace: start
## usethis namespace: end
NULL
|
/scratch/gouwar.j/cran-all/cranData/whitebox/R/whitebox-package.R
|
#' @title Install wb extension
#'
#' @description Use to install a Whitebox extension product.
#'
#' @param install_extension Name of the extension product to install. Options include: 'General Toolset Extension', 'DEM & Spatial Hydrology Extension', 'Lidar & Remote Sensing Extension', and 'Agriculture Extension'.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords WhiteboxUtilities
#'
#' @return Returns the tool text outputs.
#' @export
wbt_install_wb_extension <- function(install_extension="General Toolset Extension", wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
if (!is.null(install_extension)) {
args <- paste(args, paste0("--install_extension=", install_extension))
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "install_wb_extension"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
#' @title Launch wb runner
#'
#' @description Opens the Whitebox Runner application.
#'
#' @param clear_app_state Clear the application state memory?.
#' @param wd Changes the working directory. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_wd()` for details.
#' @param verbose_mode Sets verbose mode. If verbose mode is `FALSE`, tools will not print output messages. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_verbose()` for details.
#' @param compress_rasters Sets the flag used by 'WhiteboxTools' to determine whether to use compression for output rasters. Default: `NULL` will use the value in WhiteboxTools settings, see `wbt_compress_rasters()` for details.
#' @param command_only Return command that would be executed by `system()` rather than running tool. Default: `FALSE`.
#'
#' @keywords WhiteboxUtilities
#'
#' @return Returns the tool text outputs.
#' @export
wbt_launch_wb_runner <- function(clear_app_state=FALSE, wd=NULL, verbose_mode=NULL, compress_rasters=NULL, command_only=FALSE) {
wbt_init()
args <- ""
if (clear_app_state) {
args <- paste(args, "--clear_app_state")
}
if (!missing(wd)) {
args <- paste(args, paste0("--wd=", wbt_file_path(wd)))
}
if (!missing(compress_rasters)) {
args <- paste(args, paste0("--compress_rasters=", compress_rasters))
}
tool_name <- "launch_wb_runner"
wbt_run_tool(tool_name, args, verbose_mode, command_only)
}
|
/scratch/gouwar.j/cran-all/cranData/whitebox/R/whitebox_utilities.R
|
.onLoad <- function(libname, pkgname) {
# check_whitebox_binary() is called "loudly" only on package load either:
# 1. interactively, or
# 2. environment var R_WHITEBOX_VERBOSE=TRUE or package option whitebox.verbose=TRUE
check_whitebox_binary(silent = !wbt_verbose())
# keep track of whether we have warned about version difference
assign("whitebox.warned_version_difference", value = FALSE, envir = whitebox.env)
}
#' Check for 'WhiteboxTools' executable path
#'
#' @param silent logical. Print help on installation/setting path. Default `TRUE`.
#' @seealso [wbt_exe_path()]
#' @return logical if 'WhiteboxTools' executable file exists.
#' @export
#' @keywords General
check_whitebox_binary <- function(silent = TRUE) {
# look in standard locations
exe_path <- wbt_exe_path(shell_quote = FALSE)
res <- file.exists(exe_path)
if (!res && !silent) {
msg <- paste0(
"\n",
"------------------------------------------------------------------------\n",
"Could not find WhiteboxTools!\n",
"------------------------------------------------------------------------\n",
"\n",
"Your next step is to download and install the WhiteboxTools binary:\n",
" > whitebox::install_whitebox()\n",
"\n",
"If you have WhiteboxTools installed already run `wbt_init(exe_path=...)`': \n",
" > wbt_init(exe_path='/home/user/path/to/whitebox_tools')\n",
"\n",
"For whitebox package documentation, ask for help:\n",
" > ??whitebox\n",
"\n",
"For more information visit https://whiteboxR.gishub.org/\n",
"\n",
"------------------------------------------------------------------------\n")
message(msg)
}
res
}
|
/scratch/gouwar.j/cran-all/cranData/whitebox/R/zzz.R
|
## ---- include = FALSE---------------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
fig.width = 6,
fig.height = 6
)
## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(echo = TRUE)
# R package dataset symbol names
wbttools <- NULL
wbttoolparameters <- NULL
data("wbttools", package = "whitebox")
## -----------------------------------------------------------------------------
data("wbttools", package = "whitebox")
str(wbttools)
## -----------------------------------------------------------------------------
head(wbttools)
## -----------------------------------------------------------------------------
data("wbttoolparameters", package = "whitebox")
## -----------------------------------------------------------------------------
head(wbttoolparameters)
## -----------------------------------------------------------------------------
str(wbttoolparameters, max.level = 1)
## -----------------------------------------------------------------------------
head(subset(wbttoolparameters, grepl("ExistingFile", parameter_class) & grepl("Raster", parameter_detail)))
## ---- echo=FALSE, results='asis'----------------------------------------------
# hide this, we add the parentheses for the docs
wbttoolsshow <- wbttools
wbttoolsshow$function_name <- paste0("`", wbttoolsshow$function_name, "()`")
wbttoolssplt <- split(wbttoolsshow[,colnames(wbttoolsshow) %in% c("function_name", "description")],
list(wbttoolsshow$toolbox_name))
if (requireNamespace("knitr")) {
x <- sapply(names(wbttoolssplt), function(nm) {
cat("###", nm, "\n\n")
print(knitr::kable(
wbttoolssplt[[nm]],
caption = paste("Toolbox:", nm),
col.names = c("Function Name", "Description"),
row.names = FALSE
))
})
}
|
/scratch/gouwar.j/cran-all/cranData/whitebox/inst/doc/datasets.R
|
---
title: "whitebox Tool Metadata"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{whitebox Tool Metadata}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
fig.width = 6,
fig.height = 6
)
```
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
# R package dataset symbol names
wbttools <- NULL
wbttoolparameters <- NULL
data("wbttools", package = "whitebox")
```
# `whitebox` Tool Metadata
This vignette provides an introduction to the data sets included in the `whitebox` package. These data sets contain names, arguments and other metadata for tools available in WhiteboxTools.
### What version of WhiteboxTools are these data sets generated from?
- Current version: **`r attr(wbttools, "version")`**
Internal data sets and functions defined in the R package correspond to tool names available in the most recent version of WhiteboxTools. Data sets are _not_ dynamically generated from your WhiteboxTools installation. Relatively recent versions of WhiteboxTools should be supported backward-compatibly, though any newer functionality will not be usable.
## WhiteboxTools Tool Names and R Function Names
The first data set describes tool names in WhiteboxTools and the corresponding exported function in the R package, along with the WhiteboxTools Toolbox name and a brief description.
```{r}
data("wbttools", package = "whitebox")
str(wbttools)
```
The `wbttools` data set is a data.frame with `r nrow(wbttools)` tools and 7 variables
- `"tool_name"` - WhiteboxTools tool name
- `"function_name"` - R function tool name
- `"toolbox_name"` - WhiteboxTools toolbox name
- `"label"` - WhiteboxTools tool label
- `"description"` - Brief description
- `"github"` - GitHub link
- `"book"` - Reference manual link
- `"is_extension"` - Tool is part of General Toolset Extension (GTE), as opposed to the "open core"
```{r}
head(wbttools)
```
The R function naming style differs from the tool names in WhiteboxTools, but the core words are the same.
R function names are derived from the WhiteboxTools name as follows:
1. `PascalCase` tool names change to `snake_case`
2. All R function names get the prefix `wbt_`
For example, `StreamSlopeContinuous` in WhiteboxTools becomes `wbt_stream_slope_continuous()` in R.
## WhiteboxTools Tool and Parameter Names
The second data set provides details about the available function arguments by tool name.
```{r}
data("wbttoolparameters", package = "whitebox")
```
The `wbttoolparameters` data set is a _data.frame_ with `r nrow(wbttoolparameters)` parameters and `r ncol(wbttoolparameters)` variables:
- `"tool_name"` - WhiteboxTools tool name
- `"function_name"` - R function name
- `"toolbox_name"` - WhiteboxTools toolbox name
- `"name"` - WhiteboxTools tool parameter name
- `"flags"` - flags used to specify parameter on command line; comma-separated
- `"description"` - parameter description
- `"default_value"` - parameter default value, if any
- `"optional"` - parameter "optional" flag; note that some combination of optional parameters may be required for certain conditions
- `"parameter_class"` - parameter type
- `"parameter_detail"` - parameter details; character: data type followed by colon and more specifics, For OptionList possible values, comma-separated (if defined)
- `"is_input"` - logical. Classification of 'input' parameters
- `"is_output"` - logical. Classification of 'output' parameters
- `"argument_name"` - labels for selected subset of `"flags"` **used as R function argument names** for `wbt_` functions
```{r}
head(wbttoolparameters)
```
Several fields in this table such as `flags` and `parameter_type` are "flattened" relative to the nested `wbt_tool_parameters()` output.
The nested `parameter_type` from the JSON result is replaced with two variables in the data set: `parameter_class` and `parameter_details`
This parameter _data.frame_ is useful to construct your own functions with `wbt_run_tool()` or for inspecting the types of tools that can be run on particular data types.
```{r}
str(wbttoolparameters, max.level = 1)
```
You will find that both `tool_name` and `function_name` are present, so you can look up by whatever is convenient.
The variable `argument_name` is processed to be the subset of `flags` that corresponds to arguments to R functions, which are denoted with `function_name`.
### Example: Finding Tools by Parameter Type
To find the tools that have an "ExistingFile" argument with file type "Raster" we can use `subset()`.
```{r}
head(subset(wbttoolparameters, grepl("ExistingFile", parameter_class) & grepl("Raster", parameter_detail)))
```
## Appendix: Tables of Function Names by Toolbox
The remainder of this vignette is tables of R function names and tool descriptions from `wbttoolparameters`, organized by WhiteboxTools toolbox/extension name.
```{r, echo=FALSE, results='asis'}
# hide this, we add the parentheses for the docs
wbttoolsshow <- wbttools
wbttoolsshow$function_name <- paste0("`", wbttoolsshow$function_name, "()`")
wbttoolssplt <- split(wbttoolsshow[,colnames(wbttoolsshow) %in% c("function_name", "description")],
list(wbttoolsshow$toolbox_name))
if (requireNamespace("knitr")) {
x <- sapply(names(wbttoolssplt), function(nm) {
cat("###", nm, "\n\n")
print(knitr::kable(
wbttoolssplt[[nm]],
caption = paste("Toolbox:", nm),
col.names = c("Function Name", "Description"),
row.names = FALSE
))
})
}
```
|
/scratch/gouwar.j/cran-all/cranData/whitebox/inst/doc/datasets.Rmd
|
## ---- include = FALSE---------------------------------------------------------
knitr::opts_chunk$set(
eval = whitebox::check_whitebox_binary(),
echo = TRUE,
collapse = TRUE,
comment = "#>",
fig.width = 6,
fig.height = 6
)
## ---- include=FALSE, echo=FALSE, eval=TRUE------------------------------------
# setup so inline stats on version/tools show up
library(whitebox)
data("wbttoolparameters", package="whitebox")
## ----setup, include=FALSE-----------------------------------------------------
# # sample code to check and install whitebox to a custom path
# if (!whitebox::check_whitebox_binary()) {
# wd <- tempdir()
# whitebox::install_whitebox(wd)
# whitebox::wbt_init(wd = file.path(wd, "WBT", basename(whitebox::wbt_default_path())))
# }
# system and package dependencies must be met to build the vignette
stopifnot(requireNamespace("terra"))
## -----------------------------------------------------------------------------
library(whitebox)
## -----------------------------------------------------------------------------
wbt_exe_path(shell_quote = FALSE)
## -----------------------------------------------------------------------------
library(terra)
library(whitebox)
# DEMO: calculate slope with WhiteboxTools and raster
# Typically the input/output paths are stored as variables
# sample DEM input GeoTIFF
input <- sample_dem_data()
# output file (to be created)
output <- file.path(tempdir(), "slope.tif")
## -----------------------------------------------------------------------------
wbt_slope(input, output, units = 'radians')
## -----------------------------------------------------------------------------
if (file.exists(output)) {
# create a SpatRaster from file output path
outputras <- terra::rast(output)
}
## -----------------------------------------------------------------------------
if (file.exists(input) && file.exists(output) && !is.null(outputras)) {
# par(mfrow = c(2, 1), mar = c(1, 1, 1, 1))
# inspect the output graphically
plot(
outputras,
main = "whitebox::wbt_slope() [radians]",
axes = FALSE
)
# calculate equivalent using raster::terrain() on input
plot(
terra::terrain(terra::rast(input)),
main = "terra::terrain() [radians]",
axes = FALSE
)
}
## -----------------------------------------------------------------------------
# the SpatRaster retains a reference to the input file name
terra::sources(outputras)
## -----------------------------------------------------------------------------
# inspect where wbt_init() will be checking
wbt_exe_path(shell_quote = FALSE)
# TRUE when file is found at one of the user specified paths or package default
# FALSE when whitebox_tools does not exist at path
wbt_init()
## ---- eval=FALSE--------------------------------------------------------------
# # set path manually to whitebox_tools executable, for instance:
# wbt_init(exe_path = '/home/andrew/workspace/whitebox-tools/target/release/whitebox_tools')
## -----------------------------------------------------------------------------
# force output when run non-interactively (knitr)
wbt_verbose(TRUE)
## -----------------------------------------------------------------------------
# sample DEM file path in package extdata folder
input <- sample_dem_data()
# output file name
output <- file.path(tempdir(), "output.tif")
# run breach_depressions tool
wbt_breach_depressions(dem = input, output = output)
## -----------------------------------------------------------------------------
# sample DEM file path in package extdata folder
input <- sample_dem_data()
# output file name
output <- file.path(tempdir(), "output.tif")
# run breach_depressions tool
wbt_run_tool(tool_name = "BreachDepressions", args = paste0("--dem=", input, " --output=", output))
## -----------------------------------------------------------------------------
library(terra)
# sample DEM file path in package extdata folder
input <- sample_dem_data()
# output file name
output <- file.path(tempdir(), "output.tif")
## -----------------------------------------------------------------------------
# run breach_depressions tool
wbt_breach_depressions(dem = input, output = output)
## -----------------------------------------------------------------------------
# create raster object from input file
input <- rast(input)
if (file.exists(output)) {
# create raster object from output file
output <- rast(output)
# par(mar = c(2, 1, 2, 1))
# inspect input v.s. output
plot(input, axes = FALSE, main = "DEM")
plot(output, axes = FALSE, main = "DEM (Breached Depressions)")
# inspect numeric difference (output - input)
plot(output - input, axes = FALSE, main = "Difference ([Breached Depressions] - [DEM])")
}
## -----------------------------------------------------------------------------
library(whitebox)
library(terra)
## Sample DEM from whitebox package
toy_file <- sample_dem_data()
toy_dem <- rast(x = toy_file)
## Generate wd as a temporary directory.
## Replace with your own path, or "." for current directory
wd <- tempdir()
## Write toy_dem to working directory
writeRaster(
x = toy_dem, filename = file.path(wd, "toy_dem.tif"),
overwrite = TRUE
)
## -----------------------------------------------------------------------------
## Breach depressions to ensure continuous flow
wbt_breach_depressions(
dem = file.path(wd, "toy_dem.tif"),
output = file.path(wd, "toy_dem_breached.tif")
)
## -----------------------------------------------------------------------------
## Generate d8 flow pointer (note: other flow directions are available)
wbt_d8_pointer(
dem = file.path(wd, "toy_dem_breached.tif"),
output = file.path(wd, "toy_dem_breached_d8.tif")
)
## -----------------------------------------------------------------------------
## Generate d8 flow accumulation in units of cells (note: other flow directions are available)
wbt_d8_flow_accumulation(
input = file.path(wd, "toy_dem_breached.tif"),
output = file.path(wd, "toy_dem_breached_accum.tif"),
out_type = "cells"
)
## ---- echo = FALSE------------------------------------------------------------
wbt_list_tools(keyword = "flow pointer")
## -----------------------------------------------------------------------------
## Generate streams with a stream initiation threshold of 100 cells
wbt_extract_streams(
flow_accum = file.path(wd, "toy_dem_breached_accum.tif"),
output = file.path(wd, "toy_dem_streams.tif"),
threshold = 100
)
## -----------------------------------------------------------------------------
wbt_tributary_identifier(
d8_pntr = file.path(wd, "toy_dem_breached_d8.tif"),
streams = file.path(wd, "toy_dem_streams.tif"),
output = file.path(wd, "toy_dem_tributaries.tif")
)
## -----------------------------------------------------------------------------
if (file.exists(file.path(wd, "toy_dem_streams.tif"))) {
par(mfrow = c(2, 1), mar = c(3, 1, 2, 1))
plot(
rast(file.path(wd, "toy_dem_streams.tif")),
main = "Streams",
col = "black"
)
plot(
rast(file.path(wd, "toy_dem_tributaries.tif")),
main = "TributaryIdentifier"
)
}
## -----------------------------------------------------------------------------
wbt_help()
## -----------------------------------------------------------------------------
wbt_license()
## -----------------------------------------------------------------------------
wbt_version()
## ---- eval=FALSE--------------------------------------------------------------
# wbt_list_tools()
## -----------------------------------------------------------------------------
wbt_list_tools(keywords = "flowaccumulation")
## -----------------------------------------------------------------------------
wbt_tool_help("tributaryidentifier")
## -----------------------------------------------------------------------------
wbt_toolbox(tool_name = "aspect")
## -----------------------------------------------------------------------------
wbt_toolbox()
## -----------------------------------------------------------------------------
wbt_tool_parameters("slope")
## -----------------------------------------------------------------------------
wbt_view_code("breach_depressions")
## ---- echo=FALSE--------------------------------------------------------------
# cleanup temp files
wd <- tempdir()
unlink(file.path(wd, "slope.tif"))
unlink(file.path(wd, "output.tif"))
unlink(list.files(wd, "^toy_dem.*tif*$", full.names = TRUE))
|
/scratch/gouwar.j/cran-all/cranData/whitebox/inst/doc/demo.R
|
---
title: "whitebox Demo"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{whitebox Demo}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
eval = whitebox::check_whitebox_binary(),
echo = TRUE,
collapse = TRUE,
comment = "#>",
fig.width = 6,
fig.height = 6
)
```
```{r, include=FALSE, echo=FALSE, eval=TRUE}
# setup so inline stats on version/tools show up
library(whitebox)
data("wbttoolparameters", package="whitebox")
```
```{r setup, include=FALSE}
# # sample code to check and install whitebox to a custom path
# if (!whitebox::check_whitebox_binary()) {
# wd <- tempdir()
# whitebox::install_whitebox(wd)
# whitebox::wbt_init(wd = file.path(wd, "WBT", basename(whitebox::wbt_default_path())))
# }
# system and package dependencies must be met to build the vignette
stopifnot(requireNamespace("terra"))
```
## Introduction
whitebox is an R frontend for the 'WhiteboxTools' library, which is an advanced geospatial data analysis platform developed by Prof. John Lindsay at the University of Guelph's Geomorphometry and Hydrogeomatics Research Group.
'WhiteboxTools' can be used to perform common geographical information systems (GIS) analysis operations, such as cost-distance analysis, distance buffering, and raster reclassification. Remote sensing and image processing tasks include image enhancement (e.g. panchromatic sharpening, contrast adjustments), image mosaicing, numerous filtering operations, simple classification (k-means), and common image transformations. 'WhiteboxTools' also contains advanced tooling for spatial hydrological analysis (e.g. flow-accumulation, watershed delineation, stream network analysis, sink removal), terrain analysis (e.g. common terrain indices such as slope, curvatures, wetness index, hillshading; hypsometric analysis; multi-scale topographic position analysis), and LiDAR data processing.
WhiteboxTools is not a cartographic or spatial data visualization package; instead it is meant to serve as an analytical backend for other data visualization software, mainly GIS.
This vignette shows how to use the `whitebox` R package to run WhiteboxTools.
Suggested citation: Lindsay, J. B. (2016). Whitebox GAT: A case study in geomorphometric analysis. Computers & Geosciences, 95, 75-84. doi: http://dx.doi.org/10.1016/j.cageo.2016.07.003
## Setup
Load the `whitebox` library.
```{r}
library(whitebox)
```
### How `whitebox` works
whitebox generates `system()` calls to a local WhiteboxTools binary: `whitebox_tools` or `whitebox_tools.exe`
You can find the binary path that the package is going to use with `wbt_exe_path()`
```{r}
wbt_exe_path(shell_quote = FALSE)
```
This command always returns a "default" path, whether or not you have WhiteboxTools installed.
### Interfacing with R spatial packages
WhiteboxTools input and output are specified as file paths to rasters in GeoTIFF format, shapefiles, HTML output, LiDAR-related files, and more.
In this vignette we will use the `terra` package for visualization. Just as easily we could have used `raster`, `stars` or other options available in the R ecosystem for handling the GeoTIFF output.
The main way to view your output is to save "output" file paths as a variable so that you can use them after processing to load the result into an R spatial object.
#### Working with Raster Data
A demonstration employing the {terra} package follows:
```{r}
library(terra)
library(whitebox)
# DEMO: calculate slope with WhiteboxTools and raster
# Typically the input/output paths are stored as variables
# sample DEM input GeoTIFF
input <- sample_dem_data()
# output file (to be created)
output <- file.path(tempdir(), "slope.tif")
```
Run a tool such as `wbt_slope()` or `"Slope"`.
WhiteboxTools reads from `input` and writes to `output`.
```{r}
wbt_slope(input, output, units = 'radians')
```
```{r}
if (file.exists(output)) {
# create a SpatRaster from file output path
outputras <- terra::rast(output)
}
```
In this case, we can achieve a similar slope map result using `terra::terrain()`, so we will create and plot a SpatRaster from `output` and compare the two.
```{r}
if (file.exists(input) && file.exists(output) && !is.null(outputras)) {
# par(mfrow = c(2, 1), mar = c(1, 1, 1, 1))
# inspect the output graphically
plot(
outputras,
main = "whitebox::wbt_slope() [radians]",
axes = FALSE
)
# calculate equivalent using raster::terrain() on input
plot(
terra::terrain(terra::rast(input)),
main = "terra::terrain() [radians]",
axes = FALSE
)
}
```
The `SpatRaster`, `RasterLayer` and related classes in the terra and raster packages are perfect for maintaining the linkage between file output and an R object with the data in or out of memory.
Use `terra::sources()` to get the "source" file name(s). If you are using a raster `RasterLayer` objects the equivalent method is `raster::filename()`.
```{r}
# the SpatRaster retains a reference to the input file name
terra::sources(outputras)
```
### WhiteboxTools R setup
### Installing WhiteboxTools
In `whitebox` `wbt_init()` is the standard way to set the "exe_path" for a session.
If you do not have WhiteboxTools installed in the default location, do not have `whitebox_tools` on your PATH, and have not set up your package options, the package will not be able to find your WhiteboxTools installation on load.
Usually you can use `whitebox::install_whitebox()` to download the latest binaries that correspond to the available version of the R package. However, this is not required. You may download/compile WhiteboxTools yourself and install anywhere for use with the `whitebox` R package.
For general information consult the WhiteboxTools User Manual: https://www.whiteboxgeo.com/manual/wbt_book/install.html
For more details on building from source see: https://github.com/jblindsay/whitebox-tools
### Package Settings with `wbt_init()`
`wbt_init()` is used to set and check the path of the binary executable that commands are passed to.
The executable path and other options are stored as package options, and can be overridden by system environment variables. A default value `wbt_exe_path(shell_quote = FALSE)` is passed when the `exe_path` argument is unspecified.
```{r}
# inspect where wbt_init() will be checking
wbt_exe_path(shell_quote = FALSE)
# TRUE when file is found at one of the user specified paths or package default
# FALSE when whitebox_tools does not exist at path
wbt_init()
```
This section will cover optional arguments to `wbt_init()` (`exe_path`, `wd` and `verbose`) and their corresponding options and helper functions.
#### `exe_path` argument
The `exe_path` argument to `wbt_init()` sets the `whitebox.exe_path` package option. `exe_path` is the path to a WhiteboxTools executable file.
The default value is the package installation directory, subdirectory `"WBT"`, followed by `whitebox_tools.exe` or `whitebox_tools` depending on your operating system.
```{r, eval=FALSE}
# set path manually to whitebox_tools executable, for instance:
wbt_init(exe_path = '/home/andrew/workspace/whitebox-tools/target/release/whitebox_tools')
```
The package will automatically find an existing installation when `whitebox_tools` is in a directory on your PATH.
Package options other than `exe_path` (as detailed in `?whitebox::whitebox` and `?wbt_init`) can be set with `wbt_init(exe_path, ...)`, where `...` is additional named arguments corresponding to the `*` suffix in `whitebox.*` package options names. Use `wbt_options()` or specific methods like `wbt_verbose()`, `wbt_wd()` to get all values or set specific values.
#### `wd` argument
The `wd` argument can be used to set the WhiteboxTools working directory.
A working directory specifies a base folder path where WhiteboxTools can find inputs and create outputs. Setting the `whitebox.wd` package option (via the `wd` argument to `wbt_init()` or `wbt_wd()`) aids the process of setting file paths.
If a value is set for the option the `--wd` directory flag is added for tools that support it.
Before you set the working directory in a session the default output will be in your current R working directory unless directory is specified in your input/output arguments. You can change working directory at any time by setting the `wd` argument to `wbt_wd()` and running a tool.
NOTE: once you have set a working directory in a session, the directory needs to be set somewhere new to "replace" the old value; just dropping the flag will **not** automatically change the working directory *back to your R working directory*\* and your output will show up in whatever folder you set initially.
A helper method for setting the `whitebox.wd` option is `wbt_wd()`.
To "unset" the option in the R package you can use `wbt_wd("")` which is equivalent to `wbt_wd(getwd())`. The next tool call will change the WhiteboxTools working directory setting to the new path. After this point the flag need not be specified [until you wish to change again].
```r
wbt_wd("") # "" equivalent to getwd()
```
#### `verbose` argument
The `verbose` argument is used to set the package option related to tool "verbosity": `whitebox.verbose`. When `whitebox.verbose` is `FALSE` no output will be `cat()` to the console by running tools.
A helper method for getting and setting the `whitebox.verbose` option is `wbt_verbose()`. `wbt_verbose()` is used throughout the package to check what level of verbosity should be used.
By default, the result of `wbt_verbose()` is the result of `interactive()` so tools will print extra console output when you are there to see it. This is used in a variety of `wbt_*` methods to allow the package option to control output for many functions in a consistent manner, hide output in your automated tests, markdown documents, vignettes etc.
In this vignette we use `wbt_verbose(TRUE)` so the package option `whitebox.verbose` is set to `TRUE`
```{r}
# force output when run non-interactively (knitr)
wbt_verbose(TRUE)
```
This is mainly to print out the tool name and elapsed time whenever we run a tool:
```
#> wbt_breach_depressions - Elapsed Time (excluding I/O): 0.12s
```
This package-level verbose option can also control the `verbose_mode` values passed to `wbt_*` tool functions. Turning on "full" output requires a third option to be set for this argument: `"all"`. Use `wbt_verbose("all")`. `wbt_verbose()` will still return `TRUE` when the `whitebox.verbose` option is `"all"`.
### Long-term Package Option Settings
The package will detect when you have added the WhiteboxTools directory to your `PATH` environment variable. For long-term package option settings you can put `whitebox_tools` on `$PATH` or set `R_WHITEBOX_EXE_PATH` in your user `.Rprofile` or `.Renviron`.
On Windows you can add the path to `whitebox_tools.exe` as a new entry `R_WHITEBOX_EXE_PATH` in User or System Environment variable.
On Linux/Mac you can set `R_WHITEBOX_EXE_PATH` directly with `export R_WHITEBOX_EXE_PATH="/path/to/whitebox_tools"`.
- Note that if you set your `$PATH` in you regular shell profile (`.profile`/`.bashrc`/`.zshrc`) then it will _not_ be sourced by _RStudio_ for your R session by default.
This requires that you have the Unix tool `which` or one of its analogues.
You can also set `R_WHITEBOX_EXE_PATH` manually in R:
```r
Sys.setenv(R_WHITEBOX_EXE_PATH = Sys.which("whitebox_tools"))
```
- Replace the `Sys.which()` call with a custom path string as needed such as `"C:/path/to/whitebox_tools.exe"`.
All of the other package options can similarly be set as environment variables. They are prefixed with `R_WHITEBOX_*`. See `?whitebox` for details.
## Running tools
Specify input and output paths, and any other options, as specified in package reference:
- https://whiteboxR.gishub.org/reference/index.html
For instance, "BreachDepressions" is used below to process a Digital Elevation Model (DEM) before we identify flow pathways. This tool uses uses Lindsay's (2016) algorithm, which is preferred over depression filling in most cases.
```{r}
# sample DEM file path in package extdata folder
input <- sample_dem_data()
# output file name
output <- file.path(tempdir(), "output.tif")
# run breach_depressions tool
wbt_breach_depressions(dem = input, output = output)
```
For more info see: `?wbt_breach_depressions`
These `wbt_*_tool_name_*()` functions are wrappers around the `wbt_run_tool()` function that does the `system()` call given a function-specific argument string.
```{r}
# sample DEM file path in package extdata folder
input <- sample_dem_data()
# output file name
output <- file.path(tempdir(), "output.tif")
# run breach_depressions tool
wbt_run_tool(tool_name = "BreachDepressions", args = paste0("--dem=", input, " --output=", output))
```
The above method of creating `wbt_breach_depressions(dem = ..., output = ...)` to handle `wbt_run_tool("BreachDepressions", args = ...)` makes it easy to generate static methods that have parity with the latest WhiteboxTools interface.
### Example: Compare input v.s. output with `terra`
We use the {terra} package to read the GeoTIFF file output by WhiteboxTools.
#### Setup
```{r}
library(terra)
# sample DEM file path in package extdata folder
input <- sample_dem_data()
# output file name
output <- file.path(tempdir(), "output.tif")
```
#### Run `wbt_breach_depressions()` (BreachDepressions tool)
```{r}
# run breach_depressions tool
wbt_breach_depressions(dem = input, output = output)
```
#### Visualize results with `terra`
```{r}
# create raster object from input file
input <- rast(input)
if (file.exists(output)) {
# create raster object from output file
output <- rast(output)
# par(mar = c(2, 1, 2, 1))
# inspect input v.s. output
plot(input, axes = FALSE, main = "DEM")
plot(output, axes = FALSE, main = "DEM (Breached Depressions)")
# inspect numeric difference (output - input)
plot(output - input, axes = FALSE, main = "Difference ([Breached Depressions] - [DEM])")
}
```
### Example: Identifying Tributaries
Here we will take our processing of DEMs a bit further by performing several WhiteboxTools operations in sequence.
We are interested in identifying and ranking tributaries of watercourses (streams and rivers).
An R package that makes use of the `whitebox` R package is [hydroweight](https://github.com/bkielstr/hydroweight). Here is a brief example on the beginning of the `hydroweight` README showing how the breached DEM above can be used in a spatial analysis of stream networks.
#### Setup
```{r}
library(whitebox)
library(terra)
## Sample DEM from whitebox package
toy_file <- sample_dem_data()
toy_dem <- rast(x = toy_file)
## Generate wd as a temporary directory.
## Replace with your own path, or "." for current directory
wd <- tempdir()
## Write toy_dem to working directory
writeRaster(
x = toy_dem, filename = file.path(wd, "toy_dem.tif"),
overwrite = TRUE
)
```
#### `wbt_breach_depressions()` -- Breach DEM Depressions
First we pre-process by breaching depressions in the DEM
```{r}
## Breach depressions to ensure continuous flow
wbt_breach_depressions(
dem = file.path(wd, "toy_dem.tif"),
output = file.path(wd, "toy_dem_breached.tif")
)
```
#### `wbt_d8_pointer()` -- Calculate Flow Direction
Then we generate the direction of flow on the DEM surface using the "D8" flow pointer method
```{r}
## Generate d8 flow pointer (note: other flow directions are available)
wbt_d8_pointer(
dem = file.path(wd, "toy_dem_breached.tif"),
output = file.path(wd, "toy_dem_breached_d8.tif")
)
```
#### `wbt_d8_flow_accumulation()` -- Flow Accumulation
Once we calculate the direction of flow by some method, we calculate cumulative flow
For example with `wbt_d8_flow_accumulation()`:
```{r}
## Generate d8 flow accumulation in units of cells (note: other flow directions are available)
wbt_d8_flow_accumulation(
input = file.path(wd, "toy_dem_breached.tif"),
output = file.path(wd, "toy_dem_breached_accum.tif"),
out_type = "cells"
)
```
##### Additional Flow Direction and Accumulation Tools
In addition to D8 flow pointers (flow direction), there are several other options for both direction and accumulation such as FD8, D-infinity, and D-infinity.
- Keyword "Pointer" tools: `"D8Pointer"`, `"DInfPointer"`, `"FD8Pointer"`, `"Rho8Pointer"`
- Keyword "FlowAccumulation" tools: `"D8FlowAccumulation"`, `"DInfFlowAccumulation"`, `"FD8FlowAccumulation"`, `"Rho8FlowAccumulation"`, `"MDInfFlowAccumulation"`
Search for more tools involving `"flow pointer"` by key word: `wbt_list_tools(keyword = "flow pointer")`
```{r, echo = FALSE}
wbt_list_tools(keyword = "flow pointer")
```
This is just an example of the wealth of tool options made available by the WhiteboxTools platform.
#### `wbt_extract_streams()` -- Extract Stream Network
With our flow accumulation raster in hand, we can extract a stream network with `wbt_extract_streams()` based on a threshold (e.g. `100`) of accumulated flow. This threshold value you choose will depend on analysis goals, the choice of flow accumulation algorithm used, local topography, as well as resolution and extent of DEM.
```{r}
## Generate streams with a stream initiation threshold of 100 cells
wbt_extract_streams(
flow_accum = file.path(wd, "toy_dem_breached_accum.tif"),
output = file.path(wd, "toy_dem_streams.tif"),
threshold = 100
)
```
#### `wbt_tributary_identifier()` -- Identify Tributaries
Next, let's identify tributaries. This function `wbt_tributary_identifier()` is a little more complicated because it takes takes two inputs:
- Our raster D8 pointer file.
- And our raster streams file.
```{r}
wbt_tributary_identifier(
d8_pntr = file.path(wd, "toy_dem_breached_d8.tif"),
streams = file.path(wd, "toy_dem_streams.tif"),
output = file.path(wd, "toy_dem_tributaries.tif")
)
```
#### Compare results
Finally, we compare results of `wbt_extract_streams()` with `wbt_tributary_identifier()`
```{r}
if (file.exists(file.path(wd, "toy_dem_streams.tif"))) {
par(mfrow = c(2, 1), mar = c(3, 1, 2, 1))
plot(
rast(file.path(wd, "toy_dem_streams.tif")),
main = "Streams",
col = "black"
)
plot(
rast(file.path(wd, "toy_dem_tributaries.tif")),
main = "TributaryIdentifier"
)
}
```
## Appendix: `wbt_*` utility functions
These methods provide access to WhiteboxTools executable parameters and metadata.
### `wbt_help()`
`wbt_help()` prints the WhiteboxTools help: a listing of available commands for executable
```{r}
wbt_help()
```
### `wbt_license()`
`wbt_license()` prints the WhiteboxTools license
```{r}
wbt_license()
```
### `wbt_version()`
Prints the WhiteboxTools version
```{r}
wbt_version()
```
### `wbt_list_tools()`
Use `wbt_list_tools()` to list all available tools in WhiteboxTools. In version `r attr(wbttoolparameters, 'version')` there are over `r (length(whitebox::wbt_list_tools()) - 1)` tools! See all the available [toolboxes](https://www.whiteboxgeo.com/manual/wbt_book/available_tools/index.html) and [extensions](https://www.whiteboxgeo.com/whitebox-geospatial-extensions/).
```{r, eval=FALSE}
wbt_list_tools()
```
The full list can be an overwhelming amount of output, so you pass the `keywords` argument to search and filter.
For example we list tools with keyword 'flowaccumulation' in tool name or description.
```{r}
wbt_list_tools(keywords = "flowaccumulation")
```
### `wbt_tool_help()`
Once we find a tool that we are interested in using, we can investigate what sort of parameters it takes. The R methods generally take the same named parameters.
R functions have the naming scheme `wbt_tool_name` where `_` is used for spaces, whereas the tools themselves have no spaces.
`wbt_tool_help("tributaryidentifier")` shows the command line help for a tool by name.
```{r}
wbt_tool_help("tributaryidentifier")
```
`?wbt_tributary_identifier` shows the corresponding R function help, which is derived from the command line help page and other metadata.
### `wbt_toolbox()`
Another way that tools are organized in WhiteboxTools is by "toolbox."
`wbt_toolbox()` prints the toolbox for a specific tool (or all tools if none specified)
```{r}
wbt_toolbox(tool_name = "aspect")
```
Print the full list by not specifying `tool_name`
```{r}
wbt_toolbox()
```
### `wbt_tool_parameters()`
`wbt_tool_parameters()` retrieves the tool parameter descriptions for a specific tool as JSON formatted string.
```{r}
wbt_tool_parameters("slope")
```
### `wbt_view_code()`
WhiteboxTools is written in Rust and is open source. You can view the source code for a specific tool on the source code repository.
```{r}
wbt_view_code("breach_depressions")
```
Use the argument `viewer=TRUE` to use `browseURL()` to open a browser window to the corresponding GitHub page.
```{r, echo=FALSE}
# cleanup temp files
wd <- tempdir()
unlink(file.path(wd, "slope.tif"))
unlink(file.path(wd, "output.tif"))
unlink(list.files(wd, "^toy_dem.*tif*$", full.names = TRUE))
```
|
/scratch/gouwar.j/cran-all/cranData/whitebox/inst/doc/demo.Rmd
|
## ---- include = FALSE---------------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
eval = whitebox::check_whitebox_binary() &
requireNamespace("terra", quietly = TRUE)
)
## -----------------------------------------------------------------------------
library(whitebox)
## -----------------------------------------------------------------------------
wbt("slope")
## -----------------------------------------------------------------------------
# get file path of sample DEM
dem <- sample_dem_data()
wbt("slope", dem = dem, output = file.path(tempdir(), "slope.tif"))
## -----------------------------------------------------------------------------
wbt("slope", goof = dem, output = file.path(tempdir(), "slope.tif"))
## -----------------------------------------------------------------------------
str(wbt("slope", dem = dem, output = file.path(tempdir(), "slope.tif")), max.level = 1)
## -----------------------------------------------------------------------------
# on error there is a try-error object in $result
x <- wbt("slope")
inherits(x$result, 'try-error')
message(x$result[1])
## -----------------------------------------------------------------------------
if (requireNamespace("raster")) {
rdem <- raster::raster(dem)
# raster input; raster output
r1 <- wbt("slope", dem = rdem, output = file.path(tempdir(), "slope.tif"))
r1
class(r1$result$output)
}
## -----------------------------------------------------------------------------
tdem <- terra::rast(dem)
## terra input; terra output
t1 <- wbt("slope", dem = tdem, output = file.path(tempdir(), "slope.tif"))
t1
class(t1$result$output)
## -----------------------------------------------------------------------------
library(terra)
shp <- system.file("ex/lux.shp", package = "terra")
x <- wbt_source(shp)
x
## -----------------------------------------------------------------------------
# load the data
x2 <- query(x)
# remove area column
x2$AREA <- NULL
# create a GeoPackage
terra::writeVector(x2, filename = file.path(tempdir(), "lux.gpkg"), overwrite = TRUE)
# now the source is a temporary .shp
x3 <- wbt_source(file.path(tempdir(), "lux.gpkg"))
wbt("polygon_area", input = x3)
## -----------------------------------------------------------------------------
x <- wbt("slope", dem = dem, output = file.path(tempdir(), "slope.tif"))
x2 <- wbt(x, tool_name = "slope", output = file.path(tempdir(), "curvature.tif"))
## -----------------------------------------------------------------------------
x2
## -----------------------------------------------------------------------------
str(wbt_result(x2), max.level = 1)
## -----------------------------------------------------------------------------
str(x2$history, max.level = 1)
## -----------------------------------------------------------------------------
x <- wbt("slope")
wbt(x, "slope", output = file.path(tempdir(), "foo.tif"))
## -----------------------------------------------------------------------------
dem <- sample_dem_data()
## equivalent to:
# dem <- system.file("extdata/DEM.tif", package = "whitebox")
## -----------------------------------------------------------------------------
araster <- terra::rast(dem)
wbt("slope", dem = araster, output = file.path(tempdir(), "foo.tif"))
## -----------------------------------------------------------------------------
wbt("slope", dem = terra::rast(dem), crs = "EPSG:26918", output = file.path(tempdir(), "foo.tif"))
## -----------------------------------------------------------------------------
r1 <- terra::rast(dem) # default: EPSG:26918
r2 <- terra::deepcopy(r1)
crs(r2) <- "EPSG:26917" # something else/wrong
wbt("add",
input1 = r1,
input2 = r2,
output = file.path(tempdir(), "foo.tif")
)
## -----------------------------------------------------------------------------
wbt("add",
input1 = r1,
input2 = r2,
crs = "EPSG:26918",
output = file.path(tempdir(), "foo.tif")
)
## ---- echo=FALSE--------------------------------------------------------------
# cleanup temp files
unlink(list.files(".", pattern = "file.*tif$", full.names = TRUE))
unlink(list.files(tempdir(), pattern = "file.*tif$", full.names = TRUE))
|
/scratch/gouwar.j/cran-all/cranData/whitebox/inst/doc/wbt-method.R
|
---
title: "`wbt()` method: call 'Whitebox' tools by name"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{`wbt()` and `wbt_result`}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
eval = whitebox::check_whitebox_binary() &
requireNamespace("terra", quietly = TRUE)
)
```
# `wbt()`
The `wbt()` method is a high-level wrapper function to manage flow of
information between R and WhiteboxTools. With `wbt()` one can run sequential
analyses in Whitebox while having R prepare inputs, generate commands, and
visualize results.
```{r}
library(whitebox)
```
## Getting Started
Know what tool you want to run but _can't remember the required parameters_?
Just type `wbt("toolname")`
```{r}
wbt("slope")
```
Output produced on error and with invalid arguments helps guide use
interactively by prompting with required and optional arguments as a checklist.
## Result Objects
All calls to `wbt()` return an S3 object with class `wbt_result`.
```{r}
# get file path of sample DEM
dem <- sample_dem_data()
wbt("slope", dem = dem, output = file.path(tempdir(), "slope.tif"))
```
Whether a system call succeeds or fails the parameters that were passed to the WhiteboxTools
executable and references to any output file paths that were specified are
returned. If output files reference spatial data (e.g. a GeoTIFF file) they may
be converted to a file-based R object providing information about the result.
```{r}
wbt("slope", goof = dem, output = file.path(tempdir(), "slope.tif"))
```
When a call fails an informative error message issued, and the error will be cached
inside the result. Prior runs references are stored as well for sequential tool runs; more on that below.
### `wbt_result` class
A `wbt_result` class object is a base R `list()` with standard element
names (`"tool"`, `"args"`, `"stdout"`, `"crs"`, `"result"`, `"history"`) and
the `"class"` attribute `"wbt_result"`.
```{r}
str(wbt("slope", dem = dem, output = file.path(tempdir(), "slope.tif")), max.level = 1)
```
Any `output` produced by the tool (usually file paths set by the user) will be
included in the `wbt_result$result` list.
### `wbt_result` on error
If there is an error a `try-error` class object with an error message is
returned in lieu of a list in `$result`
```{r}
# on error there is a try-error object in $result
x <- wbt("slope")
inherits(x$result, 'try-error')
message(x$result[1])
```
## Vignette Topics
We now will cover how the `wbt()` method and `wbt_result` class can be used for
the following:
- Input and Output with R spatial objects
- Running Sequences of Tools (optionally: with pipe `|>` or `%>%`)
- Handling Coordinate Reference Systems
# Input and Output with R spatial objects
A feature of `wbt()` is that it handles input/output and file name management
if you are using R objects as input. It can be an onerous task to manage files
for workflows involving many tool runs.
If you use a `terra` object as input, you will get a `SpatRaster`. If you use
a `raster` object as your input object frontend, you will get a `RasterLayer`
object as output for tools that produce a raster. There will be file paths
associated with that R object.
### Compare `raster` and `terra` as R raster object frontends
```{r}
if (requireNamespace("raster")) {
rdem <- raster::raster(dem)
# raster input; raster output
r1 <- wbt("slope", dem = rdem, output = file.path(tempdir(), "slope.tif"))
r1
class(r1$result$output)
}
```
```{r}
tdem <- terra::rast(dem)
## terra input; terra output
t1 <- wbt("slope", dem = tdem, output = file.path(tempdir(), "slope.tif"))
t1
class(t1$result$output)
```
The user still needs to specify paths but `wbt()` eases the process
of converting input objects to paths and reading output paths to R objects
after the tool has run. In principle any R object that references a file with
type that Whitebox supports can be handled under the current (simple; proof of
concept) system. Using file-based representations may not be the most
efficient, but allows for a tangible trail of the steps in a workflow to be
followed that otherwise might be hard to track.
# `wbt_source()`: rasters in memory, and vector data
The terra and raster packages use pointers to a file/raster connection except
when a grid is entirely in memory. Processing these types of rasters with
whitebox requires writing out as a temporary GeoTIFF file for tool input. In general
`wbt()` can handle this for you.
Vector data (point, line and polygon geometries) are commonly stored stored in
sf data.frames, sp objects, or terra SpatVector objects. These types are
read into memory on creation.
Reading vector data into R memory is
not needed to run Whitebox tools, so `wbt_source()` provides a means to annotate objects
with information about source file path (similar to how terra/raster handle raster sources)
such that they can be processed further by `wbt()` with minimal overhead.
Objects like the terra SpatVectorProxy use delayed read by default. Passing a file path
to `wbt_source()` will create a SpatVectorProxy with necessary information for use with `wbt()`.
For instance, we can create a reference for a sample ESRI Shapefile via `wbt_source()`. The result is a SpatVectorProxy.
```{r}
library(terra)
shp <- system.file("ex/lux.shp", package = "terra")
x <- wbt_source(shp)
x
```
The SpatVectorProxy provides a light-weight means to create an R object reference to a large file; allowing the "heavy" lifting for that file to be done primarily by WhiteboxTools (or GDAL via {terra}).
At time of writing this document, WhiteboxTools does not support vector data inputs other than Shapefile. If we have, for example, a GeoPackage, `wbt_source()` will convert the input to a temporary shapefile and return a SpatVectorProxy that references that file. This object can then be used as input to `wbt()`.
```{r}
# load the data
x2 <- query(x)
# remove area column
x2$AREA <- NULL
# create a GeoPackage
terra::writeVector(x2, filename = file.path(tempdir(), "lux.gpkg"), overwrite = TRUE)
# now the source is a temporary .shp
x3 <- wbt_source(file.path(tempdir(), "lux.gpkg"))
wbt("polygon_area", input = x3)
```
# Running Sequences of Tools
When you call `wbt()` and the first argument is a `wbt_result` the `output`
from the input `wbt_result` is passed as the first `input` to the new tool run.
This general "pass the output as the first input" works even if the first
`input` parameter (`"-i"` flag) is something different such as `dem` or
`input1`.
This makes it possible to chain different operations together in a sequence.
If all of the required parameters are specified the tool will be run.
Here we run "Slope" on a DEM, then run "Slope" on it again to get a second
derivative "curvature".
```{r}
x <- wbt("slope", dem = dem, output = file.path(tempdir(), "slope.tif"))
x2 <- wbt(x, tool_name = "slope", output = file.path(tempdir(), "curvature.tif"))
```
## Using pipes
Nested chained operation syntax can be transformed to use pipe operators ({base} R 4.1+ `|>` or {magrittr} `%>%`). This can improve the readability of the code (fewer nested parentheses) and the first argument transfer behavior allows results from each step to be transferred to the input of the next.
```{r, eval = FALSE, purl = FALSE}
wbt("slope", dem = dem, output = file.path(tempdir(), "slope.tif")) |>
wbt("slope", output = file.path(tempdir(), "curvature.tif"))
```
The `wbt_result` output that prints to the console will reflect the
input/output parameters of the most recent tool run in a tool chain.
```{r}
x2
```
`wbt_result()` is the method to get `$result` for single runs or all `$result`
in `$history` for chained runs from a `wbt_result` object.
```{r}
str(wbt_result(x2), max.level = 1)
```
The `$history` element is a list of the `wbt_result` from individual runs.
```{r}
str(x2$history, max.level = 1)
```
If you pass invalid results from one step to the next, you get an informative
error message.
```{r}
x <- wbt("slope")
wbt(x, "slope", output = file.path(tempdir(), "foo.tif"))
```
# Coordinate Reference Systems (CRS)
On top of handling file paths it is necessary for Geographic Information
Systems to handle Coordinate Reference System (CRS) information. Many R tools
in the GDAL/PROJ sphere require valid CRS to operate.
WhiteboxTools will read the GeoKey information from your _GeoTIFF_ files
specified by path and propagate that to the output file result. When you read
those files with R, you should find that the original file's CRS has been
transferred.
`wbt()` and `wbt_result` help ensure consistent file and CRS information across
sequences of operations and within calls--especially those _involving R spatial
objects_.
If you specified the CRS in R, or made the raster entirely in R, you might need
a hand setting up the file-based representation that WhiteboxTools will use.
This is easy enough to do with `crs()`, `writeRaster()` and the equivalent but
often requires more boilerplate code than just specifying the argument, or
having CRS propagate from input.
For inputs that have a file-based representation (e.g. `RasterLayer` and
`SpatRaster` objects) `wbt()` provides an interface where R objects can be
substituted for file names and vice versa. User and workflow level attributes
like CRS and working directory be handled at the same time.
```{r}
dem <- sample_dem_data()
## equivalent to:
# dem <- system.file("extdata/DEM.tif", package = "whitebox")
```
In the process of reading/writing files that may contain CRS information, such
as this sample DEM, the CRS can be inspected, modified and propagated to file
or R objects.
## Setting the CRS
If the CRS is specified in the input `SpatRaster` object, `wbt()` makes sure it is
propagated to the R object result. `wbt()` does not alter or copy the source or
output files which may or may not have CRS information.
```{r}
araster <- terra::rast(dem)
wbt("slope", dem = araster, output = file.path(tempdir(), "foo.tif"))
```
Alternately you can specify the `crs` argument to `wbt()` instead of `rast()`. This will directly set the `crs` element of the `wbt_result` of your output.
```{r}
wbt("slope", dem = terra::rast(dem), crs = "EPSG:26918", output = file.path(tempdir(), "foo.tif"))
```
In either case wherever you specify the `crs` argument the `crs` is
stored in the `wbt_result` and propagated to the relevant output. Again, the
source files are unchanged if they had no CRS or invalid CRS (until you write that updated CRS to file).
If two input R objects have different (or no) CRS then the `wbt()` method will
provide a message to the user:
```{r}
r1 <- terra::rast(dem) # default: EPSG:26918
r2 <- terra::deepcopy(r1)
crs(r2) <- "EPSG:26917" # something else/wrong
wbt("add",
input1 = r1,
input2 = r2,
output = file.path(tempdir(), "foo.tif")
)
```
This message is suppressed and output CRS set accordingly if the `crs` argument is specified. This user set CRS is only in the SpatRaster object, and does not necessarily match that of the file used as input or returned as output.
```{r}
wbt("add",
input1 = r1,
input2 = r2,
crs = "EPSG:26918",
output = file.path(tempdir(), "foo.tif")
)
```
<!--
# Future Plans
Future additions to this vignette may include:
- Managing WhiteboxTools working directories
- Managing WhiteboxTools file types
In the future users will be able to:
- Set a temporary or persistent working
directory and have output file paths/names auto-generated, allowing them to
work entirely with R objects and `wbt_result` while making an intermediate file
record in the background.
- Use a wrapper class for generic
groups of Whitebox file types; allowing file name references for any R object
or output file type to be stored: optimized/customizable read/write methods used for
specific file types and generic .rda files with metadata for others.
- Batch of tool runs on e.g. watershed extents -->
```{r, echo=FALSE}
# cleanup temp files
unlink(list.files(".", pattern = "file.*tif$", full.names = TRUE))
unlink(list.files(tempdir(), pattern = "file.*tif$", full.names = TRUE))
```
|
/scratch/gouwar.j/cran-all/cranData/whitebox/inst/doc/wbt-method.Rmd
|
---
title: "whitebox Tool Metadata"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{whitebox Tool Metadata}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
fig.width = 6,
fig.height = 6
)
```
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
# R package dataset symbol names
wbttools <- NULL
wbttoolparameters <- NULL
data("wbttools", package = "whitebox")
```
# `whitebox` Tool Metadata
This vignette provides an introduction to the data sets included in the `whitebox` package. These data sets contain names, arguments and other metadata for tools available in WhiteboxTools.
### What version of WhiteboxTools are these data sets generated from?
- Current version: **`r attr(wbttools, "version")`**
Internal data sets and functions defined in the R package correspond to tool names available in the most recent version of WhiteboxTools. Data sets are _not_ dynamically generated from your WhiteboxTools installation. Relatively recent versions of WhiteboxTools should be supported backward-compatibly, though any newer functionality will not be usable.
## WhiteboxTools Tool Names and R Function Names
The first data set describes tool names in WhiteboxTools and the corresponding exported function in the R package, along with the WhiteboxTools Toolbox name and a brief description.
```{r}
data("wbttools", package = "whitebox")
str(wbttools)
```
The `wbttools` data set is a data.frame with `r nrow(wbttools)` tools and 7 variables
- `"tool_name"` - WhiteboxTools tool name
- `"function_name"` - R function tool name
- `"toolbox_name"` - WhiteboxTools toolbox name
- `"label"` - WhiteboxTools tool label
- `"description"` - Brief description
- `"github"` - GitHub link
- `"book"` - Reference manual link
- `"is_extension"` - Tool is part of General Toolset Extension (GTE), as opposed to the "open core"
```{r}
head(wbttools)
```
The R function naming style differs from the tool names in WhiteboxTools, but the core words are the same.
R function names are derived from the WhiteboxTools name as follows:
1. `PascalCase` tool names change to `snake_case`
2. All R function names get the prefix `wbt_`
For example, `StreamSlopeContinuous` in WhiteboxTools becomes `wbt_stream_slope_continuous()` in R.
## WhiteboxTools Tool and Parameter Names
The second data set provides details about the available function arguments by tool name.
```{r}
data("wbttoolparameters", package = "whitebox")
```
The `wbttoolparameters` data set is a _data.frame_ with `r nrow(wbttoolparameters)` parameters and `r ncol(wbttoolparameters)` variables:
- `"tool_name"` - WhiteboxTools tool name
- `"function_name"` - R function name
- `"toolbox_name"` - WhiteboxTools toolbox name
- `"name"` - WhiteboxTools tool parameter name
- `"flags"` - flags used to specify parameter on command line; comma-separated
- `"description"` - parameter description
- `"default_value"` - parameter default value, if any
- `"optional"` - parameter "optional" flag; note that some combination of optional parameters may be required for certain conditions
- `"parameter_class"` - parameter type
- `"parameter_detail"` - parameter details; character: data type followed by colon and more specifics, For OptionList possible values, comma-separated (if defined)
- `"is_input"` - logical. Classification of 'input' parameters
- `"is_output"` - logical. Classification of 'output' parameters
- `"argument_name"` - labels for selected subset of `"flags"` **used as R function argument names** for `wbt_` functions
```{r}
head(wbttoolparameters)
```
Several fields in this table such as `flags` and `parameter_type` are "flattened" relative to the nested `wbt_tool_parameters()` output.
The nested `parameter_type` from the JSON result is replaced with two variables in the data set: `parameter_class` and `parameter_details`
This parameter _data.frame_ is useful to construct your own functions with `wbt_run_tool()` or for inspecting the types of tools that can be run on particular data types.
```{r}
str(wbttoolparameters, max.level = 1)
```
You will find that both `tool_name` and `function_name` are present, so you can look up by whatever is convenient.
The variable `argument_name` is processed to be the subset of `flags` that corresponds to arguments to R functions, which are denoted with `function_name`.
### Example: Finding Tools by Parameter Type
To find the tools that have an "ExistingFile" argument with file type "Raster" we can use `subset()`.
```{r}
head(subset(wbttoolparameters, grepl("ExistingFile", parameter_class) & grepl("Raster", parameter_detail)))
```
## Appendix: Tables of Function Names by Toolbox
The remainder of this vignette is tables of R function names and tool descriptions from `wbttoolparameters`, organized by WhiteboxTools toolbox/extension name.
```{r, echo=FALSE, results='asis'}
# hide this, we add the parentheses for the docs
wbttoolsshow <- wbttools
wbttoolsshow$function_name <- paste0("`", wbttoolsshow$function_name, "()`")
wbttoolssplt <- split(wbttoolsshow[,colnames(wbttoolsshow) %in% c("function_name", "description")],
list(wbttoolsshow$toolbox_name))
if (requireNamespace("knitr")) {
x <- sapply(names(wbttoolssplt), function(nm) {
cat("###", nm, "\n\n")
print(knitr::kable(
wbttoolssplt[[nm]],
caption = paste("Toolbox:", nm),
col.names = c("Function Name", "Description"),
row.names = FALSE
))
})
}
```
|
/scratch/gouwar.j/cran-all/cranData/whitebox/vignettes/datasets.Rmd
|
---
title: "whitebox Demo"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{whitebox Demo}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
eval = whitebox::check_whitebox_binary(),
echo = TRUE,
collapse = TRUE,
comment = "#>",
fig.width = 6,
fig.height = 6
)
```
```{r, include=FALSE, echo=FALSE, eval=TRUE}
# setup so inline stats on version/tools show up
library(whitebox)
data("wbttoolparameters", package="whitebox")
```
```{r setup, include=FALSE}
# # sample code to check and install whitebox to a custom path
# if (!whitebox::check_whitebox_binary()) {
# wd <- tempdir()
# whitebox::install_whitebox(wd)
# whitebox::wbt_init(wd = file.path(wd, "WBT", basename(whitebox::wbt_default_path())))
# }
# system and package dependencies must be met to build the vignette
stopifnot(requireNamespace("terra"))
```
## Introduction
whitebox is an R frontend for the 'WhiteboxTools' library, which is an advanced geospatial data analysis platform developed by Prof. John Lindsay at the University of Guelph's Geomorphometry and Hydrogeomatics Research Group.
'WhiteboxTools' can be used to perform common geographical information systems (GIS) analysis operations, such as cost-distance analysis, distance buffering, and raster reclassification. Remote sensing and image processing tasks include image enhancement (e.g. panchromatic sharpening, contrast adjustments), image mosaicing, numerous filtering operations, simple classification (k-means), and common image transformations. 'WhiteboxTools' also contains advanced tooling for spatial hydrological analysis (e.g. flow-accumulation, watershed delineation, stream network analysis, sink removal), terrain analysis (e.g. common terrain indices such as slope, curvatures, wetness index, hillshading; hypsometric analysis; multi-scale topographic position analysis), and LiDAR data processing.
WhiteboxTools is not a cartographic or spatial data visualization package; instead it is meant to serve as an analytical backend for other data visualization software, mainly GIS.
This vignette shows how to use the `whitebox` R package to run WhiteboxTools.
Suggested citation: Lindsay, J. B. (2016). Whitebox GAT: A case study in geomorphometric analysis. Computers & Geosciences, 95, 75-84. doi: http://dx.doi.org/10.1016/j.cageo.2016.07.003
## Setup
Load the `whitebox` library.
```{r}
library(whitebox)
```
### How `whitebox` works
whitebox generates `system()` calls to a local WhiteboxTools binary: `whitebox_tools` or `whitebox_tools.exe`
You can find the binary path that the package is going to use with `wbt_exe_path()`
```{r}
wbt_exe_path(shell_quote = FALSE)
```
This command always returns a "default" path, whether or not you have WhiteboxTools installed.
### Interfacing with R spatial packages
WhiteboxTools input and output are specified as file paths to rasters in GeoTIFF format, shapefiles, HTML output, LiDAR-related files, and more.
In this vignette we will use the `terra` package for visualization. Just as easily we could have used `raster`, `stars` or other options available in the R ecosystem for handling the GeoTIFF output.
The main way to view your output is to save "output" file paths as a variable so that you can use them after processing to load the result into an R spatial object.
#### Working with Raster Data
A demonstration employing the {terra} package follows:
```{r}
library(terra)
library(whitebox)
# DEMO: calculate slope with WhiteboxTools and raster
# Typically the input/output paths are stored as variables
# sample DEM input GeoTIFF
input <- sample_dem_data()
# output file (to be created)
output <- file.path(tempdir(), "slope.tif")
```
Run a tool such as `wbt_slope()` or `"Slope"`.
WhiteboxTools reads from `input` and writes to `output`.
```{r}
wbt_slope(input, output, units = 'radians')
```
```{r}
if (file.exists(output)) {
# create a SpatRaster from file output path
outputras <- terra::rast(output)
}
```
In this case, we can achieve a similar slope map result using `terra::terrain()`, so we will create and plot a SpatRaster from `output` and compare the two.
```{r}
if (file.exists(input) && file.exists(output) && !is.null(outputras)) {
# par(mfrow = c(2, 1), mar = c(1, 1, 1, 1))
# inspect the output graphically
plot(
outputras,
main = "whitebox::wbt_slope() [radians]",
axes = FALSE
)
# calculate equivalent using raster::terrain() on input
plot(
terra::terrain(terra::rast(input)),
main = "terra::terrain() [radians]",
axes = FALSE
)
}
```
The `SpatRaster`, `RasterLayer` and related classes in the terra and raster packages are perfect for maintaining the linkage between file output and an R object with the data in or out of memory.
Use `terra::sources()` to get the "source" file name(s). If you are using a raster `RasterLayer` objects the equivalent method is `raster::filename()`.
```{r}
# the SpatRaster retains a reference to the input file name
terra::sources(outputras)
```
### WhiteboxTools R setup
### Installing WhiteboxTools
In `whitebox` `wbt_init()` is the standard way to set the "exe_path" for a session.
If you do not have WhiteboxTools installed in the default location, do not have `whitebox_tools` on your PATH, and have not set up your package options, the package will not be able to find your WhiteboxTools installation on load.
Usually you can use `whitebox::install_whitebox()` to download the latest binaries that correspond to the available version of the R package. However, this is not required. You may download/compile WhiteboxTools yourself and install anywhere for use with the `whitebox` R package.
For general information consult the WhiteboxTools User Manual: https://www.whiteboxgeo.com/manual/wbt_book/install.html
For more details on building from source see: https://github.com/jblindsay/whitebox-tools
### Package Settings with `wbt_init()`
`wbt_init()` is used to set and check the path of the binary executable that commands are passed to.
The executable path and other options are stored as package options, and can be overridden by system environment variables. A default value `wbt_exe_path(shell_quote = FALSE)` is passed when the `exe_path` argument is unspecified.
```{r}
# inspect where wbt_init() will be checking
wbt_exe_path(shell_quote = FALSE)
# TRUE when file is found at one of the user specified paths or package default
# FALSE when whitebox_tools does not exist at path
wbt_init()
```
This section will cover optional arguments to `wbt_init()` (`exe_path`, `wd` and `verbose`) and their corresponding options and helper functions.
#### `exe_path` argument
The `exe_path` argument to `wbt_init()` sets the `whitebox.exe_path` package option. `exe_path` is the path to a WhiteboxTools executable file.
The default value is the package installation directory, subdirectory `"WBT"`, followed by `whitebox_tools.exe` or `whitebox_tools` depending on your operating system.
```{r, eval=FALSE}
# set path manually to whitebox_tools executable, for instance:
wbt_init(exe_path = '/home/andrew/workspace/whitebox-tools/target/release/whitebox_tools')
```
The package will automatically find an existing installation when `whitebox_tools` is in a directory on your PATH.
Package options other than `exe_path` (as detailed in `?whitebox::whitebox` and `?wbt_init`) can be set with `wbt_init(exe_path, ...)`, where `...` is additional named arguments corresponding to the `*` suffix in `whitebox.*` package options names. Use `wbt_options()` or specific methods like `wbt_verbose()`, `wbt_wd()` to get all values or set specific values.
#### `wd` argument
The `wd` argument can be used to set the WhiteboxTools working directory.
A working directory specifies a base folder path where WhiteboxTools can find inputs and create outputs. Setting the `whitebox.wd` package option (via the `wd` argument to `wbt_init()` or `wbt_wd()`) aids the process of setting file paths.
If a value is set for the option the `--wd` directory flag is added for tools that support it.
Before you set the working directory in a session the default output will be in your current R working directory unless directory is specified in your input/output arguments. You can change working directory at any time by setting the `wd` argument to `wbt_wd()` and running a tool.
NOTE: once you have set a working directory in a session, the directory needs to be set somewhere new to "replace" the old value; just dropping the flag will **not** automatically change the working directory *back to your R working directory*\* and your output will show up in whatever folder you set initially.
A helper method for setting the `whitebox.wd` option is `wbt_wd()`.
To "unset" the option in the R package you can use `wbt_wd("")` which is equivalent to `wbt_wd(getwd())`. The next tool call will change the WhiteboxTools working directory setting to the new path. After this point the flag need not be specified [until you wish to change again].
```r
wbt_wd("") # "" equivalent to getwd()
```
#### `verbose` argument
The `verbose` argument is used to set the package option related to tool "verbosity": `whitebox.verbose`. When `whitebox.verbose` is `FALSE` no output will be `cat()` to the console by running tools.
A helper method for getting and setting the `whitebox.verbose` option is `wbt_verbose()`. `wbt_verbose()` is used throughout the package to check what level of verbosity should be used.
By default, the result of `wbt_verbose()` is the result of `interactive()` so tools will print extra console output when you are there to see it. This is used in a variety of `wbt_*` methods to allow the package option to control output for many functions in a consistent manner, hide output in your automated tests, markdown documents, vignettes etc.
In this vignette we use `wbt_verbose(TRUE)` so the package option `whitebox.verbose` is set to `TRUE`
```{r}
# force output when run non-interactively (knitr)
wbt_verbose(TRUE)
```
This is mainly to print out the tool name and elapsed time whenever we run a tool:
```
#> wbt_breach_depressions - Elapsed Time (excluding I/O): 0.12s
```
This package-level verbose option can also control the `verbose_mode` values passed to `wbt_*` tool functions. Turning on "full" output requires a third option to be set for this argument: `"all"`. Use `wbt_verbose("all")`. `wbt_verbose()` will still return `TRUE` when the `whitebox.verbose` option is `"all"`.
### Long-term Package Option Settings
The package will detect when you have added the WhiteboxTools directory to your `PATH` environment variable. For long-term package option settings you can put `whitebox_tools` on `$PATH` or set `R_WHITEBOX_EXE_PATH` in your user `.Rprofile` or `.Renviron`.
On Windows you can add the path to `whitebox_tools.exe` as a new entry `R_WHITEBOX_EXE_PATH` in User or System Environment variable.
On Linux/Mac you can set `R_WHITEBOX_EXE_PATH` directly with `export R_WHITEBOX_EXE_PATH="/path/to/whitebox_tools"`.
- Note that if you set your `$PATH` in you regular shell profile (`.profile`/`.bashrc`/`.zshrc`) then it will _not_ be sourced by _RStudio_ for your R session by default.
This requires that you have the Unix tool `which` or one of its analogues.
You can also set `R_WHITEBOX_EXE_PATH` manually in R:
```r
Sys.setenv(R_WHITEBOX_EXE_PATH = Sys.which("whitebox_tools"))
```
- Replace the `Sys.which()` call with a custom path string as needed such as `"C:/path/to/whitebox_tools.exe"`.
All of the other package options can similarly be set as environment variables. They are prefixed with `R_WHITEBOX_*`. See `?whitebox` for details.
## Running tools
Specify input and output paths, and any other options, as specified in package reference:
- https://whiteboxR.gishub.org/reference/index.html
For instance, "BreachDepressions" is used below to process a Digital Elevation Model (DEM) before we identify flow pathways. This tool uses uses Lindsay's (2016) algorithm, which is preferred over depression filling in most cases.
```{r}
# sample DEM file path in package extdata folder
input <- sample_dem_data()
# output file name
output <- file.path(tempdir(), "output.tif")
# run breach_depressions tool
wbt_breach_depressions(dem = input, output = output)
```
For more info see: `?wbt_breach_depressions`
These `wbt_*_tool_name_*()` functions are wrappers around the `wbt_run_tool()` function that does the `system()` call given a function-specific argument string.
```{r}
# sample DEM file path in package extdata folder
input <- sample_dem_data()
# output file name
output <- file.path(tempdir(), "output.tif")
# run breach_depressions tool
wbt_run_tool(tool_name = "BreachDepressions", args = paste0("--dem=", input, " --output=", output))
```
The above method of creating `wbt_breach_depressions(dem = ..., output = ...)` to handle `wbt_run_tool("BreachDepressions", args = ...)` makes it easy to generate static methods that have parity with the latest WhiteboxTools interface.
### Example: Compare input v.s. output with `terra`
We use the {terra} package to read the GeoTIFF file output by WhiteboxTools.
#### Setup
```{r}
library(terra)
# sample DEM file path in package extdata folder
input <- sample_dem_data()
# output file name
output <- file.path(tempdir(), "output.tif")
```
#### Run `wbt_breach_depressions()` (BreachDepressions tool)
```{r}
# run breach_depressions tool
wbt_breach_depressions(dem = input, output = output)
```
#### Visualize results with `terra`
```{r}
# create raster object from input file
input <- rast(input)
if (file.exists(output)) {
# create raster object from output file
output <- rast(output)
# par(mar = c(2, 1, 2, 1))
# inspect input v.s. output
plot(input, axes = FALSE, main = "DEM")
plot(output, axes = FALSE, main = "DEM (Breached Depressions)")
# inspect numeric difference (output - input)
plot(output - input, axes = FALSE, main = "Difference ([Breached Depressions] - [DEM])")
}
```
### Example: Identifying Tributaries
Here we will take our processing of DEMs a bit further by performing several WhiteboxTools operations in sequence.
We are interested in identifying and ranking tributaries of watercourses (streams and rivers).
An R package that makes use of the `whitebox` R package is [hydroweight](https://github.com/bkielstr/hydroweight). Here is a brief example on the beginning of the `hydroweight` README showing how the breached DEM above can be used in a spatial analysis of stream networks.
#### Setup
```{r}
library(whitebox)
library(terra)
## Sample DEM from whitebox package
toy_file <- sample_dem_data()
toy_dem <- rast(x = toy_file)
## Generate wd as a temporary directory.
## Replace with your own path, or "." for current directory
wd <- tempdir()
## Write toy_dem to working directory
writeRaster(
x = toy_dem, filename = file.path(wd, "toy_dem.tif"),
overwrite = TRUE
)
```
#### `wbt_breach_depressions()` -- Breach DEM Depressions
First we pre-process by breaching depressions in the DEM
```{r}
## Breach depressions to ensure continuous flow
wbt_breach_depressions(
dem = file.path(wd, "toy_dem.tif"),
output = file.path(wd, "toy_dem_breached.tif")
)
```
#### `wbt_d8_pointer()` -- Calculate Flow Direction
Then we generate the direction of flow on the DEM surface using the "D8" flow pointer method
```{r}
## Generate d8 flow pointer (note: other flow directions are available)
wbt_d8_pointer(
dem = file.path(wd, "toy_dem_breached.tif"),
output = file.path(wd, "toy_dem_breached_d8.tif")
)
```
#### `wbt_d8_flow_accumulation()` -- Flow Accumulation
Once we calculate the direction of flow by some method, we calculate cumulative flow
For example with `wbt_d8_flow_accumulation()`:
```{r}
## Generate d8 flow accumulation in units of cells (note: other flow directions are available)
wbt_d8_flow_accumulation(
input = file.path(wd, "toy_dem_breached.tif"),
output = file.path(wd, "toy_dem_breached_accum.tif"),
out_type = "cells"
)
```
##### Additional Flow Direction and Accumulation Tools
In addition to D8 flow pointers (flow direction), there are several other options for both direction and accumulation such as FD8, D-infinity, and D-infinity.
- Keyword "Pointer" tools: `"D8Pointer"`, `"DInfPointer"`, `"FD8Pointer"`, `"Rho8Pointer"`
- Keyword "FlowAccumulation" tools: `"D8FlowAccumulation"`, `"DInfFlowAccumulation"`, `"FD8FlowAccumulation"`, `"Rho8FlowAccumulation"`, `"MDInfFlowAccumulation"`
Search for more tools involving `"flow pointer"` by key word: `wbt_list_tools(keyword = "flow pointer")`
```{r, echo = FALSE}
wbt_list_tools(keyword = "flow pointer")
```
This is just an example of the wealth of tool options made available by the WhiteboxTools platform.
#### `wbt_extract_streams()` -- Extract Stream Network
With our flow accumulation raster in hand, we can extract a stream network with `wbt_extract_streams()` based on a threshold (e.g. `100`) of accumulated flow. This threshold value you choose will depend on analysis goals, the choice of flow accumulation algorithm used, local topography, as well as resolution and extent of DEM.
```{r}
## Generate streams with a stream initiation threshold of 100 cells
wbt_extract_streams(
flow_accum = file.path(wd, "toy_dem_breached_accum.tif"),
output = file.path(wd, "toy_dem_streams.tif"),
threshold = 100
)
```
#### `wbt_tributary_identifier()` -- Identify Tributaries
Next, let's identify tributaries. This function `wbt_tributary_identifier()` is a little more complicated because it takes takes two inputs:
- Our raster D8 pointer file.
- And our raster streams file.
```{r}
wbt_tributary_identifier(
d8_pntr = file.path(wd, "toy_dem_breached_d8.tif"),
streams = file.path(wd, "toy_dem_streams.tif"),
output = file.path(wd, "toy_dem_tributaries.tif")
)
```
#### Compare results
Finally, we compare results of `wbt_extract_streams()` with `wbt_tributary_identifier()`
```{r}
if (file.exists(file.path(wd, "toy_dem_streams.tif"))) {
par(mfrow = c(2, 1), mar = c(3, 1, 2, 1))
plot(
rast(file.path(wd, "toy_dem_streams.tif")),
main = "Streams",
col = "black"
)
plot(
rast(file.path(wd, "toy_dem_tributaries.tif")),
main = "TributaryIdentifier"
)
}
```
## Appendix: `wbt_*` utility functions
These methods provide access to WhiteboxTools executable parameters and metadata.
### `wbt_help()`
`wbt_help()` prints the WhiteboxTools help: a listing of available commands for executable
```{r}
wbt_help()
```
### `wbt_license()`
`wbt_license()` prints the WhiteboxTools license
```{r}
wbt_license()
```
### `wbt_version()`
Prints the WhiteboxTools version
```{r}
wbt_version()
```
### `wbt_list_tools()`
Use `wbt_list_tools()` to list all available tools in WhiteboxTools. In version `r attr(wbttoolparameters, 'version')` there are over `r (length(whitebox::wbt_list_tools()) - 1)` tools! See all the available [toolboxes](https://www.whiteboxgeo.com/manual/wbt_book/available_tools/index.html) and [extensions](https://www.whiteboxgeo.com/whitebox-geospatial-extensions/).
```{r, eval=FALSE}
wbt_list_tools()
```
The full list can be an overwhelming amount of output, so you pass the `keywords` argument to search and filter.
For example we list tools with keyword 'flowaccumulation' in tool name or description.
```{r}
wbt_list_tools(keywords = "flowaccumulation")
```
### `wbt_tool_help()`
Once we find a tool that we are interested in using, we can investigate what sort of parameters it takes. The R methods generally take the same named parameters.
R functions have the naming scheme `wbt_tool_name` where `_` is used for spaces, whereas the tools themselves have no spaces.
`wbt_tool_help("tributaryidentifier")` shows the command line help for a tool by name.
```{r}
wbt_tool_help("tributaryidentifier")
```
`?wbt_tributary_identifier` shows the corresponding R function help, which is derived from the command line help page and other metadata.
### `wbt_toolbox()`
Another way that tools are organized in WhiteboxTools is by "toolbox."
`wbt_toolbox()` prints the toolbox for a specific tool (or all tools if none specified)
```{r}
wbt_toolbox(tool_name = "aspect")
```
Print the full list by not specifying `tool_name`
```{r}
wbt_toolbox()
```
### `wbt_tool_parameters()`
`wbt_tool_parameters()` retrieves the tool parameter descriptions for a specific tool as JSON formatted string.
```{r}
wbt_tool_parameters("slope")
```
### `wbt_view_code()`
WhiteboxTools is written in Rust and is open source. You can view the source code for a specific tool on the source code repository.
```{r}
wbt_view_code("breach_depressions")
```
Use the argument `viewer=TRUE` to use `browseURL()` to open a browser window to the corresponding GitHub page.
```{r, echo=FALSE}
# cleanup temp files
wd <- tempdir()
unlink(file.path(wd, "slope.tif"))
unlink(file.path(wd, "output.tif"))
unlink(list.files(wd, "^toy_dem.*tif*$", full.names = TRUE))
```
|
/scratch/gouwar.j/cran-all/cranData/whitebox/vignettes/demo.Rmd
|
---
title: "`wbt()` method: call 'Whitebox' tools by name"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{`wbt()` and `wbt_result`}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
eval = whitebox::check_whitebox_binary() &
requireNamespace("terra", quietly = TRUE)
)
```
# `wbt()`
The `wbt()` method is a high-level wrapper function to manage flow of
information between R and WhiteboxTools. With `wbt()` one can run sequential
analyses in Whitebox while having R prepare inputs, generate commands, and
visualize results.
```{r}
library(whitebox)
```
## Getting Started
Know what tool you want to run but _can't remember the required parameters_?
Just type `wbt("toolname")`
```{r}
wbt("slope")
```
Output produced on error and with invalid arguments helps guide use
interactively by prompting with required and optional arguments as a checklist.
## Result Objects
All calls to `wbt()` return an S3 object with class `wbt_result`.
```{r}
# get file path of sample DEM
dem <- sample_dem_data()
wbt("slope", dem = dem, output = file.path(tempdir(), "slope.tif"))
```
Whether a system call succeeds or fails the parameters that were passed to the WhiteboxTools
executable and references to any output file paths that were specified are
returned. If output files reference spatial data (e.g. a GeoTIFF file) they may
be converted to a file-based R object providing information about the result.
```{r}
wbt("slope", goof = dem, output = file.path(tempdir(), "slope.tif"))
```
When a call fails an informative error message issued, and the error will be cached
inside the result. Prior runs references are stored as well for sequential tool runs; more on that below.
### `wbt_result` class
A `wbt_result` class object is a base R `list()` with standard element
names (`"tool"`, `"args"`, `"stdout"`, `"crs"`, `"result"`, `"history"`) and
the `"class"` attribute `"wbt_result"`.
```{r}
str(wbt("slope", dem = dem, output = file.path(tempdir(), "slope.tif")), max.level = 1)
```
Any `output` produced by the tool (usually file paths set by the user) will be
included in the `wbt_result$result` list.
### `wbt_result` on error
If there is an error a `try-error` class object with an error message is
returned in lieu of a list in `$result`
```{r}
# on error there is a try-error object in $result
x <- wbt("slope")
inherits(x$result, 'try-error')
message(x$result[1])
```
## Vignette Topics
We now will cover how the `wbt()` method and `wbt_result` class can be used for
the following:
- Input and Output with R spatial objects
- Running Sequences of Tools (optionally: with pipe `|>` or `%>%`)
- Handling Coordinate Reference Systems
# Input and Output with R spatial objects
A feature of `wbt()` is that it handles input/output and file name management
if you are using R objects as input. It can be an onerous task to manage files
for workflows involving many tool runs.
If you use a `terra` object as input, you will get a `SpatRaster`. If you use
a `raster` object as your input object frontend, you will get a `RasterLayer`
object as output for tools that produce a raster. There will be file paths
associated with that R object.
### Compare `raster` and `terra` as R raster object frontends
```{r}
if (requireNamespace("raster")) {
rdem <- raster::raster(dem)
# raster input; raster output
r1 <- wbt("slope", dem = rdem, output = file.path(tempdir(), "slope.tif"))
r1
class(r1$result$output)
}
```
```{r}
tdem <- terra::rast(dem)
## terra input; terra output
t1 <- wbt("slope", dem = tdem, output = file.path(tempdir(), "slope.tif"))
t1
class(t1$result$output)
```
The user still needs to specify paths but `wbt()` eases the process
of converting input objects to paths and reading output paths to R objects
after the tool has run. In principle any R object that references a file with
type that Whitebox supports can be handled under the current (simple; proof of
concept) system. Using file-based representations may not be the most
efficient, but allows for a tangible trail of the steps in a workflow to be
followed that otherwise might be hard to track.
# `wbt_source()`: rasters in memory, and vector data
The terra and raster packages use pointers to a file/raster connection except
when a grid is entirely in memory. Processing these types of rasters with
whitebox requires writing out as a temporary GeoTIFF file for tool input. In general
`wbt()` can handle this for you.
Vector data (point, line and polygon geometries) are commonly stored stored in
sf data.frames, sp objects, or terra SpatVector objects. These types are
read into memory on creation.
Reading vector data into R memory is
not needed to run Whitebox tools, so `wbt_source()` provides a means to annotate objects
with information about source file path (similar to how terra/raster handle raster sources)
such that they can be processed further by `wbt()` with minimal overhead.
Objects like the terra SpatVectorProxy use delayed read by default. Passing a file path
to `wbt_source()` will create a SpatVectorProxy with necessary information for use with `wbt()`.
For instance, we can create a reference for a sample ESRI Shapefile via `wbt_source()`. The result is a SpatVectorProxy.
```{r}
library(terra)
shp <- system.file("ex/lux.shp", package = "terra")
x <- wbt_source(shp)
x
```
The SpatVectorProxy provides a light-weight means to create an R object reference to a large file; allowing the "heavy" lifting for that file to be done primarily by WhiteboxTools (or GDAL via {terra}).
At time of writing this document, WhiteboxTools does not support vector data inputs other than Shapefile. If we have, for example, a GeoPackage, `wbt_source()` will convert the input to a temporary shapefile and return a SpatVectorProxy that references that file. This object can then be used as input to `wbt()`.
```{r}
# load the data
x2 <- query(x)
# remove area column
x2$AREA <- NULL
# create a GeoPackage
terra::writeVector(x2, filename = file.path(tempdir(), "lux.gpkg"), overwrite = TRUE)
# now the source is a temporary .shp
x3 <- wbt_source(file.path(tempdir(), "lux.gpkg"))
wbt("polygon_area", input = x3)
```
# Running Sequences of Tools
When you call `wbt()` and the first argument is a `wbt_result` the `output`
from the input `wbt_result` is passed as the first `input` to the new tool run.
This general "pass the output as the first input" works even if the first
`input` parameter (`"-i"` flag) is something different such as `dem` or
`input1`.
This makes it possible to chain different operations together in a sequence.
If all of the required parameters are specified the tool will be run.
Here we run "Slope" on a DEM, then run "Slope" on it again to get a second
derivative "curvature".
```{r}
x <- wbt("slope", dem = dem, output = file.path(tempdir(), "slope.tif"))
x2 <- wbt(x, tool_name = "slope", output = file.path(tempdir(), "curvature.tif"))
```
## Using pipes
Nested chained operation syntax can be transformed to use pipe operators ({base} R 4.1+ `|>` or {magrittr} `%>%`). This can improve the readability of the code (fewer nested parentheses) and the first argument transfer behavior allows results from each step to be transferred to the input of the next.
```{r, eval = FALSE, purl = FALSE}
wbt("slope", dem = dem, output = file.path(tempdir(), "slope.tif")) |>
wbt("slope", output = file.path(tempdir(), "curvature.tif"))
```
The `wbt_result` output that prints to the console will reflect the
input/output parameters of the most recent tool run in a tool chain.
```{r}
x2
```
`wbt_result()` is the method to get `$result` for single runs or all `$result`
in `$history` for chained runs from a `wbt_result` object.
```{r}
str(wbt_result(x2), max.level = 1)
```
The `$history` element is a list of the `wbt_result` from individual runs.
```{r}
str(x2$history, max.level = 1)
```
If you pass invalid results from one step to the next, you get an informative
error message.
```{r}
x <- wbt("slope")
wbt(x, "slope", output = file.path(tempdir(), "foo.tif"))
```
# Coordinate Reference Systems (CRS)
On top of handling file paths it is necessary for Geographic Information
Systems to handle Coordinate Reference System (CRS) information. Many R tools
in the GDAL/PROJ sphere require valid CRS to operate.
WhiteboxTools will read the GeoKey information from your _GeoTIFF_ files
specified by path and propagate that to the output file result. When you read
those files with R, you should find that the original file's CRS has been
transferred.
`wbt()` and `wbt_result` help ensure consistent file and CRS information across
sequences of operations and within calls--especially those _involving R spatial
objects_.
If you specified the CRS in R, or made the raster entirely in R, you might need
a hand setting up the file-based representation that WhiteboxTools will use.
This is easy enough to do with `crs()`, `writeRaster()` and the equivalent but
often requires more boilerplate code than just specifying the argument, or
having CRS propagate from input.
For inputs that have a file-based representation (e.g. `RasterLayer` and
`SpatRaster` objects) `wbt()` provides an interface where R objects can be
substituted for file names and vice versa. User and workflow level attributes
like CRS and working directory be handled at the same time.
```{r}
dem <- sample_dem_data()
## equivalent to:
# dem <- system.file("extdata/DEM.tif", package = "whitebox")
```
In the process of reading/writing files that may contain CRS information, such
as this sample DEM, the CRS can be inspected, modified and propagated to file
or R objects.
## Setting the CRS
If the CRS is specified in the input `SpatRaster` object, `wbt()` makes sure it is
propagated to the R object result. `wbt()` does not alter or copy the source or
output files which may or may not have CRS information.
```{r}
araster <- terra::rast(dem)
wbt("slope", dem = araster, output = file.path(tempdir(), "foo.tif"))
```
Alternately you can specify the `crs` argument to `wbt()` instead of `rast()`. This will directly set the `crs` element of the `wbt_result` of your output.
```{r}
wbt("slope", dem = terra::rast(dem), crs = "EPSG:26918", output = file.path(tempdir(), "foo.tif"))
```
In either case wherever you specify the `crs` argument the `crs` is
stored in the `wbt_result` and propagated to the relevant output. Again, the
source files are unchanged if they had no CRS or invalid CRS (until you write that updated CRS to file).
If two input R objects have different (or no) CRS then the `wbt()` method will
provide a message to the user:
```{r}
r1 <- terra::rast(dem) # default: EPSG:26918
r2 <- terra::deepcopy(r1)
crs(r2) <- "EPSG:26917" # something else/wrong
wbt("add",
input1 = r1,
input2 = r2,
output = file.path(tempdir(), "foo.tif")
)
```
This message is suppressed and output CRS set accordingly if the `crs` argument is specified. This user set CRS is only in the SpatRaster object, and does not necessarily match that of the file used as input or returned as output.
```{r}
wbt("add",
input1 = r1,
input2 = r2,
crs = "EPSG:26918",
output = file.path(tempdir(), "foo.tif")
)
```
<!--
# Future Plans
Future additions to this vignette may include:
- Managing WhiteboxTools working directories
- Managing WhiteboxTools file types
In the future users will be able to:
- Set a temporary or persistent working
directory and have output file paths/names auto-generated, allowing them to
work entirely with R objects and `wbt_result` while making an intermediate file
record in the background.
- Use a wrapper class for generic
groups of Whitebox file types; allowing file name references for any R object
or output file type to be stored: optimized/customizable read/write methods used for
specific file types and generic .rda files with metadata for others.
- Batch of tool runs on e.g. watershed extents -->
```{r, echo=FALSE}
# cleanup temp files
unlink(list.files(".", pattern = "file.*tif$", full.names = TRUE))
unlink(list.files(tempdir(), pattern = "file.*tif$", full.names = TRUE))
```
|
/scratch/gouwar.j/cran-all/cranData/whitebox/vignettes/wbt-method.Rmd
|
#' @title Undirected edge pairing of roads connecting nodes
#' @description Data used to establish possible connections used by Jack between nodes
#' @format A data frame with 767 rows and 2 variables
#' \describe{
#' \item{x}{The smaller integer of the pair of vertices}
#' \item{y}{The larger integer of the pair of vertices}
#' }
"roads"
#' @title Undirected edge pairing of alley connecting nodes
#' @description Data used to establish possible connections used by Jack between nodes via alleyways
#' @format A data frame with 452 rows and 2 variables
#' \describe{
#' \item{x}{The smaller integer of the pair of vertices}
#' \item{y}{The larger integer of the pair of vertices}
#' }
"alley"
#' @title x,y coordinates of node points from the game board
#' @description Data used to place nodes in graphical output according to their relative positions on the game board
#' @format A data frame with 195 rows and 4 variables
#' \describe{
#' \item{id}{An artifact of the computer vision process used to obtain coordinates}
#' \item{x}{The number of pixels from the left edge of the board to the center of the node}
#' \item{y}{The number of pixels from the top edge of the board to the center of the node}
#' \item{name}{The integer assigned to the node on the game board}
#' }
"node_locations"
|
/scratch/gouwar.j/cran-all/cranData/whitechapelR/R/data.R
|
#' @export
end_round = function(paths,hideouts=NULL){
#' @title Manage list of possible hideouts
#'
#' @description Create or update a list of possible hideouts based on final positions from the list of possible paths traveled.
#'
#' @param paths list of all possible paths already traveled
#' @param hideouts optional vector of possible hideouts from previous rounds. Not used in round 1, only rounds 2 and 3
#'
#' @return list of all possible hideouts
#' @examples
#' possibilities = start_round(64)
#' possibilities = take_a_step(possibilities,roads)
#' possibilities = take_a_step(possibilities,roads,blocked=list(c(63,82),c(63,65)))
#' possibilities = inspect_space(possibilities,space = c(29,30), clue = FALSE)
#' possibilities = inspect_space(possibilities,space = 49, clue = TRUE)
#' hideouts = end_round(possibilities,hideouts=NULL)
#' possibilities = start_round(67)
#' possibilities = take_a_step(possibilities,roads)
#' hideouts = end_round(possibilities,hideouts=hideouts)
possible_hideouts = lapply(paths,function(x){
rev(x)[1]
})
possible_hideouts = unique(unlist(possible_hideouts))
if(is.null(hideouts)) return(sort(possible_hideouts))
hideouts = intersect(hideouts,possible_hideouts)
return(sort(hideouts))
}
|
/scratch/gouwar.j/cran-all/cranData/whitechapelR/R/end_round.R
|
#' @export
inspect_space = function(paths,space,clue){
#' @title Update paths based on inspections
#'
#' @description Updated the list of possible paths based on the results of police investigation
#'
#' @param paths list of all possible paths already traveled
#' @param space vector of integers of the spaces inspected
#' @param clue single logical value indicating if evidence of Jack was found
#'
#' @return list of all possible paths traveled by Jack
#' @examples
#' possibilities = start_round(64)
#' possibilities = take_a_step(possibilities,roads)
#' possibilities = take_a_step(possibilities,roads,blocked=list(c(63,82),c(63,65)))
#' possibilities = inspect_space(possibilities,space = c(29,30), clue = FALSE)
#' possibilities = inspect_space(possibilities,space = 49, clue = TRUE)
if(clue){
paths = lapply(paths,found_clue,space=space)
} else {
paths = lapply(paths,found_nothing,space=space)
}
return(plyr::compact(paths))
}
found_clue = function(path,space){
if(!any(path %in% space)) return(NULL)
return(path)
}
found_nothing = function(path,space){
if(any(path %in% space)) return(NULL)
return(path)
}
|
/scratch/gouwar.j/cran-all/cranData/whitechapelR/R/inspect_space.R
|
#' @export
show_board = function(paths=NULL,hideouts=NULL,roads,alley,node_locations){
#' @title Display game board representation
#'
#' @description Show a graph representation of the game board with nodes placed in the appropriate relative spot, colored by the number of paths which include a particular node. Possible hideouts are marked with blue squares.
#'
#' @param paths optional list of all possible paths already traveled
#' @param hideouts optional vector of possible hideouts from previous rounds.
#' @param roads data.frame of non-directional edge pairs for the road graph
#' @param alley data.frame of non-directional edge pairs for the alley graph
#' @param node_locations data.frame of where nodes should be placed in the graph
#'
#' @return plotted igraph object
#'
#' @details
#' roads, alley and node_locations are all bundled with the package (e.g. \code{data(roads)}).
#' Solid lines in the graph represent road connections between nodes. Dashed lines represent alley way connections.
#'
#' @examples
#' possibilities = start_round(64)
#' possibilities = take_a_step(possibilities,roads)
#' possibilities = take_a_step(possibilities,roads,blocked=list(c(63,82),c(63,65)))
#' possibilities = take_a_step(possibilities,alley)
#' show_board(paths=possibilities,hideouts=NULL,roads,alley,node_locations)
r = roads
a = alley
r$lty = 1
a$lty = 3
r$weight = 1
a$weight = 1
l = as.matrix(node_locations[order(node_locations$name),c("x","y")])
l[,2] = l[,2]*-1
v = data.frame(name = 1:195
,cex=0.7
,color="white"
,shape="circle"
,stringsAsFactors = FALSE)
if(!is.null(paths)){
colors = c("#FFD9D9","#F5C5C5","#ECB1B1","#E39D9D","#D98A8A","#D07676","#C76262","#BE4E4E","#B43B3B","#AB2727","#A21313","#990000")
tbl = table(unlist(paths))
to_replace = colors[round(tbl/max(tbl)*10,0)]
v$color[as.numeric(names(tbl))] = to_replace
}
if(!is.null(hideouts)){
v$shape[hideouts] = "square"
v$color[hideouts] = "sky blue"
}
g = igraph::graph_from_data_frame(rbind(r,a),directed = FALSE,vertices = v)
par(mai=c(0,0,0,0))
plot(g,layout=l,vertex.size = 5)
}
|
/scratch/gouwar.j/cran-all/cranData/whitechapelR/R/show_board.R
|
#' @export
start_round = function(initial_murder){
#' @title Start a new round
#'
#' @description Generate the initial list for a new round
#'
#' @param initial_murder integer Space of the initial murder(s)
#'
#' @return list with the initial murder location(s) as the starting point(s)
#' @examples
#' possibilities = start_round(64)
#' possibilities = start_round(128)
l = list()
l[[1]] = initial_murder[1]
if(length(initial_murder) == 2) l[[2]] = initial_murder[2]
return(l)
}
|
/scratch/gouwar.j/cran-all/cranData/whitechapelR/R/start_round.R
|
globalVariables(c("roads"))
take_a_step = function(paths,roads,blocked = NULL){
#' @title Track one movement
#'
#' @description Track one step of unknown movement by Jack, either on roads or through alleyways
#'
#' @param paths list of all possible paths already traveled
#' @param roads data.frame of non-directional edge pairs for either the road graph or the alley graph
#' @param blocked list of node pairs which cannot be traversed because a police officer blocks it (should not be used for special movement)
#'
#' @return list of all possible paths traveled by Jack
#'
#' @details
#' The non-directional edge pairs are available via \code{data(roads)} or \code{data(alley)}
#' This function does not account for the rule that Jack cannot travel through a road occupied by a police officer.
#'
#' @examples
#' possibilities = start_round(64)
#' possibilities = take_a_step(possibilities,roads)
#' possibilities = take_a_step(possibilities,roads,blocked=list(c(63,82),c(63,65)))
#' possibilities = take_a_step(possibilities,alley)
paths = lapply(paths,gen_possibilities,roads=roads,blocked=blocked)
paths = unlist(paths,recursive = FALSE)
return(paths)
}
take_a_carriage = function(paths){
#' @title Track carriage movement
#'
#' @description Track two steps of unknown movement by Jack, on roads
#'
#' @param paths list of all possible paths already traveled
#'
#' @return list of all possible paths traveled by Jack
#' @examples
#' possibilities = start_round(64)
#' possibilities = take_a_carriage(possibilities)
data(roads,envir = environment())
paths = take_a_step(paths,roads)
paths = take_a_step(paths,roads)
paths = Filter(function(x){rx = rev(x); rx[1] != rx[3]}, paths)
return(paths)
}
trim_possibilities = function(paths,node){
#' @title Trim possible paths
#'
#' @description Remove known impossible end points for Jack, typically as a result of having found, but not arrested Jack.
#'
#' @param paths list of all possible paths already traveled
#' @param node vector of length 1 or 2 which specifies blocked nodes due to the presence of a policeman
#'
#' @return list of trimmed possible paths traveled by Jack
#' @examples
#' possibilities = start_round(64)
#' possibilities = take_a_carriage(possibilities)
#' possibilities = trim_possibilities(possibilities,82)
#' possibilities = trim_possibilities(possibilities,c(66,67))
keep = unlist(lapply(paths,function(x){!identical(sort(rev(x)[seq_along(node)]),sort(node))}))
return(paths[keep])
}
gen_possibilities = function(path,roads,blocked = NULL){
start = rev(path)[1]
p = unique(unlist(roads[roads$x == start | roads$y == start,]))
p = p[p != start]
full_paths = lapply(p,add_possibilities,path=path)
if(!is.null(blocked)){
r = lapply(blocked,trim_possibilities,paths=full_paths)
full_paths = Reduce(intersect,r,init=r[[1]])
}
return(full_paths)
}
add_possibilities = function(p,path){
return(c(path,p))
}
|
/scratch/gouwar.j/cran-all/cranData/whitechapelR/R/take_a_step.R
|
### corplot.R (2018-07-03)
###
### Plot correlations and loadings
###
### Copyright 2018 Korbinian Strimmer
###
###
### This file is part of the `whitening' library for R and related languages.
### It is made available under the terms of the GNU General Public
### License, version 3, or at your option, any later version,
### incorporated herein by reference.
###
### 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, write to the Free
### Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
### MA 02111-1307, USA
# helper function for plotting correlations
# adapted from img.matcor() in CCA
corplot = function(cca.out, X, Y)
{
p = dim(X)[2]
q = dim(Y)[2]
lambda.cor = cca.out$lambda.cor
RXY = (1-lambda.cor)*cor(X, Y)
Xcor = (1-lambda.cor)*cor(X)+lambda.cor*diag(p)
Ycor = (1-lambda.cor)*cor(Y)+lambda.cor*diag(q)
lX = ncol(Xcor)
lY = ncol(Ycor)
def.par = par(no.readonly = TRUE)
layout(matrix(c(1, 2, 3, 3, 0, 0), ncol = 2, nrow = 3,
byrow = TRUE), widths = 1, heights = c(0.8, 1, 0.06))
par(pty = "s", mar = c(2, 2, 2, 1))
image(1:lX, 1:lX, t(Xcor[lX:1, ]), zlim = c(-1, 1),
main = "X correlation", axes = FALSE, xlab = "",
ylab = "", col = tim.colors(64))
box()
image(1:lY, 1:lY, t(Ycor[lY:1, ]), zlim = c(-1, 1),
main = "Y correlation", col = tim.colors(64), axes = FALSE,
xlab = "", ylab = "")
box()
partXY = RXY
if (lX > lY)
{
partXY = t(RXY)
lX = ncol(Ycor)
lY = ncol(Xcor)
}
par(pty = "m", mar = c(5, 4, 2, 3), mai = c(0.8, 0.5, 0.3, 0.4))
image(1:lY, 1:lX, t(partXY), zlim = c(-1, 1), main = "Cross-correlation",
axes = FALSE, xlab = "", ylab = "", col = tim.colors(64))
box()
image.plot(legend.only = TRUE, zlim = c(-1, 1), horizontal = TRUE, legend.width = 2.5)
par(def.par)
}
loadplot = function(cca.out, numScores)
{
if (cca.out$scale ==TRUE) c = "Correlation" else c=""
maxcor=max(max(cca.out$PhiX^2), max(cca.out$PhiY^2))
def.par = par(no.readonly = TRUE)
par(mfrow=c(1,2))
par(mar=c(5.1, 4.5 ,4.1, 2.1))
image( (t(cca.out$PhiX^2)[,numScores:1]), axes=FALSE, col=tim.colors(64), zlim=c(0,maxcor),
main=paste("Squared", c, "Loadings X"),
xlab=expression(paste(X[i])), ylab=expression(paste(tilde(X[i]))))
par(mar=c(5.1, 4.5 ,4.1, 10))
image.plot((t(cca.out$PhiY^2)[,numScores:1]), axes=FALSE, col=tim.colors(64), zlim=c(0,maxcor),
main=paste("Squared", c, "Loadings Y"),
xlab=expression(paste(Y[i])), ylab=expression(paste(tilde(Y)[i])))
par(def.par)
}
|
/scratch/gouwar.j/cran-all/cranData/whitening/R/corplot.R
|
### explainedVariation.R (2022-06-01)
###
### Compute explained variation from loadings
###
### Copyright 2022 Korbinian Strimmer
###
###
### This file is part of the `whitening' library for R and related languages.
### It is made available under the terms of the GNU General Public
### License, version 3, or at your option, any later version,
### incorporated herein by reference.
###
### 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, write to the Free
### Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
### MA 02111-1307, USA
# explained variation
# = column sum of squares of the loadings
explainedVariation = function(Phi) colSums(Phi^2)
|
/scratch/gouwar.j/cran-all/cranData/whitening/R/explainedVariation.R
|
### getPhiPsiW.R (2022-06-02)
###
### Compute loadings (Phi, Psi) and whitening matrix (W)
###
### Copyright 2018-22 Korbinian Strimmer
###
###
### This file is part of the `whitening' library for R and related languages.
### It is made available under the terms of the GNU General Public
### License, version 3, or at your option, any later version,
### incorporated herein by reference.
###
### 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, write to the Free
### Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
### MA 02111-1307, USA
makePosDiag = function(U) return( sweep(U, 2, sign(diag(U)), "*") ) # U %*% diag( sign(diag(U)) )
# compute whitening matrix W from given covariance matrix Sigma
# or the loadings matrix Phi (= inverse of W)
getPhiPsiW = function(Sigma,
method=c("ZCA", "ZCA-cor", "PCA", "PCA-cor", "Cholesky"),
returnW=FALSE, returnPhiPsi=FALSE)
{
method=match.arg(method)
v = diag(Sigma)
if(method=="ZCA" | method=="PCA")
{
eSigma = eigen(Sigma, symmetric=TRUE)
U = eSigma$vectors
lambda = eSigma$values
}
if(method=="ZCA-cor" | method=="PCA-cor")
{
R = cov2cor(Sigma)
eR = eigen(R, symmetric=TRUE)
G = eR$vectors
theta = eR$values
}
if(method=="ZCA")
{
if (returnW)
W = U %*% diag(1/sqrt(lambda)) %*% t(U)
if (returnPhiPsi)
{
Phi = U %*% diag(sqrt(lambda)) %*% t(U)
Psi = diag(1/sqrt(v)) %*% Phi
}
}
if(method=="PCA")
{
# fix sign ambiguity in eigenvectors by making U positive diagonal
U = makePosDiag(U)
if (returnW)
W = diag(1/sqrt(lambda)) %*% t(U)
if (returnPhiPsi)
{
Phi = U %*% diag(sqrt(lambda))
Psi = diag(1/sqrt(v)) %*% Phi
}
}
if(method=="Cholesky") # Chol-cov (lower triangular loadings and whitening matrix)
{
if (returnW)
W = solve(t(chol(Sigma))) # t() because R chol() returns upper triangular matrix
if (returnPhiPsi)
{
Phi = t(chol(Sigma))
Psi = diag(1/sqrt(v)) %*% Phi
}
}
if(method=="ZCA-cor")
{
if (returnW)
W = G %*% diag(1/sqrt(theta)) %*% t(G) %*% diag(1/sqrt(v))
if (returnPhiPsi)
{
Psi = G %*% diag(sqrt(theta)) %*% t(G)
Phi = diag(sqrt(v)) %*% Psi
}
}
if(method=="PCA-cor")
{
# fix sign ambiguity in eigenvectors by making G positive diagonal
G = makePosDiag(G)
if (returnW)
W = diag(1/sqrt(theta)) %*% t(G) %*% diag(1/sqrt(v))
if (returnPhiPsi)
{
Psi = G %*% diag(sqrt(theta))
Phi = diag(sqrt(v)) %*% Psi
}
}
result=list()
if (returnW)
{
colnames(W) = colnames(Sigma)
rownames(W) = paste0("L", 1:ncol(Sigma))
attr(W, "method") = method
result$W = W
}
if (returnPhiPsi)
{
rownames(Phi) = colnames(Sigma)
colnames(Phi) = paste0("L", 1:ncol(Sigma))
attr(Phi, "method") = method
result$Phi = Phi
rownames(Psi) = colnames(Sigma)
colnames(Psi) = paste0("L", 1:ncol(Sigma))
attr(Psi, "method") = method
result$Psi = Psi
}
return(result)
}
|
/scratch/gouwar.j/cran-all/cranData/whitening/R/getPhiPsiW.R
|
# 2018 modified from fields package version 9.6
# see https://CRAN.R-project.org/package=fields
tim.colors = function (n)
{
orig <- c("#00008F", "#00009F", "#0000AF", "#0000BF", "#0000CF",
"#0000DF", "#0000EF", "#0000FF", "#0010FF", "#0020FF",
"#0030FF", "#0040FF", "#0050FF", "#0060FF", "#0070FF",
"#0080FF", "#008FFF", "#009FFF", "#00AFFF", "#00BFFF",
"#00CFFF", "#00DFFF", "#00EFFF", "#00FFFF", "#10FFEF",
"#20FFDF", "#30FFCF", "#40FFBF", "#50FFAF", "#60FF9F",
"#70FF8F", "#80FF80", "#8FFF70", "#9FFF60", "#AFFF50",
"#BFFF40", "#CFFF30", "#DFFF20", "#EFFF10", "#FFFF00",
"#FFEF00", "#FFDF00", "#FFCF00", "#FFBF00", "#FFAF00",
"#FF9F00", "#FF8F00", "#FF8000", "#FF7000", "#FF6000",
"#FF5000", "#FF4000", "#FF3000", "#FF2000", "#FF1000",
"#FF0000", "#EF0000", "#DF0000", "#CF0000", "#BF0000",
"#AF0000", "#9F0000", "#8F0000", "#800000")
if (n == 64 )
return(orig)
else
stop("only n=64 supported")
}
image.plot = function (..., add = FALSE, breaks = NULL, nlevel = 64, col = NULL,
horizontal = FALSE, legend.shrink = 0.9, legend.width = 1.2,
legend.mar = ifelse(horizontal, 3.1, 5.1), legend.lab = NULL,
legend.line = 2, graphics.reset = FALSE, bigplot = NULL,
smallplot = NULL, legend.only = FALSE, lab.breaks = NULL,
axis.args = NULL, legend.args = NULL, legend.cex = 1, midpoint = FALSE,
border = NA, lwd = 1)
{
old.par <- par(no.readonly = TRUE)
if (is.null(col)) {
col <- tim.colors(nlevel)
}
else {
nlevel <- length(col)
}
info <- imagePlotInfo(..., breaks = breaks, nlevel = nlevel)
breaks <- info$breaks
if (add) {
big.plot <- old.par$plt
}
if (legend.only) {
graphics.reset <- TRUE
}
if (is.null(legend.mar)) {
legend.mar <- ifelse(horizontal, 3.1, 5.1)
}
temp <- imageplot.setup(add = add, legend.shrink = legend.shrink,
legend.width = legend.width, legend.mar = legend.mar,
horizontal = horizontal, bigplot = bigplot, smallplot = smallplot)
smallplot <- temp$smallplot
bigplot <- temp$bigplot
if (!legend.only) {
if (!add) {
par(plt = bigplot)
}
if (!info$poly.grid) {
image(..., breaks = breaks, add = add, col = col)
}
else {
stop("poly.image() not supported")
}
big.par <- par(no.readonly = TRUE)
}
if ((smallplot[2] < smallplot[1]) | (smallplot[4] < smallplot[3])) {
par(old.par)
stop("plot region too small to add legend\n")
}
ix <- 1:2
iy <- breaks
nBreaks <- length(breaks)
midpoints <- (breaks[1:(nBreaks - 1)] + breaks[2:nBreaks])/2
iz <- matrix(midpoints, nrow = 1, ncol = length(midpoints))
par(new = TRUE, pty = "m", plt = smallplot, err = -1)
if (!horizontal) {
image(ix, iy, iz, xaxt = "n", yaxt = "n", xlab = "",
ylab = "", col = col, breaks = breaks)
}
else {
image(iy, ix, t(iz), xaxt = "n", yaxt = "n", xlab = "",
ylab = "", col = col, breaks = breaks)
}
if (!is.null(lab.breaks)) {
axis.args <- c(list(side = ifelse(horizontal, 1, 4),
mgp = c(3, 1, 0), las = ifelse(horizontal, 0, 2),
at = breaks, labels = lab.breaks), axis.args)
}
else {
axis.args <- c(list(side = ifelse(horizontal, 1, 4),
mgp = c(3, 1, 0), las = ifelse(horizontal, 0, 2)),
axis.args)
}
do.call("axis", axis.args)
box()
if (!is.null(legend.lab)) {
legend.args <- list(text = legend.lab, side = ifelse(horizontal,
1, 4), line = legend.line, cex = legend.cex)
}
if (!is.null(legend.args)) {
do.call(mtext, legend.args)
}
mfg.save <- par()$mfg
if (graphics.reset | add) {
par(old.par)
par(mfg = mfg.save, new = FALSE)
invisible()
}
else {
par(big.par)
par(plt = big.par$plt, xpd = FALSE)
par(mfg = mfg.save, new = FALSE)
invisible()
}
}
imagePlotInfo = function (..., breaks = NULL, nlevel)
{
temp <- list(...)
xlim <- NA
ylim <- NA
zlim <- NA
poly.grid <- FALSE
if (is.list(temp[[1]])) {
xlim <- range(temp[[1]]$x, na.rm = TRUE)
ylim <- range(temp[[1]]$y, na.rm = TRUE)
zlim <- range(temp[[1]]$z, na.rm = TRUE)
if (is.matrix(temp[[1]]$x) & is.matrix(temp[[1]]$y) &
is.matrix(temp[[1]]$z)) {
poly.grid <- TRUE
}
}
if (length(temp) >= 3) {
if (is.matrix(temp[[1]]) & is.matrix(temp[[2]]) & is.matrix(temp[[3]])) {
poly.grid <- TRUE
}
}
if (is.matrix(temp[[1]]) & !poly.grid) {
xlim <- c(0, 1)
ylim <- c(0, 1)
zlim <- range(temp[[1]], na.rm = TRUE)
}
if (length(temp) >= 3) {
if (is.matrix(temp[[3]])) {
xlim <- range(temp[[1]], na.rm = TRUE)
ylim <- range(temp[[2]], na.rm = TRUE)
zlim <- range(temp[[3]], na.rm = TRUE)
}
}
if (!is.na(zlim[1])) {
if (zlim[1] == zlim[2]) {
if (zlim[1] == 0) {
zlim[1] <- -1e-08
zlim[2] <- 1e-08
}
else {
delta <- 0.01 * abs(zlim[1])
zlim[1] <- zlim[1] - delta
zlim[2] <- zlim[2] + delta
}
}
}
if (is.matrix(temp$x) & is.matrix(temp$y) & is.matrix(temp$z)) {
poly.grid <- TRUE
}
xthere <- match("x", names(temp))
ythere <- match("y", names(temp))
zthere <- match("z", names(temp))
if (!is.na(zthere))
zlim <- range(temp$z, na.rm = TRUE)
if (!is.na(xthere))
xlim <- range(temp$x, na.rm = TRUE)
if (!is.na(ythere))
ylim <- range(temp$y, na.rm = TRUE)
if (!is.null(temp$zlim))
zlim <- temp$zlim
if (!is.null(temp$xlim))
xlim <- temp$xlim
if (!is.null(temp$ylim))
ylim <- temp$ylim
if (is.null(breaks)) {
midpoints <- seq(zlim[1], zlim[2], , nlevel)
delta <- (midpoints[2] - midpoints[1])/2
breaks <- c(midpoints[1] - delta, midpoints + delta)
}
list(xlim = xlim, ylim = ylim, zlim = zlim, poly.grid = poly.grid,
breaks = breaks)
}
imageplot.setup =function (x, add = FALSE, legend.shrink = 0.9, legend.width = 1,
horizontal = FALSE, legend.mar = NULL, bigplot = NULL, smallplot = NULL,
...)
{
old.par <- par(no.readonly = TRUE)
if (is.null(smallplot))
stick <- TRUE
else stick <- FALSE
if (is.null(legend.mar)) {
legend.mar <- ifelse(horizontal, 3.1, 5.1)
}
char.size <- ifelse(horizontal, par()$cin[2]/par()$din[2],
par()$cin[1]/par()$din[1])
offset <- char.size * ifelse(horizontal, par()$mar[1], par()$mar[4])
legend.width <- char.size * legend.width
legend.mar <- legend.mar * char.size
if (is.null(smallplot)) {
smallplot <- old.par$plt
if (horizontal) {
smallplot[3] <- legend.mar
smallplot[4] <- legend.width + smallplot[3]
pr <- (smallplot[2] - smallplot[1]) * ((1 - legend.shrink)/2)
smallplot[1] <- smallplot[1] + pr
smallplot[2] <- smallplot[2] - pr
}
else {
smallplot[2] <- 1 - legend.mar
smallplot[1] <- smallplot[2] - legend.width
pr <- (smallplot[4] - smallplot[3]) * ((1 - legend.shrink)/2)
smallplot[4] <- smallplot[4] - pr
smallplot[3] <- smallplot[3] + pr
}
}
if (is.null(bigplot)) {
bigplot <- old.par$plt
if (!horizontal) {
bigplot[2] <- min(bigplot[2], smallplot[1] - offset)
}
else {
bottom.space <- old.par$mar[1] * char.size
bigplot[3] <- smallplot[4] + offset
}
}
if (stick & (!horizontal)) {
dp <- smallplot[2] - smallplot[1]
smallplot[1] <- min(bigplot[2] + offset, smallplot[1])
smallplot[2] <- smallplot[1] + dp
}
return(list(smallplot = smallplot, bigplot = bigplot))
}
|
/scratch/gouwar.j/cran-all/cranData/whitening/R/internal.R
|
### scca.R (2018-07-09)
###
### Estimate canonical correlations, canonical directions, and loading
###
### Copyright 2018 Korbinian Strimmer
###
###
### This file is part of the `whitening' library for R and related languages.
### It is made available under the terms of the GNU General Public
### License, version 3, or at your option, any later version,
### incorporated herein by reference.
###
### 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, write to the Free
### Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
### MA 02111-1307, USA
# empirical version - same as scca but with lambda.cor=0 and verbose=FALSE
cca = function(X, Y, scale=TRUE)
{
out = scca(X, Y, lambda.cor=0, scale=scale, verbose=FALSE)
return(out)
}
scca = function(X, Y, lambda.cor, scale=TRUE, verbose=TRUE)
{
if (!is.matrix(X)) stop("X needs to be a matrix!")
if (!is.matrix(Y)) stop("Y needs to be a matrix!")
p = dim(X)[2]
q = dim(Y)[2]
n = dim(X)[1]
if (dim(Y)[1] !=n ) stop("X and Y needs to have the same number of rows!")
# find regularization parameter for the correlation matrix
if( missing(lambda.cor) )
{
lambda.cor.estimated = TRUE
# regularize the joint correlation matrix (X and Y combined)
lambda.cor = estimate.lambda( cbind(X,Y), verbose=verbose )
}
else
{
lambda.cor.estimated = FALSE
}
# memory and time-saving way of computing cross products of shrinkage correlation matrix
# RX^{alpha} %*% m
cpLeft = function(x, m, alpha, lambda.cor)
{
a = crossprod.powcor.shrink(x, m, alpha=alpha, lambda=lambda.cor, verbose = FALSE)
attr(a, "class") = NULL
attr(a, "lambda.estimated") = NULL
attr(a, "lambda") = NULL
return(a)
}
# m %*% RX^{alpha}
cpRight = function(x, m, alpha, lambda.cor)
t( cpLeft(x, t(m), alpha, lambda.cor ) )
# shrinkage estimate of cross-correlation
RXY = (1-lambda.cor)*cor(X, Y)
# adjusted cross-correlations pxq K = RXX^(-1/2) %*% RXY %*% isqrtRYY^(-1/2)
# this avoids to compute the full matrices RXX^(-1/2) and RYY^(-1/2)
K = cpRight(Y, cpLeft(X, RXY, -1/2, lambda.cor), -1/2, lambda.cor)
# decompose adjusted cross-correlations K into rotation matrices and canonical correlation
#svd.out = fast.svd(K)
svd.out = svd(K)
QX = t(svd.out$u) # t(U) mxp
QY = t(svd.out$v) # t(V) mxq
lambda = svd.out$d # canonical correlations (singular values of K) m
# check decomposition: sum( (K - t(QX) %*% diag(lambda) %*% QY)^2 )
# fix sign ambiguity by making QX and QY positive diagonal
sQX = sign(diag(QX)) # m
sQY = sign(diag(QY)) # m
QX = sweep(QX, 1, sQX, "*") # diag(sQX) %*% QX
QY = sweep(QY, 1, sQY, "*") # diag(sQY) %*% QY
lambda = lambda*sQX*sQY # some canonical correlations may now be negative
# SVD decomposition is still valid: sum( (K - t(QX) %*% diag(lambda) %*% QY)^2 )
# compute canonical directions
# canonical directions for X (rows contain directions) = t(Xcoef)
WX = cpRight(X, QX, -1/2, lambda.cor) # QX %*% RXX^(-1/2) (mxp)
# canonical directions for Y (rows contain directions) = t(Ycoef)
WY = cpRight(Y, QY, -1/2, lambda.cor) # QY %*% RYY^(-1/2) (mxq)
# bring back scale into the canonical directions if data should not be scaled
if( !scale)
{
SDX = apply(X, 2, sd) # standard deviations for X
SDY = apply(Y, 2, sd) # standard deviations for Y
WX = sweep(WX, 2, SDX, "/")
WY = sweep(WY, 2, SDY, "/")
}
colnames(WX) = colnames(X)
colnames(WY) = colnames(Y)
# compute loadings
# loadings for X
PhiX = cpRight(X, QX, 1/2, lambda.cor) # QX %*% RXX^(-1/2) (mxp)
# loadings for Y
PhiY = cpRight(Y, QY, 1/2, lambda.cor) # QY %*% RYY^(-1/2) (mxq)
# bring back scale into the loadings if data should not be scaled
if( !scale)
{
WX = sweep(PhiX, 2, SDX, "*")
WY = sweep(PhiY, 2, SDY, "*")
}
colnames(PhiX) = colnames(X)
colnames(PhiY) = colnames(Y)
return( list(K=K, lambda=lambda, WX=WX, WY=WY, PhiX=PhiX, PhiY=PhiY, scale=scale,
lambda.cor.estimated=lambda.cor.estimated,
lambda.cor=lambda.cor) )
}
|
/scratch/gouwar.j/cran-all/cranData/whitening/R/scca.R
|
### simOrtho.R (2022-05-24)
###
### Simulate random orthogonal matrix
###
### Copyright 2021-2022 Korbinian Strimmer
###
###
### This file is part of the `whitening' library for R and related languages.
### It is made available under the terms of the GNU General Public
### License, version 3, or at your option, any later version,
### incorporated herein by reference.
###
### 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, write to the Free
### Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
### MA 02111-1307, USA
# simulate random orthogonal matrix of dimension d
# G.W. Stewart. 1980. The efficient generation of random orthogonal
# matrices with an application to condition estimators.
# SIAM J. Numer. Anal. 17:403-409.
# https://doi.org/10.1137/0717034
#
# See Section 3 page 404
simOrtho = function(d, nonNegDiag = FALSE)
{
A = matrix(rnorm(d*d), d, d)
# QR decomposition of A
qr.out = qr(A)
Q = qr.Q(qr.out)
R = qr.R(qr.out) # upper triangular, with arbitrary signs on diagonal
if (nonNegDiag)
{
sgn = sign(diag(Q))
}
else # default
{
sgn = sign(diag(R))
#R.new = diag(sgn) %*% R # now signs on diagonal are all positive
}
Q.new = Q %*% diag(sgn) # adjust Q correspondingly
return( Q.new )
}
|
/scratch/gouwar.j/cran-all/cranData/whitening/R/simOrtho.R
|
### whiten.R (2022-05-29)
###
### Whitening data matrix
###
### Copyright 2018-20 Korbinian Strimmer
###
###
### This file is part of the `whitening' library for R and related languages.
### It is made available under the terms of the GNU General Public
### License, version 3, or at your option, any later version,
### incorporated herein by reference.
###
### 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, write to the Free
### Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
### MA 02111-1307, USA
# whiten data using empirical covariance matrix
whiten = function(X, center=FALSE,
method=c("ZCA", "ZCA-cor",
"PCA", "PCA-cor",
"Cholesky"))
{
method = match.arg(method)
S = cov(X)
W = whiteningMatrix(S, method=method)
Z = tcrossprod(X, W) # whitened data
if(center) Z = sweep(Z, 2, colMeans(Z))
colnames(Z) = paste0("L", 1:ncol(X))
attr(Z, "method") = method
return(Z)
}
|
/scratch/gouwar.j/cran-all/cranData/whitening/R/whiten.R
|
### whiteningCrossCov.R (2022-06-01)
###
### Compute cross-covariance matrix
###
### Copyright 2018-22 Korbinian Strimmer
###
###
### This file is part of the `whitening' library for R and related languages.
### It is made available under the terms of the GNU General Public
### License, version 3, or at your option, any later version,
### incorporated herein by reference.
###
### 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, write to the Free
### Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
### MA 02111-1307, USA
# create whitening cross-covariance matrix Phi.old from given covariance matrix Sigma
# note that t(Phi.old) = W^{-1}
whiteningCrossCov = function(Sigma,
method=c("ZCA", "ZCA-cor",
"PCA", "PCA-cor",
"Cholesky"))
{
.Deprecated("whiteningLoadings") # notify user to use whiteningLoadings instead.
Phi.old = t( getPhiPsiW(Sigma=Sigma, method=method, returnPhiPsi=TRUE)$Phi )
return (Phi.old)
}
|
/scratch/gouwar.j/cran-all/cranData/whitening/R/whiteningCrossCov.R
|
### whiteningLoadings.R (2022-06-02)
###
### Compute (correlation) loadings Phi and Psi
###
### Copyright 2018-22 Korbinian Strimmer
###
###
### This file is part of the `whitening' library for R and related languages.
### It is made available under the terms of the GNU General Public
### License, version 3, or at your option, any later version,
### incorporated herein by reference.
###
### 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, write to the Free
### Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
### MA 02111-1307, USA
# compute whitening loadings (cross-covariance matrix Phi)
# and correlation loadings (cross-correlation matrix Psi)
# from a given covariance matrix Sigma
whiteningLoadings = function(Sigma,
method=c("ZCA", "ZCA-cor",
"PCA", "PCA-cor",
"Cholesky"))
{
method=match.arg(method)
PhiPsi = getPhiPsiW(Sigma, method, returnPhiPsi=TRUE)
return(PhiPsi)
}
|
/scratch/gouwar.j/cran-all/cranData/whitening/R/whiteningLoadings.R
|
### whiteningMatrix.R (2022-06-02)
###
### Compute whitening matrix
###
### Copyright 2018-22 Korbinian Strimmer
###
###
### This file is part of the `whitening' library for R and related languages.
### It is made available under the terms of the GNU General Public
### License, version 3, or at your option, any later version,
### incorporated herein by reference.
###
### 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, write to the Free
### Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
### MA 02111-1307, USA
# compute whitening matrix W from given covariance matrix Sigma
whiteningMatrix = function(Sigma,
method=c("ZCA", "ZCA-cor",
"PCA", "PCA-cor",
"Cholesky"))
{
method=match.arg(method)
return( getPhiPsiW(Sigma, method, returnW=TRUE)$W )
}
|
/scratch/gouwar.j/cran-all/cranData/whitening/R/whiteningMatrix.R
|
# Reproduces the LUSC TCGA data analysis in
# Jendoubi and Strimmer. 2019. A whitening approach to probabilistic canonical
# correlation analysis for omics data integration. BMC Bioinformatics 20:15.
# https://doi.org/10.1186/s12859-018-2572-9
##### load package and data ################################
# load "whitening" library
library("whitening") # contains CCA functions and data
# load data
data(lusc)
X = lusc$rnaseq2
Y = lusc$methyl
dim(X) # 130 206 gene expression
dim(Y) # 130 234 methylation
##### start CCA analysis ###################################
# CCA with shrinkage estimate of joint correlation
cca.out = scca(X, Y, scale=TRUE)
cca.out
# shrinkage intensity
lambda.cor = cca.out$lambda.cor
lambda.cor # 0.1852659
# estimated canonical correlations
cca.out$lambda
sum(cca.out$lambda < 0) # 96
range(cca.out$lambda) # -0.9291533 0.9754134
hist( cca.out$lambda )
# whitened data
CCAX = tcrossprod( scale(X), cca.out$WX )
CCAY = tcrossprod( scale(Y), cca.out$WY )
##### Basic plots ##########################################
# plot correlation matrices
#pdf(file="lusc-matcor.pdf", width=7, height=7)
corplot(cca.out, X, Y)
#dev.off()
# plot canonical correlations
#pdf(file="lusc-barplot.pdf", width=7, height=5)
barplot(cca.out$lambda, xlab = "Dimension",
ylab = "Canonical Correlations", names.arg = 1:length(cca.out$lambda))
#dev.off()
##### plot squared correlation loadings ####################
#pdf(file="lusc-loadings.pdf", width=10)
loadplot(cca.out, 10)
#dev.off()
# column sums of squared correlation loadings add to 1
colSums(cca.out$PhiX^2)
##### scatter plots with labeled data points ##############
# get labels
colpacks = rep(1, 130) # black 90 or less
colpacks[ lusc$packs > 90] = 2 # red > 90
colpacks[ is.na(lusc$packs) ] = 3 # unknown
table(colpacks)
ppch = rep(21, length(lusc$sex)) # circle 90 or less
ppch[is.na(lusc$packs)] = 22 # reverse triangle 20
ppch[lusc$packs > 90] = 25 # square
#pdf(width=11, height=5,file="lusc-scatter.pdf")
par(mfrow=c(1,2))
par(mar=c(4.1, 4.5, 1.9, 2.1))
plot(CCAX[,1], CCAY[,1], xlim=c(-2.75,2.75), ylim=c(-2.75,2.75),
xlab=expression(paste(tilde(X)[1])),
ylab=expression(paste(tilde(Y)[1])),
col=1, pch=21, bg=ifelse(lusc$sex=="male", 1, 0) )
legend("bottomright", c("male", "female"), pch=c(21,21),
col=c(1,1), pt.bg=c(1,0))
text(1, 0, "male")
text(-2, -1, "female")
plot(CCAX[,1], CCAX[,2], xlim=c(-2.75,2.75), ylim=c(-2.75,2.75),
xlab=expression(paste(tilde(X)[1])),
ylab=expression(paste(tilde(X)[2])),
col=colpacks, pch=ppch, bg=ifelse(lusc$sex=="male", colpacks, 0) )
text(1.8, -0.5, "male")
text(-2, 1.8, "female")
pos = legend("bottomleft", c(expression(paste(" ", "">90, " packs")),
expression(paste(" ", ""<=90, " packs")), " unknown packs"))
points(x=rep(pos$text$x, times=2) - c(0.25, 0.25, 0.25, 0.05, 0.05, 0.05),
y=rep(pos$text$y, times=2), pch=c(25,21,22,25,21,22),
col=c(2,1,3,2,1,3), bg=c(2,1,3,0,0,0) )
par(mar=c(5.1, 4.1, 4.1, 2.1))
par(mfrow=c(1,1))
#dev.off()
##### survival plots #######################################
require("survival")
s = Surv(lusc$survivalTime, lusc$censoringStatus)
cox = coxph(s ~ lusc$sex)
n.class <- 2
pv <- 1 - pchisq(2 * (cox$loglik[2] - cox$loglik[1]), df = n.class - 1)
#pdf(file="lusc-surv.pdf")
plot(survfit(s ~ lusc$sex), xlab = "Years",
ylab = "Probability of survival", col = c(1,1), lty=c(2,1), lwd=c(2,2))
legend("topright", legend = c("male", "female"), col = c(1,1), lty =c(1,2),
lwd=c(2,2), box.lwd=1)
text(10.3, 0.7, paste("p =", as.character(round(pv, 4))))
#dev.off()
|
/scratch/gouwar.j/cran-all/cranData/whitening/inst/doc/lusc.R
|
# Reproduces the nutrimouse data analysis in
# Jendoubi and Strimmer. 2019. A whitening approach to probabilistic canonical
# correlation analysis for omics data integration. BMC Bioinformatics 20:15.
# https://doi.org/10.1186/s12859-018-2572-9
##### load package and data ################################
# load "whitening" library
library("whitening") # contains CCA functions and data
# load data
data(nutrimouse)
X = as.matrix(nutrimouse$gene)
Y = as.matrix(nutrimouse$lipid)
dim(X) # 40 120
dim(Y) # 40 21
##### start CCA analysis ###################################
# CCA with shrinkage estimate of joint correlation
cca.out = scca(X, Y, scale=TRUE)
cca.out
# shrinkage intensity
lambda.cor = cca.out$lambda.cor
lambda.cor # 0.1599767
# estimated canonical correlations
cca.out$lambda
# [1] -0.9605275617 -0.9476499457 -0.9264858941 0.8660390307 -0.8591510518
# [6] -0.8057844616 -0.7314092050 -0.7192164996 -0.6702938353 -0.6416074974
#[11] -0.4937654758 0.4686423030 0.3895309296 -0.3588989722 -0.3049187235
#[16] -0.2546627651 -0.2261556012 0.1596697930 -0.1179019917 -0.1013979520
#[21] 0.0009561428
sum(cca.out$lambda < 0) # 16
range(cca.out$lambda) # -0.9605276 0.8660390
hist(cca.out$lambda)
# whitened data
CCAX = tcrossprod( scale(X), cca.out$WX )
CCAY = tcrossprod( scale(Y), cca.out$WY )
##### Basic plots ##########################################
# plot correlation matrices
#pdf(file="nutrimouse-matcor.pdf", width=7, height=7)
corplot(cca.out, X,Y)
#dev.off()
# plot canonical correlations
#pdf(file="nutrimouse-barplot.pdf", width=7, height=5)
barplot(cca.out$lambda, xlab = "Dimension",
ylab = "Canonical Correlations", names.arg = 1:length(cca.out$lambda))
#dev.off()
##### plot squared correlation loadings ####################
#pdf(file="nutrimouse-loadings.pdf", width=10)
loadplot(cca.out, 5)
#dev.off()
# column sums of squared correlation loadings add to 1
colSums(cca.out$PhiY^2)
##### scatter plots with labeled data points ##############
# get labels
g=nutrimouse$genotype
levels(g)
# wt vs ppar
# wild-type and PPARalpha -/-
# 1 wt
# 2 ppar
table(g)
#wt ppar
# 20 20
d=nutrimouse$diet
levels(d)
# coc fish lin ref sun
# 1 coconut oil (COC) black square
# 2 fish oils (FISH). red triangle filled
# 3 linseed oil (LIN) green triangle open
# 4 reference diet (REF), blue circle filled
# 5 sunflower oil (SUN) light blue circle open
table(d)
#coc fish lin ref sun
# 8 8 8 8 8
bgcol=ifelse(g=="ppar", 0, d) # no fill vs filled
dpch=rep(21, length(d)) # coc = circle
dpch[d=="fish"] = 22 # square
dpch[d=="lin"] = 23 # diamond
dpch[d=="ref"] = 24 # triangle
dpch[d=="sun"] = 25 # reverse triangle
## plot pairs of canonical covariates
#pdf(width=9.1, height=8.3, file="nutrimouse-between.pdf")
par(mfrow=c(2,2))
par(mar=c(4.1, 4.5, 1.9, 2.1))
plot(CCAX[,1], -CCAY[,1], xlim=c(-2.5,2.5), ylim=c(-2.5,2.5),
xlab=expression(paste(tilde(X)[1])), ylab=expression(paste(-tilde(Y)[1])),
col=1, pch=21, bg=ifelse(g=="wt", 1, 0) )
legend("bottomright", c("wt", "ppar"), pch=c(21,21), col=c(1,1), pt.bg=c(1,0))
text(-.8, -1.5, "ppar")
text(1.2, 0.5, "wt")
plot(CCAX[,2], -CCAY[,2], xlim=c(-2.5,2.5), ylim=c(-2.5,2.5),
xlab=expression(paste(tilde(X)[2])), ylab=expression(paste(-tilde(Y)[2])) ,
col=d, pch=dpch)
legend("bottomright", c("COC", "FISH", "LIN", "REF", "SUN"),
pch=21:25, col=1:5)
text(-1.7, -1.2, "COC")
text(0, -0.6, "SUN / REF")
text(1.3, 0.3, "LIN / FISH /")
text(1.3, 0.6, "SUN /")
plot(CCAX[,3], -CCAY[,3], xlim=c(-2.5,2.5), ylim=c(-2.5,2.5),
xlab=expression(paste(tilde(X)[3])), ylab=expression(paste(-tilde(Y)[3])) ,
col=d, pch=dpch)
legend("bottomright", c("COC", "FISH", "LIN", "REF", "SUN"),
pch=21:25, col=1:5)
text(-1.8,-1.1, "SUN")
text(-0.2,-1, "REF")
plot(CCAX[,4], CCAY[,4], xlim=c(-2.5,2.5), ylim=c(-2.5,2.5),
xlab=expression(paste(tilde(X)[4])), ylab=expression(paste(tilde(Y)[4])) ,
col=d, pch=dpch)
legend("bottomright", c("COC", "FISH", "LIN", "REF", "SUN"),
pch=21:25, col=1:5)
text(-1.7, -1, "LIN")
text(1.5, 0.7, "FISH")
par(mfrow=c(1,1))
par(mar=c(5.1, 4.1, 4.1, 2.1))
#dev.off()
## plot first second variates within X and Y
#pdf(width=11, height=5, file="nutrimouse-within.pdf")
par(mfrow=c(1,2))
par(mar=c(4.1, 4.5, 1.9, 2.1))
plot(CCAX[,1], CCAX[,2], xlim=c(-2.5,2.5), ylim=c(-2.5,2.5),
xlab=expression(paste(tilde(X)[1])),
ylab=expression(paste(tilde(X)[2])),
col=d, pch=dpch, bg=bgcol )
pos = legend("bottomright", c(" COC", " FISH", " LIN", " REF", " SUN"))
points(x=rep(pos$text$x, times=5) - c(rep(0.25, 5), rep(0.05, 5)),
y=rep(pos$text$y, times=5),
pch=c(21:25,21:25), col=c(1:5,1:5), bg=c(1:5,0,0,0,0,0) )
legend("bottomleft", c("wt", "ppar"), pch=c(21,21), col=c(1,1), pt.bg=c(1,0))
text(-0.2, -1.5, "COC")
text(-1, 2, "ppar")
text(+1, 2, "wt")
plot(-CCAY[,1], -CCAY[,2], xlim=c(-2.5,2.5), ylim=c(-2.5,2.5),
xlab=expression(paste(tilde(-Y)[1])),
ylab=expression(paste(-tilde(Y)[2])),
col=d, pch=dpch, bg=bgcol )
pos = legend("bottomright", c(" COC", " FISH", " LIN", " REF", " SUN"))
points(x=rep(pos$text$x, times=5) - c(rep(0.25, 5), rep(0.05, 5)),
y=rep(pos$text$y, times=5),
pch=c(21:25,21:25), col=c(1:5,1:5), bg=c(1:5,0,0,0,0,0) )
legend("bottomleft", c("wt", "ppar"), pch=c(21,21), col=c(1,1), pt.bg=c(1,0))
text(-0.2, -1.5, "COC")
text(-1, 2, "ppar")
text(+1, 2, "wt")
par(mfrow=c(1,1))
par(mar=c(5.1, 4.1, 4.1, 2.1))
#dev.off()
|
/scratch/gouwar.j/cran-all/cranData/whitening/inst/doc/nutrimouse.R
|
# /*
# This is an R script containing R markdown comments. It can be run as is in R.
# To generate a document containing the formatted R code, R output and markdown
# click the "Compile Report" button in R Studio, or run the command
# rmarkdown::render() - see http://rmarkdown.rstudio.com/r_notebook_format.html
# */
#' ---
#' title: "Table 2 of Kessy, Lewin, and Strimmer (2018)"
#' output: pdf_document
#' author: ""
#' date: Requires "whitening" version 1.0.0 (March 2018) or later
#' ---
#' This script reproduces the results of Table 2 in:
#' A. Kessy, A. Lewin, and K. Strimmer. 2018.
#' *Optimal whitening and decorrelation.*
#' The American Statistician **72**: 309-314
#' https://doi.org/10.1080/00031305.2016.1277159
#'
#' # Load "whitening" package and example data
library("whitening") # available on CRAN
#' Example data set:
#' E. Anderson. 1935. The irises of the Gaspe Peninsula.
#' Bull. Am. Iris Soc. 59: 2--5
data("iris")
X = as.matrix(iris[,1:4])
d = ncol(X) # 4
n = nrow(X) # 150
colnames(X) # "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width"
#'
#' # Five natural whitening transformations applied to the iris example data set
#' ZCA-Mahalanobis whitening:
Z.ZCA = whiten(X, method="ZCA") # whitened data
zapsmall(cov(Z.ZCA))
Phi.ZCA = cov(Z.ZCA, X) # cross-covariances
Psi.ZCA = cor(Z.ZCA, X) # cross-correlations
#' PCA whitening:
Z.PCA = whiten(X, method="PCA") # whitened data
zapsmall(cov(Z.PCA))
Phi.PCA = cov(Z.PCA, X) # cross-covariances
Psi.PCA = cor(Z.PCA, X) # cross-correlations
#' Cholesky whitening:
Z.Chol = whiten(X, method="Cholesky") # whitened data
zapsmall(cov(Z.Chol))
Phi.Chol = cov(Z.Chol, X) # cross-covariances
Psi.Chol = cor(Z.Chol, X) # cross-correlations
#' ZCA-cor whitening:
Z.ZCAcor = whiten(X, method="ZCA-cor") # whitened data
zapsmall(cov(Z.ZCAcor))
Phi.ZCAcor = cov(Z.ZCAcor, X) # cross-covariances
Psi.ZCAcor = cor(Z.ZCAcor, X) # cross-correlations
#' PCA-cor whitening:
Z.PCAcor = whiten(X, method="PCA-cor") # whitened data
zapsmall(cov(Z.PCAcor))
Phi.PCAcor = cov(Z.PCAcor, X) # cross-covariances
Psi.PCAcor = cor(Z.PCAcor, X) # cross-correlations
#
#' # Create Table 2
#' Helper function to compute entries of a column in Table 2
#'(Phi: cross-covariance matrix; Psi: cross-correlation matrix):
columnTable2 = function(Phi, Psi)
{
out = c( diag(Psi), # cor(zi, xi)
sum(diag(Phi)), # trace(Phi)
sum(diag(Psi)), # trace(Psi)
max(rowSums(Phi^2)),
max(rowSums(Psi^2)) )
return( round(out, 4))
}
#' Compute Table 2:
tab2 = cbind(
columnTable2(Phi.ZCA, Psi.ZCA),
columnTable2(Phi.PCA, Psi.PCA),
columnTable2(Phi.Chol, Psi.Chol),
columnTable2(Phi.ZCAcor, Psi.ZCAcor),
columnTable2(Phi.PCAcor, Psi.PCAcor) )
colnames(tab2) = c("ZCA", "PCA", "Cholesky", "ZCA-cor", "PCA-cor")
rownames(tab2) = NULL
tab2
# /*
#' ZCA PCA Cholesky ZCA-cor PCA-cor
# [1,] 0.7137 0.8974 0.3760 0.8082 0.8902
# [2,] 0.9018 0.8252 0.8871 0.9640 0.8827
# [3,] 0.8843 0.0121 0.2700 0.6763 0.0544
# [4,] 0.5743 0.1526 1.0000 0.7429 0.0754
# [5,] 2.9829 1.2405 1.9368 2.8495 1.2754
# [6,] 3.0742 1.8874 2.5331 3.1914 1.9027
# [7,] 3.1163 4.2282 3.9544 1.7437 4.1885
# [8,] 1.9817 2.8943 2.7302 1.0000 2.9185
# */
|
/scratch/gouwar.j/cran-all/cranData/whitening/inst/doc/optimal-whitening-table2.R
|
#' This function performs a White's Test for heteroskedasticity (White, H. (1980))
#'
#' White's test is a statistical test that determines whether the variance of the residuals in a regression model is constant.
#'
#' The approach followed is the one detailed at Wooldridge, 2012, p. 275. The fitted values from the original model are:
#'
#' \deqn{\widehat{y_i} = \widehat{\beta_0} + \widehat{\beta_1}x_{i1} + ... + \widehat{\beta_k}x_{ik}}
#'
#' Heteroscedasticity could be tested as a linear regression of the squared residuals against the fitted values:
#'
#' \deqn{\widehat{u^2} = \delta_0 + \delta_1\widehat{y} + \delta_2\widehat{y^2} + error}
#'
#' The null hypothesis states that \eqn{\delta_1 = \delta_2 = 0} (homoskedasticity). The test statistic
#' is defined as:
#'
#' \deqn{LM = nR^2}
#'
#' where \eqn{R^2} is the R-squared value from the regression of \eqn{u^2}.
#'
#' @param model An object of class \code{\link[stats]{lm}}
#'
#' @return AA list with class \code{white_test} containing:\tabular{ll}{
#' \code{w_stat} \tab The value of the test statistic \cr
#' \tab \cr
#' \code{p_value} \tab The p-value of the test \cr
#' \tab \cr
#' }
#' @export
#'
#'
#' @references
#' White, H. (1980). A Heteroskedasticity-Consistent Covariance Matrix Estimator
#' and a Direct Test for Heteroskedasticity. Econometrica, 48(4), 817-838.
#'
#' Wooldridge, Jeffrey M., 1960-. (2012). Introductory econometrics : a modern approach. Mason, Ohio :
#' South-Western Cengage Learning,
#'
#' @seealso \code{\link[stats]{lm}}
#'
#' @examples
#' # Define a dataframe with heteroscedasticity
#' n <- 100
#' y <- 1:n
#' sd <- runif(n, min = 0, max = 4)
#' error <- rnorm(n, 0, sd*y)
#' X <- y + error
#' df <- data.frame(y, X)
#' # OLS model
#' fit <- lm(y ~ X, data = df)
#' # White's test
#' white_test(fit)
#' @importFrom graphics hist lines
#' @import stats
white_test <- function(model) {
# Squared residuals of fitted model
squared_residuals <- model$residuals^2
# get fitted values
.fitted <- fitted(model)
# auxiliary regression
aux_r_suared <- summary(lm(squared_residuals ~ .fitted + I(.fitted^2)))$r.squared
# test statistic
w_stat <- length(.fitted) * aux_r_suared
# compute p-value
p_value <- 1 - pchisq(w_stat, 2)
output <-
structure(
list(
w_stat = w_stat,
p_value = p_value
),
class = "white_test"
)
output
}
#' Bootstrapped version of the White's test (Jeong, J., Lee, K. (1999))
#'
#' This is a versioned White's test based on a bootstrap procedure that can improve the performance of White’s test,
#' specially in small samples. It was proposed by Jeong, J., Lee, K. (1999) (see references for further details).
#'
#' @param model An object of class \code{\link[stats]{lm}}
#' @param bootstraps Number of bootstrap to be performed. If `bootstraps` is less than 10, it will automatically be set to 10.
#' At least 500 simulations are recommended. Default value is set to 1000.
#'
#' @return A list with class \code{white_test} containing:\tabular{ll}{
#' \code{w_stat} \tab The value of the test statistic \cr
#' \tab \cr
#' \code{p_value} \tab The p-value of the test \cr
#' \tab \cr
#' \code{iters} \tab The number of bootstrap samples \cr
#' \tab \cr
#' }
#' @export
#'
#' @references
#' Jeong, J., & Lee, K. (1999). Bootstrapped White’s test for heteroskedasticity in regression models. Economics Letters, 63(3), 261-267.
#'
#' White, H. (1980). A Heteroskedasticity-Consistent Covariance Matrix Estimator
#' and a Direct Test for Heteroskedasticity. Econometrica, 48(4), 817-838.
#'
#' Wooldridge, Jeffrey M., 1960-. (2012). Introductory econometrics : a modern approach. Mason, Ohio :
#' South-Western Cengage Learning,
#'
#' @details The bootstrapped error term is defined by:
#'
#' \deqn{\widehat{u_i} = \sigma^2 * t_i^{*} (i = 1,...N)}
#'
#' where \eqn{t_i^{*}} follows a distribution satisfying \eqn{E(t) = 0} and \eqn{var(t) = I}.
#'
#' In particular, the selected distribution of \eqn{t} can be found at the bottom of page 196 at Handbook of Computational Econometrics (2009).
#'
#' @examples
#' # Define a dataframe with heteroscedasticity
#' n <- 100
#' y <- 1:n
#' sd <- runif(n, min = 0, max = 4)
#' error <- rnorm(n, 0, sd*y)
#' X <- y + error
#' df <- data.frame(y, X)
#' # OLS model
#' fit <- lm(y ~ X, data = df)
#' # White's test
#' white_test_boot(fit)
#'
white_test_boot <-
function(model, bootstraps = 1000) {
if (bootstraps < 10) {
bootstraps <- 10
warning("At least 10 bootstrap samples are needed. Setting 'bootstrap_samples' to 10. At least 500 is recommended.")
}
# White test with original data
wt <- white_test(model)
# Bootstrapped method
# Paper: Bootstrapped White’s test for heteroskedasticity in regression models
# Jinook Jeong, Kyoungwoo Lee
bcount <- 0
wsb <- vector(mode = 'numeric')
for (i in seq_len(bootstraps)) {
.fitted <- fitted(model)
var_res <- summary(model)$sigma^2
boot_error <- sample(c(-(sqrt(5)-1)/2, (sqrt(5)+1)/2),
size = length(.fitted),
prob = c((sqrt(5)+1)/2*sqrt(5), (sqrt(5)-1)/2*sqrt(5)),
replace = TRUE)
# wild_boot <- sample(c(-1, 1), size = length(.fitted), prob = c(.5, .5), replace = TRUE)
bootstrapped_error <- var_res * boot_error
# new_y <- model$model[[1]] + bootstrapped_error
new_y <- .fitted + bootstrapped_error
aux_m <- lm(as.formula(gsub(".*~","new_y ~", format(model$call$formula))), data = model$model)
aux_r_suared <- summary(lm(aux_m$residuals^2 ~ fitted(aux_m) + I(fitted(aux_m)^2)))$r.squared
white_stat_b <- length(new_y) * aux_r_suared
# compute p-value
if(abs(white_stat_b) >= abs(wt$w_stat)) {
bcount <- bcount + 1
}
wsb[i] <- white_stat_b
}
output <-
structure(
list(
w_stat = round(wt$w_stat, 2),
p_value = bcount/1000,
iters = bootstraps
),
class = "white_test"
)
output
}
#' @export
print.white_test <- function(x, ...) {
if(length(x) == 2) {
cat("White's test results\n",
paste0("Null hypothesis: Homoskedasticity of the residuals"),
paste0("Alternative hypothesis: Heteroskedasticity of the residuals"),
paste0("Test Statistic: ", round(x$w_stat, 2)),
paste0("P-value: ", round(x$p_value, 6)),
sep = "\n")
} else {
# x$w_stat <- ifelse(length(x$w_stat) <= 10,
# paste0(round(x$w_stat, 2), collapse = ", "),
# paste0(paste0(round(x$w_stat[1:10], 2), collapse = ", "), ",..."))
cat("Bootstrapped White's test results\n",
paste0("Null hypothesis: Homoskedasticity of the residuals"),
paste0("Alternative hypothesis: Heteroskedasticity of the residuals"),
paste0("Number of bootstrap samples: ", x$iters),
paste0("Bootstrapped Test Statistic: ", x$w_stat),
paste0("P-value: ", round(x$p_value, 6)),
sep = "\n")
}
}
|
/scratch/gouwar.j/cran-all/cranData/whitestrap/R/white_test.R
|
.onAttach <- function(libname, pkgname) {
packageStartupMessage("\nPlease cite as: \n")
packageStartupMessage("Lopez, J. (2020), White's test and Bootstrapped White's test under the methodology of Jeong, J., Lee, K. (1999) package version 0.0.1")
}
|
/scratch/gouwar.j/cran-all/cranData/whitestrap/R/zzz.R
|
#' Get Current Conditions
#'
#' @return a \code{tibble} with current conditions and attributes from USGS dashboard.
#'
#' @note The time zone used in the URL call is the R session time zone. Also, the time is 1-hour behind.
#' Here are the attributes that are with the data.frame: AgencyCode,SiteNumber,SiteName,SiteTypeCode,Latitude,Longitude,
#' CurrentConditionID,ParameterCode,TimeLocal,TimeZoneCode,Value,
#' ValueFlagCode,RateOfChangeUnitPerHour,StatisticStatusCode,FloodStageStatusCode.
#' @export
#'
#' @examples \dontrun{
#'
#' current_conditions <- ww_current_conditions()
#'
#' }
#'
ww_current_conditions <- function(){
user_date <- lubridate::as_date(Sys.time())
user_time <- format(Sys.time()-3600, "%H:%M:%S")
ids <- paste0("https://dashboard.waterdata.usgs.gov/service/cwis/1.0/odata/CurrentConditions?$top=15000&$filter=(UpdatedUtc%20gt%20",
user_date,"T",user_time,".190Z)%20and%20(AccessLevelCode%20eq%20%27P%27)%20and%20(1%20eq%201%20and%20true)%20and%20(SiteTypeCode%20in%20(%27ST%27,%27ST-TS%27,%27ST-CA%27,%27ST-DCH%27))%20and%20(ParameterCode%20in%20(%2730208%27,%2730209%27,%2750042%27,%2750050%27,%2750051%27,%2772137%27,%2772138%27,%2772139%27,%2772177%27,%2772243%27,%2774072%27,%2781395%27,%2799060%27,%2799061%27,%2700056%27,%2700058%27,%2700059%27,%2700060%27,%2700061%27))&$select=AgencyCode,SiteNumber,SiteName,SiteTypeCode,Latitude,Longitude,CurrentConditionID,ParameterCode,TimeLocal,TimeZoneCode,Value,ValueFlagCode,RateOfChangeUnitPerHour,StatisticStatusCode,FloodStageStatusCode&$orderby=SiteNumber,AgencyCode,ParameterCode,TimeLocal%20desc&caller=National%20Water%20Dashboard%20default")
error_ids <- httr::GET(url = ids,
httr::write_disk(path = file.path(tempdir(),
"nld_tmp.json"),overwrite = TRUE))
status_current <- jsonlite::fromJSON(file.path(tempdir(),"nld_tmp.json"))$value %>%
tibble()
status_current <- status_current %>%
dplyr::mutate(
StatisticsStatusDescription = dplyr::case_when(
StatisticStatusCode == "P0" ~'All-time low for this day',
StatisticStatusCode == "P0_10"~"Much below normal",
StatisticStatusCode == "P10_25"~"Below normal",
StatisticStatusCode == "P25_75"~"Normal",
StatisticStatusCode == "P75_90"~"Above normal",
StatisticStatusCode == "P90_100"~"Much above normal",
StatisticStatusCode == "P100" ~ 'All-time high for this day',
StatisticStatusCode == "NR_0FLOW"~"Not flowing",
StatisticStatusCode == "NR_REVFLOW"~"Not ranked",
StatisticStatusCode == "NR_NOMEAS"~"Measurement flag",
!is.na(ValueFlagCode) & is.na(StatisticStatusCode) ~ "Measurement flag",
TRUE~"Not ranked"
),
StatisticsStatusDescription = factor(StatisticsStatusDescription,
levels = c("Not ranked",
"Measurement flag",
"Not flowing",
"All-time low for this day",
"Much below normal",
"Below normal",
"Normal",
"Above normal",
"Much above normal",
"All-time high for this day")),
StatisticsStatusColorFill = dplyr::case_when(
StatisticsStatusDescription == "Not ranked" ~ '#999999',
StatisticsStatusDescription == "Measurement flag" ~ '#989898',
StatisticsStatusDescription == "Not flowing" ~ '#a9a9a9',
StatisticsStatusDescription == "All-time low for this day" ~ "#FF0000",
StatisticsStatusDescription == "Much below normal" ~ "#BB2222",
StatisticsStatusDescription == "Below normal" ~ "#FFAA00",
StatisticsStatusDescription == "Normal" ~ "#00ff00",
StatisticsStatusDescription == "Above normal" ~ "#44dddd",
StatisticsStatusDescription == "Much above normal" ~ "#0000FF",
StatisticsStatusDescription == "All-time high for this day" ~ "#000055",
TRUE ~ NA_character_
),
StatisticsStatusColorStroke = dplyr::case_when(
StatisticsStatusDescription == "Not ranked" ~ '#666666',
StatisticsStatusDescription == "Measurement flag" ~ '#996633',
StatisticsStatusDescription == "Not flowing" ~ '#997700',
StatisticsStatusDescription == "All-time low for this day" ~ "#990000",
StatisticsStatusDescription == "Much below normal" ~ "#661111",
StatisticsStatusDescription == "Below normal" ~ "#996600",
StatisticsStatusDescription == "Normal" ~ "#009900",
StatisticsStatusDescription == "Above normal" ~ "#11aaaa",
StatisticsStatusDescription == "Much above normal" ~ "#000099",
StatisticsStatusDescription == "All-time high for this day" ~ "#000000",
TRUE ~ NA_character_
)
)
}
|
/scratch/gouwar.j/cran-all/cranData/whitewater/R/current_conditions.R
|
#' Process USGS daily values
#' @description This function is a wrapper around \link[dataRetrieval]{readNWISdv} but includes
#' added variables like water year, lat/lon, station name, altitude and tidied dates.
#' @param sites A vector of USGS NWIS sites
#' @param parameter_cd A USGS code for metric, default is "00060".
#' @param start_date A character of date format, e.g. \code{"1990-09-01"}
#' @param end_date A character of date format, e.g. \code{"1990-09-01"}
#' @param stat_cd character USGS statistic code. This is usually 5 digits. Daily mean (00003) is the default.
#' @param parallel \code{logical} indicating whether to use future_map().
#' @param wy_month \code{numeric} indicating the start month of the water year. e.g. 10 (default).
#' @param verbose \code{logical} for printing information. TRUE (default).
#' @param ... arguments to pass on to \link[furrr]{future_map}.
#'
#'
#' @note Use it the same way you would use \link[dataRetrieval]{readNWISdv}.
#' @return A \code{tibble} with daily metrics and added meta-data.
#' @export
#'
#' @examples \dontrun{
#'
#' library(whitewater)
#' yaak_river_dv <- ww_dvUSGS('12304500',
#' parameter_cd = '00060',
#' wy_month = 10)
#'
#' #parallel
#'
#' #get sites
#'
#' huc17_sites <- dataRetrieval::whatNWISdata(huc = 17,
#' siteStatus = 'active',
#' service = 'dv',
#' parameterCd = '00060')
#'
#' library(future)
#' #need to call future::plan()
#' plan(multisession(workers = availableCores()-1))
#'
#' pnw_dv <- ww_dvUSGS(huc17_sites$site_no,
#' parameter_cd = '00060',
#' wy_month = 10,
#' parallel = TRUE)
#'
#' }
#' @importFrom dataRetrieval readNWISdv renameNWISColumns readNWISsite
#' @importFrom dplyr select left_join "%>%"
#' @importFrom purrr safely
ww_dvUSGS <- function(sites,
parameter_cd = "00060",
start_date = "",
end_date = "",
stat_cd = "00003",
parallel = FALSE,
wy_month = 10,
verbose = TRUE,
...) {
if(!is.character(sites)) sites = as.character(sites)
site_id_usgs <- data.frame(sites = sites)
delay <- delay_setup()
if(isTRUE(parallel)){
usgs_raw_dv <- site_id_usgs %>%
split(.$sites) %>%
furrr::future_map(purrr::safely(~prepping_USGSdv(.$sites,
parameter_cd,
start_date,
end_date,
stat_cd,
verbose,
delay = delay
)),
...) %>%
purrr::keep(~length(.) != 0) %>%
purrr::map(~.x[['result']]) %>%
plyr::rbind.fill()
} else {
usgs_raw_dv <- site_id_usgs %>%
split(.$sites) %>%
purrr::map(purrr::safely(~prepping_USGSdv(.$sites,
parameter_cd,
start_date,
end_date,
stat_cd,
verbose,
delay = 0
))) %>%
purrr::keep(~length(.) != 0) %>%
purrr::map(~.x[['result']]) %>%
plyr::rbind.fill()
}
if(is.null(usgs_raw_dv)){usethis::ui_stop("site query ran into an error: please check parameters or stat code...")}
leap_years <- c(seq(1832,by = 4, length.out = 2000))
usgs_raw_dv <- usgs_raw_dv %>%
dt_to_tibble() %>%
mutate(Date = lubridate::as_date(Date),
year = year(Date),
month = month(Date),
day = day(Date),
doy=lubridate::yday(Date),
wy_doy = ifelse(!(year %in% leap_years),ifelse(doy >= month_to_doy(wy_month, leap = F),
doy-month_to_doy(wy_month, leap = F)+1,
(365-month_to_doy(wy_month, leap = F)+1+doy)),
ifelse(doy >= month_to_doy(wy_month, leap = T),
doy-month_to_doy(wy_month, leap = T)+1,
(366-month_to_doy(wy_month, leap = T)+1+doy))),
month_day = str_c(month, day, sep = "-"),
wy = waterYear(Date, wy_month, TRUE),
month_abb = factor(month.abb[month], levels = month.abb),
month_day = str_c(month, day, sep = "-"),
drainage_area = drainage_area*0.621371) %>%
add_date_counts()
attr(usgs_raw_dv, 'wy_month') <- wy_month
attr(usgs_raw_dv, 'parameter_cd') <- parameter_cd
attr(usgs_raw_dv, 'stat_cd') <- stat_cd
attr(usgs_raw_dv, 'parameter_cd_names') <- cols_to_update(usgs_raw_dv)
usgs_raw_dv %>%
dplyr::relocate(Station, site_no, drainage_area,
lat, long, altitude,dplyr::everything())
}
#' Prep USGS daily
#'
#' @param site_no A NWIS site number.
#' @param parameter_cd A USGS code for metric, default is "00060".
#' @param start_date A character of date format, e.g. \code{"1990-09-01"}
#' @param end_date A character of date format, e.g. \code{"1990-09-01"}
#' @param stat_cd character USGS statistic code. This is usually 5 digits. Daily mean (00003) is the default.
#' @param verbose logical for printing information.
#' @param delay time to delay in future_call
#' @importFrom crayon red
#' @noRd
#' @return A tidied data frame with gage meta-data.
prepping_USGSdv <- function(site_no, parameter_cd, start_date, end_date, stat_cd, verbose, delay) {
gage_data <- readNWISdv(siteNumbers = site_no,
parameterCd = parameter_cd,
startDate = start_date,
endDate = end_date,
statCd = stat_cd) %>%
dataRetrieval::renameNWISColumns(p70290 = "Chloride")
# could use attr(gage_data, 'siteInfo') but not a big deal IMO
gage_info <- tibble(
site_no = site_no,
drainage_area = readNWISsite(site_no) %>% dplyr::select(drain_area_va) %>% as.numeric(),
Station = readNWISsite(site_no) %>% dplyr::select(station_nm) %>% as.character(),
lat = readNWISsite(site_no) %>% dplyr::select(dec_lat_va) %>% as.numeric(),
long = readNWISsite(site_no) %>% dplyr::select(dec_long_va) %>% as.numeric(),
altitude = readNWISsite(site_no) %>% dplyr::select(alt_va) %>% as.numeric()
)
final_data <- dplyr::left_join(gage_data, gage_info, by = 'site_no')
if(isTRUE(verbose)){
if(nrow(final_data) < 1){
final_data <- NULL
cli::cli_alert('{usethis::ui_field(final_data$Station)} {crayon::red("your request for ")} {usethis::ui_value("daily values")} with stat_cd ({stat_cd}), parameter_cd ({parameter_cd}) and site # ({site_no}) ran into a request error.')
} else {
cols_in_fd <- cols_to_update(final_data)
names_in_params <- name_params_to_update(parameter_cd)
if(length(unique(names_in_params)) != length(cols_in_fd)){
cli::cli_alert_success('{usethis::ui_field(dplyr::slice(final_data, 1)$Station)} {usethis::ui_value("daily")} was successfully downloaded.
{crayon::red("(warning)")} parameter_cd {usethis::ui_value(names_in_params[which(!(names_in_params %in% cols_in_fd))])} returned no data for {usethis::ui_field(dplyr::slice(final_data, 1)$Station)}.')
} else {
cli::cli_alert_success('{usethis::ui_field(dplyr::slice(final_data, 1)$Station)} {usethis::ui_value("daily")} was successfully downloaded.')
}
}}
Sys.sleep(delay)
final_data
}
#' Water Year Stats (USGS)
#' @description This function uses the results of the \link[whitewater]{ww_dvUSGS} object to
#' generate mean, maximum, median, standard deviation and some normalization methods (drainage
#' area, scaled by log and standard deviation) per water year.
#' @param procDV A previously created \link[whitewater]{ww_dvUSGS} object.
#' @param sites A \code{character} vector with NWIS site numbers (optional).
#' @param parallel \code{logical} indicating whether to use future_map().
#' @param verbose \code{logical} for printing information. TRUE (default).
#' @param ... arguments to pass on to \link[furrr]{future_map} and/or \link[whitewater]{ww_dvUSGS}.
#'
#' @note If a previously created \link[whitewater]{ww_dvUSGS} object is not used then the user needs to
#' provide a \code{sites} vector. This will run \link[whitewater]{ww_dvUSGS} in the background.
#' @return A \code{tibble} filtered by water year with added meta-data.
#' @export
#'
#' @examples \dontrun{
#'
#' library(whitewater)
#' yaak_river_dv <- ww_dvUSGS('12304500',
#' parameter_cd = '00060',
#' wy_month = 10)
#'
#' yaak_river_wy <- ww_wyUSGS(yaak_river_dv)
#'
#' #parallel
#'
#' #get sites
#'
#' huc17_sites <- dataRetrieval::whatNWISdata(huc = 17,
#' siteStatus = 'active',
#' service = 'dv',
#' parameterCd = '00060')
#'
#' library(future)
#' #need to call future::plan()
#' plan(multisession(workers = availableCores()-1))
#'
#' pnw_dv <- ww_dvUSGS(huc17_sites$site_no,
#' parameter_cd = '00060',
#' wy_month = 10,
#' parallel = TRUE)
#'
#' pnw_wy <- ww_wyUSGS(pnw_dv,
#' parallel = TRUE)
#' }
#'
#' @importFrom lubridate year month day
#' @importFrom dplyr mutate filter group_by summarise slice_head ungroup everything row_number n
#' @importFrom stringr str_c str_remove_all
#' @importFrom stats median sd
#'
ww_wyUSGS <- function(procDV,
sites = NULL,
parallel = FALSE,
verbose = TRUE,
...) {
if(missing(procDV)) {
if(isTRUE(parallel)){
usgs_raw <- suppressMessages(ww_dvUSGS(sites = sites, parallel = parallel, ...) %>%
pad_zero_for_logging())
} else {
usgs_raw <- suppressMessages(ww_dvUSGS(sites = sites, ...) %>%
pad_zero_for_logging())
}
} else {
usgs_raw <- procDV %>%
pad_zero_for_logging()
}
#summarize by water year with different stats for different params
cols <- cols_to_update(usgs_raw)
suppressWarnings(usgs_min_max_wy <- usgs_raw %>%
group_by(Station,wy,site_no) %>%
summarise(across(dplyr::any_of(cols),
list(
sum = ~sum(.x, na.rm = TRUE),
max = ~max(.x, na.rm = TRUE),
min = ~min(.x, na.rm = TRUE),
mean = ~mean(.x, na.rm = TRUE),
median = ~median(.x, na.rm = TRUE),
stdev = ~sd(.x, na.rm = TRUE),
coef_var = ~sd(.x, na.rm = TRUE)/mean(.x, na.rm = TRUE),
max_dnorm = ~max(.x, na.rm = TRUE)/drainage_area,
min_dnorm = ~min(.x, na.rm = TRUE)/drainage_area,
mean_dnorm = ~mean(.x, na.rm = TRUE)/drainage_area,
med_dnorm = ~median(.x, na.rm = TRUE)/drainage_area,
max_sdnorm = ~log(max(.x, na.rm = TRUE))/sd(log(.x), na.rm = TRUE),
min_sdnorm = ~log(min(.x, na.rm = TRUE))/sd(log(.x), na.rm = TRUE),
mean_sdnorm = ~log(mean(.x, na.rm = TRUE))/sd(log(.x), na.rm = TRUE),
med_sdnorm = ~log(median(.x, na.rm = TRUE))/sd(log(.x), na.rm = TRUE),
sd_norm = ~sd(log(.x), na.rm = TRUE)))) %>%
slice_head(n=1) %>%
ungroup() %>%
dt_to_tibble() %>%
dplyr::left_join(usgs_raw %>%
dplyr::select(
wy,
drainage_area,
lat,
long,
altitude,
site_no,
obs_per_wy) %>%
dplyr::group_by(site_no,wy) %>%
dplyr::slice(1) %>%
dplyr::ungroup(), by = c('site_no', 'wy')) %>%
dplyr::group_by(site_no) %>%
dplyr::add_count(name = 'wy_count') %>%
dplyr::ungroup() %>%
dplyr::relocate(Station, site_no, drainage_area,
lat, long, altitude, obs_per_wy, wy_count, dplyr::everything())
)
if(nrow(usgs_min_max_wy) < 1){
usgs_min_max_wy <- NULL
} else {
if(isTRUE(verbose)){
cli::cli_alert_success('{usethis::ui_value("water year")} was successfully downloaded.')
}
}
if("Flow" %in% cols){
delay <- delay_setup()
wy_month <- attributes(usgs_raw)$wy_month
if(isTRUE(verbose)){
cli::cli_alert('now starting to gather peak flows using dataRetrieval::readNWISpeak')
}
usgs_min_max_wy <- ww_peakUSGSdv(usgs_min_max_wy, parallel = parallel, wy_month = wy_month, verbose = verbose, delay = delay)
}
usgs_min_max_wy
}
#' Get Peak Flows
#'
#' @param sites A vector of USGS NWIS sites
#' @param parallel \code{logical} indicating whether to use future_map().
#' @param wy_month \code{numeric} indicating the start month of the water year. e.g. 10 (default).
#' @param verbose \code{logical} for printing information. TRUE (default).
#' @param ... arguments to pass on to \link[furrr]{future_map}.
#'
#' @return a \code{tibble} with peaks by water year
#' @export
ww_peakUSGS <- function(sites, parallel = FALSE,wy_month = 10,verbose = TRUE, ...) {
peak_sites <- data.frame(peaks = sites)
delay = delay_setup()
if(isTRUE(parallel)){
peaks <- peak_sites %>%
split(.$peaks) %>%
furrr::future_map(purrr::safely(~peaks_USGS(.$peaks,
wy_month = wy_month,
verbose = verbose,
dv = F,
,
delay = delay)), ...) %>%
purrr::keep(~length(.) != 0) %>%
purrr::map(~.x[['result']]) %>%
plyr::rbind.fill()
} else {
peaks <- peak_sites %>%
split(.$peaks) %>%
purrr::map(purrr::safely(~peaks_USGS(.$peaks,
wy_month = wy_month,
verbose = verbose,
dv = F,
delay = 0))) %>%
purrr::keep(~length(.) != 0) %>%
purrr::map(~.x[['result']]) %>%
plyr::rbind.fill()
}
usgs_min_max_wy <- peaks %>%
dt_to_tibble() %>%
dplyr::select(Station, site_no, wy, peak_va, peak_dt, dplyr::everything())
}
#' Water Year & Monthly Stats (USGS)
#'
#' @description This function uses the results of the \link[whitewater]{ww_dvUSGS} object to
#' generate mean, maximum, median, standard deviation and coefficient of variation
#' per water year per month.
#' @param procDV A previously created \link[whitewater]{ww_dvUSGS} object.
#' @param sites A \code{character} vector with NWIS site numbers (optional).
#' @param parallel \code{logical} indicating whether to use future_map().
#' @param verbose \code{logical} for printing information. TRUE (default).
#' @param ... arguments to pass on to \link[furrr]{future_map} and \link[whitewater]{ww_dvUSGS}.
#'
#' @note If a previously created \link[whitewater]{ww_dvUSGS} object is not used then the user needs to
#' provide a \code{sites} vector. This will run \link[whitewater]{ww_dvUSGS} in the background.
#' @return A \code{tibble} filtered by water year and month with added meta-data.
#' @export
#'
#' @examples \dontrun{
#'
#' library(whitewater)
#' yaak_river_dv <- ww_dvUSGS('12304500',
#' parameter_cd = '00060',
#' wy_month = 10)
#'
#' yaak_river_wym <- ww_wymUSGS(yaak_river_dv)
#'
#' }
#'
#' @importFrom dplyr group_by mutate across summarise rename right_join ungroup n
#' @importFrom tidyr pivot_wider
#' @importFrom lubridate parse_date_time ymd
#' @importFrom stringr str_c
#'
ww_wymUSGS <- function(procDV, sites = NULL, parallel = FALSE, verbose = TRUE, ...) {
if(missing(procDV)) {
if(isTRUE(parallel)){
usgs_raw <- ww_dvUSGS(sites = sites, parallel = TRUE, ...)
} else {
usgs_raw <- ww_dvUSGS(sites = sites, parallel = FALSE, ...)
}
} else {usgs_raw <- procDV }
cols <- cols_to_update(usgs_raw)
wy_month <- attributes(usgs_raw)$wy_month
suppressWarnings(final_data <- usgs_raw %>%
group_by(Station, site_no, wy, month_abb, month) %>%
summarise(across(dplyr::any_of(cols),
list(
sum = ~sum(.x, na.rm = TRUE),
max = ~max(.x, na.rm = TRUE),
min = ~min(.x, na.rm = TRUE),
mean = ~mean(.x, na.rm = TRUE),
median = ~median(.x, na.rm = TRUE),
stdev = ~sd(.x, na.rm = TRUE),
coef_var = ~sd(.x, na.rm = TRUE)/mean(.x, na.rm = TRUE)))) %>%
slice_head(n=1) %>%
ungroup() %>%
mutate(wy_month_day = str_c(wy, month,"1", sep = "-"),
wy_month_day = parse_date_time(wy_month_day, orders = c("%y-%m-%d", "%y%m%d", "%y-%m-%d %H:%M")),
wy_month_day = ymd(as.character(wy_month_day)),
doy = dplyr::case_when(month == 1 ~ 1,
month == 2 ~ 32,
month == 3 ~ 60,
month == 4 ~ 91,
month == 5 ~ 122,
month == 6 ~ 152,
month == 7 ~ 182,
month == 8 ~ 213,
month == 9 ~ 244,
month == 10 ~ 274,
month == 11 ~ 305,
month == 12 ~ 335,
TRUE ~ NA_real_),
ifelse(doy >= month_to_doy(wy_month, leap = F),
doy-month_to_doy(wy_month, leap = F)+1,
(365-month_to_doy(wy_month, leap = F)+1+doy))) %>%
dplyr::left_join(usgs_raw %>%
dplyr::select(
wy,
month,
drainage_area,
lat,
long,
altitude,
site_no,
obs_per_wy,
obs_per_month) %>%
dplyr::group_by(site_no, wy, month) %>%
dplyr::slice(1) %>%
dplyr::ungroup(), by = c('site_no', 'wy', 'month')) %>%
dplyr::group_by(site_no, wy) %>%
dplyr::add_count(name = 'wym_count') %>%
dplyr::ungroup() %>%
dplyr::relocate(Station, site_no, wy, wy_month_day, doy, drainage_area,
lat, long, altitude, obs_per_wy,
obs_per_month, wym_count, dplyr::everything())
)
if(nrow(final_data) < 1){
final_data <- NULL
} else {
if(isTRUE(verbose)){
cli::cli_alert_success('{usethis::ui_value("water year and month")} was successfully downloaded.')
}
}
final_data %>%
dplyr::relocate(Station, site_no, drainage_area,
lat, long, altitude,dplyr::everything())
}
#' Month-Only Stats (USGS)
#'
#' @description This function uses the results of the \link[whitewater]{ww_dvUSGS} object to
#' generate mean, maximum, median, standard deviation and coefficient of variation for month only.
#' @param procDV A previously created \link[whitewater]{ww_dvUSGS} object.
#' @param sites A \code{character} vector with NWIS site numbers (optional).
#' @param parallel \code{logical} indicating whether to use future_map().
#' @param verbose \code{logical} for printing information. TRUE (default).
#' @param ... arguments to pass on to \link[furrr]{future_map} and \link[whitewater]{ww_dvUSGS}.
#' @note If a previously created \link[whitewater]{ww_dvUSGS} object is not used then the user needs to
#' provide a \code{sites} vector. This will run \link[whitewater]{ww_dvUSGS} in the background.
#' @return A \code{tibble} filtered by month and added meta-data.
#' @export
#' @examples \dontrun{
#'
#' library(whitewater)
#' yaak_river_dv <- ww_dvUSGS('12304500',
#' parameter_cd = '00060',
#' wy_month = 10)
#'
#' yaak_river_month <- ww_monthUSGS(yaak_river_dv)
#'
#' }
#' @importFrom dplyr group_by summarise mutate relocate
#'
#'
ww_monthUSGS <- function(procDV, sites = NULL, parallel = FALSE, verbose = TRUE, ...) {
if(missing(procDV)) {
if(isTRUE(parallel)){
usgs_raw <- ww_dvUSGS(sites = sites, parallel = TRUE, ...)
} else {
usgs_raw <- ww_dvUSGS(sites = sites, parallel = FALSE, ...)
}
} else {
usgs_raw <- procDV }
cols <- cols_to_update(usgs_raw)
suppressWarnings( final_data <- usgs_raw %>%
group_by(Station,site_no, month_abb) %>%
summarise(across(dplyr::any_of(cols),
list(
sum = ~sum(.x, na.rm = TRUE),
max = ~max(.x, na.rm = TRUE),
min = ~min(.x, na.rm = TRUE),
mean = ~mean(.x, na.rm = TRUE),
median = ~median(.x, na.rm = TRUE),
stdev = ~sd(.x, na.rm = TRUE),
coef_var = ~sd(.x, na.rm = TRUE)/mean(.x, na.rm = TRUE)))) %>%
ungroup()%>%
dplyr::left_join(usgs_raw %>%
dplyr::select(
drainage_area,
lat,
long,
altitude,
site_no,
month_abb) %>%
dplyr::group_by(site_no, month_abb) %>%
dplyr::slice(1) %>%
dplyr::ungroup(), by = c('site_no', 'month_abb')))
if(nrow(final_data) < 1){
final_data <- NULL
} else {
if(isTRUE(verbose)){
cli::cli_alert_success('{usethis::ui_value("monthly")} data was successfully downloaded.')
}
}
final_data %>%
dplyr::relocate(Station, site_no, drainage_area,
lat, long, altitude,dplyr::everything())
}
#' Floor IV USGS
#' @description This function generates instantaneous NWIS data from \url{https://waterservices.usgs.gov/}
#' and then floors to a user defined interval with \link[whitewater]{wwOptions}
#' ('1 hour' is default) by taking the mean.
#' @param procDV A previously created \link[whitewater]{ww_dvUSGS} object.
#' @param sites A \code{vector} of USGS NWIS sites (optional).
#' @param parameter_cd A USGS code parameter code, only if using \code{sites} argument.
#' @param options A \link[whitewater]{wwOptions} call.
#' @param parallel \code{logical} indicating whether to use future_map().
#' @param verbose \code{logical} for printing information. TRUE (default).
#' @param ... arguments to pass on to \link[furrr]{future_map}.
#'
#'
#' @note For performance reasons, with multi-site retrievals you may
#' retrieve data since October 1, 2007 only. If a previously created \link[whitewater]{ww_dvUSGS} object is not used then the user needs to
#' provide a \code{sites} vector. This will run \link[whitewater]{ww_dvUSGS} in the background.
#' @return A \code{tibble} with a user defined interval time step.
#' @examples \dontrun{
#'
#' library(whitewater)
#' yaak_river_dv <- ww_dvUSGS('12304500',
#' parameter_cd = '00060',
#' wy_month = 10)
#'
#' yaak_river_iv <- ww_floorIVUSGS(yaak_river_dv)
#'
#' #change floor method
#'
#' yaak_river_iv <- ww_floorIVUSGS(yaak_river_dv,
#' options = wwOptions(floor_iv = '6-hour'))
#'
#' #change number of days
#'
#' yaak_river_iv <- ww_floorIVUSGS(yaak_river_dv,
#' options = wwOptions(floor_iv = '2-hour',
#' period = 365))
#'
#' # get by date range
#'
#'
#' yaak_river_wy <- ww_floorIVUSGS(yaak_river_dv,
#' options = wwOptions(date_range = 'date_range',
#' dates = c('2022-03-01', '2022-05-11')))
#'
#' #parallel
#'
#' #get sites
#'
#' huc17_sites <- dataRetrieval::whatNWISdata(huc = 17,
#' siteStatus = 'active',
#' service = 'dv',
#' parameterCd = '00060')
#'
#' library(future)
#' #need to call future::plan()
#' plan(multisession(workers = availableCores()-1))
#'
#' pnw_dv <- ww_dvUSGS(huc17_sites$site_no,
#' parameter_cd = '00060',
#' wy_month = 10,
#' parallel = TRUE)
#'
#' pnw_iv <- ww_floorIVUSGS(pnw_dv,
#' parallel = TRUE)
#' }
#' @export
#' @importFrom lubridate ymd_hm floor_date
#' @importFrom dplyr mutate rename rename_with group_by mutate relocate summarise ungroup contains
#' @importFrom dataRetrieval renameNWISColumns readNWISsite setAccess
#' @importFrom httr GET write_disk http_error
#'
ww_floorIVUSGS <- function(procDV,
sites = NULL,
parameter_cd = NULL,
options = wwOptions(),
parallel = FALSE,
verbose = TRUE,
...) {
if(!is.null(sites) & !missing(procDV)){stop("Can't use both Sites and procDV")}
if(is.null(sites) & missing(procDV)){stop("Need at least one argument!")}
#create iteration value
site_station_days <- prepping_reports(procDV, sites, parameter_cd, options)
cols <- site_station_days$cols$cols
#run over api, pulling necessary data.
delay <- delay_setup()
if(isTRUE(parallel)){
usgs_download_hourly <- site_station_days %>%
split(.$sites) %>%
furrr::future_map(safely(~iv_USGS(., options = .$options[[1]],
type = 'hour', verbose = verbose,
delay = delay)), ...) %>%
purrr::keep(~length(.) != 0) %>%
purrr::map(~.x[['result']]) %>%
purrr::map(~rename_with(., ~gsub(".*_","", .x),
dplyr::ends_with(paste0('_', cols)))) %>%
plyr::rbind.fill()
} else {
usgs_download_hourly <- site_station_days %>%
split(.$sites) %>%
purrr::map(safely(~iv_USGS(., options = .$options[[1]],
type = 'hour', verbose = verbose,
delay = 0)))%>%
purrr::keep(~length(.) != 0) %>%
purrr::map(~.x[['result']]) %>%
purrr::map(~rename_with(., ~gsub(".*_","", .x),
dplyr::ends_with(paste0('_', cols)))) %>%
plyr::rbind.fill()
}
#final step: clean up data
usgs_download_hourly <- usgs_download_hourly %>%
dt_to_tibble() %>%
mutate(date = ymd_hm(datetime))
suppressWarnings(usgs_download_hourly <- usgs_download_hourly %>%
mutate(date=floor_date(date, options[['floor_iv']])) %>%
mutate(across(dplyr::any_of(cols), readr::parse_number)) %>%
group_by(Station, site_no,param_type, date) %>%
dplyr::summarise(across(dplyr::any_of(cols),
~mean(.x, na.rm = TRUE))) %>%
ungroup()) %>%
dplyr::mutate_all(~ifelse(is.nan(.), NA_real_, .))
# usgs_download_hourly <- usgs_download_hourly %>%
# tidyr::pivot_wider(names_from = param_type, values_from = dplyr::any_of(cols)) %>%
# dplyr::select_if(all_na) %>%
# dplyr::rename_with(~name_params_to_update(.x), dplyr::contains('param'))
usgs_download_hourly <- usgs_download_hourly %>% dplyr::filter(!is.na(date))
}
#' Instantaneous USGS
#' @description This function generates Instantaneous NWIS data from
#' \url{https://waterservices.usgs.gov/}.
#' @param procDV A previously created \link[whitewater]{ww_dvUSGS} object.
#' @param sites A \code{vector} of USGS NWIS sites. \code{optional}
#' @param parameter_cd A USGS code parameter code, only if using \code{sites} argument.
#' @param options A \link[whitewater]{wwOptions} call.
#' @param parallel \code{logical} indicating whether to use future_map().
#' @param verbose \code{logical} for printing information. TRUE (default).
#' @param ... arguments to pass on to \link[furrr]{future_map}.
#'
#' @note For performance reasons, with multi-site retrievals you may
#' retrieve data since October 1, 2007 only. If a previously created \link[whitewater]{ww_dvUSGS} object is not used then the user needs to
#' provide a \code{sites} vector. This will run \link[whitewater]{ww_dvUSGS} in the background.
#' @return A \code{tibble} with instantaneous values.
#' @export
#'
#' @examples \dontrun{
#'
#' library(whitewater)
#' yaak_river_dv <- ww_dvUSGS('12304500',
#' parameter_cd = '00060',
#' wy_month = 10)
#'
#' yaak_river_iv <- ww_instantaneousUSGS(yaak_river_dv)
#'
#' #change number of days
#'
#' yaak_river_iv <- ww_instantaneousUSGS(yaak_river_dv,
#' options = wwOptions(period = 365))
#'
#' # get by date range
#'
#' yaak_river_wy <- ww_instantaneousUSGS(yaak_river_dv,
#' options = wwOptions(date_range = 'date_range',
#' dates = c('2022-03-01', '2022-05-11')))
#'
#' # get most recent
#'
#' yaak_river_wy <- ww_instantaneousUSGS(yaak_river_dv,
#' options = wwOptions(date_range = 'recent'))
#'
#' #parallel
#'
#' #get sites
#'
#' huc17_sites <- dataRetrieval::whatNWISdata(huc = 17,
#' siteStatus = 'active',
#' service = 'dv',
#' parameterCd = '00060')
#'
#' library(future)
#' #need to call future::plan()
#' plan(multisession(workers = availableCores()-1))
#'
#' pnw_dv <- ww_dvUSGS(huc17_sites$site_no,
#' parameter_cd = '00060',
#' wy_month = 10,
#' parallel = TRUE)
#'
#' pnw_iv <- ww_instantaneousUSGS(pnw_dv,
#' parallel = TRUE)
#' }
#'
#' @importFrom lubridate ymd_hm floor_date
#' @importFrom dplyr mutate rename rename_with group_by mutate relocate summarise ungroup contains
#' @importFrom dataRetrieval renameNWISColumns readNWISsite
#' @importFrom httr GET write_disk http_error
#'
ww_instantaneousUSGS <- function(procDV,
sites = NULL,
parameter_cd = NULL,
options = wwOptions(),
parallel = FALSE,
verbose = TRUE,
...) {
if(!is.null(sites) & !missing(procDV)){stop("Can't use both Sites and procDV")}
if(is.null(sites) & missing(procDV)){stop("Need at least one argument!")}
#create iteration value
site_station_days <- prepping_reports(procDV, sites, parameter_cd, options)
cols <- site_station_days$cols$cols
#run over api, pulling necessary data.
delay <- delay_setup()
if(isTRUE(parallel)){
usgs_download_inst <- site_station_days %>%
split(.$sites) %>%
furrr::future_map(safely(~iv_USGS(., options = .$options[[1]],
type = 'inst', verbose = verbose,
delay = delay)),...) %>%
purrr::keep(~length(.) != 0) %>%
purrr::map(~.x[['result']])%>%
purrr::map(~rename_with(., ~gsub(".*_","", .x),
dplyr::ends_with(paste0('_', cols)))) %>%
plyr::rbind.fill()
} else {
usgs_download_inst <- site_station_days %>%
split(.$sites) %>%
purrr::map(safely(~iv_USGS(., options = .$options[[1]],
type = 'inst', verbose = verbose,
delay = 0)))%>%
purrr::keep(~length(.) != 0) %>%
purrr::map(~.x[['result']]) %>%
purrr::map(~rename_with(., ~gsub(".*_","", .x),
dplyr::ends_with(paste0('_', cols)))) %>%
plyr::rbind.fill()
}
#final step: clean up data
usgs_download_inst <- usgs_download_inst %>%
dt_to_tibble()
suppressWarnings(usgs_download_inst <- usgs_download_inst %>%
mutate(across(dplyr::any_of(cols), iv_error_codes, .names = "{.col}_error")) %>%
mutate(across(dplyr::any_of(cols), readr::parse_number)) %>%
select(Station, site_no,param_type,date = 'datetime', dplyr::any_of(cols), dplyr::ends_with("_error")))
# usgs_download_inst <- usgs_download_inst %>%
# tidyr::pivot_wider(names_from = param_type, values_from = dplyr::any_of(cols)) %>%
# dplyr::select_if(all_na) %>%
# dplyr::rename_with(~name_params_to_update(.x), dplyr::contains('param'))
usgs_download_inst <- usgs_download_inst %>%
dplyr::filter(!is.na(date)) %>%
dplyr::mutate_all(~ifelse(is.nan(.), NA_real_, .)) %>%
mutate(date = lubridate::ymd_hm(as.character(date, "%Y-%m-%d %H:%M")))
}
#' Prep USGS Instantaneous
#'
#' @param data the original data.frame
#' @param options a list of API arguments
#' @param type character of API call
#' @param verbose logical for printing information
#' @param delay time to delay in future_call
#'
#' @noRd
#' @return A data.frame with instantaneous values
#'
iv_USGS <- function(data, options, type, verbose, delay){
df_final <- data.frame()
for(i in data$params[[1]]){
# download csv
base_url <- switch(options$date_range,
'pfn' = paste0(
"https://waterservices.usgs.gov/nwis/iv/?format=rdb&sites=",
data$sites,
"&period=P",options$period,"D¶meterCd=", i, "&siteStatus=", options$site_status
),
'date_range' = paste0(
"https://waterservices.usgs.gov/nwis/iv/?format=rdb&sites=",
data$sites,
"&startDT=",options$dates[[1]],"T00:00-0000&endDT=",options$dates[[2]],"T00:00-0000",
"¶meterCd=", i, "&siteStatus=", options$site_status
),
"recent" = paste0(
"https://waterservices.usgs.gov/nwis/iv/?format=rdb&sites=",
data$sites,
"¶meterCd=", i, "&siteStatus=", options$site_status
)
)
# try to download the data
error <- httr::GET(url = base_url,
httr::write_disk(path = file.path(tempdir(),
"usgs_tmp.csv"),
overwrite = TRUE))
# read RDB file to R
df <- utils::read.table(file.path(tempdir(),"usgs_tmp.csv"),
header = TRUE,
sep = "\t",
stringsAsFactors = FALSE)
#remove excess data
df <- df[-1,]
df <- df %>% dplyr::mutate(dplyr::across(contains(c('agency_cd', 'site_no', 'datetime')), ~dplyr::na_if(.,"")))
df <- renameNWISColumns(df) %>%
select(site_no, datetime, dplyr::contains(data$cols[[1]]))
#add metadata
df <- df %>%
mutate(Station = paste0(data$station),
param_type = paste0('param_',i)) %>%
relocate(Station)
df_final <- plyr::rbind.fill(df_final, df)
}
if(isTRUE(verbose)){
if(all(is.na(df_final[,c('site_no', 'datetime')]))){
cli::cli_alert_warning('{usethis::ui_field({data$station})} ran into an error (no data for user input).')
} else {
final_data_logic <- df_final %>%
dplyr::group_by(param_type) %>%
dplyr::summarise(dplyr::across(c('site_no'), ~all(is.na(.))))
param_names <- name_params_to_update(final_data_logic[which(final_data_logic['site_no']$site_no == TRUE),]$param_type)
if(purrr::is_empty(param_names)){
if(type == 'inst'){
cli::cli_alert_success('{usethis::ui_field(dplyr::slice(df_final, 1)$Station)} {usethis::ui_value("instantaneous values")} were successfully downloaded.')
} else if (type == 'hour'){
cli::cli_alert_success('{usethis::ui_field(dplyr::slice(df_final, 1)$Station)} {usethis::ui_value("floored values")} were successfully downloaded.')
}
} else {
if(type == 'inst'){
cli::cli_alert_success('{usethis::ui_field(dplyr::slice(df_final, 1)$Station)} {usethis::ui_value("instantaneous values")} were successfully downloaded.
{crayon::red("(warning)")} Parameter(s) {usethis::ui_value(param_names)} returned no data.')
} else if (type == 'hour'){
cli::cli_alert_success('{usethis::ui_field(dplyr::slice(df_final, 1)$Station)} {usethis::ui_value("floored values")} were successfully downloaded.
{crayon::red("(warning)")} Parameter(s) {usethis::ui_value(param_names)} returned no data.')
}
}
}
}
Sys.sleep(delay)
df_final
}
#' Prepping Peaks
#'
#' @param site_no A \code{character} USGS NWIS site.
#' @param wy_month a water year to filter by
#' @param verbose \code{logical} for printing information. TRUE (default).
#' @param dv internal logical
#' @param delay time to delay in future_call
#'
#' @return a data.frame with instantaneous peaks from USGS
#' @noRd
peaks_USGS <- function(site_no, wy_month, verbose, dv = TRUE, delay){
final_data <- dataRetrieval::readNWISpeak(site_no)%>% select(peak_va, peak_dt, site_no) %>%
mutate(wy = waterYear(peak_dt, wy_month, TRUE))
if(!isTRUE(dv)){
gage_info <- tibble(
site_no = site_no,
drainage_area = readNWISsite(site_no) %>% select(drain_area_va) %>% as.numeric(),
Station = readNWISsite(site_no) %>% select(station_nm) %>% as.character(),
lat = readNWISsite(site_no) %>% select(dec_lat_va) %>% as.numeric(),
long = readNWISsite(site_no) %>% select(dec_long_va) %>% as.numeric(),
altitude = readNWISsite(site_no) %>% select(alt_va) %>% as.numeric()
)
final_data <- dplyr::left_join(final_data, gage_info, by = c('site_no'))
}
if(isTRUE(verbose)){
if(nrow(final_data) < 1){
cli::cli_alert_warning('{usethis::ui_field(dplyr::slice(final_data, 1)$site_no)} ran into an error.')
} else {
cli::cli_alert_success('{usethis::ui_field(dplyr::slice(final_data, 1)$site_no)} {usethis::ui_value("peak flows")} were successfully downloaded.')
}
}
Sys.sleep(delay)
final_data
}
#' Get Peak Flows
#'
#' @param data data.frame
#' @param parallel whether to use future_map or not
#' @param wy_month a water year to filter by
#' @param verbose \code{logical} for printing information. TRUE (default).
#' @param delay time to delay in future_call
#' @param ... other stuff to pass to future_map
#'
#' @return a \code{tibble} with peaks by water year
#' @noRd
ww_peakUSGSdv <- function(data, parallel,wy_month,verbose,delay, ...) {
peak_sites <- data.frame(peaks = unique(data$site_no))
if(isTRUE(parallel)){
peaks <- peak_sites %>%
split(.$peaks) %>%
furrr::future_map(purrr::safely(~peaks_USGS(.$peaks,
wy_month = wy_month,
verbose = verbose,
delay = delay)), ...) %>%
purrr::keep(~length(.) != 0) %>%
purrr::map(~.x[['result']]) %>%
plyr::rbind.fill()
} else {
peaks <- peak_sites %>%
split(.$peaks) %>%
purrr::map(purrr::safely(~peaks_USGS(.$peaks,
wy_month = wy_month,
verbose = verbose,
delay = 0))) %>%
purrr::keep(~length(.) != 0) %>%
purrr::map(~.x[['result']]) %>%
plyr::rbind.fill()
}
usgs_min_max_wy <- data %>%
dt_to_tibble() %>%
dplyr::left_join(peaks, by = c("site_no", "wy")) %>%
dplyr::select(Station, site_no, wy, peak_va, peak_dt, dplyr::everything())
}
|
/scratch/gouwar.j/cran-all/cranData/whitewater/R/download_USGS.R
|
utils::globalVariables(c(".", "Base-flow", "Date", "Flow", "Maximum", "Mean",
"Median", "Minimum", "Percentile", "Standard_Deviation",
"Station", "Total", "Flow", "aes", "alt_va", "annotation_logticks",
"atmf", "bflow", "bflowsum", "datetime", "day_nu", "dec_lat_va",
"dec_long_va", "drain_area_va", "drainage_area", "drainage_area_cut",
"fl_val", "flow", "flow_sum", "left_join", "m_d", "mean_va",
"month_abb", "month_day", "month_nu", "name", "pct", "peak_dt",
"peak_va", "quantile", "safely", "scale_x_continuous",
"scale_y_log10", "season", "site_name", "site_no",
"snow_depth", "snow_water_equivalent", "station_nm",
"value", "value1", "wy", "year_month", "year_nu",
"Total Flow", "param_type", "endDate", "lat", "long",
"altitude", "obs_per_wy", "wy_count", "obs_per_month",
"doy", "wy_month_day", "wym_count", "parameter_cd",
"StatisticsStatusDescription", 'pnw_wy')
)
|
/scratch/gouwar.j/cran-all/cranData/whitewater/R/globals.R
|
#' A subset of USGS stations in HUC 17
#'
#' @format A data frame with 18934 rows and 30 variables:
#' \describe{
#' \item{Station}{name of USGS station}
#' \item{site_no}{station site id number}
#' \item{wy}{water year}
#' \item{peak_va}{peak flow value}
#' \item{peak_dt}{peak flow date}
#' \item{drainage_area}{drainage area in sq.miles}
#' \item{lat}{latitude}
#' \item{long}{longitude}
#' \item{altitude}{altitude in meters}
#' \item{obs_per_wy}{observations per water year per site}
#' \item{wy_count}{water year count per site}
#' \item{Flow_sum}{Sum of Flow}
#' \item{Flow_max}{Maximum of Flow}
#' \item{Flow_min}{Minimum of Flow}
#' \item{Flow_mean}{Mean of Flow}
#' \item{Flow_median}{Median of Flow}
#' \item{Flow_stdev}{Standard Deviation of Flow}
#' \item{Flow_coef_var}{Coeffiecient of Variation of Flow}
#' \item{Flow_max_dnorm}{Maximum of Flow normalized by drainage area}
#' \item{Flow_min_dnorm}{Minimum of Flow normalized by drainage area}
#' \item{Flow_mean_dnorm}{Mean of Flow normalized by drainage area}
#' \item{Flow_med_dnorm}{Median of Flow normalized by drainage area}
#' \item{Flow_max_sdnorm}{Maximum of Flow normalized by drainage area}
#' \item{Flow_min_sdnorm}{Minimum of Flow normalized by standard deviation}
#' \item{Flow_mean_sdnorm}{Mean of Flow normalized by standard deviation}
#' \item{Flow_med_sdnorm}{Median of Flow normalized by standard deviation}
#' \item{Flow_sd_norm}{Standard Deviation of Flow normalized by standard deviation}
#' \item{decade}{decade}
#' \item{COMID}{comid of site}
#' \item{DamIndex}{dam index}
#' }
#' @return a tibble
"pnw_wy"
|
/scratch/gouwar.j/cran-all/cranData/whitewater/R/pnw_wy.R
|
#' USGS stats
#' @description This function uses the \link[dataRetrieval]{readNWISstat} to gather daily, monthly or yearly
#' percentiles.
#' @param procDV A previously created \link[whitewater]{ww_dvUSGS} object.
#' @param sites A \code{character} USGS NWIS site.
#' @param temporalFilter A \code{character} for the stat summary window, e.g. 'daily' (default), 'monthly', 'yearly'.
#' @param parameter_cd A USGS code parameter code, only if using \code{sites} argument.
#' @param days A \code{numeric} input of days to go back from today (only needed if using .temporalFilter = 'daily').
#' @param parallel \code{logical} indicating whether to use future_map().
#' @param verbose \code{logical} for printing information. TRUE (default).
#' @param ... arguments to pass on to \link[furrr]{future_map}.
#'
#' @note Be aware, the parameter values ('Flow', 'Wtemp', etc) are calculated from the \link[whitewater]{ww_floorIVUSGS}
#' function by taking the daily mean of the hourly data. Thus, the instantaneous values will look different than the daily mean values, as it should.
#' The \code{.temporalFilter} argument is used to generate the window of percentiles.
#' @return a tibble with associated site statistics.
#' @importFrom dataRetrieval readNWISstat
#' @importFrom lubridate mday
#' @importFrom dplyr tibble
#' @export
#' @examples \dontrun{
#' # get by date range
#'
#' yaak_river_dv <- ww_dvUSGS('12304500')
#'
#' #daily
#' yaak_river_stats <- ww_statsUSGS(yaak_river_dv,
#' temporalFilter = 'daily',
#' days = 10)
#' #monthly
#' yaak_river_stats <- ww_statsUSGS(yaak_river_dv,
#' temporalFilter = 'monthly',
#' days = 10)
#' #yearly
#' yaak_river_stats <- ww_statsUSGS(yaak_river_dv,
#' temporalFilter = 'yearly',
#' days = 10)
#'}
ww_statsUSGS <- function(procDV,
sites = NULL,
temporalFilter = 'daily',
parameter_cd = NULL,
days = 10,
parallel = FALSE,
verbose = TRUE,
...) {
switch(temporalFilter,
'daily' = ww_reportUSGSdv(procDV = procDV,
sites = sites,
parameter_cd = parameter_cd,
days = days,
parallel = parallel,
verbose = verbose,
...),
'monthly' = ww_reportUSGSmv(procDV = procDV,
sites = sites,
parameter_cd = parameter_cd,
parallel = parallel,
verbose = verbose,
...),
'yearly' = ww_reportUSGSav(procDV = procDV,
sites = sites,
parameter_cd = parameter_cd,
parallel = parallel,
verbose = verbose,
...))
}
#' USGS Report Daily
#' @description This function uses the \link[dataRetrieval]{readNWISstat} to gather daily
#' statistics like quantiles/percentiles. Be aware, the parameter values ('Flow', 'Wtemp', etc) are calculated from the \link[whitewater]{ww_floorIVUSGS}
#' function by taking the daily mean of the hourly data. Thus, the instantaneous values will look different than the daily mean values, as it should.
#' @param procDV A previously created \link[whitewater]{ww_dvUSGS} object.
#' @param sites A \code{character} USGS NWIS site.
#' @param parameter_cd A USGS code parameter code, only if using \code{sites} argument.
#' @param days A \code{numeric} input of days.
#' @param parallel \code{logical} indicating whether to use future_map().
#' @param verbose \code{logical} for printing information. TRUE (default).
#' @param ... arguments to pass on to \link[furrr]{future_map}.
#'
#' @return A \code{tibble} with daily stats.
#' @noRd
#' @importFrom dataRetrieval readNWISstat
#' @importFrom lubridate mday
#' @importFrom dplyr tibble
#'
ww_reportUSGSdv <- function(procDV,
sites = NULL,
parameter_cd = NULL,
days = 10,
parallel = FALSE,
verbose = TRUE,
...) {
if(!is.character(sites)) sites <- as.character(sites)
site_station_days <- prepping_reports(procDV, sites, parameter_cd)
delay <- delay_setup()
#run over api, pulling necessary data.
if(isTRUE(parallel)){
usgs_statsdv <- site_station_days %>%
split(.$sites) %>%
furrr::future_map(safely(~usgs_stats_fun(., type = 'daily',
verbose = verbose,
delay = delay)),...) %>%
purrr::keep(~length(.) != 0) %>%
purrr::map(~.x[['result']]) %>%
plyr::rbind.fill() %>%
dt_to_tibble()
} else {
usgs_statsdv <- site_station_days %>%
split(.$sites) %>%
purrr::map(safely(~usgs_stats_fun(., type = 'daily',
verbose = verbose,
delay = 0))) %>%
purrr::keep(~length(.) != 0) %>%
purrr::map(~.x[['result']]) %>%
plyr::rbind.fill() %>%
dt_to_tibble()
}
#join it with original
final_data <- clean_hourly_dv_report(pp = site_station_days,
data = usgs_statsdv,
days = days,
parallel = parallel)
final_data %>%
group_by(site_no,parameter_cd) %>%
dplyr::mutate(dplyr::across(site_station_days$cols$cols,
~dplyr::case_when(
.x <= min_va ~'All-time low for this day',
.x <= p10_va & .x > min_va ~"Much below normal",
.x > p10_va & .x <= p25_va ~ "Below normal",
.x > p25_va & .x <= p75_va ~"Normal",
.x > p75_va & .x <= p90_va~"Above normal",
.x > p90_va & .x < max_va ~ "Much above normal",
.x >= max_va ~ 'All-time high for this day',
is.na(.x) ~ NA_character_,
TRUE~"Not ranked"
), .names = "{.col}_StatisticsStatusDescription")) %>%
mutate(across(contains("_StatisticsStatusDescription"),
~factor(.x,
levels = c("Not ranked",
"All-time low for this day",
"Much below normal",
"Below normal",
"Normal",
"Above normal",
"Much above normal",
"All-time high for this day")))) %>%
ungroup() %>%
mutate(Date = lubridate::as_date(Date)) %>%
dplyr::relocate(Station, site_no, drainage_area,
lat, long, altitude,dplyr::everything())
}
#' get daily stats
#'
#' @param data data.frame
#' @param type what type of temporal stat to perform
#' @param verbose logical to print information
#' @param delay time to delay in future_call
#'
#' @return a data.frame with daily or monthly stats from readNWISstat
#' @noRd
usgs_stats_fun <- function(data, type, verbose, delay) {
final_data <- switch(type,
'daily' = suppressMessages(dataRetrieval::readNWISstat(data$sites,
parameterCd = data$params[[1]],
statType = 'all',
statReportType = 'daily')) %>%
mutate(
drainage_area = readNWISsite(site_no) %>% select(drain_area_va) %>% as.numeric(),
Station = readNWISsite(site_no) %>% select(station_nm) %>% as.character(),
lat = readNWISsite(site_no) %>% select(dec_lat_va) %>% as.numeric(),
long = readNWISsite(site_no) %>% select(dec_long_va) %>% as.numeric(),
altitude = readNWISsite(site_no) %>% select(alt_va) %>% as.numeric()),
'monthly' = suppressMessages(dataRetrieval::readNWISstat(data$sites,
parameterCd = data$params[[1]],
statType = 'all',
statReportType = 'monthly')) %>%
mutate(
drainage_area = readNWISsite(site_no) %>% select(drain_area_va) %>% as.numeric(),
Station = readNWISsite(site_no) %>% select(station_nm) %>% as.character(),
lat = readNWISsite(site_no) %>% select(dec_lat_va) %>% as.numeric(),
long = readNWISsite(site_no) %>% select(dec_long_va) %>% as.numeric(),
altitude = readNWISsite(site_no) %>% select(alt_va) %>% as.numeric()),
'yearly' = suppressMessages(dataRetrieval::readNWISstat(data$sites,
parameterCd = data$params[[1]],
statType = 'all',
statReportType = 'annual')) %>%
mutate(
drainage_area = readNWISsite(site_no) %>% select(drain_area_va) %>% as.numeric(),
Station = readNWISsite(site_no) %>% select(station_nm) %>% as.character(),
lat = readNWISsite(site_no) %>% select(dec_lat_va) %>% as.numeric(),
long = readNWISsite(site_no) %>% select(dec_long_va) %>% as.numeric(),
altitude = readNWISsite(site_no) %>% select(alt_va) %>% as.numeric()))
if(isTRUE(verbose)){
if(nrow(final_data) < 1){
cli::cli_alert_success('{usethis::ui_field(data$Station)} {usethis::ui_value("no values")} for Temporal Filter ({type}) and parameter_cd ({data$params[[1]]}).')
} else {
if(length(unique(final_data$parameter_cd)) != length(data$params[[1]])){
cli::cli_alert_success('{usethis::ui_field(dplyr::slice(final_data, 1)$Station)} {usethis::ui_value("NWIS Stat")} for Temporal Filter ({type}) was successfully downloaded.
{crayon::red("(warning)")} parameter_cd {data$params[[1]][which(!(data$params[[1]] %in% unique(final_data$parameter_cd)))]} returned no data for {usethis::ui_field(dplyr::slice(final_data, 1)$Station)}.')
} else {
cli::cli_alert_success('{usethis::ui_field(dplyr::slice(final_data, 1)$Station)} {usethis::ui_value("NWIS Stat")} for Temporal Filter ({type}) was successfully downloaded.')
}
}
}
Sys.sleep(delay)
final_data
}
#' clean up hourly report
#'
#' @param pp a parameter names
#' @param data data original
#' @param days number of days back
#' @param ... args to pass to ww_floorIVUSGS
#'
#' @return a data.frame
#' @noRd
#'
clean_hourly_dv_report <- function(pp, data, days, ...) {
cols <- pp$cols[[1]]
u_hour <- suppressMessages(ww_floorIVUSGS(sites = pp$sites,
parameter_cd = pp$params[[1]],
options = wwOptions(period = days),
...))
u_hour <- u_hour %>%
mutate(Date = lubridate::as_date(date),
year = year(Date),
month = month(Date),
day = day(Date),
month_day = str_c(month, day, sep = "-")) %>%
group_by(Station, param_type, month_day, Date) %>%
summarise(across(dplyr::any_of(cols), ~mean(.x, na.rm = TRUE)), .groups = 'drop') %>%
dplyr::rename(parameter_cd = 'param_type') %>%
dplyr::mutate(parameter_cd = stringr::str_remove_all(parameter_cd, "param_"))
u_hour <- u_hour %>% dplyr::mutate_all(~ifelse(is.nan(.), NA_real_, .))
usgs_statsdv <- data %>%
mutate(month_day = str_c(month_nu, day_nu, sep = "-"))
t <- vector()
for(i in 0:days){
time <- lubridate::date(Sys.time()) - i
time <- time %>% paste(month(.), mday(.), sep = "-") %>% stringr::str_remove("...........")
t <- append(t, time)
}
usgs_statsdv <- usgs_statsdv %>% filter(month_day %in% t)
u_hour <- u_hour %>% filter(month_day %in% t)
usgs_statsdv <- usgs_statsdv %>% left_join(u_hour, by = c("Station", "parameter_cd", "month_day"))
}
#' USGS Report Monthly
#' @description Uses \link[dataRetrieval]{readNWISstat} to gather monthly mean flows. Furthermore,
#' monthly quantiles are generated similar to \link[whitewater]{ww_reportUSGSdv}.
#' @param procDV A previously created \link[whitewater]{ww_dvUSGS} object.
#' @param sites A \code{character} USGS NWIS site.
#' @param parameter_cd A USGS code parameter code, only if using \code{sites} argument.
#' @param parallel \code{logical} indicating whether to use future_map().
#' @param verbose \code{logical} for printing information. TRUE (default).
#' @param ... arguments to pass on to \link[furrr]{future_map}.
#' @return A \code{tibble} with monthly stats.
#' @noRd
#' @importFrom dataRetrieval readNWISstat
#' @importFrom dplyr summarize arrange desc
#'
ww_reportUSGSmv <- function(procDV,
sites = NULL,
parameter_cd = NULL,
parallel = FALSE,
verbose = TRUE,
...) {
if(missing(procDV) & is.null(sites))stop("Need at least one argument")
site_station_days <- prepping_reports(procDV, sites, parameter_cd)
delay <- delay_setup()
#run over api, pulling necessary data.
if(isTRUE(parallel)){
usgs_statsmv <- site_station_days %>%
split(.$sites) %>%
furrr::future_map(safely(~usgs_stats_fun(., type = 'monthly', verbose = verbose,delay = delay)),...) %>%
purrr::keep(~length(.) != 0) %>%
purrr::map(~.x[['result']]) %>%
plyr::rbind.fill() %>%
dt_to_tibble()
} else {
usgs_statsmv <- site_station_days %>%
split(.$sites) %>%
purrr::map(safely(~usgs_stats_fun(., type = 'monthly', verbose = verbose, delay = 0))) %>%
purrr::keep(~length(.) != 0) %>%
purrr::map(~.x[['result']]) %>%
plyr::rbind.fill() %>%
dt_to_tibble()
}
summary_stats <- usgs_statsmv %>%
group_by(Station, parameter_cd, month = month_nu) %>%
summarize(p100_va = quantile(mean_va, probs = 1, na.rm = TRUE),
p95_va = quantile(mean_va, probs = .95, na.rm = TRUE),
p90_va = quantile(mean_va, probs = .90, na.rm = TRUE),
p80_va = quantile(mean_va, probs = .80, na.rm = TRUE),
p75_va = quantile(mean_va, probs = .75, na.rm = TRUE),
p50_va = quantile(mean_va, probs = .50, na.rm = TRUE),
p25_va = quantile(mean_va, probs = .25, na.rm = TRUE),
p20_va = quantile(mean_va, probs = .20, na.rm = TRUE),
p10_va = quantile(mean_va, probs = 0.1, na.rm = TRUE),
p05_va = quantile(mean_va, probs = 0.05, na.rm = TRUE),
p0_va = quantile(mean_va, probs = 0, na.rm = TRUE))
usgs_statsmv <- usgs_statsmv %>%
arrange(desc(year_nu)) %>%
rename(month = "month_nu", mean_value = "mean_va") %>%
left_join(summary_stats, by = c("month", "Station", 'parameter_cd')) %>%
dplyr::mutate(date = lubridate::ym(paste(as.character(year_nu),'-', as.character(month)))) %>%
group_by(site_no,parameter_cd) %>%
dplyr::mutate(
StatisticsStatusDescription = dplyr::case_when(
mean_value <= p0_va ~'All-time low for this month',
mean_value <= p10_va & mean_value > p0_va ~"Much below normal",
mean_value > p10_va & mean_value <= p25_va ~ "Below normal",
mean_value > p25_va & mean_value <= p75_va ~"Normal",
mean_value > p75_va & mean_value <= p90_va~"Above normal",
mean_value > p90_va & mean_value < p100_va ~ "Much above normal",
mean_value >= p100_va ~ 'All-time high for this month',
TRUE~"Not ranked"
),
StatisticsStatusDescription = factor(StatisticsStatusDescription,
levels = c("Not ranked",
"All-time low for this month",
"Much below normal",
"Below normal",
"Normal",
"Above normal",
"Much above normal",
"All-time high for this month"))) %>%
ungroup() %>%
dplyr::relocate(Station, site_no, drainage_area,
lat, long, altitude,dplyr::everything())
}
#' USGS Report Annually
#' @description Uses \link[dataRetrieval]{readNWISstat} to gather monthly mean values. Furthermore,
#' monthly quantiles are generated similar to \link[whitewater]{ww_reportUSGSdv}.
#' @param procDV A previously created \link[whitewater]{ww_dvUSGS} object.
#' @param sites A \code{character} USGS NWIS site.
#' @param parameter_cd A USGS code parameter code, only if using \code{sites} argument.
#' @param parallel \code{logical} indicating whether to use future_map().
#' @param verbose \code{logical} for printing information. TRUE (default).
#' @param ... arguments to pass on to \link[furrr]{future_map}.
#'
#' @return A \code{tibble} with annual stats.
#' @noRd
#' @importFrom dataRetrieval readNWISstat
#' @importFrom dplyr summarize arrange desc
#'
ww_reportUSGSav <- function(procDV,
sites = NULL,
parameter_cd = NULL,
parallel = FALSE,
verbose = TRUE,
...) {
if(missing(procDV) & is.null(sites))stop("Need at least one argument")
site_station_days <- prepping_reports(procDV, sites, parameter_cd)
delay <- delay_setup()
#run over api, pulling necessary data.
if(isTRUE(parallel)){
usgs_statsav <- site_station_days %>%
split(.$sites) %>%
furrr::future_map(safely(~usgs_stats_fun(., type = 'yearly', verbose = verbose, delay = delay)),...) %>%
purrr::keep(~length(.) != 0) %>%
purrr::map(~.x[['result']]) %>%
plyr::rbind.fill() %>%
dt_to_tibble()
} else {
usgs_statsav <- site_station_days %>%
split(.$sites) %>%
purrr::map(safely(~usgs_stats_fun(., type = 'yearly', verbose = verbose, delay = 0))) %>%
purrr::keep(~length(.) != 0) %>%
purrr::map(~.x[['result']]) %>%
plyr::rbind.fill() %>%
dt_to_tibble()
}
summary_stats <- usgs_statsav %>%
group_by(Station, parameter_cd) %>%
summarize(p100_va = quantile(mean_va, probs = 1, na.rm = TRUE),
p95_va = quantile(mean_va, probs = .95, na.rm = TRUE),
p90_va = quantile(mean_va, probs = .90, na.rm = TRUE),
p80_va = quantile(mean_va, probs = .80, na.rm = TRUE),
p75_va = quantile(mean_va, probs = .75, na.rm = TRUE),
p50_va = quantile(mean_va, probs = .50, na.rm = TRUE),
p25_va = quantile(mean_va, probs = .25, na.rm = TRUE),
p20_va = quantile(mean_va, probs = .20, na.rm = TRUE),
p10_va = quantile(mean_va, probs = 0.1, na.rm = TRUE),
p05_va = quantile(mean_va, probs = 0.05, na.rm = TRUE),
p0_va = quantile(mean_va, probs = 0, na.rm = TRUE))
usgs_statsav <- usgs_statsav %>%
arrange(desc(year_nu)) %>%
rename(year = "year_nu", mean_value = "mean_va") %>%
left_join(summary_stats, by = c("Station", 'parameter_cd')) %>%
arrange(Station) %>%
group_by(site_no, parameter_cd) %>%
dplyr::mutate(
StatisticsStatusDescription = dplyr::case_when(
mean_value <= p0_va ~'All-time low for this year',
mean_value <= p10_va & mean_value > p0_va ~"Much below normal",
mean_value > p10_va & mean_value <= p25_va ~ "Below normal",
mean_value > p25_va & mean_value <= p75_va ~"Normal",
mean_value > p75_va & mean_value <= p90_va~"Above normal",
mean_value > p90_va & mean_value < p100_va ~ "Much above normal",
mean_value >= p100_va ~ 'All-time high for this year',
TRUE~"Not ranked"
),
StatisticsStatusDescription = factor(StatisticsStatusDescription,
levels = c("Not ranked",
"All-time low for this year",
"Much below normal",
"Below normal",
"Normal",
"Above normal",
"Much above normal",
"All-time high for this year"))) %>%
ungroup() %>%
dplyr::relocate(Station, site_no, drainage_area,
lat, long, altitude,dplyr::everything())
}
#' Prep Reports
#'
#' @param sites A \code{character} USGS NWIS site.
#' @param procDV A previously created \link[whitewater]{ww_dvUSGS} object.
#' @param parameter_cd A USGS code parameter code, only if using \code{sites} argument.
#' @param options A \link[whitewater]{wwOptions} call.
#'
#' @return A prepped tibble with meta data for api call
#' @noRd
prepping_reports <- function(procDV, sites, parameter_cd, options = wwOptions()){
if(is.null(sites)) {sites <- unique(procDV[['site_no']])}
#create iteration value
if(!missing(procDV)){
sites <- unique(procDV$site_no)
station <- unique(procDV$Station)
params <- attr(procDV, 'parameter_cd')
cols <- attr(procDV, 'parameter_cd_names')
} else {
if(is.null(parameter_cd)){usethis::ui_stop('need a parameter_cd')}
if(!is.null(sites) & length(sites) == 1){
sites <- unique(sites)
station <- readNWISsite(sites) %>% select(station_nm) %>% as.character()
}
if(!is.null(sites) & length(sites) > 1) {
sites <- unique(sites)
station <- vector()
for(i in 1:length(sites)){
station_1 <- readNWISsite(sites[[i]]) %>% select(station_nm) %>% as.character()
station <- append(station,station_1)
}
}
params <- parameter_cd
cols <- name_params_to_update(params)
}
#create blank dataframe to store the information in
site_station_days <- tibble(sites = sites,
station = station,
cols = list(cols = cols),
params = list(params = params),
options = list(options))
}
|
/scratch/gouwar.j/cran-all/cranData/whitewater/R/stats.R
|
#'Water Year These functions are hi-jacked from smwrBase package.
#'
#'Create an ordered factor or numeric values from a vector of dates based on
#'the water year.
#' @noRd
#' @param x an object of class "Date" or "POSIXt." Missing values are permitted and
#'result in corresponding missing values in the output.
#' @param wy_month A numeric indicating the month the water year begins.
#' @param numeric a logical value that indicates whether the returned values
#'should be numeric \code{TRUE} or an ordered factor \code{FALSE}. The default
#'value is \code{FALSE}.
#' @return An ordered factor or numeric vector corresponding to the water year.
#' @note The water year is defined as the period from October 1 to September 30.
#'The water year is designated by the calendar year in which it ends. Thus, the
#'year ending September 30, 1999, is the "1999 water year."
#' @seealso
#Flip for production/manual
#'\code{\link[lubridate]{year}}
#\code{year} (in lubridate package)
waterYear <- function(x, wy_month = 10, numeric=FALSE) {
## Coding history:
## 2005Jul14 DLLorenz Initial dated verion
## 2010Feb17 DLLorenz Added option to return numerics
## 2011Jun07 DLLorenz Conversion to R
## 2012Aug11 DLLorenz Integer fixes
## 2013Feb15 DLLorenz Prep for gitHub
##
x <- as.POSIXlt(x)
yr <- x$year + 1900L
mn <- x$mon + 1L
## adjust for water year
yr <- yr + ifelse(mn < as.integer(wy_month), 0L, 1L)
if(numeric)
return(yr)
ordered(yr)
}
#' Convert dt to tibble
#'
#' @param data a data.frame and data.table
#' @noRd
#' @return a tibble df
dt_to_tibble <- function(data) {
class(data) <- 'data.frame'
data <- dplyr::tibble(data)
}
#' all na
#' @description Remove columns with all NA's
#' @param x a data.frame
#' @noRd
all_na <- function(x){
any(!is.na(x))
}
#' Add Counts
#' @description Adds counts of observation per water and month
#'
#' @param data A daily value df
#'
#' @return counts within df
#' @noRd
add_date_counts <- function(data) {
dplyr::group_by(data, site_no, wy) %>%
dplyr::add_count(name = 'obs_per_wy') %>%
dplyr::ungroup() %>%
dplyr::group_by(site_no, wy, month) %>%
dplyr::add_count(name = 'obs_per_month') %>%
dplyr::ungroup()
}
#' water year to months
#' @description Change wy_month to doy.
#' @param wy_month A numeric
#' @param leap Logical
#' @return A numeric value
#' @noRd
month_to_doy <- function(wy_month, leap = FALSE) {
ifelse(isTRUE(leap),
dplyr::case_when(wy_month == 1 ~ 1,
wy_month == 2 ~ 32,
wy_month == 3 ~ 61,
wy_month == 4 ~ 92,
wy_month == 5 ~ 122,
wy_month == 6 ~ 153,
wy_month == 7 ~ 183,
wy_month == 8 ~ 214,
wy_month == 9 ~ 245,
wy_month == 10 ~ 275,
wy_month == 11 ~ 306,
wy_month == 12 ~ 336,
TRUE ~ NA_real_)
,
dplyr::case_when(wy_month == 1 ~ 1,
wy_month == 2 ~ 32,
wy_month == 3 ~ 60,
wy_month == 4 ~ 91,
wy_month == 5 ~ 122,
wy_month == 6 ~ 152,
wy_month == 7 ~ 182,
wy_month == 8 ~ 213,
wy_month == 9 ~ 244,
wy_month == 10 ~ 274,
wy_month == 11 ~ 305,
wy_month == 12 ~ 335,
TRUE ~ NA_real_)
)
}
#' Get param colnames
#'
#' @param data data.frame
#'
#' @return A vector with parameter names in the data.frame
#' @noRd
#'
cols_to_update <- function(data){
param_names <- c("Wtemp","Precip","Flow","GH","SpecCond",
"DO", "pH", "GWL","Turb","WLBLS", "Chloride")
names(data[which(names(data) %in% param_names)])
}
#' Get paramCd names
#'
#' @param x vector of parameter_cd
#' @return A vector of length 1 or n, matching the length of the logical input or output vectors.
#' @noRd
#'
name_params_to_update <- function(x){
param_names <- dplyr::case_when(
x == "00010" ~ "Wtemp",
x == "00045" ~ "Precip",
x == "00060" ~ "Flow",
x == "00065" ~ "GH",
x == "00095" ~ "SpecCond",
x == "00300" ~ "DO",
x == "00400" ~ "pH",
x == "62611" ~ "GWL",
x == "63680" ~ "Turb",
x == "72019" ~ "WLBLS",
x == "70290" ~ "Chloride",
x == "param_00010" ~ "Wtemp",
x == "param_00045" ~ "Precip",
x == "param_00060" ~ "Flow",
x == "param_00065" ~ "GH",
x == "param_00095" ~ "SpecCond",
x == "param_00300" ~ "DO",
x == "param_00400" ~ "pH",
x == "param_62611" ~ "GWL",
x == "param_63680" ~ "Turb",
x == "param_72019" ~ "WLBLS",
x == "param_70290" ~ "Chloride",
x == "Wtemp_param_00010" ~ "Wtemp",
x == "Precip_param_00045" ~ "Precip",
x == "Flow_param_00060" ~ "Flow",
x == "GH_param_00065" ~ "GH",
x == "SpecCond_param_00095" ~ "SpecCond",
x == "DO_param_00300" ~ "DO",
x == "pH_param_00400" ~ "pH",
x == "GWL_param_62611" ~ "GWL",
x == "Turb_param_63680" ~ "Turb",
x == "WLBLS_param_72019" ~ "WLBLS",
x == "Chloride_param_70290" ~ "Chloride")
}
#' @title Filter Null List
#' @description Taken from leaflet filterNULL function
#' remove NULL elements from a list
#' @param x A list whose NULL elements will be filtered
#' @return A list that has NULL elements removed
#' @noRd
wwfilterNULL <- function(x) {
if (length(x) == 0 || !is.list(x)) return(x)
x[!unlist(lapply(x, is.null))]
}
#' @title Get error codes
#' @description Used for instantneous API call where sometimes an error occurrs. We just
#' want to capture the description.
#' @param x A character
#' @return A vector of length 1 or n, matching the length of the logical input or output vectors.
#' @noRd
iv_error_codes <- function(x){
dplyr::case_when(x == "Bkw" ~ 'Value is affected by backwater at the measurement site.',
x == 'Dis' ~ 'Record has been discontinued at the measurement site.',
x == 'Dry' ~ 'Dry condition exists at the measurement site.',
x == 'Eqp' ~ 'Value affected by equipment malfunction.',
x == 'Fld' ~ 'Value is affected by flooding conditions at the measurement site.',
x == 'Ice' ~ 'Value is affected by ice at the measurement site.',
x == 'Mnt' ~ 'Site under going maintenance.',
x == 'Pr' ~ 'Parameter only partially monitored over specific range of values or time periods.',
x == 'Pmp' ~ 'Value is affected by pumping at time of measurement.',
x == 'Rat' ~ 'Rating being developed.',
x == 'Ssn' ~ 'Parameter monitored seasonally.',
x == 'Tst' ~ 'Value is affected by artificial test condition.',
x == 'Zfl' ~ 'Zero flow condition present at the measurement site.',
x == '***' ~ 'Value unavailable.',
TRUE ~ NA_character_)
}
#' Prepping for loggin
#'
#' @param data data.frame
#'
#' @return values are padded if zero for parameter of interest
#' @noRd
#'
pad_zero_for_logging <- function(data){
param_names <- c("Wtemp","Precip","Flow","GH","SpecCond",
"DO", "pH", "GWL","Turb","WLBLS")
cols_to_update <- names(data[which(names(data) %in% param_names)])
data %>%
mutate(across(dplyr::all_of(cols_to_update), ~ifelse(.x <= 0 , .x + 0.000001, .x)))
}
#' Delay
#'
#' @return a number for amount of time to delay
#'
delay_setup <- function(){
## max 120 requests per minute
max_freq_per_min <- 120
## delay in seconds between requests
delay <- 60/max_freq_per_min * future::nbrOfWorkers()
}
|
/scratch/gouwar.j/cran-all/cranData/whitewater/R/utils.R
|
#' Options
#'
#' @param date_range A \code{character}. Indicating how to call the API. 'pfn' = Period from now,
#' 'date_range' = a date range, "recent" = the most recent value.
#' @param period A \code{numeric}. Return all values from a period from now (only if 'pfn' is used).
#' @param dates A \code{vector}. Return all values within an absolute date range (start and end dates).
#' Only if 'date_range' is used.
#' @param site_status A \code{character} indicating site status. Example, 'all' = both active and inactive,
#' 'active' = only active sites, 'inactive' = only inactive sites.
#' @param floor_iv A \code{character} on how to floor the instantaneous values, '1 hour' (default).
#' @param ... other options used for options.
#'
#' @note A site is considered active if; it has collected time-series (automated) data within the last 183 days (6 months) or
#' it has collected discrete (manually collected) data within 397 days (13 months).
#'
#' @return A list with API options.
#' @export
#' @examples \dontrun{
#'
#' library(whitewater)
#' yaak_river_dv <- ww_dvUSGS('12304500',
#' parameter_cd = '00060',
#' wy_month = 10)
#'
#' yaak_river_iv <- ww_floorIVUSGS(yaak_river_dv)
#'
#' #change floor method
#'
#' yaak_river_iv <- ww_floorIVUSGS(yaak_river_dv,
#' options = wwOptions(floor_iv = '6-hour'))
#'
#' #change number of days
#'
#' yaak_river_iv <- ww_floorIVUSGS(yaak_river_dv,
#' options = wwOptions(floor_iv = '2-hour',
#' period = 365))
#'
#' # get by date range
#'
#'
#' yaak_river_wy <- ww_floorIVUSGS(yaak_river_dv,
#' options = wwOptions(date_range = 'date_range',
#' dates = c('2022-03-01', '2022-05-11')))
#'
#'
#' # site status as 'active'
#'
#' yaak_river_wy <- ww_floorIVUSGS(yaak_river_dv,
#' options = wwOptions(site_status = 'active',
#' date_range = 'date_range',
#' dates = c('2022-03-01', '2022-05-11')))
#' }
wwOptions <- function(date_range = 'pfn',
period = 11,
dates = NULL,
site_status = 'all',
floor_iv = '1 hour',
...){
wwfilterNULL(
list(date_range = date_range,
period = period,
dates = dates,
site_status = site_status,
floor_iv = floor_iv,
...)
)
}
|
/scratch/gouwar.j/cran-all/cranData/whitewater/R/wwOptions.R
|
.onAttach <- function(libname, pkgname){
packageStartupMessage(paste0(crayon::black(" Due to potentially crashing (USGS Water Services) REST services \n parallel processing is kept to "), crayon::red(crayon::bold(" 120 requests/min. ")),crayon::black("\n Thank you!")))
}
|
/scratch/gouwar.j/cran-all/cranData/whitewater/R/zzz.R
|
# Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
#' Estimate heterozygote miscall rate for different read depth categories (no nulls)
#'
#' To see how this Rcpp function is applied, see the code in
#' \code{\link{infer_m}}.
#' @param Y the 012,-1 matrix that is N x L giving the observed genotypes of the N individuals
#' at L SNPs.
#' @param R integer matrix that is N x L giving the read depth categories. These must be indexed from
#' 1 up to num_cats. Missing data should be -1.
#' @param init_m starting value for m. Typically you might want to use the m estimated
#' from init_m
#' @param num_cats the number of read depth categories.
#' @param p_prior two-vector that holds the beta parameters for a prior on the
#' allele frequency for each locus. Typical value is c(0.5, 0.5).
#' @param m_prior two-vector that holds the beta parameters for a prior on the
#' heterozygote miscall rate for each locus. Typical value is c(0.5, 0.5).
#' @param num_reps the number of MCMC sweeps to do.
#' @keywords internal
estimate_m_rd <- function(Y, R, init_m, num_cats, p_prior, m_prior, num_reps) {
.Call('_whoa_estimate_m_rd', PACKAGE = 'whoa', Y, R, init_m, num_cats, p_prior, m_prior, num_reps)
}
#' simulate a new miscall rate for each read depth category given X and Y
#'
#' This just writes new values into M as if it were an output variable.
#' Internal function used within \code{\link{estimate_m_rd}}.
#' @keywords internal
gibbsM <- function(M, num_cats, X, Y, R, pri) {
invisible(.Call('_whoa_gibbsM', PACKAGE = 'whoa', M, num_cats, X, Y, R, pri))
}
#' simulate new reference allele frequencies from their beta full conditional
#'
#' This just writes new values into P as if it were an output variable.
#' Internal function used within \code{\link{estimate_m_rd}}.
#' @keywords internal
gibbsP <- function(p, X, pri) {
invisible(.Call('_whoa_gibbsP', PACKAGE = 'whoa', p, X, pri))
}
#' compute full conditional for each X given Y, p, R, and m, and then sample from it
#'
#' This just writes new values into X as if it were an output variable.
#' Internal function used within \code{\link{estimate_m_rd}}.
#' @keywords internal
gibbsX <- function(X, Y, R, p, M) {
invisible(.Call('_whoa_gibbsX', PACKAGE = 'whoa', X, Y, R, p, M))
}
#' just a quick function for making an 012 matrix from a character matrix
#'
#' The standard way within R of pulling values out of a named
#' vector really bogs down on large data sets. So I will do this instead.
#' @param M a character matrix of variant call format (VCF) genotypes and no dimnames. Allowable values are
#' "0/0", and "0|0", which get coverted to integer 0; "0/1", "0|1", "1/0", and "1|0",
#' which get converted to integer 1; and
#' "1/1", and "1|1", which get converted to integer 2. Everything else gets
#' converted to -1 to denote missing data.
#' @return An integer matrix of values which are 0, 1, 2, or -1.
#' @export
#' @examples
#' # get an 012 matrix from the lobster data
#' tmp <- t(vcfR::extract.gt(lobster_buz_2000, element = "GT"))
#' dimnames(tmp) <- NULL
#' g <- make_it_012(tmp)
make_it_012 <- function(M) {
.Call('_whoa_make_it_012', PACKAGE = 'whoa', M)
}
|
/scratch/gouwar.j/cran-all/cranData/whoa/R/RcppExports.R
|
#' bin read depths of SNPs into categories having at least S observations
#'
#' @param D a matrix of read depths. Rows are individuals, columns are SNPs. Cells where data are missing
#' in the genotype matrix must be denoted as NA
#' @param S the min number of observations to have in each bin
#' @return This returns a list with two components. \code{dp_bins} is a matrix of the same
#' shape as D with the bin categories (as 1, 2, ...) and -1 for this cells
#' corresponding to missing genotypes. \code{num_cats} is the number of depth bins.
#' \code{tidy_bins} is a long format description of the bins.
#' \code{bin_stats} is a tibble giving summary information about the read depth bins which
#' is useful for plotting things, etc.
#' @export
#' @keywords internal
#' @examples
#'
#' # get a matrix of read depths and make it an integer matrix
#' depths <- vcfR::extract.gt(lobster_buz_2000, element = "DP")
#' storage.mode(depths) <- "integer"
#'
#' # get a character matrix of genotypes, so we can figure out which
#' # are missing and mask those from depths
#' genos <- vcfR::extract.gt(lobster_buz_2000, element = "GT")
#'
#' # make missing in depths if missing in genos
#' depths[is.na(genos)] <- NA
#'
#' # bin the read depths into bins with at least 1000 observations in each bin
#' bins <- bin_depths(depths, 1000)
bin_depths <- function(D, S) {
# first, count things up and get them into a reasonable format
dcnts <- as_tibble(as.data.frame(table(D))) %>%
mutate(D = as.integer(as.character(D))) %>%
setNames(c("D", "Freq")) %>%
rename(dp = D,
n = Freq) %>%
arrange(dp) # just to make sure it is in increasing order
# now we lump them up. We just use a for loop for this
idx <- 1
sum <- 0
n <- dcnts$n
res <- rep(NA, length(n))
for(i in seq_along(n)) {
res[i] <- idx
sum <- sum + n[i]
if(sum > S) {
idx <- idx + 1
sum <- 0
}
}
# at the end of that, we take the very last bin and just merge is with the
# preceding one, so that it doesn't have just a small number in it.
# but we only do this if there is more than one read depth bin!
if(max(res) > 1) {
res[res == max(res)] <- max(res) - 1
}
# and we add it on there with a mutate which will bark an error is something has gone awry
tidy_bins <- dcnts %>%
mutate(bin = as.integer(res))
# now we have to cut the original matrix up into these categories
left_endpoints <- tidy_bins %>%
group_by(bin) %>%
summarise(ends = max(dp) + 0.2)
cut_vec <- c(-0.01, left_endpoints$ends)
dp_bins <- D
dp_bins[] <- cut(D, breaks = cut_vec)
dp_bins[is.na(dp_bins)] <- -1L
# finally summarize the bin stats
bin_stats <- tidy_bins %>%
group_by(bin) %>%
summarise(total_n = sum(n),
mean_dp = sum(dp * n) / sum(n))
list(dp_bins = dp_bins,
num_cats = max(tidy_bins$bin),
tidy_bins = tidy_bins,
bin_stats = bin_stats
)
}
|
/scratch/gouwar.j/cran-all/cranData/whoa/R/bin_depths.R
|
#' Restriction-associated digest (RAD) sequence data from 36 lobsters at 2000 single nucleotide polymorphisms (SNPs)
#'
#' A data set from the study by Benestan et al. (2016).
#'
#' @format A `vcfR' object in which the original data set has
#' been reduced to just the 36 lobsters from the BUZ population
#' and a randomly sampled 2000 SNPs from the 10,156 originally
#' available.
#'
#' This is the sort of object obtained after calling \code{vcfR::read.vcfR()}
#' on a variant call format (VCF) file.
#'
#' @source \url{https://datadryad.org/stash/dataset/doi:10.5061/dryad.q771r}
"lobster_buz_2000"
#' An 012 matrix from (RAD) sequence data from 36 lobsters at 2000 single nucleotide polymorphisms (SNPs)
#'
#' A data set from the study by Benestan et al. (2016).
#'
#' @format This is an integer matrix with positions in rows and samples in columns.
#' It is an 012 matrix that corresponds to lobster_buz_2000. It is useful as
#' an example of the necessary format for the d012 argument to \code{\link{exp_and_obs_geno_freqs}}.
#'
#'
#' @source \url{https://datadryad.org/stash/dataset/doi:10.5061/dryad.q771r}
"lobster_buz_2000_as_012_matrix"
|
/scratch/gouwar.j/cran-all/cranData/whoa/R/data.R
|
#' Computed expected and observed genotype frequencies from a `vcfR' object
#'
#' Under the assumption of Hardy-Weinberg equilibrium, this function uses the
#' estimated allele frequencies from the data set in v to compute expected genotype
#' frequencies, and then reports these along with the observed genotype frequencies.
#' Loci come out named as CHROM--POS.
#'
#' @param v a `vcfR' object. Exactly one of \code{v} or \code{d012} is required. But you
#' can't use both!
#' @param d012 an integer matrix (or a numeric matrix, which will be coerced to
#' be of integer type) with individuals in columns, and markers in rows.
#' 0 denotes a genotype homozygous for the reference allele, 1 is a heterozygote, 2 is a
#' homozygote for the alternate allele, and -1 denotes missing data. This matrix is not
#' required to have column (sample) names. They won't be used if they are present. But,
#' the matrix must have rownames, which should be in the format of CHROM--POS (i.e. the "chromosome"
#' name (or the "contig" name) followed by a "--" followed by the position of the marker in the "chromosome").
#' Exactly one of \code{v} or \code{d012} is required. But you
#' can't use both!
#' @param prop_indv_required loci will be dropped if a proportion of
#' individuals less than prop_indv_required have non-missing data at that locus.
#' Default is 0.5
#' @param prop_loci_required individual will be dropped if their proportion of
#' non-missing loci is less than prop_loci_required. Default is 0.5.
#' @export
#' @return Returns a tibble with the following columns: \code{snp} = the locus name
#' as CHROM--POS; \code{p} = The frequency of the alternate (ALT) allele; \code{ntot} = the total
#' number of individuals with no missing data at the locus; \code{geno} = column
#' telling which genotype (0, 1, or 2) is referred to; \code{p_exp} = expected
#' frequency of the genotype; \code{p_obs} = observed frequency of genotype;
#' \code{n_exp} = expected number of such genotypes; \code{n_obs} = observed
#' number of such genotypes; \code{z_score} = simple statistic giving how far
#' the observed genotype frequency is from that expected under Hardy-Weinberg
#' equilibrium.
#'
#' @examples
#' eao <- exp_and_obs_geno_freqs(v = lobster_buz_2000)
#'
#' # if you wanted to run that on an 012 matrix,
#' # it would be like this:
#' eao012 <- exp_and_obs_geno_freqs(d012 = lobster_buz_2000_as_012_matrix)
exp_and_obs_geno_freqs <- function(v = NULL, d012 = NULL, prop_indv_required = 0.5, prop_loci_required = 0.5) {
if(!xor(is.null(v), is.null(d012))) {
stop("Exactly one of v or d012 must be present.")
}
if(!is.null(v)) {
# first get an 012 matrix with loci in the columns
# and samples in the rows
tmp <- vcfR::extract.gt(v, element = "GT")
dimnames(tmp) <- NULL
g012 <- t(make_it_012(tmp))
colnames(g012) <- paste(v@fix[,1], v@fix[,2], sep = "--") # name the Chrom--Pos
}
if(!is.null(d012)) {
# check that it is numeric or integer
if(!(storage.mode(d012) == "integer" | storage.mode(d012) == "numeric")) {
stop("d012 must be a matrix of type integer or numeric, not ", storage.mode(d012))
}
# make sure to set storage mode to integer
storage.mode(d012) <- "integer"
# check to make sure there are colnames
if(is.null(rownames(d012))) {
stop("You must have rownames on d012")
}
# remove the colnames if they are there
colnames(d012) <- NULL
# then return g012 as the transpose of d012
g012 <- t(d012)
}
# now, drop the loci with too much missing data, and after that
# drop the indivs with too much missing data
pml <- colMeans(g012 > -1)
g012 <- g012[, pml > prop_indv_required]
pmi <- rowMeans(g012 > -1)
g012 <- g012[pmi > prop_loci_required,]
gfc <- geno_freq_calc_single(g012)
gfc
}
|
/scratch/gouwar.j/cran-all/cranData/whoa/R/exp_and_obs_geno_freqs.R
|
#' function to return a tibble with the min/max values of genotype freqs possible
#'
#' These mins and maxes occur because the genotypes are used to estimate
#' the allele frequencies. The output of this function is useful for
#' putting boundaries on plots.
#' @return a tibble
#' @export
#' @keywords internal
#' @examples
#' gfb <- geno_freq_boundaries()
geno_freq_boundaries <- function() {
# first do it for the homozygote category
Poe <- seq(0,1, by = 0.005)
phat <- 1 - sqrt(Poe)
minPo <- pmax(0, 1 - 2 * phat)
maxPo <- 1 - phat
# these are the values for the two homozygote categories
homo_tib <- tibble::tibble(p_exp = rep(Poe, 4),
p_obs = rep(c(minPo, maxPo), 2),
geno = as.character(rep(c(0L, 2L), each = length(Poe) * 2)))
# now, it should be easy to get the max/min values for heterozygotes.
# They will occur where one of the homozygotes is min or max.
P1e <- 2 * phat * (1 - phat)
maxP1 <- 2 * (1 - phat - minPo)
minP1 <- 2 * (1 - phat - maxPo)
het_tib <- tibble::tibble(p_exp = rep(P1e, 2),
p_obs = c(minP1, maxP1),
geno = "1")
dplyr::bind_rows(homo_tib, het_tib)
}
|
/scratch/gouwar.j/cran-all/cranData/whoa/R/geno_freq_boundaries.R
|
#' from on 012 file compute expected (assuming HW equilbrium) and observed genotype counts
#'
#' This is an internal function.
#' @param g012 an 012 matrix, with indivs in rows and loci in columns.
#' Missing data can be -1 or NA. The matrix must
#' have colnames which are the locus names.
#' @export
#' @keywords internal
#' @examples
#' # get an 012 matrix from the lobster data
#' tmp <- t(vcfR::extract.gt(lobster_buz_2000, element = "GT"))
#' locnames <- colnames(tmp)
#' g <- make_it_012(tmp)
#' colnames(g) <- locnames # put these back on since make_it_012 removes them
#' gf <- geno_freq_calc_single(g)
#' @return See information for return value of \code{\link{exp_and_obs_geno_freqs}}.
geno_freq_calc_single <- function(g012) {
g012[g012 == -1] <- NA
gc <- 2 * colSums(!is.na(g012), na.rm = TRUE) # number of non-missing gene copies
p <- colSums(g012, na.rm = TRUE) / gc
q <- 1.0 - p
n0 <- colSums(g012 == 0, na.rm = TRUE)
n1 <- colSums(g012 == 1, na.rm = TRUE)
n2 <- colSums(g012 == 2, na.rm = TRUE)
n <- n0 + n1 + n2
tibble::tibble(snp = colnames(g012),
p = p,
ntot = n,
`0` = n0,
`1` = n1,
`2` = n2
) %>%
tidyr::gather(key = "geno", value = "n_obs", `0`, `1`, `2`) %>%
dplyr::arrange(snp, geno) %>%
dplyr::mutate(p_exp = ifelse(geno == 0, (1 - p)^2,
ifelse(geno == 1, 2 * p * (1 - p),
ifelse(geno == 2, p^2, NA))),
n_exp = ntot * p_exp,
p_obs = n_obs / ntot,
z_score = (n_obs - n_exp) / sqrt(ntot * p_exp * (1 - p_exp))) %>%
dplyr::select(snp, p, ntot, geno, p_exp, p_obs, n_exp, n_obs, z_score)
}
|
/scratch/gouwar.j/cran-all/cranData/whoa/R/geno_freq_count_single.R
|
#' return a `ggplot2' plot object of observed and expected genotype freqs
#'
#' @param gfc a tibble like that created by exp_and_obs_geno_freqs()
#' @param alpha the transparency (alpha) parameter to apply to the points
#' in the scatterplot. Default is 0.2.
#' @param max_plot_loci By default this plots only 500 loci, sampled
#' randomly, to keep `ggplot2' taking forever to plot, for example, 100K
#' points. If you want to plot all the points, set this to a number
#' larger than the number of single nucleotide polymorphisms (SNPs) in the data set.
#' @export
#' @examples
#' # get the expected and observed geno freqs
#' gfreqs <- exp_and_obs_geno_freqs(lobster_buz_2000)
#' g <- geno_freqs_scatter(gfreqs)
#'
#' # now g is a 'ggplot2' object.
geno_freqs_scatter <- function(gfc, alpha = 0.2, max_plot_loci = 500) {
snps <- unique(gfc$snp)
if(length(snps) > max_plot_loci) {
ss <- sample(x = snps, size = max_plot_loci, replace = FALSE)
} else {
ss <- snps
}
g <- ggplot2::ggplot(gfc %>% dplyr::filter(snp %in% ss) , ggplot2::aes(x = p_exp, y = p_obs, colour = geno)) +
ggplot2::geom_jitter(alpha = alpha, position = ggplot2::position_jitter(width = 0.01, height = 0.01)) +
ggplot2::facet_wrap(~ geno, nrow = 1) +
ggplot2::geom_polygon(data = geno_freq_boundaries(), fill = NA, linetype = "dashed", colour = "black") +
ggplot2::geom_abline(slope = 1, intercept = 0, linetype = "solid")
g
}
|
/scratch/gouwar.j/cran-all/cranData/whoa/R/geno_freqs_scatter.R
|
#' get posterior estimates for m from different read depth categories
#'
#' This function calls internal C++ routines that perform Markov
#' chain Monte Carlo (MCMC) to sample from the posterior distribution of the
#' heterozygote miscall rate for each read depth category.
#'
#' The read depth bins are
#' determined by passing to the function \code{minBin}---the minimum number of observations desired for each read
#' depth bin. The function then breaks the observations into bins so that each read depth bin
#' has at least minBin observations.
#'
#' Note that if you want to estimate the heterozygote miscall rate \bold{overall} (i.e., not conditioning each
#' estimate on a read depth bin), then simply give a very large number (larger than the number of
#' markers times the number of individuals) for minBin. For example, you could use a number like 1e15
#' for minBin. As a consequence, all the genotypes will be put into a single read depth bin.
#' @param v a `vcfR' object holding the information from a variant call format (VCF) file with the genotype and depth data.
#' If you are going to be breaking the estimates down by read depth categories, the VCF file must have a DP field for
#' every genotype.
#' @param indivs a character vector holding
#' the names of the individuals from the VCF file to include in the analysis. By default
#' this is NULL, in which case everyone from the file is included.
#' @param minBin minimum number of observations for each read depth bin. If you have 10K markers
#' and 50 individuals then you have about 500,000 genotypes to play with. Requiring bins with at
#' least 5,000 genotypes in them will give you less than 100 bins. You can play around with this
#' number to get the right number of bins. The algorithm breaks the read depths up into bins that
#' have at least minBin genotypes in them.
#' @param init_m the initial value of the heterozygote miscall rate assumed for each read depth bin.
#' By default this is 0.1.
#' @param num_sweeps the number of sweeps of the MCMC algorithm to do. Default is 500, which is a
#' little on the short side. Run multiple times and make sure the values obtained are similar across
#' runs to assess convergence.
#' @param burn_in how many sweeps from the beginning of the chain to discard when computing the
#' posterior means and quantiles. Default is 100. Note that full traces of the visited m values
#' for every read depth bin are returned as well, so that the behavior of the chain in those early
#' steps can be investigated.
#' @return A list with six components:
#' \describe{
#' \item{m_posteriors}{A tibble with 6 columns: bin = the index of the read depth bin;
#' mean = the posterior mean estimate of the the heterozygote miscall rate in that bin;
#' lo95 = the low endpoint of the 95% credible interval; hi95 = the high endpoint of the
#' 95% credible interval; total_n = the total number of genotypes in the read depth bin;
#' and mean_dp = the mean read depth in the bin. }
#' \item{m_traces}{A tibble with all the values visited for m for every read depth bin. This tibble
#' has three columns: bin = the index of the read depth bin; sweep = the sweep number, value = the value
#' of m for that read depth bin in that particular sweep. }
#' \item{dp_summary}{A tibble summarizing how many genotypes of different read depths
#' appear in each bin.}
#' \item{bin_stats}{A tibble with a different summary of the read-depth bins.}
#' \item{num_sweeps}{Number of MCMC sweeps used.}
#' \item{burn_in}{Number of sweeps discarded as burn in.}
#' }
#' @export
#' @examples
#' # Shorter run than recommended (for quick example...)
#' im <- infer_m(lobster_buz_2000, minBin = 1000, num_sweeps = 100, burn_in = 20)
infer_m <- function(v, minBin, indivs = NULL, init_m = 0.1, num_sweeps = 500, burn_in = 100) {
message("Preparing data structures for MCMC")
# deal with the indivs
if(is.null(indivs)) {
indivs <- colnames(v@gt)[-1]
}
# check to make sure that all of indivs are included in the VCF
wrongos <- setdiff(indivs, colnames(v@gt)[-1])
if(length(wrongos) > 0) {
stop("Requesting indivs that are not in v: ", paste(wrongos, collapse = ", "))
}
# extract just those indivs. This assumes that vcfR has named the first column FORMAT
v@gt <- v@gt[,c("FORMAT", indivs)]
# prep it
p <- prep_vcf_for_est_m_rd(v, "DP", minBin)
message("Running MCMC")
# estimate it
b <- estimate_m_rd(Y = p$mat012,
R = p$dp_bins_list$dp_bins,
init_m = init_m,
num_cats = p$dp_bins_list$num_cats,
p_prior = c(0.5, 0.5),
m_prior = c(0.5, 0.5),
num_reps = num_sweeps)
message("Tidying output")
# tidy the output
res <- tidy_m_ests(E = b,
S = p$dp_bins_list$bin_stats,
TB = p$dp_bins_list$tidy_bins,
burn = burn_in)
res
}
|
/scratch/gouwar.j/cran-all/cranData/whoa/R/infer_m.R
|
#' return a `ggplot2' plot object of the posterior esimates for heterozyote miscall rates
#'
#' This just returns a `ggplot2' plot object that plots the read depth bins on the x-axis
#' and the posterior mean m estimates (and credible intervals) on the y-axis, and
#' depicts the number of genotypes in each read depth bin using color.
#' @param P the tibble that is the m_posteriors component of \code{\link{infer_m}}
#' @return a `ggplot2' plot object.
#' @export
#' @examples
#' # get something to plot (short run for example)
#' im <- infer_m(lobster_buz_2000, minBin = 1000, num_sweeps = 100, burn_in = 20)
#'
#' # then plot it
#' g <- posteriors_plot(im$m_posteriors)
#'
#' # now g is a 'ggplot2' object
posteriors_plot <- function(P) {
ggplot2::ggplot(P) +
ggplot2::geom_line(ggplot2::aes(x = mean_dp, y = mean)) +
ggplot2::geom_ribbon(ggplot2::aes(x = mean_dp, ymin = lo95, ymax = hi95), fill = "pink", alpha = 0.6) +
ggplot2::geom_point(ggplot2::aes(x = mean_dp, y = mean, colour = total_n)) +
viridis::scale_colour_viridis() +
ggplot2::xlab("Mean read depth of bin") +
ggplot2::ylab("Posterior mean estimate of miscall rate")
}
|
/scratch/gouwar.j/cran-all/cranData/whoa/R/posteriors_plot.R
|
#' convert a VCF into an 012,-1 matrix and read_depth bin matrix for estimation
#'
#' @param v a vcfR object into which a VCF file has been read
#' @param DF Field to use for obtaining total read depth. Currently
#' all that is available is DP.
#' @param minBin minimum number of observations for each read depth bin
#' @return This sends back a list with \code{mat012}: the 012,-1 matrix of genotypes, and
#' \code{dp_bins_list}: the list returned by bin_depths().
#' @export
#' @keywords internal
#' @examples
#' pv <- prep_vcf_for_est_m_rd(lobster_buz_2000, minBin = 1000)
prep_vcf_for_est_m_rd <- function(v, DF = "DP", minBin) {
# check to make sure the field named in DF exists.
#vt <- vcfR2tidy(v, info_only = TRUE)
#if(!(DF %in% vt$meta$ID)) {
# stop("The tag ", DF, " does not appear to be in the data...")
#}
# extract the matrix as an 012 file
dgt <- vcfR::extract.gt(v, element = "GT")
d012 <- make_it_012(dgt)
dimnames(d012) <- dimnames(dgt)
# now get the read depth matrix
dp <- vcfR::extract.gt(v, element = "DP")
storage.mode(dp) <- "integer"
# now, if some of the markers have been imputed, but the read depths added back on there
# there will be a genotype call, even though the DP field is a ".". Those .'s will
# have been converted to NAs, and we will now turn those into 0s. If the genotype
# is really not called (a -1 below...) then it will get turned back into an NA.
dp[is.na(dp)] <- 0
dp[d012 == -1] <- NA
# OK, now dp is a matrix of read depths with NAs where the genotype was unobserved
# now we need to bin those depths up
bd <- bin_depths(D = dp, S = minBin)
bd$dp_bins <- t(bd$dp_bins)
list(mat012 = t(d012),
dp_bins_list = bd)
}
|
/scratch/gouwar.j/cran-all/cranData/whoa/R/prep_vcf_for_est_m_rd.R
|
#' tidy up the estimate_m_rd output into something you can plot
#'
#' Internal function. See use in \code{\link{infer_m}}.
#' @param E the list returned by the estimation function
#' @param S the bin stats
#' @param TB the tidy bins
#' @param burn how much for burn in?
#' @keywords internal
#' @export
tidy_m_ests <- function(E, S, TB, burn = 50) {
# get the posteriors and the quantiles
posts <- tibble::tibble(bin = 1:nrow(E$Mtrace),
mean = rowMeans(E$Mtrace[, -(1:burn), drop = FALSE]),
lo95 = apply(E$Mtrace[, -(1:burn), drop = FALSE], 1, quantile, probs = 0.05),
hi95 = apply(E$Mtrace[, -(1:burn), drop = FALSE], 1, quantile, probs = 0.95)
) %>%
left_join(S, by = "bin")
# now, also get the traces for m values
trace <- tibble::tibble(
bin = rep(1:nrow(E$Mtrace), length.out = length(E$Mtrace)),
sweep = rep(1:ncol(E$Mtrace), each = nrow(E$Mtrace)),
value = as.numeric(E$Mtrace)
)
list(m_posteriors = posts,
m_traces = trace,
dp_summary = TB,
bin_stats = S,
num_sweeps = ncol(E$Mtrace),
burn_in = burn
)
}
|
/scratch/gouwar.j/cran-all/cranData/whoa/R/tidy_m_ests.R
|
#' whoa: Evaluation of genotyping error in genotype by sequencing data
#'
#' The name is found in the capitals here: \code{W}here's my \code{H}eterozygotes?! \code{O}bservations
#' of genotyping \code{A}ccuracy.
#'
#'
#' @section the \code{whoa} main high-level functions:
#'
#' The main function in the package whoa is \code{\link{infer_m}}.
#' This function infers the heterozygote miscall rate (the rate at
#' which true heterozygotes have been miscalled as homozygotes in
#' genotype-by-sequencing data) for calls made upon genotypes falling
#' within different read depth categories.
#'
#' The output from \code{\link{infer_m}} is easily plotted by passing the
#' m_posteriors component of the output list from \code{infer_m} into
#' \code{\link{posteriors_plot}}.
#'
#'
#' @section example data:
#'
#' The package comes with a small data set, \code{\link{lobster_buz_2000}}, which
#' was read in from a variant call format (VCF) file and is now stored in the package as a `vcfR' object.
#'
#' @docType package
#' @name whoa
#' @importFrom Rcpp evalCpp
#' @importFrom dplyr arrange
#' @importFrom dplyr group_by
#' @importFrom dplyr left_join
#' @importFrom dplyr mutate
#' @importFrom dplyr rename
#' @importFrom dplyr summarise
#' @importFrom magrittr %>%
#' @importFrom stats quantile
#' @importFrom stats setNames
#' @importFrom tibble as_tibble
#' @importFrom tibble tibble
#' @useDynLib whoa
NULL
# quiets concerns of R CMD check re: the . and other column names
# that appear in dplyr chains
if(getRversion() >= "2.15.1") {
utils::globalVariables(
c(
".",
"Freq",
"dp",
"bin",
"mean_dp",
"lo95",
"hi95",
"total_n",
"0",
"1",
"2",
"geno",
"n_exp",
"n_obs",
"ntot",
"p_exp",
"p_obs",
"snp",
"z_score"
)
)
}
|
/scratch/gouwar.j/cran-all/cranData/whoa/R/whoa.R
|
## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
## -----------------------------------------------------------------------------
# load up the package:
library(whoa)
## ---- eval=FALSE--------------------------------------------------------------
# help("lobster_buz_2000")
## ---- fig.width=7-------------------------------------------------------------
# first get compute expected and observed genotype frequencies
gfreqs <- exp_and_obs_geno_freqs(lobster_buz_2000)
# then plot those. Set max_plot_loci so that all 2000
# loci will be plotted
geno_freqs_scatter(gfreqs, max_plot_loci = 2000)
## -----------------------------------------------------------------------------
overall <- infer_m(lobster_buz_2000, minBin = 1e15)
## -----------------------------------------------------------------------------
overall$m_posteriors
## -----------------------------------------------------------------------------
binned <- infer_m(lobster_buz_2000, minBin = 2000)
## ---- fig.width=7-------------------------------------------------------------
posteriors_plot(binned$m_posteriors)
|
/scratch/gouwar.j/cran-all/cranData/whoa/inst/doc/whoa_tutorial.R
|
---
title: "whoa Tutorial"
author: "Eric C. Anderson"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{whoa Tutorial}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
This is a small, lightweight package that lets users investigate the
distribution of genotypes in genotype-by-sequencing (GBS) data where they expect (by and large)
Hardy-Weinberg equilibrium, in order to assess rates of genotyping errors and
the dependence of those rates on read depth.
The name comes from the bolded letters in this sentence:
**W**here's my **H**eterozygotes at? **O**bservations on genotyping **A**ccuracy.
It also fits well with my reaction when I started investigating
heterozygote miscall rates (rates at which true heterozygotes are
incorrectly called as homozygotes) in some restriction associated digest (RAD)
sequencing data sets---My eyes
bugged out and I said, "Whoa!"
The package comes with a small bit of data from lobster to play with. The rest of
this document shows a quick run through a few of the functions to do an
analysis of a data set.
## A quick run
### Packages
```{r}
# load up the package:
library(whoa)
```
### Lobster data
Read about the lobster data here. Execute this if you want:
```{r, eval=FALSE}
help("lobster_buz_2000")
```
The main thing to know is that it is a 'vcfR' object. You can
make such an object yourself by reading in a variant call format (VCF) file
using `vcfR::read.vcfR()`.
### Make a quick genotype frequency scatter plot
```{r, fig.width=7}
# first get compute expected and observed genotype frequencies
gfreqs <- exp_and_obs_geno_freqs(lobster_buz_2000)
# then plot those. Set max_plot_loci so that all 2000
# loci will be plotted
geno_freqs_scatter(gfreqs, max_plot_loci = 2000)
```
### Now infer an overall heterozygote miscall rate.
If we want to estimate the het miscall rate (over all read depth bins)
we just set the minimum bin size to a very large value so it make just one bin, and
use the `infer_m` function which implements a Markov chain Monte Carlo (MCMC) algorithm
to estimate the heteryzogote miscall rate.
```{r}
overall <- infer_m(lobster_buz_2000, minBin = 1e15)
```
Now look at that:
```{r}
overall$m_posteriors
```
Wow! (Or should we say "WHOA!") A het miscall rate of around 25%.
### Now infer a miscall rate for read depth bins
See the total_n above is about 65,000. That means 65,000 genotypes.
(2000 loci typed at 36 individuals, with some missing data).
We will bin those up so that there are at least 2000 genotypes in each
bin and then estimate the het miscall rate for each read depth bin.
```{r}
binned <- infer_m(lobster_buz_2000, minBin = 2000)
```
And then we can plot the posterior mean and CIs for each read depth bin.
```{r, fig.width=7}
posteriors_plot(binned$m_posteriors)
```
Again, WHOA! The het miscall rate at low read depths is super high!
|
/scratch/gouwar.j/cran-all/cranData/whoa/inst/doc/whoa_tutorial.Rmd
|
---
title: "whoa Tutorial"
author: "Eric C. Anderson"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{whoa Tutorial}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
This is a small, lightweight package that lets users investigate the
distribution of genotypes in genotype-by-sequencing (GBS) data where they expect (by and large)
Hardy-Weinberg equilibrium, in order to assess rates of genotyping errors and
the dependence of those rates on read depth.
The name comes from the bolded letters in this sentence:
**W**here's my **H**eterozygotes at? **O**bservations on genotyping **A**ccuracy.
It also fits well with my reaction when I started investigating
heterozygote miscall rates (rates at which true heterozygotes are
incorrectly called as homozygotes) in some restriction associated digest (RAD)
sequencing data sets---My eyes
bugged out and I said, "Whoa!"
The package comes with a small bit of data from lobster to play with. The rest of
this document shows a quick run through a few of the functions to do an
analysis of a data set.
## A quick run
### Packages
```{r}
# load up the package:
library(whoa)
```
### Lobster data
Read about the lobster data here. Execute this if you want:
```{r, eval=FALSE}
help("lobster_buz_2000")
```
The main thing to know is that it is a 'vcfR' object. You can
make such an object yourself by reading in a variant call format (VCF) file
using `vcfR::read.vcfR()`.
### Make a quick genotype frequency scatter plot
```{r, fig.width=7}
# first get compute expected and observed genotype frequencies
gfreqs <- exp_and_obs_geno_freqs(lobster_buz_2000)
# then plot those. Set max_plot_loci so that all 2000
# loci will be plotted
geno_freqs_scatter(gfreqs, max_plot_loci = 2000)
```
### Now infer an overall heterozygote miscall rate.
If we want to estimate the het miscall rate (over all read depth bins)
we just set the minimum bin size to a very large value so it make just one bin, and
use the `infer_m` function which implements a Markov chain Monte Carlo (MCMC) algorithm
to estimate the heteryzogote miscall rate.
```{r}
overall <- infer_m(lobster_buz_2000, minBin = 1e15)
```
Now look at that:
```{r}
overall$m_posteriors
```
Wow! (Or should we say "WHOA!") A het miscall rate of around 25%.
### Now infer a miscall rate for read depth bins
See the total_n above is about 65,000. That means 65,000 genotypes.
(2000 loci typed at 36 individuals, with some missing data).
We will bin those up so that there are at least 2000 genotypes in each
bin and then estimate the het miscall rate for each read depth bin.
```{r}
binned <- infer_m(lobster_buz_2000, minBin = 2000)
```
And then we can plot the posterior mean and CIs for each read depth bin.
```{r, fig.width=7}
posteriors_plot(binned$m_posteriors)
```
Again, WHOA! The het miscall rate at low read depths is super high!
|
/scratch/gouwar.j/cran-all/cranData/whoa/vignettes/whoa_tutorial.Rmd
|
.onLoad <- function(libname, pkgname) {
lookup_gh_username <<- memoize_first(lookup_gh_username)
}
is_string <- function(x) {
is.character(x) && length(x) == 1 && !is.na(x)
}
memoize_first <- function(fun) {
fun
cache <- list()
dec <- function(arg, ...) {
if (!is_string(arg)) return(fun(arg, ...))
if (is.null(cache[[arg]])) cache[[arg]] <<- fun(arg, ...)
cache[[arg]]
}
dec
}
gh_url <- "https://api.github.com"
ok <- function(x) {
!inherits(x, "try-error") &&
!is.null(x) &&
length(x) == 1 &&
x != "" &&
!is.na(x)
}
`%or%` <- function(l, r) {
if (ok(l)) l else r
}
str_trim <- function(x) {
gsub("\\s+$", "", gsub("^\\s+", "", x))
}
fallback_or_stop <- function(fallback, msg) {
if (!is.null(fallback)) {
fallback
} else {
stop(msg)
}
}
#' User name of the current user
#'
#' Tries the \code{LOGNAME}, \code{USER}, \code{LNAME}, \code{USERNAME}
#' environment variables first. Then it tries the `id` command on Unix-like
#' platforms and `whoami` on Windows.
#'
#' @param fallback If not \code{NULL} then this value is returned
#' if the username cannot be found, instead of triggering an error.
#' @return The user name of the current user.
#'
#' @family user names
#' @export
#' @examples
#' \dontrun{
#' username()
#' }
username <- function(fallback = NULL) {
e <- Sys.getenv()
user <- e["LOGNAME"] %or% e["USER"] %or% e["LNAME"] %or% e["USERNAME"]
if (ok(user)) return(as.vector(user))
if (.Platform$OS.type == "unix") {
user <- try(str_trim(system("id -un", intern = TRUE)), silent = TRUE)
if (ok(user)) return(user)
} else if (.Platform$OS.type == "windows") {
user <- try({
user <- system("whoami", intern = TRUE, show.output.on.console = FALSE)
user <- sub("^.*\\\\", "", str_trim(user))
}, silent = TRUE)
if (ok(user)) return(user)
} else {
return(fallback_or_stop(
fallback,
"Unknown platform, cannot determine username"
))
}
fallback_or_stop(fallback, "Cannot determine username")
}
#' Full name of the current user
#'
#' Uses the \code{FULLNAME} environment variable, if set.
#' Otherwise tries system full names and the git configuration as well.
#'
#' @param fallback If not \code{NULL} then this value is returned
#' if the full name of the user cannot be found, instead of
#' triggering an error.
#' @return The full name of the current user.
#'
#' @family user names
#' @export
#' @examples
#' \dontrun{
#' fullname()
#' }
fullname <- function(fallback = NULL) {
if ((x <- Sys.getenv("FULLNAME", "")) != "") return(x)
if (Sys.info()["sysname"] == "Darwin") {
user <- try({
user <- system("id -P", intern = TRUE)
user <- str_trim(user)
user <- strsplit(user, ":")[[1]][8]
}, silent = TRUE)
if (ok(user)) return(user)
user <- try({
user <- system("osascript -e \"long user name of (system info)\"",
intern = TRUE)
user <- str_trim(user)
}, silent = TRUE)
if (ok(user)) return(user)
} else if (.Platform$OS.type == "windows") {
user <- try(suppressWarnings({
user <- system("git config --global user.name", intern = TRUE)
user <- str_trim(user)
}), silent = TRUE)
if (ok(user)){
return(user)
} else{
user <- try(suppressWarnings({
user <- system(paste0("git config --file ",
file.path(Sys.getenv("USERPROFILE"),
".gitconfig"),
" user.name"), intern = TRUE)
user <- str_trim(user)
}), silent = TRUE)
if(ok(user)){
return(user)
}
}
user <- try({
username <- username()
user <- system(
paste0("wmic useraccount where name=\"", username,
"\" get fullname"),
intern = TRUE
)
user <- sub("FullName", "", user)
user <- str_trim(paste(user, collapse = ""))
}, silent = TRUE)
if (ok(user)) return(user)
} else {
user <- try({
user <- system("getent passwd $(whoami)", intern = TRUE)
user <- str_trim(user)
user <- strsplit(user, ":")[[1]][5]
user <- sub(",.*", "")
}, silent = TRUE)
if (ok(user)) return(user)
}
user <- try(suppressWarnings({
user <- system("git config --global user.name", intern = TRUE)
user <- str_trim(user)
}), silent = TRUE)
if (ok(user)){
return(user)
} else{
user <- try(suppressWarnings({
user <- system(paste0("git config --file ",
file.path(Sys.getenv("USERPROFILE"),
".gitconfig"),
" user.name"), intern = TRUE)
user <- str_trim(user)
}), silent = TRUE)
if(ok(user)){
return(user)
}
}
fallback_or_stop(fallback, "Cannot determine full name")
}
#' Email address of the current user
#'
#' If uses the \code{EMAIL} environment variable, if set.
#' Otherwise it tries to find it in the user's global git configuration.
#'
#' @param fallback If not \code{NULL} then this value is returned
#' if the email address cannot be found, instead of triggering an error.
#' @return Email address on success. Otherwise an error is thrown.
#'
#' @family user names
#' @export
#' @examples
#' \dontrun{
#' email_address()
#' }
email_address <- function(fallback = NULL) {
if ((x <- Sys.getenv("EMAIL", "")) != "") return(x)
email <- try(suppressWarnings({
email <- system("git config --global user.email", intern = TRUE)
email <- str_trim(email)
}), silent = TRUE)
if (ok(email)){
return(email)
} else{
user <- try(suppressWarnings({
email <- system(paste0("git config --file ",
file.path(Sys.getenv("USERPROFILE"),
".gitconfig"),
" user.email"), intern = TRUE)
email <- str_trim(email)
}), silent = TRUE)
if(ok(email)){
return(email)
}
}
fallback_or_stop(fallback, "Cannot get email address")
}
#' Find the current user's GitHub username
#'
#' Uses the \code{GITHUB_USERNAME} global variable or searches on GitHub,
#' for the user's email address, see
#' \code{\link{email_address}}.
#'
#' This function caches the username in the current R session, and if the
#' email address of the user is unchanged, it does not perform another
#' GitHub query.
#'
#' @param token GitHub token to use. By default it uses
#' the \code{GITHUB_TOKEN} environment variable, if set.
#' If unset, uses the \code{GITHUB_PAT} environment
#' variable, if set.
#' @param fallback If not \code{NULL} then this value is returned
#' if the GitHub username cannot be found, instead of triggering an
#' error.
#' @return GitHub username, or an error is thrown if it cannot be found.
#'
#' @family user names
#' @export
#' @importFrom httr GET add_headers status_code content
#' @importFrom jsonlite fromJSON
#' @importFrom utils URLencode
#' @examples
#' \dontrun{
#' gh_username()
#' }
gh_username <- function(token = NULL,
fallback = NULL) {
# try reading username from global variable
env_gh_username <- Sys.getenv("GITHUB_USERNAME")
if (nzchar(env_gh_username)) return(env_gh_username)
email <- try(email_address(), silent = TRUE)
if (ok(email)) {
if (! grepl('@', email)) {
return(fallback_or_stop(
fallback,
"This does not seem to be an email address"
))
}
lookup_gh_username(email, token)
} else {
fallback_or_stop(fallback, "Cannot get GitHub username")
}
}
lookup_gh_username <- function(email, token) {
url <- URLencode(paste0(gh_url, "/search/users?q=", email,
" in:email"))
if(is.null(token)){
token <- Sys.getenv("GITHUB_TOKEN", Sys.getenv("GITHUB_PAT"))
}
auth <- character()
if (token != "") auth <- c("Authorization" = paste("token", token))
resp <- GET(
url,
add_headers("user-agent" = "https://github.com/r-lib/whoami",
'accept' = 'application/vnd.github.v3+json',
.headers = auth)
)
if (status_code(resp) >= 300) {
return(fallback_or_stop(fallback, "Cannot find GitHub username"))
}
data <- fromJSON(content(resp, as = "text"), simplifyVector = FALSE)
if (data$total_count == 0) {
return(
fallback_or_stop(fallback, "Cannot find GitHub username for email")
)
}
data$items[[1]]$login
}
#' User name and full name of the current user
#'
#' Calls \code{\link{username}} and \code{\link{fullname}}.
#'
#' @return A named character vector with entries: \code{username},
#' \code{fullname}, \code{email_address}, \code{gh_username}.
#'
#' @family user names
#' @export
#' @examples
#' \dontrun{
#' whoami()
#' }
#' @details
#' For the username it tries the `LOGNAME`, `USER`,
#' `LNAME` and `USERNAME` environment variables first.
#' If these are all unset, or set to an empty string,
#' then it tries running `id` on Unix-like
#' systems and `whoami` on Windows.
#'
#' For the full name of the user, it queries the system services
#' and also tries the user's global git configuration.
#' On Windows, it tries finding the global git configuration
#' in `Sys.getenv("USERPROFILE")` if it doesn't find it
#' in `Sys.getenv("HOME")` (often "Documents").
#'
#' For the email address it uses the user's global git
#' configuration. It tries finding the global git
#' configuration in `Sys.getenv("USERPROFILE")`
#' if it doesn't find it in `Sys.getenv("HOME")`.
#'
#' For the GitHub username it uses the `GITHUB_USERNAME`
#' environment variable then it tries searching on GitHub
#' for the user's email address.
whoami <- function() {
c("username" = username(),
"fullname" = fullname(),
"email_address" = email_address(),
"gh_username" = gh_username()
)
}
|
/scratch/gouwar.j/cran-all/cranData/whoami/R/whoami.R
|
#' Separation Reliability: Person Separation Reliability
#'
#' Copied from eRm::SepRel(), v1.0-1: This function calculates the proportion of person variance that is not due to error. The concept of person separation reliability is very similar to reliability indices such as Cronbach's alpha.
#'
#' @param pobject Object of class \code{ppar} (see \code{?eRm::person.parameter}).
#'
#' @return SepRel returns a list object of class eRm_SepRel containing:
#' \item{sep.rel}{the person separation reliability,}
#' \item{SSD.PS}{the squared standard deviation (i.e., total person variability),}
#' \item{MSE}{the mean square measurement error (i.e., model error variance).}
#'
#' @details
#' See full documentation at \url{https://www.rdocumentation.org/packages/eRm/versions/1.0-1/topics/Separation\%20Reliability}
#'
#' @author Original code by Adrian Brügger (\email{[email protected]}), adapted by Marco J. Maier in package \code{eRm} v1.0-1
#'
#' @references
#' Wright, B.D., and Stone, M.H. (1999). Measurement essentials. Wide Range Inc., Wilmington. (\url{https://www.rasch.org/measess/me-all.pdf} 28Mb).
#'
#'
#' @export
SepRel_1.0.1 <- function (pobject)
{
if (!("ppar" %in% class(pobject)))
stop("\"pobject\" must be of class \"ppar\"")
PersonScoresFull <- pobject[["theta.table"]][["Person Parameter"]]
PersonScores <- PersonScoresFull[stats::complete.cases(PersonScoresFull)]
StandardErrors <- unlist(pobject[["se.theta"]])
SSD.PersonScores <- var(PersonScores)
MSE <- sum((StandardErrors)^2)/length(StandardErrors)
separation.reliability <- (SSD.PersonScores - MSE)/SSD.PersonScores
result <- structure(list(sep.rel = separation.reliability,
SSD.PS = SSD.PersonScores, MSE = MSE), class = "eRm_SepRel")
return(result)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/SepRel_101.R
|
#' Example of WHO Model Disability Survey data for adults
#'
#' An dummy data set of data from the WHO Model Disability Survey. All survey variables and demographic characteristics (except work status) are randomly generated. Responses to the survey questions and work status are from randomly selected rows of the 2014 Chilean implementation of the MDS, ENDIS II (2014).
#'
#' @format A tibble with 2500 rows and 90 variables:
#' \describe{
#' \item{HHID}{household number}
#' \item{strata}{survey strata}
#' \item{PSU}{PSU id}
#' \item{weight}{survey weights}
#' \item{sex}{sex, Male or Female}
#' \item{age}{age in years}
#' \item{age_cat}{age catgory, one of "18-24", "25-39", "40-64", or "64-100"}
#' \item{edu_cat}{highest level of education attained}
#' \item{work_cat}{whether respondent is currently working, binary}
#' \item{disability_score}{metric scale of performance, from Rasch analysis}
#' \item{disability_cat}{performance level, as definted by WHO cutoffs of disability_score}
#' \emph{Functioning section: On a scale from 1 (none) to 5 (extreme), in the last 30 days, taking into account any help or support you receive, how much has of a problem has it been for you to...}
#' \item{F1}{...stand up from sitting?}
#' \item{F2}{...stand for long periods of time, for example 30 minutes?}
#' \item{F3}{...leave the house?}
#' \item{F4}{...walk short distances, such as a street block or 100 meters?}
#' \item{F5}{...walk 10 blocks or a kilometer?}
#' \item{F6}{...do vigorous activities, such as play footbal, lift heavy objects, ride a bike or run?}
#' \item{F7}{...get where you want to go?}
#' \item{F8}{...manipulate small objects or opening a container?}
#' \item{F9}{...lift a 2L full bottle of water from your waist to eye level?}
#' \item{F10}{...wash or dress yourself?}
#' \item{F11}{...feed yourself?}
#' \item{F12}{...use the bathroom?}
#' \item{F13}{...cut your toenails?}
#' \item{F14}{...take care of your health, for example exercise, eat well or take your medications?}
#' \item{F15}{...see objects at a distance?}
#' \item{F16}{...see objects at arms length?}
#' \item{F17}{...hear a conversation in a quiet room?}
#' \item{F18}{...hear a conversation in a loud room?}
#' \item{F19}{...feel pain?}
#' \item{F20}{...sleep?}
#' \item{F21}{...feel tired or not have enough energy?}
#' \item{F22}{...feel short of breath?}
#' \item{F23}{...cough or wheeze?}
#' \item{F24}{...feel sad, down or depressed?}
#' \item{F25}{...feel worried, nervous or anxious?}
#' \item{F26}{...get along with people close to you, including your family and friends?}
#' \item{F27}{...get along with people you don't know?}
#' \item{F28}{...make new friends or maintain your friendships?}
#' \item{F29}{...have intimiate relationships?}
#' \item{F30}{...manage stress?}
#' \item{F31}{...cope with everything you have to do?}
#' \item{F32}{...be understood in your usual language?}
#' \item{F33}{...understand others in your usual language?}
#' \item{F34}{...forget things?}
#' \item{F35}{...remember the important things you have to do day-to-day?}
#' \item{F36}{...find solutions to your day-to-day problems?}
#' \item{F37}{...complete household tasks, like sweeping, cooking, arranging the house or taking our the trash?}
#' \item{F38}{...manage the money you have?}
#' \item{F39}{...do things for relaxation?}
#' \item{F40}{...participate in community activities?}
#' \item{F41}{...participate in local or national policitics or civil society?}
#' \item{F42}{...take care of others?}
#' \item{F43}{...get a job?}
#' \item{F44}{...obtain a higher education?}
#' \item{F45}{...use public transportation?}
#' \item{F46}{...get things done in your job (if not currently working, NA)?}
#' \item{F47}{...get things done at your school (if not currently studying, NA)?}
#' \emph{Capacity section: On a scale from 1 (none) to 5 (extreme), in the last 30 days, withing taking into account any type of help or support, due to your health how much difficulty have you had with...}
#' \item{C2}{...seeing, without contact lenses or glasses?}
#' \item{C3}{...hearing, without hearing aids?}
#' \item{C4}{...walking or climbing steps?}
#' \item{C5}{...remembering or concentrating?}
#' \item{C6}{...washing or dressing?}
#' \item{C7}{...communicating in your usual language?}
#' \item{C8}{...feeding yourself?}
#' \item{C9}{...using the bathroom?}
#' \item{C10}{...waking up and getting out of bed?}
#' \item{C11}{...going out to the street?}
#' \item{C12}{...doing shopping or going to the doctor?}
#' \item{C13}{...manipulating small objects or opening a container?}
#' \item{C14}{...sleeping?}
#' \item{C15}{...breathing?}
#' \item{C16}{...doing household tasks like sweeping, cooking, arranging the house or taking out the trash?}
#' \item{C17}{...taking care of others?}
#' \item{C18}{...participating in community activities?}
#' \item{C19}{...feeling sad, down or depressed?}
#' \item{C20}{...feeling worried, nervous or anxious?}
#' \item{C21}{...getting along with people close to you, including your family and friends?}
#' \item{C22}{...coping with everything you have to do?}
#' \item{C23}{...feeling pain?}
#' \item{C24}{...getting things done in your job (if not currently working, NA)?}
#' \item{C25}{...getting things done at your school (if not currently studying, NA)?}
#' \emph{Environmental factors section: On a scale from 1 (very easy) to 5 (very hard), to what extent...}
#' \item{EF1}{...do health facilities you need regularly make it easy or hard for you to use them?}
#' \item{EF2}{...do places where you socialize and engage in community activities make it easy or hard for you to do this?}
#' \item{EF3}{...do the shops, banks and post office in your neighbourhood make it easy or hard for you to use them?}
#' \item{EF4}{...do your regular places of worship make it easy or hard for you to worship?}
#' \item{EF5}{...does the transportation you need or want to use make it easy or hard for you to use it?}
#' \item{EF6}{...does your dwelling (including the toilet and all rooms) make it easy or hard for you to live there?}
#' \item{EF7}{...do the temperature, terrain, and climate of the place you usually live make it easy or hard for you to live there?}
#' \item{EF8}{...does the lighting in your surroundings make it easy or hard for you to live there?}
#' \item{EF9}{...does the noise in your surroundings make it easy or hard for you to live there?}
#' \item{EF10}{...do the crowds in your surroundings make it easy or hard for you to live there?}
#' \item{EF11}{...does your workplace make it easy or hard for you to work or learn (if not currently working, NA)?}
#' \item{EF12}{...does your educational institution make it easy or hard for you to work or learn (if not currently studying, NA)?}
#' }
"df_adults"
#' Example of WHO Model Disability Survey data for children
#'
#' An dummy data set of data from the WHO Model Disability Survey for children. All survey variables and demographic characterstics (except age variables) are randomly generated. Responses to the survey questions and age variables are from randomly selected rows of the 2014 Chilean implementation of the MDS, ENDIS II (2014).
#'
#' @format A tibble with 2500 rows and 42 variables:
#' \describe{
#' \item{HHID}{household number}
#' \item{strata}{survey strata}
#' \item{PSU}{PSU id}
#' \item{weight}{survey weights}
#' \item{sex}{sex, Male or Female}
#' \item{age}{age in years}
#' \item{age_cat}{age catgory, one of "Age2to4", "Age5to9", or "Age10to17"}
#' \emph{Functioning section: On a scale from 1 (none) to 5 (extreme), in the last 30 days, taking into account any help or support the child receives, compared with children of the same age, how much has of a problem it been for the child to...}
#' \item{child1}{...walk?}
#' \item{child2}{...manipulat small objects or opening a container?}
#' \item{child3}{...see things from a long distance?}
#' \item{child4}{...hear?}
#' \item{child5}{...feel pain?}
#' \item{child6}{...not have enough energy?}
#' \item{child7}{...have too much energy}
#' \item{child8}{...feel short of breath?}
#' \item{child9}{...feel sad, down or depressed?}
#' \item{child10}{...feel worried, nervous or anxious?}
#' \item{child11}{...(for children aged 5 to 17) wash or dress him- or herself?}
#' \item{child12}{...(for children aged 2 to 4) bite or hit other children or adults?}
#' \item{child13}{...(for children aged 5 to 17) control his or her own behavior?}
#' \item{child14}{...(for children aged 5 to 17) get along with children of the same age?}
#' \item{child15}{...(for children aged 2 to 4) understand what you say to him or her?}
#' \item{child16}{(for children aged 2 to 4) How much of a problem has it been for you to understand what the child says?}
#' \item{child17}{...(for children aged 5 to 17) understand other people?}
#' \item{child18}{...(for children aged 5 to 17) be understood?}
#' \item{child19}{...(for children aged 2 to 3) learn the names of household objects?}
#' \item{child20}{...(for children aged 3 to 17) learn to do new things?}
#' \item{child21}{...(for children aged 5 to 17) complete a task?}
#' \item{child22}{...(for children aged 5 to 17) make changes to his or her routine?}
#' \item{child23}{...(for children aged 5 to 17) do homework as requested at school?}
#' \item{child24}{...(for children aged 2 to 5) play with toys or domestic objects?}
#' \item{child25}{...(for children aged 2 to 12) play with other children?}
#' \item{child26}{...(for children aged 13 to 17) do activities with other children?}
#' \item{child27}{...(for children aged 5 to 17) participate in community activities?}
#' \emph{Capacity section: On a scale from 1 (none) to 5 (extreme), in the last 30 days, without taking into account any help or support the child receives, how much has difficulty has the child had with...}
#' \item{child28}{...seeing without glasses?}
#' \item{child29}{...hearing without hearing aids?}
#' \item{child30}{...walking?}
#' \item{child31}{...understanding you or others?}
#' \item{child32}{...learning?}
#' \item{child33}{...controling his or her behavior?}
#' \item{child34}{...completing a task?}
#' \item{child35}{...getting along with other children?}
#' }
"df_children"
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/data.R
|
#' Print a graph showing significant correlations between survey items
#'
#' @param LIDforgraph a square matrix of item correlations
#' @param LIDcutoff a numeric value between 0 and 1 for the cut-off for significant correlation
#' @param path_output a string with the path to the output folder
#' @param extra_file_label a string to tack on to the end of names of files outputted and the title of the plot. Default is NULL.
#' @param vertex_print_grey a character vector with the names of vertices to print in \code{"lightgrey"}, with all others printed in \code{"skyblue"}. If left as default NULL, all vertices will be printed in \code{"lightgrey"}.
#'
#' @return Returns a ggplot graph showing the items with correlation >= \code{LIDcutoff} and prints a csv of the corresponding correlations
#'
#' @details This function could be applied to visualize any kind of correlations. But within the context of the Rasch Analysis used for the WHO Model Disability Survey, the residual correlations are used when analyzing item dependence.
#' @export
#'
#' @family figure functions
fig_LID <- function(LIDforgraph, LIDcutoff = 0.2, path_output, extra_file_label = NULL, vertex_print_grey = NULL) {
#create dependency graph
fullgraph <- igraph::graph_from_adjacency_matrix((LIDforgraph >= LIDcutoff)*1,
diag=FALSE,
mode="upper")
#remove vertices not connected to other vertices
comp.no <- which(igraph::components(fullgraph)$csize>1)
igraph::V(fullgraph)$comp <- igraph::components(fullgraph)$membership
finalgraph <- igraph::induced_subgraph(fullgraph, igraph::V(fullgraph)$comp %in% comp.no)
# df_finalgraph <- igraph::as_long_data_frame(finalgraph)
#save file names
if (is.null(extra_file_label)) {
# plot_file_label <- paste0(path_output,"/LID_plot.pdf")
spreadsheet_file_label <- paste0(path_output,"/LID_above_", LIDcutoff,".csv")
title_label <- paste("Local Dependencies above cut-off", LIDcutoff)
} else {
# plot_file_label <- paste0(path_output,"/LID_plot_", extra_file_label,".pdf")
spreadsheet_file_label <- paste0(path_output,"/LID_above_", LIDcutoff, "_", extra_file_label,".csv")
title_label <- paste("Local Dependencies above cut-off", LIDcutoff, extra_file_label)
}
#save vector for colors
if (is.null(vertex_print_grey)) vertex_color <- "lightgrey"
else vertex_color <- c("skyblue","lightgrey")[1+igraph::V(finalgraph)$name %in% vertex_print_grey]
#create plot
if (all(igraph::components(fullgraph)$csize == 1)) {
final_plot <- ggplot2::ggplot() +
ggplot2::ggtitle(paste("No LID found above cut-off", LIDcutoff))
} else {
# final_plot <- GGally::ggnet2(finalgraph, label = TRUE, color = vertex_color) +
# ggplot2::ggtitle(title_label)
final_plot <- finalgraph %>%
tidygraph::as_tbl_graph() %>%
tidygraph::activate(nodes) %>%
dplyr::mutate(vert_clr = vertex_color) %>%
ggraph::ggraph(layout = "fr") +
ggraph::geom_edge_link() +
ggraph::geom_node_point(aes(color = vert_clr), size = 20) +
ggplot2::scale_color_manual(values = vertex_color) +
ggraph::geom_node_text(aes(label = name)) +
ggplot2::ggtitle(title_label) +
ggplot2::theme(legend.position = "none",
panel.background = ggplot2::element_rect(fill = "white"))
}
#print plot
# grDevices::pdf(plot_file_label)
# final_plot
# grDevices::dev.off()
# if (igraph::components(finalgraph)$no==0) {
# grDevices::pdf(plot_file_label)
# graphics::plot(0,0, col="white", bty="n", xaxt="n", yaxt="n", xlab="", ylab="")
# graphics::text(-0.25,0, "No LID found!", col="blue", cex=1.4)
# grDevices::dev.off()
# } else {
# grDevices::pdf(plot_file_label)
# graphics::plot(finalgraph,
# layout=igraph::layout.kamada.kawai,
# vertex.label=igraph::V(finalgraph)$name,
# vertex.size=25,
# main= title_label,
# vertex.color=vertex_color,
# vertex.label.color="black",
# edge.color="black")
# grDevices::dev.off()
# }
#print spreadsheet with only correlations above cut-off
LIDforgraph[is.na(LIDforgraph)] <- 0
LIDforgraph[which(LIDforgraph < LIDcutoff)] <- 0
utils::write.csv(LIDforgraph, spreadsheet_file_label)
return(final_plot)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/fig_LID.R
|
#' Plot a density of a score
#'
#' @param df a data frame where each row is an individual, containing at least a score column (between 0 and 100)
#' @param score a string (length 1) of the column name for the score variable to print the distribution of
#' @param var_color a string (length 1) of the column name for the variable to set color of density lines by. Default is NULL.
#' @param var_facet a string (length 1) of the column name for the variable to create a \code{ggplot2::facet_grid()} with. Default is NULL.
#' @param cutoffs a numeric vector of the cut-offs for the score categorization. Default is NULL.
#' @param x_lab a string (length 1) of x-axis label. Default is "Score".
#' @param pal a string specifying either a manual color to use for the color aesthetic, a character vector explictly specifying the colors to use for the color scale, or as the name of a palette to pass to \code{RColorBrewer::brewer.pal()} with the name of the color palette to use for the color scale. Default is \code{"Paired"}
#' @param adjust a numeric value to pass to \code{adjust} argument of \code{ggplot2::geom_density()}. Default is 2.
#' @param size a numeric value to pass to \code{size} argument of \code{ggplot2::geom_density()}. Default is 1.5.
#'
#' @return A density figure
#'
#' @details Plots a histogram of a score that ranges between 0 and 100, with the fill determined by some set categorization of the score. This is the function used to plot the distributions of disability scores resulting from the WHO Model Disability Survey.
#'
#' @family figure functions
#' @export
#'
#' @import ggplot2
#' @import dplyr
#'
#' @examples
#' fig_density(df_adults, score = "disability_score", cutoffs = c(19.1, 34.4, 49.6),
#' x_lab = "Disability score")
#' fig_density(df_adults, score = "disability_score", var_color = "sex",
#' cutoffs = c(19.1, 34.4, 49.6), x_lab = "Disability score")
#' fig_density(df_adults, score = "disability_score", var_color = "sex",
#' var_facet = "age_cat", cutoffs = c(19.1, 34.4, 49.6), x_lab = "Disability score")
fig_density <- function(df, score, var_color = NULL, var_facet = NULL,
cutoffs = NULL, x_lab = "Score",
pal = "Paired", adjust = 2, size = 1.5){
#convert to tibble
if (!tibble::is_tibble(df)) df <- df %>% as_tibble()
#Initialize plot
if (is.null(var_color)) {
plot_density <- ggplot(df, aes(x = !!rlang::sym(score)))
} else {
if (!is.factor(pull(df, var_color))) stop("var_color must be a factor")
plot_density <- ggplot(df, aes(x = !!rlang::sym(score),
color = !!rlang::sym(var_color)))
}
#set colors
if (length(pal) == 1) {
if (pal %in% rownames(RColorBrewer::brewer.pal.info)) {
#if length == 1 and pal in palettes -> brewer scale
plot_density <- plot_density +
geom_density(adjust = adjust, size = size) +
scale_color_brewer(palette = pal)
} else {
#if length == 1 and pal not in palettes -> color aesthetic
plot_density <- plot_density +
geom_density(adjust = adjust, size = size, color = pal)
}
} else {
#if length != 1 -> manual color scale
plot_density <- plot_density +
geom_density(adjust = adjust, size = size) +
scale_color_manual(values = pal)
}
#Continue plot with formatting
plot_density <- plot_density +
scale_x_continuous(limits = c(min(0, min(cutoffs)), 100)) +
labs(x = x_lab) +
theme(
panel.background = element_rect(fill = "transparent"), # bg of the panel
panel.grid.major = element_line(colour = "grey90"),
panel.grid.minor = element_blank(), # get rid of minor grid
legend.background = element_rect(fill = "transparent"), # get rid of legend bg
legend.title = element_blank(),
legend.position="top",
legend.box = "horizontal",
legend.text = element_text(size = 12),
plot.background = element_rect(fill = "transparent", color = NA), # bg of the plot
plot.margin = unit(c(1, 1, 3, 1), "lines"),
axis.text.y = element_text(size = 12, colour = "black"),
axis.text.x = element_text(size = 12, colour = "black", angle = 0, hjust = 0.5, vjust = 0.5),
axis.title.y = element_text(size = 14),
axis.title.x = element_text(size = 14)
)
#add cutoffs lines if non-NULL
if (!is.null(cutoffs)) {
plot_density <- plot_density +
geom_vline(xintercept = cutoffs, color="black", linetype="dashed", size=.5)
}
#add facet grid if var_facet non-NULL
if (!is.null(var_facet)) {
plot_density <- plot_density +
facet_grid(stats::formula(paste("~", var_facet)))
}
return(plot_density)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/fig_density.R
|
#' Plot a distribution of a score
#'
#' @param df a data frame where each row is an individual, containing at least a score column (between 0 and 100) and a categorization of that score
#' @param score a string (length 1) of the column name for the score variable to print the distribution of
#' @param score_cat a string (length 1) of the column name for the categorization of the score variable
#' @param cutoffs a numeric vector of the cut-offs for the score categorization
#' @param x_lab a string (length 1) of x-axis label. Default is "Score".
#' @param y_max a numeric value of the maximum limit on the y-axis. Default is NULL to use default value from \code{geom_histogram()}
#' @param pcent a logical value determining whether or not to display the distribution as percentages or frequency. Default is FALSE, to display as frequency.
#' @param pal a string to pass to \code{RColorBrewer::brewer.pal()} with the name of the color palette to use
#' @param binwidth a numeric value giving the width of the bins in the histograph. Default is 5.
#'
#' @return A score distribution figure with fill based on categorization of the score
#'
#' @details Plots a histogram of a score that ranges between 0 and 100, with the fill determined by some set categorization of the score. This is the function used to plot the distributions of disability scores resulting from the WHO Model Disability Survey.
#'
#' @family figure functions
#' @export
#'
#' @import ggplot2
#' @import dplyr
#'
#' @examples
#' fig_dist(df_adults, score = "disability_score", score_cat = "disability_cat",
#' cutoffs = c(19.1, 34.4, 49.6), x_lab = "Disability score")
#' fig_dist(df_adults, score = "disability_score", score_cat = "disability_cat",
#' cutoffs = c(19.1, 34.4, 49.6), x_lab = "Disability score", y_max = 2000)
#' fig_dist(df_adults, score = "disability_score", score_cat = "disability_cat",
#' cutoffs = c(19.1, 34.4, 49.6), x_lab = "Disability score", y_max = 0.2, pcent=TRUE)
fig_dist <- function(df, score, score_cat, cutoffs,
x_lab = "Score", y_max = NULL, pcent=FALSE, pal = "Blues", binwidth = 5){
#convert to tibble
if (!tibble::is_tibble(df)) df <- df %>% as_tibble()
if (pcent) {
y_lab <- "Percent"
type <- "..count../sum(..count..)"
# default y-axis values to try
possible_scale <- c(0.01,0.05,0.1,0.2,0.25)
final_scale <- 0.05
lab <- scales::percent_format()
} else {
y_lab <- "Frequency"
type <- "..count.."
# default y-axis values to try
possible_scale <- c(200,250,300,500,1000)
final_scale <- 100
lab <- waiver()
}
fill_colors <- RColorBrewer::brewer.pal(length(levels(pull(df,score_cat))),pal)
#Begin plot
plot_dist <- ggplot(df, aes_string(x = score, fill = score_cat)) +
geom_histogram(position = "identity", binwidth = binwidth, aes_string(y=type), col="black") +
scale_fill_manual(values = fill_colors, drop=FALSE) +
scale_x_continuous(breaks = seq(0, 100, by = 10), limits = c(min(-2.5,min(cutoffs)),102.5)) +
# scale_y_continuous(breaks = seq(0, y_max, by = final_scale), limits=c(NA,y_max), labels=lab) +
labs(x = x_lab, y = y_lab) +
geom_vline(xintercept = cutoffs, color="black", linetype="dashed", size=1) +
theme(plot.margin = unit(c(1, 1, 3, 1), "lines"),
legend.title=element_blank(),
panel.grid.minor = element_blank(),
panel.grid.major = element_line(colour = "grey90"),
panel.background = element_rect(fill = "white"),
legend.position="top",
legend.box = "horizontal",
axis.text.y = element_text(size = 12, colour = "black"),
axis.text.x = element_text(size = 12, colour = "black"),
axis.title.y = element_text(size = 14),
axis.title.x = element_text(size = 14),
legend.text = element_text(size = 12))
if (!is.null(y_max)) {
# Calculate a good y-axis scale to use
divis <- possible_scale[y_max %% possible_scale == 0]
cond <- y_max/divis > 5 & y_max/divis < 16
if (any(cond)) {
final_possible_scale <- divis[cond]
final_scale <- utils::tail(final_possible_scale,1)
}
plot_dist <- plot_dist +
scale_y_continuous(breaks = seq(0, y_max, by = final_scale), limits=c(NA,y_max), labels=lab)
} else {
plot_dist <- plot_dist +
scale_y_continuous(labels=lab)
}
return(plot_dist)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/fig_dist.R
|
#' Print a population pyramid
#'
#' @param var_age a string (length 1) of the name of the age column
#' @param var_sex a string (length 1) of the name of the sex column
#' @param x_axis a string (length 1) indicating whether to use absolute numbers or sample percentage on the x-axis. Choices are \code{"n"} (default) or \code{"pct"}.
#' @param age_plus a numeric value (length 1) indicating the age that is the first value of the oldest age group. Default is 100, for the last age group to be 100+
#' @param age_by a numeric value (length 1) indicating the width of each age group, in years. Default is 5.
#' @inheritParams rasch_mds
#'
#' @return A population pyramid figure
#'
#' @details A population pyramid gives an image of the age and sex distribution of a population.
#'
#' The function divides the \code{var_age} variable into intervals of width \code{age_by}.
#'
#' @export
#'
#' @family figure functions
#'
#' @import ggplot2
#' @import dplyr
#'
#' @examples
#' fig_poppyramid(df_adults, "age", "sex")
fig_poppyramid <- function(df, var_age, var_sex, x_axis = c("n", "pct"), age_plus = 100, age_by = 5){
#make sure x_axis contains acceptable answers
x_axis <- match.arg(x_axis)
#store x axis label based on x_axis
if (x_axis == "n") x_axis_label <- "Sample (N)"
else if (x_axis == "pct") x_axis_label <- "Sample (%)"
#convert to tibble
if (!tibble::is_tibble(df)) df <- df %>% as_tibble()
#create age labels
age_labels <- c(paste0(seq(0,age_plus-age_by,age_by),
"-",
seq(age_by-1, age_plus-1, age_by)),
paste0(age_plus,"+"))
#create age groups
df <- df %>%
mutate(age_cat = cut(!!rlang::sym(var_age),
breaks = c(seq(0, age_plus, by = age_by), Inf),
labels = age_labels,
right = FALSE))
#filter df, count, calculate percent
df_new <- df %>%
group_by_at(c("age_cat", var_sex)) %>%
summarize(n=n()) %>%
rename("sex" = !!enquo(var_sex)) %>%
ungroup() %>%
mutate(pct = round(n/sum(n)*100, 1))
#create plot
plot_pry <- df_new %>%
ggplot(aes(x = age_cat, y = !!rlang::sym(x_axis), fill = sex)) +
guides(fill = guide_legend(title = NULL)) +
geom_bar(data = filter(df_new, sex == "Female"),
stat = "identity") +
geom_bar(data = filter(df_new, sex == "Male"),
stat = "identity",
position = "identity",
mapping = aes(y = -!!rlang::sym(x_axis))) +
scale_y_continuous(labels = abs, name = x_axis_label) +
scale_x_discrete(name = "Age group (years)") +
coord_flip() +
scale_fill_brewer(palette = "Set1") +
theme_bw()
return(plot_pry)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/fig_poppyramid.R
|
#' Check a vector for particular values
#'
#' @param row a vector of data
#' @param check_type a string indicating the type of check to do on \code{row}. Options are \code{"all_equal"}, \code{"all_not_equal"}, and \code{"any_in"}. A value of \code{"all_equal"} will check that all values in \code{row} equal \code{check_value}. A value of \code{"all_not_equal"} will check that all values of \code{row} are not equal to \code{check_value}. A value of \code{"any_in"} will check if any of the values in \code{check_value} are in \code{row}.
#' @param check_value a vector of values to check against
#' @param na_rm logical indicating whether or not to perform check after removing NAs, passed to argument \code{na.rm} of \code{any()} or \code{all()}. Default is TRUE.
#'
#' @return a logical vector with the result of the check
#'
#' @details If all values of \code{row} are NA, then an NA is returned.
#'
#' @family helper functions
helper_checkrow <- function(row,
check_type = c("all_equal", "all_not_equal", "any_in"),
check_value,
na_rm = TRUE) {
#check check_type inputted correctly
check_type <- match.arg(check_type)
#check row and check_value have same mode
if (mode(row) != mode(check_value))
stop("row and check_value must be the same mode")
#check check_value has length 1 for check_type == "all_equal" or "all_not_equal"
if ((check_type %in% c("all_equal", "all_not_equal")) &
length(check_value) > 1)
stop("check_value must be length 1")
#apply the check
if (all(is.na(row))) {
out <- NA
} else if (check_type == "all_equal") {
out <- all(row == check_value, na.rm = na_rm)
} else if (check_type == "all_not_equal") {
out <- all(row != check_value, na.rm = na_rm)
} else if (check_type == "any_in") {
out <- any(row %in% check_value, na.rm = na_rm)
}
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/helper_checkrow.R
|
#' Create indicators from data frame
#'
#' @param df a data frame
#' @param vars_indicators a character vector of the variables from \code{df} to create indicators for
#' @param mapvalues_from vector to pass to \code{plyr::mapvalues()} argument \code{from}
#' @param mapvalues_to vector to pass to \code{plyr::mapvalues()} argument \code{to}
#' @param make_factor a logical indicating whether resulting indicators should be factors. Default is \code{TRUE}.
#'
#' @return a data frame with new columns that are the indicators from \code{vars_indicators}, with the same names pasted with \code{"_ind"}.
#' @export
#'
#' @examples helper_indicator(df = df_adults,
#' vars_indicators = c("EF1", "EF2", "EF3"),
#' mapvalues_from = 1:5,
#' mapvalues_to = c(0,0,0,1,1))
helper_indicator <- function(df, vars_indicators, mapvalues_from , mapvalues_to, make_factor = TRUE) {
#check package plyr is installed
rlang::check_installed("plyr", reason = "to use helper_indicator()")
vars_indicators_new <- paste0(vars_indicators, "_ind")
df_new <- df %>%
bind_cols(
df %>%
select(!!vars_indicators) %>%
rename_at(vars(all_of(vars_indicators)),
list(~ paste0(., "_ind")))
) %>%
mutate_at(vars(all_of(vars_indicators_new)),
list(~ plyr::mapvalues(., from = mapvalues_from, to = mapvalues_to, warn_missing = TRUE)))
if (make_factor) df_new <- df_new %>%
mutate_at(vars(all_of(vars_indicators_new)),
list( ~ factor(.)))
return(df_new)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/helper_indicator.R
|
#' Check installation of whomds is the most updated
#'
#' @description Compares build date of installed package against the date of the last commit from GitHub (\url{https://github.com/lindsayevanslee/whomds})
#'
#' @return Prints a message stating whether or not installed package is same as most updated version from Github
helper_installation <- function() {
#check packages httr and lubridate are installed
rlang::check_installed("httr", reason = "to use helper_installation()")
rlang::check_installed("lubridate", reason = "to use helper_installation()")
#capture last commit time
commit <- httr::content(httr::GET(url = "https://api.github.com/repos/lindsayevanslee/whomds/git/refs/heads/master"))
commit_info <- httr::content(httr::GET(url = commit$object$url))
last_commit_datetime <- lubridate::as_datetime(commit_info$author$date)
#capture date of installation of package
install_datetime <- utils::packageDescription("whomds", fields = "Built")
install_datetime <- stringr::str_split(install_datetime, "; ")
install_datetime <- base::unlist(install_datetime)
install_datetime <- base::suppressWarnings(lubridate::as_datetime(install_datetime))
install_datetime <- stats::na.exclude(install_datetime)
#compare installation and commit dates and change startup message accordingly
if (last_commit_datetime > install_datetime) {
message("There is a more updated version of the package available on github. You may want to reinstall this package to update it.")
} else {
message("Installed version is most updated.")
}
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/helper_installation.R
|
#use this function for generating the color palette (from colorspace package)
#' Color palette for the MDS
#'
#' @param c. chroma value in the HCL color description.
#' @inheritParams colorspace::heat_hcl
#'
#' @details Generated with \code{colorspace::choose_palette()}
#'
#' @return \code{n} hex codes from the color palette
#'
#' @family helper functions
#'
helper_palette <- function(n, h = c(-100, 100), c. = c(60, 100), l = c(15, 95),
power = c(2, 0.9), fixup = TRUE, gamma = NULL, alpha = 1,
...) {
if (!is.null(gamma))
warning("'gamma' is deprecated and has no effect")
if (n < 1L)
return(character(0L))
h <- rep(h, length.out = 2L)
c <- rep(c., length.out = 2L)
l <- rep(l, length.out = 2L)
power <- rep(power, length.out = 2L)
rval <- seq(1, 0, length = n)
rval <- colorspace::hex(colorspace::polarLUV(L = l[2L] - diff(l) * rval^power[2L],
C = c[2L] - diff(c) * rval^power[1L], H = h[2L] - diff(h) *
rval), fixup = fixup, ...)
if (!missing(alpha)) {
alpha <- pmax(pmin(alpha, 1), 0)
alpha <- format(as.hexmode(round(alpha * 255 + 1e-04)),
width = 2L, upper.case = TRUE)
rval <- paste(rval, alpha, sep = "")
}
return(rval)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/helper_palette.R
|
#' Perform row sum
#'
#' @param x an array of two or more dimensions, containing numeric, complex, integer or logical values, or a numeric data frame
#' @param allNA0 logical indicating that if a whole row is NA to give the row sum as NA. Only works for two dimensional \code{x} and if \code{na.rm} is \code{TRUE}.
#' @param ... other arguments to pass to \code{base::rowSums()}
#'
#' @return A numeric or complex array of suitable size, or a vector if the result is one-dimensional.
#'
#' @details Essentially equivalent to \code{base::rowSums()} except with the addition of the \code{allNA0} argument.
#' @export
#'
#' @examples
#' x <- data.frame(v1 = c(NA,1:4), v2 = c(NA, 2:5), v3 = c(NA, 1:2, NA, 3))
#' helper_rowSums(x, na.rm = TRUE, allNA0 = TRUE)
#' helper_rowSums(x, na.rm = TRUE, allNA0 = FALSE)
helper_rowSums <- function (x, allNA0 = TRUE, ...)
{
#store arguments to pass to base::rowSums
dots <- list(...)
#perform rowSums
if (length(dots)== 0) out <- base::rowSums(x = x)
else out <- base::rowSums(x = x, ...)
#if whole row is NA, make rowSum NA (only worry about 2 dimensional x)
if (length(dim(x))==2L & allNA0) {
out[apply(x, 1, function(r) all(is.na(r)))] <- NA
}
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/helper_rowSums.R
|
#' Convert list to vector with unique elements
#'
#' @param vars_list a list of character vectors
#'
#' @return a character vector of all unique items from \code{vars_list}
#'
#' @family helper functions
#'
helper_varslist <- function(vars_list) {
vars_vec <- vars_list %>%
unlist() %>%
unique() %>%
sort()
return(vars_vec)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/helper_varslist.R
|
#' Perform analysis of Differential Item Functioning (DIF) for Rasch Model
#'
#' @param residuals_PCM a matrix giving the residuals of the person parameters from the Rasch Model. Row names are the numbers of the people and the columns are for each variable.
#' @param breaks a numeric value giving the number if class intervals. Default is 6.
#' @inheritParams rasch_mds
#' @inheritParams rasch_factor
#'
#' @return a list with results from the DIF analysis:
#' \item{df_DIF_class}{the person residuals from the Rasch Model, the assigned class intervals, and the variables used for DIF analysis}
#' \item{tab_aov_DIF}{the results of the ANOVA used to analyze DIF}
#' \item{DIF_results}{string of various that exhibit some form of DIF}
#'
#' @details Differential Item Functioning (DIF) refers to the circumstance when different groups in a sample respond to items in different ways. For instance, DIF would be observed if men and women had different patterns of responses to a set of survey questions. DIF can cause poor fit for the Rasch Model, and therefore should be analyzed. This function uses ANOVA to find DIF by the variables supplied and by a generated class interval.
#'
#' @family rasch functions
#'
#' @export
#' @import dplyr
#'
#' @note Currently the calculation of the class intervals is quite slow. Reducing the number of breaks can improve speed.
rasch_DIF <- function(df, vars_metric, vars_DIF, residuals_PCM, split_strategy = NULL, print_results = FALSE, path_output = NULL, breaks = 6) {
#convert to tibble
if (!tibble::is_tibble(df)) df <- df %>% as_tibble()
#save data frame for DIF
df_DIF <- df %>%
select(c(vars_metric,vars_DIF))
df_metric <- df_DIF %>%
select(vars_metric)
### "DIF analysis bases on the residuals
residuals_PCM <- residuals_PCM %>%
as.data.frame() %>%
tibble::rownames_to_column("person") %>%
rename_at(vars(vars_metric), list(~ paste0(.,"_Res")))
vars_metric_res <- colnames(residuals_PCM)[-1] #list of names of variable residuals
rows <- residuals_PCM %>%
pull(person) %>%
stringr::str_extract_all("[:digit:]+") %>%
unlist() %>%
as.numeric()
###create class intervals
#Get the residuals....
residuals_PCM_cols <- residuals_PCM %>%
select(-person)
df_metric_rows <- df_metric %>%
slice(rows)
df_metric_rows_sums <- rowSums(df_metric_rows,na.rm=TRUE)
rows_sums_quantile <- stats::quantile(df_metric_rows_sums, probs = seq(0, 1, 1/breaks), na.rm=TRUE)
lst <- purrr::map(list()[1:(breaks-1)], ~ c("<","<="))
Gri <- expand.grid(lst) %>%
as_tibble() %>%
mutate_all(as.character)
Grid <- Gri %>%
mutate(Var6 = "<=")
Mat <- rows_sums_quantile[-1] %>%
tibble() %>%
t() %>%
as_tibble() %>%
slice(rep(1,nrow(Grid)))
Intervals <- purrr::map2_dfc(Grid, Mat, ~paste0(..1, ..2))
Dmat <- df_metric_rows_sums %>%
tibble() %>%
t() %>%
as_tibble() %>%
slice(rep(1,nrow(Grid)))
###here save the group intervals
Detect <- function(x,y){
Dbound <- outer(x, y, paste)
Where <- apply(Dbound, c(1, 2), function(elem) eval(parse(text = elem)))
apply(Where, 1, function(r) min(which(r), na.rm = TRUE))
}
what <- list()
for(i in 1:nrow(Dmat)){ #very slow
what[[i]] <- Detect(Dmat[i,],Intervals[i,])
}
names(what) <- paste0("v",1:length(what))
sol <- bind_cols(what) %>% t() %>% as_tibble()
k <- apply(sol,1,table)
if (inherits(k, "matrix")){
Grouping <- which.min(apply(k,2,var))
} else {
take_in <- which(lapply(k, length)==breaks)
K <- k[take_in]
Grouping <- take_in[which.min(unlist(lapply(K,var)))]
}
class_intervals <- sol %>%
slice(Grouping) %>%
t()
df_DIF_class <- bind_cols(class_intervals = class_intervals[,1],
select(residuals_PCM,-person),
slice(df_DIF, rows))
#perform ANOVA for each vars_metric_res and each vars_DIF
list_aov_DIF <- purrr::map(.x = vars_metric_res,
.f = ~ purrr::map2(.x, .y = vars_DIF,
.f = function(res, dif) {
# if there was a split AND this vars_DIF was used to split vars AND if this vars_metric was split by this vars_DIF
if(!is.null(split_strategy) &
(dif %in% names(split_strategy)) &
(unlist(strsplit(res,"_"))[1] %in% split_strategy[[dif]])){
result <- matrix(NA, nrow = 4, ncol = 5)
}
#if there was not a split OR this vars_DIF not used to split vars OR this variable not split by this vars_DIF
else {
#Anova of item residual and dif group
result <- try(matrix(unlist(summary(
stats::aov(
as.numeric(pull(df_DIF_class, res)) ~ # residual
as.factor(pull(df_DIF_class, dif)) + #demographic
as.factor(pull(df_DIF_class, "class_intervals")) + #class interval
as.factor(pull(df_DIF_class, dif)):as.factor(pull(df_DIF_class, "class_intervals")) #interaction between demo and class_intervals
)
)), ncol = 5), silent = TRUE)
}
if (!inherits(result, "try-error")) {
colnames(result) <-
c("Df", "Sum Sq", "Mean Sq", "F value", "Pr(>F)")
rownames(result) <-
c(
dif,
"class interval",
paste0(dif, ":class interval"),
"residuals"
)
result <- result %>%
as_tibble(rownames = "anova") %>%
tibble::add_column(DIF = dif, .before = 1)
}
return(result)
}) %>% bind_rows()
)
names(list_aov_DIF) <- vars_metric_res
#store Bonferonni corrected p-value
Bonferonni <- 0.05 / (length(vars_DIF) *
3 *
(length(vars_DIF) + length(vars_metric)))
#tab_aov_DIF stacks data frames for each variable vertically and flags possible DIF
tab_aov_DIF <- bind_rows(list_aov_DIF, .id = "variable") %>%
mutate(!!rlang::sym(paste0("significant_at_",Bonferonni)) := case_when(
`Pr(>F)` < Bonferonni ~ "X",
TRUE ~ "-"
))
DIF_results <- tab_aov_DIF %>%
select(variable, contains("significant")) %>%
filter_at(vars(contains("significant")),
all_vars(. == "X")) %>%
pull(variable) %>%
paste(collapse = ", ")
if (print_results) {
readr::write_csv(df_DIF_class, file = paste0(path_output,"/Anova_Residuals.csv"))
readr::write_csv(tab_aov_DIF, file = paste0(path_output, "/DIF_rumm.csv"))
}
DIF_result <- list(df_DIF_class = df_DIF_class,
tab_aov_DIF = tab_aov_DIF,
DIF_results = DIF_results)
return(DIF_result)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/rasch_DIF.R
|
#' Nest data by age group
#'
#' @inheritParams rasch_mds_children
#'
#' @return nested tibble with two columns: the age group given by \code{vars_group} and \code{df_split} with the split data
#' @export
#'
#' @family rasch functions
#' @family children analysis functions
#'
rasch_df_nest <- function(df, vars_group, vars_id) {
#remove people with NA for age group
df_nest <- df %>%
filter(!is.na(!!rlang::sym(vars_group)))
#split data by age group and add back the max and min rows row
df_nest <- df_nest %>%
group_by_at(vars_group) %>%
tidyr::nest() %>%
rename(df_split = data) %>%
mutate(df_split = purrr::map(df_split, function(df_age) {
df_age <- bind_rows(df_age,
df %>% filter(!!rlang::sym(vars_id) %in% c("MAX","MIN")))
}))
return(df_nest)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/rasch_df_nest.R
|
#' Drop items from a Rasch Analysis
#'
#' @inheritParams rasch_mds
#' @inheritParams rasch_testlet
#'
#' @return a named list with:
#' \item{vars_metric}{new \code{vars_metric} after dropping the desired variables}
#' \item{max_values}{new \code{max_values} after dropping the desired variables}
#'
#' @details Dropping variables might be desirable if one finds that particular items are causing a lot of problems for the fit of a Rasch Model.
#'
#' @family rasch functions
#' @family children analysis functions
#'
#' @export
rasch_drop <- function(vars_metric, drop_vars, max_values) {
if (!all(drop_vars %in% helper_varslist(vars_metric))) stop("You input a string that is not included in the variable list.")
#edit list of variables
if (is.list(vars_metric)) {
vars_metric <- purrr::map(vars_metric, function(vset) {
if (any(drop_vars %in% vset)) {
new_vset <- vset[-which(vset %in% drop_vars)]
} else {
new_vset <- vset
}
return(new_vset)
})
} else {
vars_metric <- vars_metric[-which(vars_metric %in% drop_vars)]
}
#edit data.frame of maximum possible values
max_values <- max_values %>%
filter(!(var %in% drop_vars))
drop_result <- list(vars_metric = vars_metric,
max_values = max_values)
return(drop_result)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/rasch_drop.R
|
#' Calculate a factor analysis for a Rasch Model
#'
#' @param path_output a string with the path to the output folder. Default is NULL.
#' @inheritParams rasch_mds
#'
#' @return a named list with results from the factor analysis for a Rasch Model:
#' \item{cor_poly}{the matrix of polychoric correlations}
#' \item{eigenvalues}{the eigenvalues}
#' \item{parallel_analysis}{permutation parallel analysis distribution}
#' \item{results_scree}{results of a scree analysis}
#' \item{n_group_factors}{number of factors from the parallel analysis in the scree analysis}
#' \item{fa_onefactor}{results from factor analysis with one factor}
#' \item{fa_resid}{local dependency based on polychoric correlations of the items}
#'
#' @details Unidimensionality of the data is one of the core assumptions of the Rasch Model. This function performs the factor analysis to assess the unidimensionality of the data.
#'
#' @family rasch functions
#'
#' @export
#'
#' @importFrom GPArotation GPForth
#' @importFrom psych fa factor.residuals vgQ.bimin
rasch_factor <- function(df, vars_metric, print_results = FALSE, path_output = NULL) {
#----------------------------
#convert to tibble
if (!tibble::is_tibble(df)) df <- df %>% as_tibble()
# create data frame with ordered factors
df_ordered <- df %>%
dplyr::select(all_of(vars_metric)) %>%
dplyr::mutate_all(list(~ ordered(.))) %>%
as.data.frame()
df_numeric <- df %>%
dplyr::select(all_of(vars_metric)) %>%
as.data.frame()
# calculate polychoric correlations
cor_poly <- polycor::hetcor(df_ordered, use ="pairwise.complete.obs", ML = FALSE, std.err=FALSE)
#----------------------------
# permuted parallel analysis to test the unidimensionality
eigenvalues <- nFactors::eigenComputes(x=df_numeric, use="pairwise.complete.obs")
# Permutation parallel analysis distribution
parallel_analysis <- nFactors::eigenBootParallel(x=df_numeric, quantile=0.95, nboot=30, option="permutation",
cor=TRUE, model="components", use="pairwise.complete.obs")$quantile
# number of components to retain
results_scree <- nFactors::nScree(x = eigenvalues, aparallel = parallel_analysis)
n_group_factors <- results_scree$Components$nparallel
#----------------------------
# bi-factor analysis to test the unidimensionality
fa_bifactor <- try(psych::fa(cor_poly$correlations,n_group_factors+1,rotate="bifactor"), silent=TRUE) # bi-factor model
fa_onefactor <- psych::fa(cor_poly$correlations,1,rotate="bifactor") # single factor model
if (any(inherits(fa_bifactor, "try-error"))) message("Bi-factor model unable to be computed")
#------------------------------------
# local dependency based on polychoric correlations of the items
fa_resid <- psych::factor.residuals(cor_poly$correlations,fa_onefactor)
# PRINT RESULTS
if (print_results) {
if (is.null(path_output)) stop("You need to give an path for the output")
# polychoric correlations
save(cor_poly, file = paste0(path_output,"/cor_poly.RData"))
utils::write.csv(round(cor_poly$correlations, 3), file=paste0(path_output,"/cor_poly.csv"))
# scree plot
grDevices::pdf(file=paste0(path_output,"/parallel_analysis_scree.pdf"), width=7, height=7)
nFactors::plotnScree(results_scree)
grDevices::dev.off()
#bi-factor plot
if (!any(inherits(fa_bifactor, "try-error"))) { #if fa_bifactor was able to be computed
#create vector of possible colors
col_factors <- RColorBrewer::brewer.pal(ncol(fa_bifactor$loadings),"Spectral")
#create pdf of bifactor analysis
grDevices::pdf(file=paste0(path_output,"/bifactor_analysis.pdf"), width=7, height=7)
# par(col="black", mar=c(13, 4, 4, 2) + 0.1)
graphics::plot(fa_bifactor$loadings[,1], type="l", ylim=c(-0.5,1), lwd=1.5, col="black", xaxt="n", xlab="", ylab="Loadings" )
graphics::axis(side=1, at = 1:length(vars_metric), labels = vars_metric, las=2)
for(i in 2:ncol(fa_bifactor$loadings)){
graphics::lines(fa_bifactor$loadings[,i], col=col_factors[i], lwd=1.3)
}
graphics::lines(fa_onefactor$loadings[,1], col="black", lty="dotted", lwd=1.5)
grDevices::dev.off()
utils::write.csv(cbind(fa_bifactor$loadings, fa_onefactor$loadings), file=paste0(path_output,"/bifactor_loadings.csv"))
} else { #if fa_bifactor was not able to be computed
utils::write.csv(unclass(fa_onefactor$loadings), file=paste0(path_output,"/bifactor_loadings.csv"))
}
# local dependency based on polychoric correlations of the items
utils::write.csv(round(fa_resid,3), file=paste0(path_output,"/fa_resid.csv"))
}
factor_result <- list(cor_poly = cor_poly,
eigenvalues = eigenvalues,
parallel_analysis = parallel_analysis,
results_scree = results_scree,
n_group_factors = n_group_factors,
fa_onefactor = fa_onefactor,
fa_resid = fa_resid)
return(factor_result)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/rasch_factor.R
|
#' Top-level function to perform Rasch Analysis on WHO Model Disability Survey data
#'
#' @param df a data frame of individual survey data, where each row is an individual
#' @param vars_metric a character vector of items to use in the Rasch Analysis
#' @param vars_id a string with column name uniquely identifying individuals
#' @param vars_DIF a string with the column names to use for analyzing differential item functioning (DIF). Default is NULL, to skip analysis of DIF.
#' @param resp_opts a numeric vector of possible response options for \code{vars_metric}. Must begin with 1. Default is 1:5
#' @param max_NA a numeric value for the maximum number of NAs allowed per individual among \code{vars_metric}. Default is 2.
#' @param print_results a logical value indicating whether or not to print various files displaying results from the Rasch Model. Default is FALSE, to not print the files.
#' @param path_parent a string with the path to the folder where results from multiple models will be outputted. Default is NULL
#' @param model_name a string with a name for the model, which is used to create a new folder for model output. Default is NULL.
#' @param testlet_strategy a list giving the strategy to take for creating testlets, passed to \code{rasch_testlet()}. One element of the list per testlet to create. Each element of the list must be a character vector of column names to use for the testlet. Optionally, name the element of the list to give the name of the new testlet. Otherwise, the new testlet will be the original column names separated by "_". Default is NULL, to not create testlets.
#' @param recode_strategy a named list giving the strategy to take for recoding variables, passed to \code{rasch_recode()}. One element of the list per recode strategy. Each element of the list is a numeric vector giving the new values to map the variables to. The names of the list are the groups of column names to use for each recoding strategy, separated only by ",". Default is NULL, to not recode items.
#' @param drop_vars a character vector of column names to drop from the Rasch Analysis. Default is NULL, to not drop items.
#' @param split_strategy a named list giving the strategy to take for splitting variables by categories, passed to \code{rasch_split()}. One element of the list per variable to split by. Each element of the list must be a character vector of column names to split. The names of the list are the variables to split each group of variables by. Default is NULL, to not split items.
#' @param comment a string giving a comment describing the analysis, printed to a txt file. Default is NULL, to not print a comment.
#'
#' @details This function combines all of the separate analyses of model fit necessary to assess the quality of the Rasch Model. It is designed to require minimal intervention from the user. Users wishing to have more control over the analysis can use the other Rasch functions in this package separately.
#'
#' @return a named list with:
#' \item{df}{a tibble with new columns representing the original person abilities (\code{person_pars}) and the rescaled person abilities (\code{rescaled})}
#' \item{vars_metric}{a character vector with the variables used in the metric after all adjustments}
#' \item{df_results}{a tibble of one row with key results of the model}
#'
#' If \code{print_results} is TRUE, prints files to the working directory with the results of the Rasch Model.
#'
#' @family rasch functions
#'
#' @export
#'
#' @import dplyr
rasch_mds <- function(df,
vars_metric,
vars_id,
vars_DIF = NULL,
resp_opts = 1:5,
max_NA = 2,
print_results = FALSE,
path_parent = NULL,
model_name = NULL,
testlet_strategy = NULL,
recode_strategy = NULL,
drop_vars = NULL,
split_strategy = NULL,
comment = NULL
) {
# # examples:
# testlet_strategy <- list(mobility = c("c1","c2"), c("c3","c4","c5"))
# recode_strategy <- list("c1,c2" = c(0,1,2,3,3),
# "c3,c4,c5" = c(0,1,1,2,2))
# drop_vars <- c("c1","c2")
# split_strategy <- list("sex" = c("c1","c2","c3"))
#perform some checks
if (resp_opts[1]!=1) stop("resp_opts must start with 1")
if (max_NA >= length(vars_metric)) stop("max_NA must be less than length of vars_metric")
# SAVE OUTPUT PATH ---------------------
if (print_results) {
if (!is.null(path_parent) & !is.null(model_name)) {
path_output <- paste0(path_parent, model_name)
dir.create(path_output, showWarnings = FALSE)
} else{
warning("You said you wanted to print results but did not provide an explicit path. Results will be printed to working directory.")
path_output <- NULL
}
} else message("Results will not be printed (print_results is FALSE).")
# PREPARE DATA ------------
#convert to tibble
if (!tibble::is_tibble(df)) df <- df %>% as_tibble()
#recode non-resp_opts to NA, make vars_id character
to_NA <- df %>%
select(all_of(vars_metric)) %>%
unlist() %>%
unique() %>%
setdiff(c(resp_opts, NA))
df <- df %>%
mutate_at(vars(all_of(vars_metric)),
list(~ plyr::mapvalues(., from = to_NA, to = rep(NA, length(to_NA)), warn_missing = FALSE
))) %>%
mutate_at(vars(all_of(vars_id)), list(as.character))
#remove people with too many NAs
rm_rows <- df %>%
select(all_of(vars_metric)) %>%
is.na() %>%
rowSums()
rm_rows <- rm_rows > max_NA
df <- df %>%
filter(!rm_rows)
#convert values to start at 0 (explictly convert first to numeric, in case df has factor columns)
df <- df %>%
mutate_at(vars(all_of(vars_metric)),
list(~ as.numeric(as.character(.)) - 1))
#store initial data frame of maximum possible values for each variable
max_values <- tibble(var = vars_metric,
max_val = max(resp_opts)-1)
# save comment
if (!is.null(comment)) utils::write.table(comment, file = paste0(path_output, "/Comment.txt"), row.names = FALSE, col.names = FALSE)
# PERFORM TESTLETS--------
if (!is.null(testlet_strategy)) {
testlet_result <- rasch_testlet(df = df,
vars_metric = vars_metric,
testlet_strategy = testlet_strategy,
max_values = max_values,
resp_opts = resp_opts)
df <- testlet_result[["df"]]
vars_metric <- testlet_result[["vars_metric"]]
testlet_strategy <- testlet_result[["testlet_strategy"]]
max_values <- testlet_result[["max_values"]]
if (print_results) {
testlet_strategy %>%
tibble::enframe(name = "testlet", value = "original_var") %>%
tidyr::unnest(cols = original_var) %>%
readr::write_csv(file = paste0(path_output, "/testlet_strategy.csv"))
}
message("Testlet creation completed.")
}
# PERFORM RECODING --------
if (!is.null(recode_strategy)) {
recode_result <- rasch_recode(df = df,
vars_metric = vars_metric,
recode_strategy = recode_strategy,
max_values = max_values)
df <- recode_result[["df"]]
max_values <- recode_result[["max_values"]]
if (print_results) {
recode_strategy %>%
tibble::enframe(name = "variable", value = "recoded") %>%
tidyr::separate(col = variable,
#programmatically determine number of columns to separate into
into = pull(., "variable") %>%
stringr::str_split(",") %>%
purrr::map_dbl(length) %>%
max() %>%
`:`(1,.) %>%
paste0("var",.),
sep = ",") %>%
tidyr::pivot_longer(cols = starts_with("var"),
values_to = "variable") %>%
dplyr::filter(!is.na(variable)) %>%
dplyr::rowwise() %>%
dplyr::mutate(original = list(0:(length(recoded) - 1))) %>%
tidyr::unnest(cols = c(original, recoded)) %>%
dplyr::select(variable, original, recoded) %>%
readr::write_csv(file = paste0(path_output, "/recode_strategy.csv"))
}
message("Recoding variables completed.")
}
# DROP VARIABLES ---------
if (!is.null(drop_vars)) {
drop_result <- rasch_drop(vars_metric = vars_metric,
drop_vars = drop_vars,
max_values = max_values)
vars_metric <- drop_result[["vars_metric"]]
max_values <- drop_result[["max_values"]]
if (print_results) {
tibble::tibble(dropped_var = drop_vars) %>%
readr::write_csv(file = paste0(path_output, "/drop_vars.csv"))
}
message("Dropping variables completed.")
}
# PRINT RESPONSE FREQUENCIES -------
if (print_results) {
df %>%
dplyr::select(all_of(vars_metric)) %>%
purrr::map(~ table(resp = ., useNA = "always")) %>%
purrr::map(~ as_tibble(.)) %>%
bind_rows(.id = "Q") %>%
tidyr::pivot_wider(names_from = Q, values_from = n) %>%
dplyr::mutate(resp = as.numeric(resp)) %>%
dplyr::arrange(resp) %>%
readr::write_csv(paste0(path_output, "/response_freq.csv"))
}
# PERFORM FACTOR ANALYSIS ------------
factor_result <- rasch_factor(df = df,
vars_metric = vars_metric,
print_results = print_results,
path_output = path_output)
message("Factor analysis completed.")
# PERFORM SPLIT -------
if (!is.null(split_strategy)) {
split_result <- rasch_split(df = df,
vars_metric = vars_metric,
split_strategy = split_strategy,
max_values = max_values)
df <- split_result[["df"]]
vars_metric <- split_result[["vars_metric"]]
max_values <- split_result[["max_values"]]
if (print_results) {
split_strategy %>%
tibble::enframe(name = "split_category", value = "variable_to_split") %>%
tidyr::unnest(cols = c(split_category, variable_to_split)) %>%
readr::write_csv(file = paste0(path_output, "/split_strategy.csv"))
}
message("Splitting variables completed.")
}
# ADD RAW SCORE ---------
df <- rasch_rawscore(df = df,
vars_metric = vars_metric,
vars_id = vars_id,
max_values = max_values)
# PERFORM RASCH ANALYSIS -----
model_result <- rasch_model(df = df,
vars_metric = vars_metric,
vars_id = vars_id,
print_results = print_results,
path_output = path_output)
residuals_PCM <- model_result[["residuals_PCM"]]
df_score <- model_result[["df_score"]]
message("Rasch Model completed.")
# PERFORM DIF ANALYSIS ---------
if (!is.null(vars_DIF)) {
DIF_result <- rasch_DIF(df = df,
vars_metric = vars_metric,
vars_DIF = vars_DIF,
residuals_PCM = residuals_PCM,
split_strategy = split_strategy,
print_results = print_results,
path_output = path_output)
message("DIF analysis completed.")
} else DIF_result <- list(DIF_results = "did not calculate")
# RESCALE SCORE --------
df_final <- rasch_rescale(df = df,
df_score = df_score,
vars_id = vars_id)
# PRINT DATA ---------
if (print_results) df_final %>% readr::write_csv(file = paste0(path_output, "/Data_final.csv"))
# PREPARE RESULTS DF ROW ----------
df_results <- tibble(model_name = model_name,
vars_metric = paste(vars_metric, collapse = ", "),
comment = comment,
LID = model_result$LID_results,
unidimensionality = factor_result$n_group_factors,
disordering = model_result$disordered_results,
DIF = DIF_result$DIF_results,
item_fit = model_result$fit_results,
model_fit = model_result$PSI)
# RETURN DATA WITH SCORE ----------
return(list(df = df_final,
vars_metric = vars_metric,
df_results = df_results))
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/rasch_mds.R
|
#' Top-level function to perform Rasch Analysis on WHO Model Disability Survey data for children
#'
#' @param vars_group a string with the column name identifying grouping variable
#' @param vars_metric_common a character vector the common items among all individuals
#' @param vars_metric_grouped a named list of character vectors with the items to use in the Rasch Analysis per group. The list should have names corresponding to the different groups, and contain character vectors of the corresponding items for each group.
#' @param TAM_model a string with the type of IRT model to use, passed to \code{irtmodel} argument of \code{TAM::tam()}. Default is \code{"PCM2"}
#' @param vars_DIF Currently does nothing. In the future, a string with the column names to use for analyzing differential item functioning (DIF). Default is NULL, to skip analysis of DIF.
#' @param has_at_least_one a numeric vector with the response options that a respondent must have at least one of in order to be included in the metric calculation. See details for more information.
#' @param max_NA a numeric value for the maximum number of NAs allowed per individual among \code{vars_metric_common} and the relevant items from \code{vars_metric_grouped}. Default is 2.
#' @inheritParams rasch_mds
#'
#' @details This function combines all of the separate analyses of model fit necessary to assess the quality of the Rasch Model. It is designed to require minimal intervention from the user. Users wishing to have more control over the analysis can use the other Rasch functions in this package separately.
#'
#' Often Rasch Analysis of children data is more difficult because of the extreme skewness of the responses. For this reason, it is often advisable to build a scale only with the respondents on the more severe end of the disability continuum. By specifying \code{has_at_least_one}, the function will remove all children from the sample who do endorse an answer of any of \code{has_at_least_one} in at least one \code{vars_metric}. The scores created can be reunited with the excluded children post-hoc.
#'
#' @return a tibble with new columns representing the original person abilities (\code{person_pars}) and the rescaled person abilities (\code{rescaled}).
#'
#' If \code{print_results} is TRUE, prints files to the working directory with the results of the Rasch Model.
#'
#' @family rasch functions
#' @family children analysis functions
#'
#' @export
#'
#' @import dplyr
rasch_mds_children <- function(df,
vars_id,
vars_group,
vars_metric_common,
vars_metric_grouped = NULL,
TAM_model = "PCM2",
vars_DIF = NULL,
resp_opts = 1:5,
has_at_least_one = 4:5,
max_NA = 2,
print_results = FALSE,
path_parent = NULL,
model_name = NULL,
testlet_strategy = NULL,
recode_strategy = NULL,
drop_vars = NULL,
split_strategy = NULL,
comment = NULL
) {
# # examples:
# testlet_strategy <- list(mobility = c("c1","c2"), c("c3","c4","c5"))
# recode_strategy <- list("c1,c2" = c(0,1,2,3,3),
# "c3,c4,c5" = c(0,1,1,2,2))
# drop_vars <- c("c1","c2")
# split_strategy <- list("sex" = c("c1","c2","c3"))
#TO IMPLEMENT
#DONE take input of common items and age-specific items
#DONE argument of models to try for TAM
#DONE how to do age split
#DONE adapt testlet, drop, recode, split to account for list of variables across groups -> should testlets be allowed between common items and specific items?
#DONE split df by age group
#DONE 6_RunModels through 10_ModelQuality should be basically fine
#DONE 13_Thresholds, dependency graph, levels should ve mostly ok
#DONE adapt so that either anchored or multigroup model can be used
#factor analysis? DIF?
#combine items into one list
vars_metric <- c(list(common = vars_metric_common),
vars_metric_grouped)
#perform some checks
if (resp_opts[1]!=1) stop("resp_opts must start with 1")
if (!is.null(vars_metric_grouped) & is.null(vars_metric_common)) stop("vars_metric_grouped cannot be specified without vars_metric_common")
if (max_NA >= length(helper_varslist(vars_metric))) stop("max_NA must be less than length of vars_metric")
# SAVE OUTPUT PATH ---------------------
if (print_results) {
if (!is.null(path_parent) & !is.null(model_name)) {
path_output <- paste0(path_parent, model_name)
dir.create(path_output, showWarnings = FALSE)
} else{
warning("You said you wanted to print results but did not provide an explicit path. Results will be printed to working directory.")
path_output <- NULL
}
} else message("Results will not be printed (print_results is FALSE).")
# PREPARE DATA ------------
#convert to tibble
if (!tibble::is_tibble(df)) df <- df %>% as_tibble()
#recode non-resp_opts to NA, make vars_id character
to_NA <- df %>%
select(all_of(helper_varslist(vars_metric))) %>%
unlist() %>%
unique() %>%
setdiff(c(resp_opts, NA))
df <- df %>%
mutate_at(vars(all_of(helper_varslist(vars_metric))),
list(~ plyr::mapvalues(.,
from = to_NA,
to = rep(NA, length(to_NA)),
warn_missing = FALSE)
)
) %>%
mutate_at(vars(all_of(vars_id)), list(~ as.character(.)))
#remove people with too many NAs
# rm_rows <- df %>%
# select(helper_varslist(vars_metric)) %>%
# is.na() %>%
# rowSums()
rm_rows <- df %>%
select(all_of(c(vars_group, helper_varslist(vars_metric)))) %>%
rowwise() %>%
group_split() %>%
purrr::map_dbl(.f = function(df_row) {
this_group <- as.character(pull(df_row, vars_group))
vars_to_check <- unique(c(vars_metric_common, vars_metric_grouped[[this_group]]))
df_row %>%
select(all_of(vars_to_check)) %>%
is.na() %>%
rowSums()
})
rm_rows <- rm_rows > max_NA
df <- df %>%
filter(!rm_rows)
#convert values to start at 0
df <- df %>%
mutate_at(vars(all_of(helper_varslist(vars_metric))),
list(~ as.numeric(as.character(.)) - 1))
#store initial data frame of maximum possible values for each variable
max_values <- tibble(var = helper_varslist(vars_metric),
max_val = max(resp_opts)-1)
# save comment
if (!is.null(comment)) utils::write.table(comment, file = paste0(path_output, "/Comment.txt"), row.names = FALSE, col.names = FALSE)
# keep only those with at least one of vars_metric in has_at_least_one ---------
if (!is.null(has_at_least_one)) {
df <- df %>%
filter_at(vars(all_of(helper_varslist(vars_metric))),
any_vars(. %in% (has_at_least_one - 1)))
}
# SPLIT BY AGE/MAKE VARS DISCRETE BY AGE --------
if (length(vars_metric) > 1) {
split_age_result <- rasch_split_age(df = df,
vars_group = vars_group,
vars_metric = vars_metric,
vars_id = vars_id,
max_values = max_values)
df <- split_age_result[["df"]]
vars_metric <- split_age_result[["vars_metric"]]
max_values <- split_age_result[["max_values"]]
message("Splitting by age to create discrete age-specific variables completed.")
}
# PERFORM TESTLETS--------
if (!is.null(testlet_strategy)) {
testlet_result <- rasch_testlet(df = df,
vars_metric = vars_metric,
testlet_strategy = testlet_strategy,
max_values = max_values,
resp_opts = resp_opts)
df <- testlet_result[["df"]]
vars_metric <- testlet_result[["vars_metric"]]
testlet_strategy <- testlet_result[["testlet_strategy"]]
max_values <- testlet_result[["max_values"]]
message("Testlet creation completed.")
}
# PERFORM RECODING --------
if (!is.null(recode_strategy)) {
recode_result <- rasch_recode(df = df,
vars_metric = vars_metric,
recode_strategy = recode_strategy,
max_values = max_values)
df <- recode_result[["df"]]
max_values <- recode_result[["max_values"]]
message("Recoding variables completed.")
}
# DROP VARIABLES ---------
if (!is.null(drop_vars)) {
drop_result <- rasch_drop(vars_metric = vars_metric,
drop_vars = drop_vars,
max_values = max_values)
vars_metric <- drop_result[["vars_metric"]]
max_values <- drop_result[["max_values"]]
message("Dropping variables completed.")
}
# PERFORM SPLIT -------
if (!is.null(split_strategy)) {
split_result <- rasch_split(df = df,
vars_metric = vars_metric,
split_strategy = split_strategy,
max_values = max_values)
df <- split_result[["df"]]
vars_metric <- split_result[["vars_metric"]]
max_values <- split_result[["max_values"]]
message("Splitting variables completed.")
}
# PRINT RESPONSE FREQUENCIES -------
if (print_results) {
df %>%
select(helper_varslist(vars_metric)) %>%
purrr::map(~ table(resp = ., useNA = "always")) %>%
purrr::map(~ as_tibble(.)) %>%
bind_rows(.id = "Q") %>%
tidyr::pivot_wider(names_from = Q, values_from = n) %>%
readr::write_csv(paste0(path_output, "/response_freq.csv"))
}
# SPLIT DATA BY AGE -----
df_nest <- rasch_df_nest(df = df,
vars_group = vars_group,
vars_id = vars_id)
# CALCULATE MODELS --------------
df_nest <- rasch_model_children(df = df,
df_nest = df_nest,
vars_metric = vars_metric,
vars_group = vars_group,
TAM_model = TAM_model)
message("Models completed.")
# CALCULATE MODEL QUALITY -----------
df_nest <- rasch_quality_children(df_nest = df_nest,
vars_metric = vars_metric)
message("Model quality calculated.")
# PRINT RESULTS ------------
if (print_results) {
rasch_quality_children_print(df_nest = df_nest,
vars_metric = vars_metric,
vars_group = vars_group,
TAM_model = TAM_model,
path_output = path_output)
message("Model quality printed.")
}
# # PERFORM DIF ANALYSIS ---------
# if (!is.null(vars_DIF)) {
# DIF_result <- rasch_DIF(df = df,
# vars_metric = vars_metric,
# vars_DIF = vars_DIF,
# residuals_PCM = residuals_PCM,
# split_strategy = split_strategy,
# print_results = print_results,
# path_output = path_output)
#
# message("DIF analysis completed.")
# }
# RESCALE SCORE --------
df_final <- rasch_rescale_children(df = df,
df_nest = df_nest,
vars_group = vars_group,
vars_id = vars_id)
# PRINT DATA ---------
if (print_results) df_final %>% readr::write_csv(file = paste0(path_output, "/Data_final.csv"))
# RETURN DATA WITH SCORE ----------
return(list(df = df_final,
vars_metric = vars_metric))
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/rasch_mds_children.R
|
#' Run the Rasch Model and print diagnostic results
#'
#' @param path_output a string with the path to the output folder. Default is NULL.
#' @param LIDcutoff either a numeric value between 0 and 1 indicating the cut-off for significant local item dependence, or the string "christensen" to use the cut-off suggested by Christensen et al. 2017 (see reference). If "christensen" cut-off fails, defaults to 0.2.
#' @inheritParams rasch_mds
#'
#' @details The Rasch Model is calculated using the function \code{eRm::PCM()}.
#'
#' @return a list with results from the Rasch Model:
#' \item{model}{the results from the Rasch Model}
#' \item{df_score}{a tibble with the items used in the analysis and the person abilities}
#' \item{thresholds}{the item thresholds (i.e., crossings)}
#' \item{person_parameters}{person abilities}
#' \item{PSI}{the person-separation index}
#' \item{item_fit}{infit and outfit statistics per item}
#' \item{residuals_PCM}{the standardized person residuals}
#' \item{LID}{matrix with the item residual correlations}
#' \item{targeting}{a matrix with information on the targeting of the model}
#' \item{fit_results}{a string with results of the item fit}
#' \item{LID_results}{a string with results of the local item dependency}
#' \item{disordered_results}{a string listing items with disordered thresholds}
#'
#' @family rasch functions
#'
#' @references Christensen, K. B., Makransky, G., & Horton, M. (2017). Critical Values for Yen’s Q 3 : Identification of Local Dependence in the Rasch Model Using Residual Correlations. Applied Psychological Measurement, 41(3), 178-194. \doi{10.1177/0146621616677520}
#'
#' @export
#'
#' @import eRm
rasch_model <- function(df, vars_metric, vars_id, print_results = FALSE, path_output = NULL, LIDcutoff = 0.2) {
#convert to tibble
if (!tibble::is_tibble(df)) df <- df %>% as_tibble()
#1. PCM analysis
model <- PCM(df[,vars_metric])
#-------------------------------------------------------------------------------
#2. Item Difficulty thresholds
Thr_PCM <- thresholds(model)
Thresholds_Table_Recoded <- cbind(Thr_PCM$threshpar, Thr_PCM$se.thresh)
colnames(Thresholds_Table_Recoded) <- c("Threshold", "SE Threshold")
disordered_results <- Thresholds_Table_Recoded %>%
as.data.frame() %>%
tibble::rownames_to_column("var") %>%
as_tibble() %>%
mutate(var = stringr::str_replace_all(var, "thresh beta ", "")) %>%
tidyr::separate(col = var, into = c("var", "n_threshold"), sep = "\\.") %>%
select(-`SE Threshold`) %>%
arrange(var, n_threshold) %>%
group_by(var) %>%
summarize(disordered = is.unsorted(Threshold)) %>%
filter(disordered) %>%
pull(var) %>%
paste(collapse = ", ")
#-------------------------------------------------------------------------------
#4. person parameters
person_parameters <- person.parameter(model)
#-------------------------------------------------------------------------------
#5. Person separation index
PSIreport <- as.numeric(SepRel_1.0.1(person_parameters)[1])
#-------------------------------------------------------------------------------
#6. item.fit
Itemfit <- eRm::itemfit(person_parameters)
table_Itemfit <- as.data.frame(cbind(Itemfit$i.fit, Itemfit$i.df, Itemfit$i.outfitMSQ, Itemfit$i.infitMSQ, Itemfit$i.outfitZ, Itemfit$i.infitZ ) )
names(table_Itemfit) <- c("i.fit", "i.df", "i.outfitMSQ", "i.infitMSQ", "i.outfitZ", "i.infitZ" )
fit_results <- table_Itemfit %>%
tibble::rownames_to_column("var") %>%
as_tibble() %>%
select(var, contains("MSQ")) %>%
mutate_at(vars(contains("MSQ")),
list(~ case_when(
. > 1.1 ~ "Overfit",
. < 0.9 ~ "Underfit",
TRUE ~ "OK"
))) %>%
mutate(fit = case_when(
i.outfitMSQ == "Underfit" & i.infitMSQ == "Overfit" ~ "Underfit & Overfit",
i.infitMSQ == "Underfit" & i.outfitMSQ == "Overfit" ~ "Underfit & Overfit",
i.outfitMSQ == "Underfit" | i.infitMSQ == "Underfit" ~ "Underfit",
i.outfitMSQ == "Overfit" | i.infitMSQ == "Overfit" ~ "Overfit",
TRUE ~ "OK"
)) %>%
select(var, fit) %>%
group_by(fit) %>%
summarize(vars = paste(var, collapse = ",")) %>%
tidyr::unite(col = "fit_results", fit, vars, sep = ": ") %>%
pull(fit_results) %>%
paste(collapse = "; ")
##additional cut-off for the fit based on Smith (see litterature)
Sample_Size <- nrow(df)
Cut_Infit <- 1+(2/sqrt(Sample_Size))
Cut_Outfit <- 1+(6/sqrt(Sample_Size))
Additional_Row <- as.data.frame(rbind(table_Itemfit,rep(NA, ncol(table_Itemfit)), rep(NA,ncol(table_Itemfit))))
Additional_Row <- apply(Additional_Row,2,as.numeric)
Additional_Row[nrow(Additional_Row)-1,3] <- Cut_Outfit
Additional_Row[nrow(Additional_Row)-1,4] <- Cut_Infit
Additional_Row[nrow(Additional_Row),1] <- PSIreport
rownames(Additional_Row) <- c(vars_metric,"Smith's Critical Cut-Offs", "PSI")
#-------------------------------------------------------------------------------
#7. Standardized Residuals
Residuals_PCM_Recoded <- stats::residuals(person_parameters)
#-------------------------------------------------------------------------------
#8. Person Abilities
person_par <- person_parameters$theta.table
names(person_par) <- c("person_pars", "NAgroup", "Interpolated")
table(person_par$Interpolated, is.na(person_par$person_pars))
data_persons <- cbind(df[,c(vars_id,vars_metric)],person_par)
summary(data_persons$person_pars)
for(i in 1:nrow(data_persons)){
if(is.na(data_persons[i,"person_pars"])){
data_persons[i,"person_pars"]<-min(data_persons[,"person_pars"], na.rm=TRUE)
}
}
###more persons abilities
Person_Abilities <- cbind(person_parameters$thetapar$NAgroup1,person_parameters$se.theta$NAgroup1)
colnames(Person_Abilities) <- c("Abil", "SE_Abil")
###
#-------------------------------------------------------------------------------
#9. Local Dependency
#Correlation Plot for Local Dependence
LID <- stats::cor(Residuals_PCM_Recoded, use="pairwise.complete", method="pearson")
LIDforgraph <- LID
if (LIDcutoff == "christensen") {
LIDcutoff <- mean(LID[(LID < 1)]) + 0.2
if (is.na(LIDcutoff) | is.null(LIDcutoff) | is.nan(LIDcutoff)) {
warning("Christensen LID cut-off did not work. Defaulting to 0.2")
LIDcutoff <- 0.2
}
} else if (is.character(LIDcutoff)) {
warning("Unknown specification for LIDcutoff. Defaulting to 0.2")
LIDcutoff <- 0.2
}
LID_results <- ((LIDforgraph >= LIDcutoff)*1 - diag(length(vars_metric))) %>%
data.frame()
LID_results[upper.tri(LID_results)] <- 0
LID_results <- LID_results %>%
tibble::rownames_to_column("var1") %>%
as_tibble() %>%
tidyr::pivot_longer(!var1, names_to = "var2", values_to = "LID") %>%
filter(LID == 1) %>%
select(-LID) %>%
tidyr::unite(col = "vars", var1, var2, sep = " & ") %>%
pull(vars) %>%
paste(collapse = "; ")
#-------------------------------------------------------------------------------
#10. Principal component analyis: PCA
PCA <- try(stats::prcomp(LID,center=TRUE, retx=TRUE), silent=TRUE)
Eigen_Value <- try(eigen(LID)$values, silent=TRUE)
if (!any(inherits(Eigen_Value, "try-error"))) {
Percentage_Eigen_Value <- Eigen_Value/sum(Eigen_Value)*100
Cumulative_Percentage_Eigen_Value <- cumsum(Percentage_Eigen_Value)
Eigen_Value_Table <- cbind(Eigen_Value,Percentage_Eigen_Value,Cumulative_Percentage_Eigen_Value)
}
#------------------------------------------------------------------------------
#11. Targeting
#Item Difficulties
Mean_Difficulty <- mean(Thresholds_Table_Recoded[,1], na.rm=TRUE)
SD_Difficulty <- sd(Thresholds_Table_Recoded[,1], na.rm=TRUE)
Mean_Resi_Dif <- mean(Thresholds_Table_Recoded[,2], na.rm=TRUE)
SD_Resi_Dif <- sd(Thresholds_Table_Recoded[,2], na.rm=TRUE)
Target_Difficulty <- cbind(Mean_Difficulty, SD_Difficulty, Mean_Resi_Dif, SD_Resi_Dif)
#Person Abilities
Mean_Ability <- mean(Person_Abilities[,1])
SD_Ability <- sd(Person_Abilities[,1])
Mean_Resi_Abil <- mean(Person_Abilities[,2])
SD_Resi_Abil <- sd(Person_Abilities[,2])
Target_Ability <- cbind(Mean_Ability, SD_Ability, Mean_Resi_Abil, SD_Resi_Abil)
Targeting <- cbind(rbind(Target_Difficulty, Target_Ability), PSIreport)
rownames(Targeting) <- c("Difficulty", "Ability")
colnames(Targeting) <- c("Mean", "SD", "Mean Residuals", "SD Residuals", "PSI")
#PRINT RESULTS
if (print_results) {
#model
save(model, file=paste0(path_output,"/PCM_model.RData"))
#thresholds
utils::write.csv(Thr_PCM[3], paste0(path_output,"/Location_Threshold.csv"))
utils::write.csv(Thresholds_Table_Recoded, file=paste0(path_output,"/PCM_thresholds_CI_Recoded.csv"))
#save ICC curves
grDevices::pdf(paste0(path_output,"/ICC_curves.pdf"))
plotICC(model, ask=FALSE)
grDevices::dev.off()
#save the person-item map
grDevices::pdf(file=paste0(path_output,"/PImap.pdf"), width=7, height=9)
plotPImap(model, sorted = TRUE)
grDevices::dev.off()
#item fit
utils::write.csv(Additional_Row, file=paste0(path_output,"/Item_MSQs.csv"))
utils::write.csv(table_Itemfit, file=paste0(path_output,"/item_fit.csv"))
#standardized residuals
utils::write.csv(Residuals_PCM_Recoded,file=paste0(path_output,"/Residuals_PCM.csv"))
#data with abilities
readr::write_csv(data_persons, paste0(path_output,"/DatawAbilities.csv"))
#person parameters
utils::write.csv(Person_Abilities, file=paste0(path_output,"/PersonPara.csv"))
#residual correlations
utils::write.csv(LID, file=paste0(path_output,"/Residual_Correlations.csv"))
grDevices::pdf(paste0(path_output,"/LID_plot.pdf"))
print(fig_LID(LIDforgraph, LIDcutoff, path_output))
grDevices::dev.off()
#PCA
if (!any(inherits(Eigen_Value, "try-error"))) {
utils::write.csv(Eigen_Value_Table, file= paste0(path_output,"/Original_Data_Eigenvalues.csv"))
}
if (!any(inherits(PCA, "try-error"))) {
utils::write.csv(PCA$rotation, file=paste0(path_output,"/Original_Data_PCA.csv"))
grDevices::pdf(paste0(path_output,"/Original_Data_Screeplot.pdf"))
graphics::barplot(Eigen_Value, main="metric")
stats::screeplot(PCA, type="lines", main="metric")
grDevices::dev.off()
}
#Targeting
utils::write.csv(Targeting, file=paste0(path_output,"/Targeting.csv"))
}
model_result <- list(model = model,
df_score = data_persons,
thresholds = Thr_PCM,
person_parameters = person_parameters,
PSI = PSIreport,
item_fit = Itemfit,
residuals_PCM = Residuals_PCM_Recoded,
LID = LID,
targeting = Targeting,
fit_results = fit_results,
LID_results = LID_results,
disordered_results = disordered_results)
return(model_result)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/rasch_model.R
|
#' Run the multigroup and anchored Rasch Model
#'
#' @param df_nest a nested tibble that contains the column \code{df_split} with the data split by the categories in the column \code{vars_group}
#' @inheritParams rasch_mds
#' @inheritParams rasch_mds_children
#'
#' @family rasch functions
#' @family children analysis functions
#'
#' @return a nested tibble with new columns with the Rasch Models calculated with the \code{TAM} package
#' @export
#'
rasch_model_children <- function(df, df_nest, vars_metric, vars_group, TAM_model) {
#choose tam model function based on TAM_model
if (TAM_model == "PCM2") {
tam.f <- TAM::tam.mml
} else {
tam.f <- TAM::tam.mml.2pl
}
#Calculate start models and store in list column called mod_start
df_nest <- df_nest %>%
dplyr::mutate(df_split_selected = purrr::map2(df_split, !!rlang::sym(vars_group),
~ dplyr::select(..1, c(vars_metric[["common"]], vars_metric[[as.character(..2)]])))
)
#test if some variables only have one chosen response value for an age group
if (df_nest$df_split_selected %>%
purrr::map(~ purrr::map(., table)) %>%
purrr::flatten() %>%
purrr::map(length) %>%
purrr::flatten_dbl() %>%
`==`(1) %>%
any()) warning("Some items have only one chosen response option for an age group, which can cause problems with TAM. Check the response frequencies.")
df_nest <- df_nest %>%
dplyr::mutate(
mod_start = purrr::map(df_split_selected,
.f = function(df_obj) {tam.f(resp = df_obj, irtmodel = TAM_model, verbose = FALSE)})
)
#Calculate multigroup model with only common items
mod_multigroup <- df %>%
dplyr::select(vars_metric[["common"]]) %>%
tam.f(resp = .,
irtmodel = TAM_model,
group = pull(df, vars_group),
beta.fixed = FALSE,
verbose = FALSE)
df_nest <- df_nest %>%
dplyr::mutate(mod_multigroup = list(mod_multigroup))
#Calculate anchored model
if (length(vars_metric) > 1) {
df_nest <- df_nest %>%
dplyr::mutate(start_xsi = purrr::map(mod_start, "xsi.fixed.estimated"),
multigroup_xsi = purrr::map(mod_multigroup, "xsi.fixed.estimated"),
index_uniqueitems = purrr::map2(start_xsi, !!rlang::sym(vars_group),
~ which(grepl(pattern = paste(vars_metric[[as.character(..2)]], collapse="|"), rownames(..1)))),
anchored_xsi = purrr::pmap(list(multigroup_xsi, start_xsi, index_uniqueitems),
~ rbind(..1, ..2[..3,])),
mod_anchored = purrr::map2(df_split_selected, anchored_xsi,
~ tam.f(resp = ..1,
irtmodel = TAM_model,
xsi.fixed = ..2,
verbose = FALSE))
)
}
return(df_nest)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/rasch_model_children.R
|
#' Calculate quality of multigroup and anchored Rasch Models
#'
#' @inheritParams rasch_mds_children
#' @inheritParams rasch_model_children
#'
#' @return a nested tibble with new columns with information about model quality
#' @export
#'
#' @family rasch functions
#' @family children analysis functions
#'
rasch_quality_children <- function(df_nest, vars_metric) {
#calculate start model quality
df_nest <- df_nest %>%
mutate(itemfit_start = purrr::map(mod_start, ~ TAM::msq.itemfit(.)$itemfit),
cor_start = purrr::map(mod_start, ~ cor(TAM::IRT.residuals(.)$stand_residuals, use="pairwise.complete.obs")),
xsithresh_start = purrr::map(mod_start, ~ cbind(.$xsi[vars_metric[["common"]],],
TAM::tam.threshold(.)[vars_metric[["common"]], ])),
tthresh_start = purrr::map(mod_start, ~ TAM::tam.threshold(.)),
eigen_start = purrr::map(cor_start, ~ ifelse(any(is.na(.)),
"NA in residual correlation matrix for start model. Unable to calculate eigenvalues and eigenvectors. Consider changing your testlets.",
list(eigen(.)$values))),
PCA_start = purrr::map(cor_start, ~ ifelse(any(is.na(.)),
"NA in residual correlation matrix for start model. Unable to calculate eigenvalues and eigenvectors. Consider changing your testlets.",
list(eigen(.)$vectors[,1]))),
WLE_start = purrr::map(mod_start, ~ TAM::tam.wle(., progress = FALSE)),
EAP_start = purrr::map(mod_start, ~ .$EAP.rel[1])
)
#calculate multigroup model quality
df_nest <- df_nest %>%
mutate(itemfit_multigroup = purrr::map(mod_multigroup, ~ TAM::msq.itemfit(.)$itemfit),
cor_multigroup = purrr::map(mod_multigroup, ~ cor(TAM::IRT.residuals(.)$stand_residuals, use="pairwise.complete.obs")),
xsithresh_multigroup = purrr::map(mod_multigroup, ~ cbind(.$xsi[vars_metric[["common"]],],
TAM::tam.threshold(.)[vars_metric[["common"]], ])),
tthresh_multigroup = purrr::map(mod_multigroup, ~ TAM::tam.threshold(.)),
eigen_multigroup = purrr::map(cor_multigroup, ~ ifelse(any(is.na(.)),
"NA in residual correlation matrix for start model. Unable to calculate eigenvalues and eigenvectors. Consider changing your testlets.",
list(eigen(.)$values))),
PCA_multigroup = purrr::map(cor_multigroup, ~ ifelse(any(is.na(.)),
"NA in residual correlation matrix for start model. Unable to calculate eigenvalues and eigenvectors. Consider changing your testlets.",
list(eigen(.)$vectors[,1]))),
WLE_multigroup = purrr::map(mod_multigroup, ~ TAM::tam.wle(., progress = FALSE)),
EAP_multigroup = purrr::map(mod_multigroup, ~ .$EAP.rel[1])
)
#calculate anchored model quality
if (length(vars_metric) > 1) {
df_nest <- df_nest %>%
mutate(itemfit_anchored = purrr::map(mod_anchored, ~ TAM::msq.itemfit(.)$itemfit),
cor_anchored = purrr::map(mod_anchored, ~ cor(TAM::IRT.residuals(.)$stand_residuals, use="pairwise.complete.obs")),
xsithresh_anchored = purrr::map(mod_anchored, ~ cbind(.$xsi[vars_metric[["common"]],],
TAM::tam.threshold(.)[vars_metric[["common"]], ])),
tthresh_anchored = purrr::map(mod_anchored, ~ TAM::tam.threshold(.)),
eigen_anchored = purrr::map(cor_anchored, ~ ifelse(any(is.na(.)),
"NA in residual correlation matrix for start model. Unable to calculate eigenvalues and eigenvectors. Consider changing your testlets.",
list(eigen(.)$values))),
PCA_anchored = purrr::map(cor_anchored, ~ ifelse(any(is.na(.)),
"NA in residual correlation matrix for start model. Unable to calculate eigenvalues and eigenvectors. Consider changing your testlets.",
list(eigen(.)$vectors[,1]))),
WLE_anchored = purrr::map(mod_anchored, ~ TAM::tam.wle(., progress = FALSE)),
EAP_anchored = purrr::map(mod_anchored, ~ .$EAP.rel[1])
)
}
return(df_nest)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/rasch_quality_children.R
|
#' Print results of analysis of Rasch Model quality
#'
#' @inheritParams rasch_mds
#' @inheritParams rasch_mds_children
#' @inheritParams rasch_model_children
#' @inheritParams fig_LID
#'
#' @return does not return anything to the environment, but prints files to the folder specified in \code{path_output}
#' @export
#'
#' @family rasch functions
#' @family children analysis functions
#'
rasch_quality_children_print <- function(df_nest, vars_metric, vars_group, TAM_model, LIDcutoff = 0.2, path_output) {
for (r in 1:nrow(df_nest)) {
age_name <- df_nest %>%
dplyr::pull(vars_group) %>%
.[r]
### Print multigroup results (only need to do once because should all be identical) ----------
if (r==1) {
#print scree plot multigroup
if (is.numeric(unlist(df_nest$eigen_multigroup[[r]]))) {
grDevices::pdf(paste0(path_output,"/ScreePlot_Multigroup_",TAM_model,".pdf"))
nFactors::plotnScree(nFactors::nScree(x = unlist(df_nest$eigen_multigroup[[r]])))
grDevices::dev.off()
}
utils::capture.output(summary(df_nest$mod_multigroup[[r]]), file = paste0(path_output, "/", TAM_model,"_summary_multigroup.txt"))
utils::write.csv(df_nest$itemfit_multigroup[[r]], file = paste0(path_output, "/", TAM_model,"_itemfit_multigroup.csv"))
utils::write.csv(df_nest$cor_multigroup[[r]], file = paste0(path_output, "/", TAM_model,"_residual_correlation_multigroup.csv"))
utils::write.csv(df_nest$xsithresh_multigroup[[r]], file = paste0(path_output, "/", TAM_model,"_xsi_thresholds_multigroup.csv"))
utils::write.csv(df_nest$eigen_multigroup[[r]] %>% unlist() %>% tibble::as_tibble_col(), file = paste0(path_output, "/", TAM_model,"_eigenvalues_multigroup.csv"))
utils::write.csv(df_nest$PCA_multigroup[[r]] %>% unlist() %>% tibble::as_tibble_col(), file = paste0(path_output, "/", TAM_model,"_first_vector_loadings_multigroup.csv"))
utils::capture.output(df_nest$WLE_multigroup[[r]],file = paste0(path_output, "/", TAM_model,"_WLE_multigroup.txt"))
utils::write.csv(df_nest$EAP_multigroup[[r]], file = paste0(path_output, "/", TAM_model,"_EAP_reliability_multigroup.csv"))
#save Thurstonian thresholds (always ordered) and save
utils::write.csv(df_nest$tthresh_multigroup[[r]],
paste0(path_output, "/ThurstonianThresholds_multigroup.csv"))
#generate matrix for color of symbols
color_matrix <-
matrix(rep(helper_palette(ncol(df_nest$tthresh_multigroup[[r]])), nrow(df_nest$tthresh_multigroup[[r]])),
nrow(df_nest$tthresh_multigroup[[r]]),
ncol(df_nest$tthresh_multigroup[[r]]),
byrow = TRUE)
#print Wright Map
grDevices::pdf(paste0(path_output,"/WrightMap_multigroup.pdf"))
WrightMap::wrightMap(
df_nest$WLE_multigroup[[r]]$theta,
df_nest$tthresh_multigroup[[r]][order(df_nest$mod_multigroup[[r]]$item$xsi.item),],
label.items.srt = 45,
show.thr.lab = FALSE,
thr.sym.col.fg = color_matrix,
thr.sym.col.bg = color_matrix,
thr.sym.cex = 1.5,
breaks=50
)
grDevices::dev.off()
#create dependency graph
grDevices::pdf(paste0(path_output,"/LID_plot_Multigroup.pdf"))
print(fig_LID(LIDforgraph = df_nest$cor_multigroup[[r]],
LIDcutoff = LIDcutoff,
path_output = path_output,
extra_file_label = "Multigroup"))
grDevices::dev.off()
}
#print scree plot start
if (is.numeric(unlist(df_nest$eigen_start[[r]]))) {
grDevices::pdf(paste0(path_output,"/ScreePlot_Start_",TAM_model,"_",age_name,".pdf"))
nFactors::plotnScree(nFactors::nScree(x = unlist(df_nest$eigen_start[[r]])))
grDevices::dev.off()
}
### Print Anchored results --------
if (length(vars_metric) > 1) {
#print scree plot anchored
if (is.numeric(unlist(df_nest$eigen_anchored[[r]]))) {
grDevices::pdf(paste0(path_output,"/ScreePlot_Anchored_",TAM_model,"_",age_name,".pdf"))
nFactors::plotnScree(nFactors::nScree(x = unlist(df_nest$eigen_anchored[[r]])))
grDevices::dev.off()
}
utils::capture.output(summary(df_nest$mod_anchored[[r]]), file = paste0(path_output, "/", TAM_model,"_summary_anchored_",age_name,".txt"))
#save Thurstonian thresholds (always ordered)
utils::write.csv(df_nest$tthresh_anchored[[r]],
paste0(path_output, "/ThurstonianThresholds_anchored",age_name, ".csv"))
#generate matrix for color of symbols
color_matrix <-
matrix(rep(helper_palette(ncol(df_nest$tthresh_anchored[[r]])), nrow(df_nest$tthresh_anchored[[r]])),
nrow(df_nest$tthresh_anchored[[r]]),
ncol(df_nest$tthresh_anchored[[r]]),
byrow = TRUE)
#print Wright Map
grDevices::pdf(paste0(path_output,"/WrightMap_anchored_",age_name,".pdf"))
WrightMap::wrightMap(
df_nest$WLE_anchored[[r]]$theta,
df_nest$tthresh_anchored[[r]][order(df_nest$mod_anchored[[r]]$item$xsi.item),],
label.items.srt = 45,
show.thr.lab = FALSE,
thr.sym.col.fg = color_matrix,
thr.sym.col.bg = color_matrix,
thr.sym.cex = 1.5,
breaks=50
)
grDevices::dev.off()
#create dependency graph
grDevices::pdf(paste0(path_output,"/LID_plot_",age_name,".pdf"))
print(fig_LID(LIDforgraph = df_nest$cor_anchored[[r]],
LIDcutoff = LIDcutoff,
path_output = path_output,
extra_file_label = age_name,
vertex_print_grey = vars_metric[["common"]]))
grDevices::dev.off()
#print csv/txt output
utils::write.csv(df_nest$itemfit_anchored[[r]], file = paste0(path_output, "/", TAM_model,"_itemfit_anchored_", age_name, ".csv"))
utils::write.csv(df_nest$cor_anchored[[r]], file = paste0(path_output, "/", TAM_model,"_residual_correlation_anchored_", age_name, ".csv"))
utils::write.csv(df_nest$xsithresh_anchored[[r]], file = paste0(path_output, "/", TAM_model,"_xsi_thresholds_anchored_", age_name, ".csv"))
utils::write.csv(df_nest$eigen_anchored[[r]] %>% unlist() %>% tibble::as_tibble_col(), file = paste0(path_output, "/", TAM_model,"_eigenvalues_anchored_", age_name, ".csv"))
utils::write.csv(df_nest$PCA_anchored[[r]] %>% unlist() %>% tibble::as_tibble_col(), file = paste0(path_output, "/", TAM_model,"_first_vector_loadings_anchored_", age_name, ".csv"))
utils::capture.output(df_nest$WLE_anchored[[r]],file = paste0(path_output, "/", TAM_model,"_WLE_anchored_", age_name, ".txt"))
utils::write.csv(df_nest$EAP_anchored[[r]], file = paste0(path_output, "/", TAM_model,"_EAP_reliability_anchored_", age_name, ".csv"))
}
}
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/rasch_quality_children_print.R
|
#' Add the raw scores to the data and artificial individuals attaining the minimum and/or maximum
#'
#' @inheritParams rasch_mds
#' @inheritParams rasch_testlet
#'
#' @return a tibble with a new column \code{RawScore} with the raw sum score of \code{vars_metric} for each individual, and artificial rows with individuals that attain the minimum and/or maximum if either is not attained in \code{df}. The artificial maximum row has value "MAX" in the \code{vars_id} column, and likewise the artificial minimum row has the value "MIN" in this column.
#'
#' @family rasch functions
#'
#' @export
#'
rasch_rawscore <- function(df, vars_metric, vars_id, max_values) {
#convert to tibble
if (!tibble::is_tibble(df)) df <- df %>% as_tibble()
df <- df %>%
mutate(RawScore = rowSums(df %>% select(vars_metric), na.rm=TRUE))
max_value <- max_values %>% pull(max_val) %>% sum
#if max value not attained, add row with artificial maximum
if (!any(pull(df, RawScore)==max_value, na.rm=TRUE)) {
df_max <- t(max_values) %>%
as_tibble() %>%
rename_all(list(~ pull(max_values, var))) %>%
slice(2) %>%
mutate_all(list(~ as.numeric(.))) %>%
mutate(!!rlang::sym(vars_id) := "MAX",
RawScore = max_value)
df <- df %>% full_join(df_max)
}
#if min value not attained, add row with artificial minimum
if (!any(pull(df, RawScore)==0, na.rm=TRUE)){
df_min <- matrix(0,1,length(vars_metric),
dimnames = list(NA,vars_metric)) %>%
as_tibble() %>%
mutate(!!rlang::sym(vars_id) := "MIN",
RawScore = 0)
df <- df %>% full_join(df_min)
}
return(df)
}
|
/scratch/gouwar.j/cran-all/cranData/whomds/R/rasch_rawscore.R
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.