Title: | Canadian Hydrological Analyses |
---|---|
Description: | A collection of user submitted functions to aid in the analysis of hydrological data. |
Authors: | Kevin Shook [cre, aut], Paul Whitfield [aut], Robert Chlumsky [aut], Daniel Moore [aut], Martin Durocher [aut], Matthew Lemieux [ctb], Jason Chiang [ctb], Joel Trubilowicz [ctb], SJ Kim [ctb] |
Maintainer: | Kevin Shook <[email protected]> |
License: | AGPL-3 |
Version: | 1.2.3 |
Built: | 2024-11-12 05:13:18 UTC |
Source: | https://github.com/cshs-hydrology/cshshydrology |
CSHShydRology is intended for the use of hydrologists, particularly those in Canada. It will contain functions which focus on the use of Canadian data sets, such as those from Environment Canada. The package will also contain functions which are suited to Canadian hydrology, such as the important cold-region hydrological processes. CSHShydRology will also contain functions which work with Canadian hydrological models, such as Raven, CRHM, Watflood, and MESH.
This packages has been developed with the assistance of the Canadian Society for Hydrological Sciences (CSHS) https://cshs.cwra.org/en which is an affiliated society of the Canadian Water Resources Association (CWRA) https://cwra.org/.
The CSHShydRology will contain functions grouped into several themes, including:
trend detection, data screening, frequency analysis, regionalization
input/conversion/adapter functions, missing data infilling
data visualization, standardized plotting functions
basin delineation, landscape data analysis, working with GIS
rating curve analysis, velocity profiles, naturalization
homogeneity assessment
fisheries and ecological analysis
between other packages and CSHShydRology
To cite CSHShydRology in publications, use the command citation("CSHShydRology")
to get the current version of this citation.
These functions read in or convert values among formats
Reads a file of WSC daily flows from ECDataExplorer
Reads station meta data from ECDataExplorer
Reads station information from a data file produced by ECDE
Reads file of daily AHCCD values
Reads file of monthly AHCCD values
Reads flows using tidyhydat and converts to ECDE format
Reads station meta data using tidyhydat and converts to ECDE-like format
Daily river discharge for the station 01AD002 on St. John River at Fort Kent, New Brunswick. Data ranges from 1926 to 2014, for basin area of 14700 sq km.
CAN01AD002
CAN01AD002
An object of class data.frame
with 32234 rows and 2 columns.
Martin Durocher
A dataframe of Water Survey of Canada (WSC) daily flows for station 05AA008, CROWSNEST RIVER AT FRANK Alberta. Drainage area 403 km2.
CAN05AA008
CAN05AA008
A dateframe with 25252 rows and 5 columns spanning the period 1910-2013.
Variables:
StationID
Parameter 1=Flow, 2=Level
R date
Daily flow in m/s
Water Survey FLags A, B, D, E
Water Survey of Canada
Generates an axis for day of year or day of water year; used by
ch_regime_plot
. Obtaining the day of water year needs to be done separately.
ch_axis_doy(wyear = 1)
ch_axis_doy(wyear = 1)
wyear |
Month of beginning of water year, |
Plots a water year axis on a standard R plot
Paul Whitfield
a <- seq(1, 365) b <- runif(365) plot(a, b, type = "p", xlab = "", xaxt = "n") ch_axis_doy(wyear = 10) # starts in October
a <- seq(1, 365) b <- runif(365) plot(a, b, type = "p", xlab = "", xaxt = "n") ch_axis_doy(wyear = 10) # starts in October
Compares two time periods of data using the Mann-Whitney test.
Data are binned based upon a bin size, and data are extracted for two time periods
and tests for change between two such periods
result can be passed to ch_polar_plot
or ch_decades_plot
for visualization.
ch_binned_MannWhitney( DF, step, range1, range2, ptest = 0.05, variable = "discharge", metadata = NULL )
ch_binned_MannWhitney( DF, step, range1, range2, ptest = 0.05, variable = "discharge", metadata = NULL )
DF |
A data frame of hydrometric data from |
step |
An integer indicating the degree of smoothing eg. 1, 5, 11. |
range1 |
The first and last year of first period, as |
range2 |
The first and last year of second period, as |
ptest |
The significance level default is |
variable |
Name of variable. Default is discharge |
metadata |
dataframe of station metadata, default is HYDAT_list |
Returns a list containing:
StationID |
ID of station |
Station_lname |
Name of station |
bin_width |
Smoothing time step |
range1 |
First range of years |
range2 |
Second range of years |
p_used |
p_value |
fail |
TRUE if test failed due to missing values |
bin_method |
method used for binning |
test_method |
Mann-Whitney U-statistic |
series |
a data frame containing: |
period |
period numbers i.e. 1:365/step |
period1 |
median values for each bin in period 1 |
period2 |
median values for each bin in period 2 |
mwu |
Mann-Whitney U-statistic for each bin between the two periods |
prob |
probability of U-statistic for each period |
code |
significance codes for each bin |
Paul Whitfield
Whitfield, P.H., Cannon, A.J., 2000. Recent variations in climate and hydrology in Canada. Canadian Water Resources Journal 25: 19-65.
ch_polar_plot
ch_polar_plot_prep
ch_decades_plot
data(HYDAT_list) data(CAN05AA008) # first example fails due to missing data in both periods range1 <- c(1960,1969) range2 <- c(1990,1999) b_MW <- ch_binned_MannWhitney(CAN05AA008, step = 5, range1, range2, ptest = 0.05) range1 <- c(1970,1979) range2 <- c(1990,1999) b_MW <- ch_binned_MannWhitney(CAN05AA008, step = 5, range1, range2, ptest = 0.05)
data(HYDAT_list) data(CAN05AA008) # first example fails due to missing data in both periods range1 <- c(1960,1969) range2 <- c(1990,1999) b_MW <- ch_binned_MannWhitney(CAN05AA008, step = 5, range1, range2, ptest = 0.05) range1 <- c(1970,1979) range2 <- c(1990,1999) b_MW <- ch_binned_MannWhitney(CAN05AA008, step = 5, range1, range2, ptest = 0.05)
A Booth plot is a plot of peaks over threshold flood events with duration on the horizontal and either magnitude (default) or volume on the vertical axis.
ch_booth_plot(events, threshold, title, type = "mag", colour1 = 1, colour2 = 1)
ch_booth_plot(events, threshold, title, type = "mag", colour1 = 1, colour2 = 1)
events |
A data frame of POT events from the function |
threshold |
The threshold used by |
title |
Plot title |
type |
The plot type, either mag (magnitude, the default) or vol (volume) |
colour1 |
A vector of length 12 with line colours of rings or symbols. Defaults to those used by Booth. |
colour2 |
A vector of length 12 with fill colours of rings or symbols. Defaults to those used by Booth. |
No value is returned; a standard R graphic is created.
Paul Whitfield
Booth, E.G., Mount, J.F., Viers, J.H. 2006. Hydrologic Variability of the Cosumnes River Floodplain. San Francisco Estuary & Watershed Science 4:21.
Whitfield, P.H., and J.W. Pomeroy. 2016. Changes to flood peaks of a mountain river: implications for analysis of the 2013 flood in the Upper Bow River, Canada. Hydrological Processes 30:4657-73. doi: 10.1002/hyp.10957.
threshold <- 0.1 * max(CAN05AA008$Flow) # arbitrary threshold peaks <- ch_get_peaks(CAN05AA008, threshold) events <- peaks$POTevents ch_booth_plot(events, threshold, title = "05AA008", type='mag') ch_booth_plot(events, threshold, title = "05AA008", type='vol')
threshold <- 0.1 * max(CAN05AA008$Flow) # arbitrary threshold peaks <- ch_get_peaks(CAN05AA008, threshold) events <- peaks$POTevents ch_booth_plot(events, threshold, title = "05AA008", type='mag') ch_booth_plot(events, threshold, title = "05AA008", type='vol')
Finds the hypsometric curve, which is the total fraction of the area below vs. elevation, for a given basin.
ch_catchment_hyps( catchment, dem, z_levels = NULL, n_levels = 10, zmin = NULL, zmax = NULL, quantiles = NULL, hypso_plot = FALSE, z_units = "m", col = "red", type = "o", xlab = "Fraction of catchment below given elevation", ylab = paste0("Elevation (", z_units, ")"), add_grid = FALSE, ... )
ch_catchment_hyps( catchment, dem, z_levels = NULL, n_levels = 10, zmin = NULL, zmax = NULL, quantiles = NULL, hypso_plot = FALSE, z_units = "m", col = "red", type = "o", xlab = "Fraction of catchment below given elevation", ylab = paste0("Elevation (", z_units, ")"), add_grid = FALSE, ... )
catchment |
A sf object containing the catchment divide. |
dem |
A raster object of the Digital Elevation Model. |
z_levels |
Vector of elevation levels for the hypsometry. If specified,
then no other elevation parameters are required. Default is |
n_levels |
If specified, sets number of elevation intervals.
Can be used with |
zmin |
Minimum elevation for hypsometry. If not specified, minimum
catchment elevation is used. Default is |
zmax |
Maximum elevation for hypsometry. If not specified, maximum
catchment elevation is used. Default is |
quantiles |
Vector of elevation quantiles. Default is |
hypso_plot |
if |
z_units |
Elevation units for plot. Default is m. |
col |
Colour for plot. Default is red. |
type |
Type of plot. Defailt is o (lines with overplotted points). |
xlab |
Plot x-axis label. |
ylab |
Plot y-axis label. |
add_grid |
If |
... |
Other parameters for the graph |
The elevations may be passed as a vector of elevations, or of elevation quantiles, or as minimum and maximum elevations and the number of elevation intervals. A plot of the curve may also be created.
Returns a data frame of elevations and catchment fractions below.
Dan Moore
## note: example tagged as 'donttest' as it is very slow to execute due to the downloading library(raster) # change the following line to specify a directory to hold the data dir_name <- tempdir(check = FALSE) # create directory to store data sets if (!dir.exists(dir_name)) { dir.create(dir_name, recursive = TRUE) } # get 25-m dem dem_fn <- file.path(dir_name, "gs_dem25.tif") dem_url <- "https://zenodo.org/record/4781469/files/gs_dem25.tif" dem_upc <- ch_get_url_data(dem_url, dem_fn) dem_upc # get catchment boundaries cb_fn <- file.path(dir_name, "gs_catchments.GeoJSON") cb_url <- "https://zenodo.org/record/4781469/files/gs_catchments.GeoJSON" cb <- ch_get_url_data(cb_url, cb_fn) # quick check plot - all catchments raster::plot(dem_upc) plot(cb, add = TRUE, col = NA) # subset 240 catchment cb_240 <- cb %>% dplyr::filter(wsc_name == "240") plot(cb_240, col = NA) ## test function # test different combinations of arguments ch_catchment_hyps(cb_240, dem_upc, quantiles = seq(0, 1, 0.1)) ch_catchment_hyps(cb_240, dem_upc, z_levels = seq(1600, 2050, 50)) ch_catchment_hyps(cb_240, dem_upc, n_levels = 6) ch_catchment_hyps(cb_240, dem_upc) ch_catchment_hyps(cb_240, dem_upc, zmin = 1600, zmax = 2050) ch_catchment_hyps(cb_240, dem_upc, zmin = 1600, zmax = 2050, n_levels = 6) # generate a graph ch_catchment_hyps(cb_240, dem_upc, hypso_plot = TRUE) ch_catchment_hyps(cb_240, dem_upc, hypso_plot = TRUE, col = "blue", type = "l", ylim = c(1500, 2200)) ch_catchment_hyps(cb_240, dem_upc, hypso_plot = TRUE, add_grid = TRUE, quantiles = seq(0, 1, 0.1)) ch_catchment_hyps(cb_240, dem_upc, hypso_plot = TRUE, ylab = expression("z ("*10^{-3} ~ "km)")) # extract specific quantiles (e.g., median and 90%) ch_catchment_hyps(cb_240, dem_upc, quantiles = c(0.5,0.9))
## note: example tagged as 'donttest' as it is very slow to execute due to the downloading library(raster) # change the following line to specify a directory to hold the data dir_name <- tempdir(check = FALSE) # create directory to store data sets if (!dir.exists(dir_name)) { dir.create(dir_name, recursive = TRUE) } # get 25-m dem dem_fn <- file.path(dir_name, "gs_dem25.tif") dem_url <- "https://zenodo.org/record/4781469/files/gs_dem25.tif" dem_upc <- ch_get_url_data(dem_url, dem_fn) dem_upc # get catchment boundaries cb_fn <- file.path(dir_name, "gs_catchments.GeoJSON") cb_url <- "https://zenodo.org/record/4781469/files/gs_catchments.GeoJSON" cb <- ch_get_url_data(cb_url, cb_fn) # quick check plot - all catchments raster::plot(dem_upc) plot(cb, add = TRUE, col = NA) # subset 240 catchment cb_240 <- cb %>% dplyr::filter(wsc_name == "240") plot(cb_240, col = NA) ## test function # test different combinations of arguments ch_catchment_hyps(cb_240, dem_upc, quantiles = seq(0, 1, 0.1)) ch_catchment_hyps(cb_240, dem_upc, z_levels = seq(1600, 2050, 50)) ch_catchment_hyps(cb_240, dem_upc, n_levels = 6) ch_catchment_hyps(cb_240, dem_upc) ch_catchment_hyps(cb_240, dem_upc, zmin = 1600, zmax = 2050) ch_catchment_hyps(cb_240, dem_upc, zmin = 1600, zmax = 2050, n_levels = 6) # generate a graph ch_catchment_hyps(cb_240, dem_upc, hypso_plot = TRUE) ch_catchment_hyps(cb_240, dem_upc, hypso_plot = TRUE, col = "blue", type = "l", ylim = c(1500, 2200)) ch_catchment_hyps(cb_240, dem_upc, hypso_plot = TRUE, add_grid = TRUE, quantiles = seq(0, 1, 0.1)) ch_catchment_hyps(cb_240, dem_upc, hypso_plot = TRUE, ylab = expression("z ("*10^{-3} ~ "km)")) # extract specific quantiles (e.g., median and 90%) ch_catchment_hyps(cb_240, dem_upc, quantiles = c(0.5,0.9))
Generates a simple map to allow a visual assessment of the catchment boundaries relative to the elevation contours.
ch_checkcatchment( dem, catchment, outlet, outlet_label = NULL, main_label = "", bbox_type = "catchment", channel_vec = NULL, cb_colour = "red", pp_colour = "red", channel_colour = "blue", contour_colour = "grey", plot_na = TRUE, plot_scale = TRUE, na_location = "tr", scale_location = "bl" )
ch_checkcatchment( dem, catchment, outlet, outlet_label = NULL, main_label = "", bbox_type = "catchment", channel_vec = NULL, cb_colour = "red", pp_colour = "red", channel_colour = "blue", contour_colour = "grey", plot_na = TRUE, plot_scale = TRUE, na_location = "tr", scale_location = "bl" )
dem |
raster DEM that catchments were generated from. |
catchment |
Catchment polygon (sf object). |
outlet |
Location of catchment outlet (sf object). |
outlet_label |
Character label for outlet. |
main_label |
Main label for catchment plot. |
bbox_type |
type of bounding box. If catchment, then the contours are bounded by the catchment, otherwise they are plotted to the extent of the DEM |
channel_vec |
Vectors of the channels will be plotted if specified. |
cb_colour |
Colour for catchment outline. Default is "red". |
pp_colour |
Colour for catchment pour points. Default is "red". |
channel_colour |
Colour for channel. Default is "blue". |
contour_colour |
Colour for contours Default is "grey". |
plot_na |
If |
plot_scale |
If |
na_location |
Location for the north arrow. Default is tr, i.e. top-right. |
scale_location |
Location for the scale bar. Default is bl, i.e. bottom-left. |
Also generates a table summarizing the catchments, including the coordinates of the outlet point and the catchment area.
TRUE
. A map of the catchments is also plotted and
the catchment parameters are printed.
Dan Moore and Kevin Shook
# Not tested automatically as requires installation of Whitebox library(raster) test_raster <- ch_volcano_raster() dem_raster_file <- tempfile(fileext = ".tif") no_sink_raster_file <- tempfile("no_sinks", fileext = ".tif") # write test raster to file writeRaster(test_raster, dem_raster_file, format = "GTiff") # remove sinks removed_sinks <- ch_wbt_removesinks(dem_raster_file, no_sink_raster_file, method = "fill") # get flow accumulations flow_acc_file <- tempfile("flow_acc", fileext = ".tif") flow_acc <- ch_wbt_flow_accumulation(no_sink_raster_file, flow_acc_file) # get pour points pourpoint_file <- tempfile("volcano_pourpoints", fileext = ".shp") pourpoints <- ch_volcano_pourpoints(pourpoint_file) snapped_pourpoint_file <- tempfile("snapped_pourpoints", fileext = ".shp") snapped_pourpoints <- ch_wbt_pourpoints(pourpoints, flow_acc_file, pourpoint_file, snapped_pourpoint_file, snap_dist = 10) # get flow directions flow_dir_file <- tempfile("flow_dir", fileext = ".tif") flow_dir <- ch_wbt_flow_direction(no_sink_raster_file, flow_dir_file) fn_catchment_ras <- tempfile("catchment", fileext = ".tif") fn_catchment_vec <- tempfile("catchment", fileext = ".shp") catchments <- ch_wbt_catchment(snapped_pourpoint_file, flow_dir_file, fn_catchment_ras, fn_catchment_vec) # check results ch_checkcatchment(test_raster, catchments, snapped_pourpoints)
# Not tested automatically as requires installation of Whitebox library(raster) test_raster <- ch_volcano_raster() dem_raster_file <- tempfile(fileext = ".tif") no_sink_raster_file <- tempfile("no_sinks", fileext = ".tif") # write test raster to file writeRaster(test_raster, dem_raster_file, format = "GTiff") # remove sinks removed_sinks <- ch_wbt_removesinks(dem_raster_file, no_sink_raster_file, method = "fill") # get flow accumulations flow_acc_file <- tempfile("flow_acc", fileext = ".tif") flow_acc <- ch_wbt_flow_accumulation(no_sink_raster_file, flow_acc_file) # get pour points pourpoint_file <- tempfile("volcano_pourpoints", fileext = ".shp") pourpoints <- ch_volcano_pourpoints(pourpoint_file) snapped_pourpoint_file <- tempfile("snapped_pourpoints", fileext = ".shp") snapped_pourpoints <- ch_wbt_pourpoints(pourpoints, flow_acc_file, pourpoint_file, snapped_pourpoint_file, snap_dist = 10) # get flow directions flow_dir_file <- tempfile("flow_dir", fileext = ".tif") flow_dir <- ch_wbt_flow_direction(no_sink_raster_file, flow_dir_file) fn_catchment_ras <- tempfile("catchment", fileext = ".tif") fn_catchment_vec <- tempfile("catchment", fileext = ".shp") catchments <- ch_wbt_catchment(snapped_pourpoint_file, flow_dir_file, fn_catchment_ras, fn_catchment_vec) # check results ch_checkcatchment(test_raster, catchments, snapped_pourpoints)
Generates a map of the generated channel network layer.
ch_checkchannels( dem, channels, outlet = NULL, main_label = "", channel_colour = "blue", pp_colour = "red", contour_colour = "grey" )
ch_checkchannels( dem, channels, outlet = NULL, main_label = "", channel_colour = "blue", pp_colour = "red", contour_colour = "grey" )
dem |
raster DEM that catchments were generated from |
channels |
channel polyline (or channels list from |
outlet |
location of catchment outlet (sf object) |
main_label |
Main label for channel plot. |
channel_colour |
Colour for channel. Default is "blue". |
pp_colour |
Colour for catchment pour points. Default is "red". |
contour_colour |
Colour for contours Default is "grey". |
Generates a simple map of the drainage network plotted over the contours to allow a visual assessment.
check_map |
a ggplot object of a map with channel layer |
Dan Moore
# Not tested automatically as requires installation of Whitebox library(raster) test_raster <- ch_volcano_raster() dem_raster_file <- tempfile(fileext = c(".tif")) no_sink_raster_file <- tempfile("no_sinks", fileext = c(".tif")) # write test raster to file writeRaster(test_raster, dem_raster_file, format = "GTiff") # remove sinks removed_sinks <- ch_wbt_removesinks(dem_raster_file, no_sink_raster_file, method = "fill") # get flow accumulations flow_acc_file <- tempfile("flow_acc", fileext = c(".tif")) flow_acc <- ch_wbt_flow_accumulation(no_sink_raster_file, flow_acc_file) # get flow directions flow_dir_file <- tempfile("flow_dir", fileext = c(".tif")) flow_dir <- ch_wbt_flow_direction(no_sink_raster_file, flow_dir_file) channel_raster_file <- tempfile("channels", fileext = c(".tif")) channel_vector_file <- tempfile("channels", fileext = c(".shp")) channels <- ch_wbt_channels(flow_acc_file, flow_dir_file, channel_raster_file, channel_vector_file, 1) # get pour points pourpoint_file <- tempfile("volcano_pourpoints", fileext = ".shp") pourpoints <- ch_volcano_pourpoints(pourpoint_file) snapped_pourpoint_file <- tempfile("snapped_pourpoints", fileext = ".shp") snapped_pourpoints <- ch_wbt_pourpoints(pourpoints, flow_acc_file, pourpoint_file, snapped_pourpoint_file, snap_dist = 10) ch_checkchannels(test_raster, channels, snapped_pourpoints)
# Not tested automatically as requires installation of Whitebox library(raster) test_raster <- ch_volcano_raster() dem_raster_file <- tempfile(fileext = c(".tif")) no_sink_raster_file <- tempfile("no_sinks", fileext = c(".tif")) # write test raster to file writeRaster(test_raster, dem_raster_file, format = "GTiff") # remove sinks removed_sinks <- ch_wbt_removesinks(dem_raster_file, no_sink_raster_file, method = "fill") # get flow accumulations flow_acc_file <- tempfile("flow_acc", fileext = c(".tif")) flow_acc <- ch_wbt_flow_accumulation(no_sink_raster_file, flow_acc_file) # get flow directions flow_dir_file <- tempfile("flow_dir", fileext = c(".tif")) flow_dir <- ch_wbt_flow_direction(no_sink_raster_file, flow_dir_file) channel_raster_file <- tempfile("channels", fileext = c(".tif")) channel_vector_file <- tempfile("channels", fileext = c(".shp")) channels <- ch_wbt_channels(flow_acc_file, flow_dir_file, channel_raster_file, channel_vector_file, 1) # get pour points pourpoint_file <- tempfile("volcano_pourpoints", fileext = ".shp") pourpoints <- ch_volcano_pourpoints(pourpoint_file) snapped_pourpoint_file <- tempfile("snapped_pourpoints", fileext = ".shp") snapped_pourpoints <- ch_wbt_pourpoints(pourpoints, flow_acc_file, pourpoint_file, snapped_pourpoint_file, snap_dist = 10) ch_checkchannels(test_raster, channels, snapped_pourpoints)
Empties and removes a working directory.
ch_clear_wd(wd, do_check = TRUE)
ch_clear_wd(wd, do_check = TRUE)
wd |
working directory file path |
do_check |
If |
The data for raster layers read in as Whitebox files are held on disk rather than in memory
result |
returns TRUE upon successful execution |
Dan Moore
ch_create_wd
to create working directory
# not tested as clearing all files in a given directory cannot be tested in CRAN # create an empty working directory my_wd <- tempdir() ch_create_wd(my_wd) # confirm creation # clear the working directory ch_clear_wd(my_wd)
# not tested as clearing all files in a given directory cannot be tested in CRAN # create an empty working directory my_wd <- tempdir() ch_create_wd(my_wd) # confirm creation # clear the working directory ch_clear_wd(my_wd)
ch_col_transparent
is used to adjust colour codes to introduce transparency.
ch_col_transparent(colour, trans)
ch_col_transparent(colour, trans)
colour |
Vector of colours you wish to add transparency to. |
trans |
Integer(s) describing the degree of transparency, from ~200 (slightly transparent) to <10 (very transparent). |
res |
returned updated colour code with transparency |
See original code on post in Stack Overflow plot points transparent in R
# plot randomly distributed data plot(rnorm(20),col='black') # create a transparent blue colour for plotting mycol <- ch_col_transparent('blue',100) # plot more random points in transparent blue colour points(rnorm(20),col=mycol) # add transparency to multiple colours ch_col_transparent( c('red','blue','green'), c(50,100,200))
# plot randomly distributed data plot(rnorm(20),col='black') # create a transparent blue colour for plotting mycol <- ch_col_transparent('blue',100) # plot more random points in transparent blue colour points(rnorm(20),col=mycol) # add transparency to multiple colours ch_col_transparent( c('red','blue','green'), c(50,100,200))
Creates contour lines from a DEM.
ch_contours(dem, zmin = NULL, zmax = NULL, n_levels = 10, z_levels = NULL)
ch_contours(dem, zmin = NULL, zmax = NULL, n_levels = 10, z_levels = NULL)
dem |
Raster object of your dem in the desired projection (note: should have had sinks removed). |
zmin |
Minimum elevation value for contours. If not specified, minimum value dem is used. |
zmax |
Maximum elevation value for contours. If not specified, maximum value dem is used. |
n_levels |
Number of contour lines. Default is 10. |
z_levels |
Levels at which to plot contours. If specified, overrides zmin, zmax and n_levels. |
Generates contour lines from a DEM, which are returned as an sf object.
The user can either provide a vector of elevation values by specifying the z_levels
argument,
or by supplying the minimum and maximum elevations (zmin
and zmax
)
and the number of contour lines (n_levels
).
contours_sf |
sf object containing contours |
Dan Moore
# use volcano DEM dem <- ch_volcano_raster() # generate contours contours <- ch_contours(dem) # plot contours map plot(contours)
# use volcano DEM dem <- ch_volcano_raster() # generate contours contours <- ch_contours(dem) # plot contours map plot(contours)
Creates a working directory.
ch_create_wd(wd)
ch_create_wd(wd)
wd |
name of a directory in which to store files created by WhiteboxTools functions |
TRUE |
returns |
Dan Moore
ch_clear_wd
to clear the working directory
# not tested automatically as will return a warning ch_create_wd(tempdir())
# not tested automatically as will return a warning ch_create_wd(tempdir())
The function could also be used to get the same period of time from several station for comparison.
ch_cut_block(DF, st_date, end_date)
ch_cut_block(DF, st_date, end_date)
DF |
A daily streamflow data frame as from |
st_date |
starting date format is %Y/%m/%d |
end_date |
ending date format is %Y/%m/%d |
Returns a portion of the original dataframe.
Paul Whitfield
data(CAN05AA008) subset <- ch_cut_block(CAN05AA008,"2000/01/01", "2010/12/31")
data(CAN05AA008) subset <- ch_cut_block(CAN05AA008,"2000/01/01", "2010/12/31")
Subsets a data frame by an specified date range, provided as
a string by the prd
argument. This function is meant to emulate the subsetting
capability of the xts package.
ch_date_subset(df, prd)
ch_date_subset(df, prd)
df |
data frame of time series data; includes a variable called |
prd |
date range as string formatted as YYYY-MM-DD/YYYY-MM-DD |
df |
subsetted data frame |
Robert Chlumsky
{ dd <- seq.Date(as.Date("2010-10-01"), as.Date("2013-09-30"), by = 1) x <- rnorm(length(dd)) y <- abs(rnorm(length(dd)))*2 df <- data.frame("Date" = dd,x,y) prd <- "2011-10-01/2012-09-30" summary(ch_date_subset(df,prd))}
{ dd <- seq.Date(as.Date("2010-10-01"), as.Date("2013-09-30"), by = 1) x <- rnorm(length(dd)) y <- abs(rnorm(length(dd)))*2 df <- data.frame("Date" = dd,x,y) prd <- "2011-10-01/2012-09-30" summary(ch_date_subset(df,prd))}
Creates a simple plot comparing two decades from the
output of ch_binned_MannWhitney
.
ch_decades_plot(mplot)
ch_decades_plot(mplot)
mplot |
List output by the function |
A standard R graphic is created.
Paul Whitfield
range1 <- c(1970, 1979) range2 <- c(1990, 1999) b_MW <- ch_binned_MannWhitney(CAN05AA008, step = 5, range1, range2, ptest = 0.05) ch_decades_plot(b_MW)
range1 <- c(1970, 1979) range2 <- c(1990, 1999) b_MW <- ch_binned_MannWhitney(CAN05AA008, step = 5, range1, range2, ptest = 0.05) ch_decades_plot(b_MW)
Converts an array of dates into a dataframe with date, year, month, doy, wyear, dowy.
The day of water year is computed from the first of the specified water year month.
ch_doys(Date, water_yr = 10)
ch_doys(Date, water_yr = 10)
Date |
an array of R dates, as produced by |
water_yr |
the month starting the water year, default is 10 (October). If
a value of |
Converts a date array into a data frame with years, wateryears, and days of year and of water year.
Returns a dataframe with date information:
Date |
in Date format |
year |
numeric calendar year |
month |
number calendar month |
doy |
numeric day of year |
wyear |
numeric water year starting on day 1 of selected month |
dwy |
numeric day of water year |
Paul Whitfield, Kevin Shook
dd <- seq.Date(as.Date("2010-01-01"), as.Date("2018-01-01"),by = 1) output <- ch_doys(dd, water_yr=10) head(output)
dd <- seq.Date(as.Date("2010-01-01"), as.Date("2018-01-01"),by = 1) output <- ch_doys(dd, water_yr=10) head(output)
A flow duration curve is a plot of flow magnitude against exceedance probability. The plot may contain the Gustard Curves (default) or they can be omitted. The default is for curves to be plotted against probability, but an option is to plot against the normalized exceedance probability. In that case, the x axis represents a normal distribution.
ch_fdcurve(DF, normal = FALSE, gust = TRUE, metadata = NULL)
ch_fdcurve(DF, normal = FALSE, gust = TRUE, metadata = NULL)
DF |
a dataframe of daily flows from |
normal |
If |
gust |
If |
metadata |
dataframe of metadata, defaults to HYDAT_list. |
Create a Flow Duration Curve based upon Observations.
Plots the flow duration curve and returns a data frame containing:
exceedance probability |
probability |
flow |
d=flow values |
Paul Whitfield
Gustard, A., A. Bullock, and J.M. Dixon. 1992. Low flow estimation in the United Kingdom. Institute of Hydrology, 292. Wallingford: Institute of Hydrology.
Vogel, R.M., and N.M. Fennessy. 1994. Flow-duration curves. I: New Interpretation and confidence intervals. Journal of Water Resources Planning and Management ASCE 120:485-504.
Vogel, R.M., and N.M. Fennessy. 1995. Flow duration curves II: A review of applications in water resources planning. Water Resources Bulletin 31:1030-9.
data(HYDAT_list) data(CAN05AA008) # plot with Gustard 1992 curves test <- ch_fdcurve(CAN05AA008, normal = FALSE, gust = TRUE) # plot with normalized exceedance probability test <- ch_fdcurve(CAN05AA008, normal = TRUE, gust = FALSE)
data(HYDAT_list) data(CAN05AA008) # plot with Gustard 1992 curves test <- ch_fdcurve(CAN05AA008, normal = FALSE, gust = TRUE) # plot with normalized exceedance probability test <- ch_fdcurve(CAN05AA008, normal = TRUE, gust = FALSE)
Produces a raster plot: years by day of year, showing magnitude of flow. This produces a plot showing the flow data in colours, showing different context than in a hydrograph. High flows are in warm colours.
ch_flow_raster( DF, rastercolours = c("lightblue", "cyan", "blue", "slateblue", "orange", "red"), metadata = NULL )
ch_flow_raster( DF, rastercolours = c("lightblue", "cyan", "blue", "slateblue", "orange", "red"), metadata = NULL )
DF |
A data frame of daily flow data as read by |
rastercolours |
A vector of colours used for flow magnitudes (default |
metadata |
A dataframe of station metadata, defaults to |
No value is returned; a standard R graphic is created.
Paul Whitfield
ch_flow_raster_trend
ch_flow_raster_qa
ch_flow_raster(CAN05AA008)
ch_flow_raster(CAN05AA008)
Raster plot with WSC quality flags. This produces a plot showing the flow data in grayscale overlain by the Water Survey of Canada quality flags. Colours are consistent with ECDataExplorer. Raster layout lets the use see the flags in a different context than in a hydrograph.
ch_flow_raster_qa(DF, metadata = NULL)
ch_flow_raster_qa(DF, metadata = NULL)
DF |
dataframe of daily streamflow read by ch_read_ECDE_flows |
metadata |
dataframe of metadata or defaults to "HYDAT_list" |
Produces a raster plot: years against day of year, showing the data flags:
A |
(Partial) in green |
B |
(Backwater) in cyan |
D |
(Dry) in yellow |
E |
(Estimated) in red |
Returns TRUE
if executed properly; a standard R graphic is created.
Paul Whitfield
ch_flow_raster_trend
ch_flow_raster
data(HYDAT_list) data(CAN05AA008) qaplot <- ch_flow_raster_qa(CAN05AA008)
data(HYDAT_list) data(CAN05AA008) qaplot <- ch_flow_raster_qa(CAN05AA008)
Creates a raster plot plus trend plots for day of year, which are binned by a number of days (step), and the max, min, and median annual discharge across years. The plot contains four panels based upon binned data.
ch_flow_raster_trend( DF, step = 5, missing = FALSE, metadata = NULL, colours = c("lightblue", "cyan", "blue", "slateblue", "darkblue", "red") )
ch_flow_raster_trend( DF, step = 5, missing = FALSE, metadata = NULL, colours = c("lightblue", "cyan", "blue", "slateblue", "darkblue", "red") )
DF |
- dataframe of daily flow data as read by ch_read_ECDE_flows |
step |
- a number indicating the degree of smoothing eg. 1, 5, 11. |
missing |
If |
metadata |
a dataframe of station metadata, default is HYDAT_list. |
colours |
A vector of colours used for the raster plot.
The default is |
The four plots are: (1) The maximum,minimum,and median flow with a trend test for each period: red arrows indicate decreases, blue arrows indicate increases. (2) The scale bar for the colours used in the raster plot, (3) The raster plot with a colour for each period and each year where data exist, and (4) A time series plot of the minimum, median, and maximum annual bin values. If there is no trend (p > 0.05) the points are black. Decreasing trends are in red, increasing trends are in blue.
Returns a list containing:
stationID |
Station ID eg. 05BB001 |
missing |
How missing values were used FALSE = used, TRUE = removed |
step |
number of days in a bin |
periods |
number of periods in a year |
period |
period numbers i.e. 1:365/step |
bins |
values for each period in each year |
med_period |
median for each period |
max_period |
maximum for each period |
min_period |
minimum for each period |
tau_period |
Kendalls Tau for each period |
prob_period |
probability of Tau for each period |
year |
years spanning the data |
median_year |
median bin for each year |
max_year |
maximum bin for each year |
min_year |
minimum bin for each year |
tau_median_year |
value of tau and probability for annual median |
tau_maximum_year |
value of tau and probability for annual maximum |
tau_minimum_year |
value of tau and probability for annual minimum |
Paul Whitfield
Whitfield, P. H., Kraaijenbrink, P. D. A., Shook, K. R., and Pomeroy, J. W. 2021. The Spatial Extent of Hydrological and Landscape Changes across the Mountains and Prairies of Canada in the Mackenzie and Nelson River Basins Based on data from a Warm Season Time Window, Hydrology and Earth Systems Sciences 25: 2513-2541.
data(CAN05AA008) mplot <- ch_flow_raster_trend(CAN05AA008, step=5)
data(CAN05AA008) mplot <- ch_flow_raster_trend(CAN05AA008, step=5)
Reads the file that is generated from ECDE 'save favourite stations' to capture the ECDE metadata. The dataframe returned contains 20 fields from ECDE.
ch_get_ECDE_metadata(filename, writefile = NULL)
ch_get_ECDE_metadata(filename, writefile = NULL)
filename |
The name of the ECDE file, FavHydatStations.tb0. |
writefile |
Default is |
Returns a dataframe consisting of:
Station |
StationID |
StationName |
Station Name |
HYDStatus |
Active or Discontinued |
Prov |
Province |
Latitude |
|
Longitude |
|
DrainageArea |
km |
Years |
Number of years with data |
From |
Start Year |
To |
End Year |
Reg. |
Regulated? |
Flow |
If TRUE/Yes flow data exists |
Level |
If TRUE/Yes level data exists |
Sed |
If TRUE/Yes sediment data exists |
OperSched |
Operations current - Continuous or Seasonal |
RealTime |
If TRUE/Yes real time data is available |
RHBN |
If TRUE/Yes the stations is in the reference hydrologic basin network |
Region |
Name of regional office operating station |
Datum |
Elevation datum |
Operator |
Operator or provider of the data |
Paul Whitfield <[email protected]>
# Not tested by check() as requires downloaded file filename <- "FavHydatStations.tb0" meta0 <- ch_get_ECDE_metadata(filename) meta1 <- ch_get_ECDE_metadata(filename, writefile="study52_metadata.csv")
# Not tested by check() as requires downloaded file filename <- "FavHydatStations.tb0" meta0 <- ch_get_ECDE_metadata(filename) meta1 <- ch_get_ECDE_metadata(filename, writefile="study52_metadata.csv")
This function is development code being shared as is. It is expected that the user will be interested in the data frame returned for POT analysis and for plotting (i.e. ch_booth_plot).
This function retrieves peaks greater than or equal to the prescribed threshold. It returns a data frame of peak characteristics suitable for subsequent analysis.
The portion under development is returns a list of the flows during an event with the values of the four preceding days and three subsequent days. If the peak is a single point the fragment is nine points long; if the events is longer the fragment contains all days above the threshold and eight additional days.
ch_get_peaks(dataframe, threshold)
ch_get_peaks(dataframe, threshold)
dataframe |
a data frame of streamflow data containing columns named Date and Flow |
threshold |
a value for the threshold. Values above the threshold are tested for peaks. |
Returns a list containing:
POTevents |
a dataframe contining details of the events |
events |
a vector with the value 0 when the flow is below the threshold and 1 when above. |
event_num |
a vector with the value 0 when the flow is below a threshold or the index of the events when the threshold was exceeded. i.e. 1,2,3, etc |
st_date |
start date of events |
case |
a list of the daily flows in each individual event (see details for more information) |
The POTevents
data frame contains five columns:
st_date |
starting date of event |
max_date |
date of maximum in the event |
max |
maximum discharge during event |
volume |
flow volume during the event |
duration |
length of the event in days |
The case
list contains the flows during an event and also for four preceding and subsequent days. Each event will have
a length between nine to n days in length. Note: in rare cases where the event is in progress when data becomes available the
event might be shorter than nine days long.
Paul Whitfield
Burn, D.H., Whitfield, P.H., Sharif, M., 2016. Identification of changes in floods and flood regimes in Canada using a peaks over threshold approach. Hydrological Processes, 39: 3303-3314. DOI:10.1002/hyp.10861
Whitfield, P.H., and J.W. Pomeroy. 2016. Changes to flood peaks of a mountain river: implications for analysis of the 2013 flood in the Upper Bow River, Canada. Hydrological Processes 30:4657-73. doi: 10.1002/hyp.10957.
CAN05AA008 <- CAN05AA008 threshold <- 0.5*max(CAN05AA008$Flow) # arbitrary threshold my_peaks <- ch_get_peaks(CAN05AA008, threshold) str(my_peaks)
CAN05AA008 <- CAN05AA008 threshold <- 0.5*max(CAN05AA008$Flow) # arbitrary threshold my_peaks <- ch_get_peaks(CAN05AA008, threshold) str(my_peaks)
Accesses data sets, via a url the first time, saves them locally, then accesses them locally after the first time the script is executed.
ch_get_url_data(gd_url, gd_filename, quiet = FALSE)
ch_get_url_data(gd_url, gd_filename, quiet = FALSE)
gd_url |
url for accessing data set |
gd_filename |
name of file on local drive, including full path |
quiet |
Optional. If |
Returns a data frame (from a .csv file), a raster
object (from a .tif file),
or an sf
object (from a GeoJSON file).
Dan Moore
# example not tested automatically as multiple large data files are downloaded # Tested using files in the Upper Penticton Creek # zenodo repository https://zenodo.org/record/4781469 library(ggplot2) library(raster) # create directory to store data sets dir_name <- tempdir(check = FALSE) if (!dir.exists(dir_name)) { dir.create(dir_name) } # test with soil moisture data in csv format sm_fn <- file.path(dir_name, "sm_data.csv") sm_url <- "https://zenodo.org/record/4781469/files/sm_data.csv" sm_data <- ch_get_url_data(sm_url, sm_fn) head(sm_data) # test with tif/tiff file containing a dem ra_fn <- file.path(dir_name, "gs_dem25.tif") ra_url <- "https://zenodo.org/record/4781469/files/gs_dem25.tif" ra_data <- ch_get_url_data(ra_url, ra_fn) plot(ra_data) # test with GeoJSON gs_fn <- file.path(dir_name, "gs_soilmaps.GeoJSON") gs_url <- "https://zenodo.org/record/4781469/files/gs_soilmaps.GeoJSON" gs_data <- ch_get_url_data(gs_url, gs_fn) ggplot(gs_data) + geom_sf(aes(fill = new_key)) + labs(fill = "Soil class", x = "UTM Easting (m)", y = "UTM Northing (m)") + coord_sf(datum = 32611) + theme_bw()
# example not tested automatically as multiple large data files are downloaded # Tested using files in the Upper Penticton Creek # zenodo repository https://zenodo.org/record/4781469 library(ggplot2) library(raster) # create directory to store data sets dir_name <- tempdir(check = FALSE) if (!dir.exists(dir_name)) { dir.create(dir_name) } # test with soil moisture data in csv format sm_fn <- file.path(dir_name, "sm_data.csv") sm_url <- "https://zenodo.org/record/4781469/files/sm_data.csv" sm_data <- ch_get_url_data(sm_url, sm_fn) head(sm_data) # test with tif/tiff file containing a dem ra_fn <- file.path(dir_name, "gs_dem25.tif") ra_url <- "https://zenodo.org/record/4781469/files/gs_dem25.tif" ra_data <- ch_get_url_data(ra_url, ra_fn) plot(ra_data) # test with GeoJSON gs_fn <- file.path(dir_name, "gs_soilmaps.GeoJSON") gs_url <- "https://zenodo.org/record/4781469/files/gs_soilmaps.GeoJSON" gs_data <- ch_get_url_data(gs_url, gs_fn) ggplot(gs_data) + geom_sf(aes(fill = new_key)) + labs(fill = "Soil class", x = "UTM Easting (m)", y = "UTM Northing (m)") + coord_sf(datum = 32611) + theme_bw()
Retrieves station information for an individual Water Survey of Canada site, based on stationID; adds a text string at position 21 that combines key elements for a title.
ch_get_wscstation(stnID, metadata = NULL)
ch_get_wscstation(stnID, metadata = NULL)
stnID |
A Water Survey of Canada station number |
metadata |
a data frame of station information from ECDataExplorer. The data frame HYDAT_list is supplied with this package. |
Returns a line from a data frame with 21 variables
Station |
StationID |
StationName |
Station Name |
HYDStatus |
Active or Discontinued |
Prov |
Province |
Latitude |
|
Longitude |
|
DrainageArea |
Area in km |
Years |
# of years with data |
From |
Start Year |
To |
End Year |
Reg. |
Regulated or natural |
Flow |
if TRUE/Yes flow data is available |
Level |
if TRUE/Yes water level data is available |
Sed |
if TRUE/Yes sediment data is available |
OperSched |
Current operation schedule- Continuous or Seasonal |
RealTime |
if TRUE/Yes real itme data exists |
RHBN |
if TRUE/Yes is in the reference hydrologic basin network |
Region |
WSC Region |
Datum |
Datum used |
Operator |
Agency responsible for collecting data |
Station_lname |
Added field combining StationID, StationName, Province and if station is RHBN an * is added |
Paul Whitfield
data("HYDAT_list") s_info <- ch_get_wscstation("05BB001", metadata = HYDAT_list) title <- s_info[21] print(title)
data("HYDAT_list") s_info <- ch_get_wscstation("05BB001", metadata = HYDAT_list) title <- s_info[21] print(title)
Creates a hydrograph plot for simulated, observed, and inflow hydrograph series, including precipitation if provided. The secondary y axis will be used to plot the precip time series.
ch_hydrograph_plot( flows = NULL, precip = NULL, prd = NULL, winter_shading = FALSE, winter_colour = "cyan", range_mult_flow = NULL, range_mult_precip = 1.5, flow_labels = NULL, ylabel = NULL, precip_label = "Precipitation [mm]", leg_pos = NULL, leg_box = NULL, zero_axis = TRUE )
ch_hydrograph_plot( flows = NULL, precip = NULL, prd = NULL, winter_shading = FALSE, winter_colour = "cyan", range_mult_flow = NULL, range_mult_precip = 1.5, flow_labels = NULL, ylabel = NULL, precip_label = "Precipitation [mm]", leg_pos = NULL, leg_box = NULL, zero_axis = TRUE )
flows |
data frame of flows to plot |
precip |
data frame of precipitation values to plot |
prd |
period to use in plotting |
winter_shading |
optionally adds a transparent cyan shading for the
December 1st to March 31st period in each year that is plotted. Default is
|
winter_colour |
colour to use in winter shading polygons |
range_mult_flow |
range multiplier for max value in hydrograph. This is useful in preventing overlap if precip is also plotted. This value should not be less than 1.0, otherwise the values will be cutoff in the plot. |
range_mult_precip |
range multiplier for max value in precipitation plot (default 1.5) |
flow_labels |
string vector of labels for flow values |
ylabel |
text label for y-axis of the plot (default 'Flow [m^3/s]') |
precip_label |
text label for precipitation y-axis (default 'Precipitation [mm]') |
leg_pos |
string specifying legend placement on plot e.g. topleft,
right, etc., and is consistent with the legend function options. If |
leg_box |
boolean on whether to put legend in an opaque white box
or not. If |
zero_axis |
fixes the y axis to start exactly at zero (default |
Assumes that the supplied time series have the same length and duration in time. If this is not true, then the defined period or period calculated from the first available flow series will be used to determine the plotting limits in time. The supplied time series should be in xts format. Note that a plot title is purposely omitted in order to allow the automatic generation of plot titles.
Returns TRUE
if the function is executed properly.
Robert Chlumsky
# example with synthetic random data dd <- seq.Date(as.Date("2010-10-01"), as.Date("2013-09-30"),by = 1) x <- abs(rnorm(length(dd))) y <- abs(rnorm(length(dd))) * x df <- data.frame("Date" = dd, x, y) myprd <- "2011-10-01/2012-09-30" precip <- data.frame("Date" = dd," precip" = abs(rnorm(length(dd))) * 10) # basic hydrograph plot ch_hydrograph_plot(flows = df, winter_shading = FALSE) # with different labels and winter shading ch_hydrograph_plot(flows = df, winter_shading = TRUE, flow_labels = c("simulated", "observed")) # add precipitation, increase the plot ranges to separate flows and precip, and add a legend box ch_hydrograph_plot(flows = df, precip = precip, range_mult_flow = 1.7, range_mult_precip = 2, leg_box = TRUE)
# example with synthetic random data dd <- seq.Date(as.Date("2010-10-01"), as.Date("2013-09-30"),by = 1) x <- abs(rnorm(length(dd))) y <- abs(rnorm(length(dd))) * x df <- data.frame("Date" = dd, x, y) myprd <- "2011-10-01/2012-09-30" precip <- data.frame("Date" = dd," precip" = abs(rnorm(length(dd))) * 10) # basic hydrograph plot ch_hydrograph_plot(flows = df, winter_shading = FALSE) # with different labels and winter shading ch_hydrograph_plot(flows = df, winter_shading = TRUE, flow_labels = c("simulated", "observed")) # add precipitation, increase the plot ranges to separate flows and precip, and add a legend box ch_hydrograph_plot(flows = df, precip = precip, range_mult_flow = 1.7, range_mult_precip = 2, leg_box = TRUE)
Produces a polar plot similar to that used in Whitfield and Cannon, 2000. It uses output
from the function ch_binned_MannWhitney
or a data structure created using
the function ch_polar_plot_prep
.
ch_polar_plot( bmw, lcol1 = c("black", "gray50"), lcol2 = c("black", "gray50"), lfill = c("yellow", "green"), lsig = c("red", "blue") )
ch_polar_plot( bmw, lcol1 = c("black", "gray50"), lcol2 = c("black", "gray50"), lfill = c("yellow", "green"), lsig = c("red", "blue") )
bmw |
output from |
lcol1 |
line colour, default is |
lcol2 |
point colour, default is |
lfill |
fill colour, default is |
lsig |
significance symbol colour, default is |
No value is returned; a standard R graphic is created.
Paul Whitfield
Whitfield, P.H. and A.J. Cannon. 2000. Polar plotting of seasonal hydrologic and climatic data. Northwest Science 74: 76-80.
Whitfield, P.H., Cannon, A.J., 2000. Recent variations in climate and hydrology in Canada. Canadian Water Resources Journal 25: 19-65.
ch_binned_MannWhitney
ch_polar_plot_prep
range1 <- c(1970,1979) range2 <- c(1990,1999) b_MW <- ch_binned_MannWhitney(CAN05AA008, step = 5, range1, range2, ptest <- 0.05) ch_polar_plot(b_MW)
range1 <- c(1970,1979) range2 <- c(1990,1999) b_MW <- ch_binned_MannWhitney(CAN05AA008, step = 5, range1, range2, ptest <- 0.05) ch_polar_plot(b_MW)
ch_polar_plot
Could be used to move data from a different type of analysis different to
the ch_binned_MannWhitney
function which uses flows. The two series need to be of the
same length and their length is related to the step size. For examples,
for five day periods there will be 73 periods.
ch_polar_plot_prep( station, plot_title, step, x0, x1, stat, prob, test_s, variable = "discharge", bin_method = "unstated", test_method = "unstated", lline1 = "Period 1", lline2 = "Period 2", pvalue = 0.05 )
ch_polar_plot_prep( station, plot_title, step, x0, x1, stat, prob, test_s, variable = "discharge", bin_method = "unstated", test_method = "unstated", lline1 = "Period 1", lline2 = "Period 2", pvalue = 0.05 )
station |
Typically a station number |
plot_title |
Polar plot title - usually a station name |
step |
The number of days binned |
x0 |
Time series of length n for a single seasonal cycle |
x1 |
Time series of length n for a single seasonal cycle |
stat |
Time series of length n for statistical test value for each bin |
prob |
Time series of length n of probability of test value |
test_s |
Vector with values of -1, 0, 1 for significance, -1 negative, 1 positive, 0 not significant |
variable |
Name of variable plotted. Default is discharge |
bin_method |
Default is unstated |
test_method |
Default is unstated |
lline1 |
Names of first period, default is Period 1 |
lline2 |
Names of second period, default is Period 2 |
pvalue |
Value of p used. Default is 0.05 |
Returns a list containing:
StationID |
ID of station |
Station_lname |
Name of station |
variable |
Name of variable |
bin_width |
Smoothing time step in days |
range1 |
First range of years |
range2 |
Second range of years |
p_used |
p_value |
fail |
TRUE if test failed due to missing values |
bin_method |
Method used for binning |
test_method |
Mann-Whitney U |
series |
A data frame containing six columns |
The series
data frame contains
period |
period numbers i.e. 1:365/step |
period1 |
median values for each bin in period 1 |
period2 |
median values for each bin in period 2 |
mwu |
Mann Whitney U-statistic for each bin between the two periods |
prob |
probability of U for each period |
code |
significance codes for each bin |
Paul Whitfield
Whitfield, P.H. and A.J. Cannon. 2000. Polar plotting of seasonal hydrologic and climatic data. Northwest Science 74: 76-80.
Whitfield, P.H., Cannon, A.J., 2000. Recent variations in climate and hydrology in Canada. Canadian Water Resources Journal 25: 19-65.
ch_binned_MannWhitney
ch_polar_plot
Plots a hydrograph of a WSC daily data file read from from ECDataExplorer (ECDE). The hydrograph shows individual days with data quality symbols [SYM] in colour and counts cases of each and reports them in the legend. The colours and symbols are those produced by ECDataExplorer.
There is an option is to provide start and end dates to show only part of the time period for which data exists and the plot is annotated to indicate this. Counts of missing observations is also provided in the legend.
ch_qa_hydrograph( DF, st_date = NULL, end_date = NULL, cts = TRUE, rescale = FALSE, sym_col = c("black", "green", "cyan", "yellow", "red", "white"), metadata = NULL )
ch_qa_hydrograph( DF, st_date = NULL, end_date = NULL, cts = TRUE, rescale = FALSE, sym_col = c("black", "green", "cyan", "yellow", "red", "white"), metadata = NULL )
DF |
Data frame retrieved from ECDataExplorer as returned by the function
|
st_date |
Optional start date in the form yyyy-mm-dd. Default is |
end_date |
Optional end date in the form yyyy-mm-dd. Default is |
cts |
If |
rescale |
If |
sym_col |
Colours used for SYM; default is those used in ECDE ("black", "green", "cyan","yellow", "red", "white"). The final "white" can be changed to highlight missing data points. |
metadata |
a dataframe of station metadata, default is |
Produces a plot and returns a list that contains:
station name or title used |
|
st_date |
starting date |
end_date |
ending data |
n |
the number of data points |
sym_count |
summary of the SYM counts |
missing |
number of missing data |
Paul Whitfield
m_test <- ch_qa_hydrograph(CAN05AA008) m_test <- ch_qa_hydrograph(CAN05AA008, st_date="1980-01-01", end_date="1999-12-31")
m_test <- ch_qa_hydrograph(CAN05AA008) m_test <- ch_qa_hydrograph(CAN05AA008, st_date="1980-01-01", end_date="1999-12-31")
This program reads an Adjusted and Homogenized Canadian Climate Data (AHCCD) of daily precipitation or temperatures. The values are arranged as month x day, which makes them difficult to read using standard R functions.
ch_read_AHCCD_daily(daily_file)
ch_read_AHCCD_daily(daily_file)
daily_file |
Required. Name of the file to be read. |
If successful, returns the values in a data frame, consisting of the date, the value and the data code.
Kevin Shook
Daily AHCCD data are available from http://crd-data-donnees-rdc.ec.gc.ca/CDAS/products/EC_data/AHCCD_daily/. Any use of the data must cite Mekis, E and L.A. Vincent, 2011: An overview of the second generation adjusted daily precipitation dataset for trend analysis in Canada. Atmosphere-Ocean, 49 (2), 163-177.
# Not tested automatically as requires a file stoon_daily_tmax <- ch_read_AHCCD_daily("dx40657120.txt")
# Not tested automatically as requires a file stoon_daily_tmax <- ch_read_AHCCD_daily("dx40657120.txt")
This program reads an Adjusted and Homogenized Canadian Climate Data (AHCCD) data of precipitation or temperatures. The values are arranged as year x month, which makes them difficult to read using standard R functions.
ch_read_AHCCD_monthly(monthly_file = NULL)
ch_read_AHCCD_monthly(monthly_file = NULL)
monthly_file |
Required. Name of the file to be read. |
If successful, returns the values in a dataframe, consisting of the year
,
the month
, the value and the data code
.
Kevin Shook
Any use of the data must cite Mekis, E and L.A. Vincent, 2011: An overview of the second generation adjusted daily temperature and precipitation dataset for trend analysis in Canada. Atmosphere-Ocean, 49 (2), 163-177.
# Not tested automatically as requires a file Stoon_monthly_precip <- ch_read_AHCCD_monthly("mt4057120.txt") NB_monthly_tmean <- ch_read_AHCCD_monthly("mm4045695.txt")
# Not tested automatically as requires a file Stoon_monthly_precip <- ch_read_AHCCD_monthly("mt4057120.txt") NB_monthly_tmean <- ch_read_AHCCD_monthly("mm4045695.txt")
Reads in a file WSC daily flows as returned from the Windows program ECDataExplorer, converts the Date, and omits the last 3 lines as these contain the data disclaimer and not data.
ch_read_ECDE_flows(filename)
ch_read_ECDE_flows(filename)
filename |
Datafile retrieved from ECDataExplorer. |
Returns a dataframe with the last three rows removed:
ID |
stationID |
PARAM |
Parameter 1 for Flow 2 for Level |
Date |
original charater string converted to date format |
Flow |
Daily mean flow m |
SYM |
Quality flag |
Paul Whitfield
# Using a dummy file name as an example mfile <- "04JD005_Daily_Flow_ts.csv" mdata <- ch_read_ECDE_flows(mfile)
# Using a dummy file name as an example mfile <- "04JD005_Daily_Flow_ts.csv" mdata <- ch_read_ECDE_flows(mfile)
Produces a regime hydrograph similar to that in the reference. It shows the flow quantiles for each day of the year and the maximum and minimum. Parameters can be set to change colours and set the y-scale to allow plots of same scale to be produced.
ch_regime_plot( DF, wyear = 1, colour = TRUE, mx = 1, metadata = NULL, quant = c(0.95, 0.9, 0.75, 0.5, 0.25, 0.1, 0.05) )
ch_regime_plot( DF, wyear = 1, colour = TRUE, mx = 1, metadata = NULL, quant = c(0.95, 0.9, 0.75, 0.5, 0.25, 0.1, 0.05) )
DF |
data frame of daily flow data |
wyear |
set |
colour |
if |
mx |
set the maximum y value; if = 1 then maximum value of the flows is used to set |
metadata |
a data frame of metadata, defaults to HYDAT_list.
the y-axis value. The value of |
quant |
quantiles; default is |
No value is returned; a standard R graphic is created.
Paul Whitfield
MacCulloch, G. and P. H. Whitfield (2012). Towards a Stream Classification System for the Canadian Prairie Provinces. Canadian Water Resources Journal 37: 311-332.
data(CAN05AA008) ch_regime_plot(CAN05AA008, colour = TRUE, wyear = 1)
data(CAN05AA008) ch_regime_plot(CAN05AA008, colour = TRUE, wyear = 1)
Calculates a matrix of distances between points in the seasonal space that characterizes timing and regularity. It is equivalent to Euclidean distance applied to regularity (radius) and timing (angle) separately.
ch_rfa_distseason(x, ...) ## S3 method for class 'numeric' ch_rfa_distseason(x, a, w = 1/pi, ...) ## S3 method for class 'data.frame' ch_rfa_distseason(x, w = 1/pi, ...) ## S3 method for class 'formula' ch_rfa_distseason(form, x, w = 1/pi, ...)
ch_rfa_distseason(x, ...) ## S3 method for class 'numeric' ch_rfa_distseason(x, a, w = 1/pi, ...) ## S3 method for class 'data.frame' ch_rfa_distseason(x, w = 1/pi, ...) ## S3 method for class 'formula' ch_rfa_distseason(form, x, w = 1/pi, ...)
x , a
|
Coordinates in the seasonal space.
Can be a data.frame or vectors with radius |
... |
Other parameters. |
w |
Weight to favor angle over radius. By default it is 1/pi, which bring angle in the interval [0,1]. |
form |
Formula and dataset providing the coordinates of the
seasonal space. Must be of the form |
Returns a matrix of distances between points in the seasonal space that characterizes timing and regularity.
Martin Durocher
Durocher, M., Burn, D. H., & Ashkar, F. (2019). Comparison of estimation methods for a nonstationary index-flood model in flood frequency analysis using peaks over threshold. https://doi.org/10.31223/osf.io/rnepc
scoord <- data.frame(radius = runif(5), angle = runif(5,0,2*pi)) ch_rfa_distseason(radius ~ angle , scoord)
scoord <- data.frame(radius = runif(5), angle = runif(5,0,2*pi)) ch_rfa_distseason(radius ~ angle , scoord)
Extracts the annual maxima of a daily time series
ch_rfa_extractamax(x, ...) ## S3 method for class 'formula' ch_rfa_extractamax(form, x, tol = 0, ...) ## Default S3 method: ch_rfa_extractamax(x, tol = 0, nlab = "n", ylab = "yy", ...)
ch_rfa_extractamax(x, ...) ## S3 method for class 'formula' ch_rfa_extractamax(form, x, tol = 0, ...) ## Default S3 method: ch_rfa_extractamax(x, tol = 0, nlab = "n", ylab = "yy", ...)
x |
Data. If no formula is passed, the first column must be the value and the second the date. |
... |
Other parameters. |
form |
Formula of the form |
tol |
Filter the years having less than |
nlab , ylab
|
Names for the added columns representing respectively
the number of yearly observations and the year.
If set to |
Returns a data frame containing the annual (Monthly) maxima, the date and the number of observations during the year.
Martin Durocher
out <- ch_rfa_extractamax(flow ~ date, CAN01AD002, tol = 350) head(out)
out <- ch_rfa_extractamax(flow ~ date, CAN01AD002, tol = 350) head(out)
Create axis for plotting circular statistics in a unitary circle.
ch_rfa_julianplot( rose.col = "gray40", rose.lwd = 1.5, rose.cex = 1.5, rose.radius = seq(0.25, 1, 0.25), ... )
ch_rfa_julianplot( rose.col = "gray40", rose.lwd = 1.5, rose.cex = 1.5, rose.radius = seq(0.25, 1, 0.25), ... )
rose.col , rose.lwd , rose.cex
|
Properties of the polar axes. |
rose.radius |
Vector of the position of the circular axis. |
... |
Other parameter passed to points. |
Returns a empty rose plot by day of year
Martin Durocher
data(flowAtlantic) ss <- ch_rfa_seasonstat(date ~ id, flowAtlantic$ams) ch_rfa_julianplot() points(y ~ x, ss, pch = 16, col = cut(ss[,'radius'], c(0,.5,.75,1)))
data(flowAtlantic) ss <- ch_rfa_seasonstat(date ~ id, flowAtlantic$ams) ch_rfa_julianplot() points(y ~ x, ss, pch = 16, col = cut(ss[,'radius'], c(0,.5,.75,1)))
Return the circular or seasonal statistics of flood peaks. The angle represents the mean timing of the floods and the radius its regularity. For example, a radius of one represents perfect regularity. Can perform the analyses on multiple sites.
ch_rfa_seasonstat(x, ...) ## S3 method for class 'data.frame' ch_rfa_seasonstat(x, ...) ## S3 method for class 'formula' ch_rfa_seasonstat(form, x, ...)
ch_rfa_seasonstat(x, ...) ## S3 method for class 'data.frame' ch_rfa_seasonstat(x, ...) ## S3 method for class 'formula' ch_rfa_seasonstat(form, x, ...)
x |
Data. If data.frame with two columns, they must be respectively the date and a site variable. |
... |
Other parameters. |
form |
Formula that specifies the date and site variable. Must be of the
form |
Returns the circular or seasonal statistics of flood peaks.
Martin Durocher
Burn, D.H. (1997). Catchment similarity for regional flood frequency analysis using seasonality measures. Journal of Hydrology 202, 212-230. https://doi.org/10.1016/S0022-1694(97)00068-1
dt <- ch_rfa_extractamax(flow~date, CAN01AD002)$date ch_rfa_seasonstat(dt) ## Illustration of the analysis of multiple sites F0 <- function(ii) data.frame(site = ii, dt = sample(dt, replace = TRUE)) x <- lapply(1:10, F0) x <- do.call(rbind, x) st <- ch_rfa_seasonstat(dt ~ site, x) ch_rfa_julianplot() points(y ~ x, st, col = 2, pch = 16)
dt <- ch_rfa_extractamax(flow~date, CAN01AD002)$date ch_rfa_seasonstat(dt) ## Illustration of the analysis of multiple sites F0 <- function(ii) data.frame(site = ii, dt = sample(dt, replace = TRUE)) x <- lapply(1:10, F0) x <- do.call(rbind, x) st <- ch_rfa_seasonstat(dt ~ site, x) ch_rfa_julianplot() points(y ~ x, st, col = 2, pch = 16)
Converts a series of a variable such as day of year into numbered bins. Whenever the number of bins does not divide in 365 evenly a message showing the number of bins created and the number of days added to the last bin is provided.
Simply put, ch_slice
is used to convert doy into a
factor which is a number of bins per year. A year can be converted into any
number of bins; slice does it based upon a number of days. So when you send it
an array of doy it slices that into bins of the desired width. For example,
if the step is 5. They 365/5 gives 73 bins and because of leap years there might
be one extra day added every four years to the final bin.
To illustrate for a bin of 5 days: doy: 1 2 3 4 5 6 7 8 9 10 11 12 Bin: 1 1 1 1 1 2 2 2 2 2 3 3
ch_slice(doy, step)
ch_slice(doy, step)
doy |
A vector of the day of calendar year for the dataset |
step |
Width of bin in days |
Returns a vector of bin numbers that is used as a factor for each day in the dataset and provides a message indicating the handling of partial bins
Paul Whitfield, Kevin Shook
ch_binned_MannWhitney
ch_flow_raster_trend
doy <- c(1:365) # first 30 days are 1, 31-60 are 2 etc dice <- ch_slice(doy, 30) plot(doy, dice)
doy <- c(1:365) # first 30 days are 1, 31-60 are 2 etc dice <- ch_slice(doy, 30) plot(doy, dice)
Sub-samples a vector every n places. Many times there are so many
years the labels on the plot overlap. ch_sub_set_years
returns the position and label
for the subset. The function can be used on any type of simple array.
ch_sub_set_Years(years, n)
ch_sub_set_Years(years, n)
years |
a vector of years |
n |
sample size |
a list containing:
position |
array of axis positions |
label |
array of labels |
Paul Whitfield
myears <- c(1900:2045) myears <- ch_sub_set_Years(myears, 20) myears a <- LETTERS my_alpha <- ch_sub_set_Years(a, 5) my_alpha
myears <- c(1900:2045) myears <- ch_sub_set_Years(myears, 20) myears a <- LETTERS my_alpha <- ch_sub_set_Years(a, 5) my_alpha
Accessing daily flow data using tidyhydat is quick and efficient. However, it sometimes conflicts with other functions as tidyhydat changes variable names and some default entries. This function converts a tibble obtained from a tidyhydat tibble to a dataframe with standard Environment and Climate Change Canada Data Explorer (ECDE) names.
ch_tidyhydat_ECDE(data)
ch_tidyhydat_ECDE(data)
data |
Tibble of daily flows retrieved using tidyhydat function |
A dataframe or a list of flows with formats consistent with datafiles read using ch_read_ECDE_flows
:
ID |
stationID |
PARAM |
Parameter 1 for Flow 2 for Level |
Date |
original charater string converted to date format |
Flow |
Daily mean flow m |
SYM |
Quality flag |
Paul Whitfield
library(tidyhydat) mdata <- hy_daily_flow(station_number=c("05CK004")) m_data <- ch_tidyhydat_ECDE(mdata) mdata <- hy_daily_flows(station_number=c("05CK004","08MF005","05BB001")) mnew <- ch_tidyhydat_ECDE(mdata) str(mnew[[1]]) str(mnew[[2]]) str(mnew[[3]]) #note the order is in increasing alphabetical order
library(tidyhydat) mdata <- hy_daily_flow(station_number=c("05CK004")) m_data <- ch_tidyhydat_ECDE(mdata) mdata <- hy_daily_flows(station_number=c("05CK004","08MF005","05BB001")) mnew <- ch_tidyhydat_ECDE(mdata) str(mnew[[1]]) str(mnew[[2]]) str(mnew[[3]]) #note the order is in increasing alphabetical order
Extracts tombstone (meta) data for stations from tidyhydat in a format similar to that used by the Environment Canada Data Explorer (ECDE). The default does not capture all the fields in ECDE, which includes the most recent status of many fields such as operating schedule. Returning these values slows the function, particularly when all WSC stations are selected.
ch_tidyhydat_ECDE_meta(stations, all_ECDE = FALSE)
ch_tidyhydat_ECDE_meta(stations, all_ECDE = FALSE)
stations |
A vector of WSC station IDs, i.e. |
all_ECDE |
Should all ECDE values be returned? If |
Returns a list with three items:
meta
- a dataframe of metadata from tidyhydat in ECDE form (not all ECDE fields are reproduced in this summary)
H_version
- version information, and
th_meta
- a dataframe with all tidyhdat fields including:
Station - StationID
StationName - Station Name
HYDStatus - Active or Discontinued
Prov - Province
Latitude
Longitude
DrainageArea - km
Years - number of years with data
From - Start Year
To - End Year
Reg. - Regulated?
Flow - not captured (differs from ECDE), unless all_ECDE = TRUE
Level - not captured (differs from ECDE), unless all_ECDE = TRUE
Sed - not captured (differs from ECDE), unless all_ECDE = TRUE
OperSched - not captured (differs from ECDE), unless all_ECDE = TRUE
RealTime - if TRUE/Yes
RHBN - if TRUE/Yes is in the reference hydrologic basin network
Region - number of region instead of name (differs from ECDE), unless all_ECDE = TRUE
Datum - reference number (differs from ECDE), unless all_ECDE = TRUE
Operator - reference number (differs from ECDE), unless all_ECDE = TRUE
Paul Whitfield, Kevin Shook
ch_get_ECDE_metadata
ch_tidyhydat_ECDE
# This example requires \pkg{tidyhydat} to be installed # the \code{HYDAT} database, which makes automatic checking slow stations <- c("05BB001", "05BB003", "05BB004", "05BB005") result <- ch_tidyhydat_ECDE_meta(stations) metadata <- result[[1]] version <- result[[2]] # This example is not run, as it can take over an hour to execute # It is intended to be used by the package maintainers to update \code{HYDAT_list} result <- ch_tidyhydat_ECDE_meta("all", TRUE) HYDAT_list <- result$meta
# This example requires \pkg{tidyhydat} to be installed # the \code{HYDAT} database, which makes automatic checking slow stations <- c("05BB001", "05BB003", "05BB004", "05BB005") result <- ch_tidyhydat_ECDE_meta(stations) metadata <- result[[1]] version <- result[[2]] # This example is not run, as it can take over an hour to execute # It is intended to be used by the package maintainers to update \code{HYDAT_list} result <- ch_tidyhydat_ECDE_meta("all", TRUE) HYDAT_list <- result$meta
Creates a file of pour points for the volcano
DEM. The
pour points define the outlets of sub-basins. These pour points are used
by examples within other functions.
ch_volcano_pourpoints(pp_shp)
ch_volcano_pourpoints(pp_shp)
pp_shp |
Name for shapefile to hold pour points |
Returns an sf object containing 2 pour points for the
volcano
DEM. The pour points are also written to the specified file.
Dan Moore and Kevin Shook
ch_volcano_raster
ch_wbt_pourpoints
pourpoint_file <- tempfile("volcano_pourpoints", fileext = c(".shp")) pourpoints <- ch_volcano_pourpoints(pourpoint_file) plot(pourpoints)
pourpoint_file <- tempfile("volcano_pourpoints", fileext = c(".shp")) pourpoints <- ch_volcano_pourpoints(pourpoint_file) plot(pourpoints)
Creates a raster object of land surface elevations, as used to test/demonstrate many functions requiring a digital elevation model (DEM).
ch_volcano_raster()
ch_volcano_raster()
No arguments are required as the DEM is created from the base
volcano
matrix of elevations.
Returns a raster object of land surface elevations.
Dan Moore and Kevin Shook
test_raster <- ch_volcano_raster()
test_raster <- ch_volcano_raster()
Delineate catchment boundaries
ch_wbt_catchment( fn_pp_snap, fn_flowdir, fn_catchment_ras, fn_catchment_vec, return_vector = TRUE )
ch_wbt_catchment( fn_pp_snap, fn_flowdir, fn_catchment_ras, fn_catchment_vec, return_vector = TRUE )
fn_pp_snap |
Name of file containing snapped pour points |
fn_flowdir |
Name of file containing flow accumulations. |
fn_catchment_ras |
Raster file to contain delineated catchment. |
fn_catchment_vec |
Vector file to contain delineated catchment. |
return_vector |
If |
If return_vector == TRUE
a vector of the catchment is returned. Otherwise
nothing is returned.
Dan Moore and Kevin Shook
# Not tested automatically as requires installation of Whitebox library(raster) test_raster <- ch_volcano_raster() dem_raster_file <- tempfile(fileext = ".tif") no_sink_raster_file <- tempfile("no_sinks", fileext = ".tif") # write test raster to file writeRaster(test_raster, dem_raster_file, format = "GTiff") # remove sinks removed_sinks <- ch_wbt_removesinks(dem_raster_file, no_sink_raster_file, method = "fill") # get flow accumulations flow_acc_file <- tempfile("flow_acc", fileext = ".tif") flow_acc <- ch_wbt_flow_accumulation(no_sink_raster_file, flow_acc_file) # get pour points pourpoint_file <- tempfile("volcano_pourpoints", fileext = ".shp") pourpoints <- ch_volcano_pourpoints(pourpoint_file) snapped_pourpoint_file <- tempfile("snapped_pourpoints", fileext = ".shp") snapped_pourpoints <- ch_wbt_pourpoints(pourpoints, flow_acc_file, pourpoint_file, snapped_pourpoint_file, snap_dist = 10) # get flow directions flow_dir_file <- tempfile("flow_dir", fileext = ".tif") flow_dir <- ch_wbt_flow_direction(no_sink_raster_file, flow_dir_file) fn_catchment_ras <- tempfile("catchment", fileext = ".tif") fn_catchment_vec <- tempfile("catchment", fileext = ".shp") catchments <- ch_wbt_catchment(snapped_pourpoint_file, flow_dir_file, fn_catchment_ras, fn_catchment_vec)
# Not tested automatically as requires installation of Whitebox library(raster) test_raster <- ch_volcano_raster() dem_raster_file <- tempfile(fileext = ".tif") no_sink_raster_file <- tempfile("no_sinks", fileext = ".tif") # write test raster to file writeRaster(test_raster, dem_raster_file, format = "GTiff") # remove sinks removed_sinks <- ch_wbt_removesinks(dem_raster_file, no_sink_raster_file, method = "fill") # get flow accumulations flow_acc_file <- tempfile("flow_acc", fileext = ".tif") flow_acc <- ch_wbt_flow_accumulation(no_sink_raster_file, flow_acc_file) # get pour points pourpoint_file <- tempfile("volcano_pourpoints", fileext = ".shp") pourpoints <- ch_volcano_pourpoints(pourpoint_file) snapped_pourpoint_file <- tempfile("snapped_pourpoints", fileext = ".shp") snapped_pourpoints <- ch_wbt_pourpoints(pourpoints, flow_acc_file, pourpoint_file, snapped_pourpoint_file, snap_dist = 10) # get flow directions flow_dir_file <- tempfile("flow_dir", fileext = ".tif") flow_dir <- ch_wbt_flow_direction(no_sink_raster_file, flow_dir_file) fn_catchment_ras <- tempfile("catchment", fileext = ".tif") fn_catchment_vec <- tempfile("catchment", fileext = ".shp") catchments <- ch_wbt_catchment(snapped_pourpoint_file, flow_dir_file, fn_catchment_ras, fn_catchment_vec)
Calls all of the ch_wbt
and other functions required to do the sub-tasks
required to delineate a catchment. The names of files to be created
are taken from the list created by the function ch_wbt_filenames
.
ch_wbt_catchment_onestep( wd, in_dem, pp_sf, sink_method = "breach_leastcost", dist = NULL, check_catchment = TRUE, threshold = NULL, snap_dist = NULL, cb_colour = "red", pp_colour = "red", channel_colour = "blue", contour_colour = "grey", plot_na = TRUE, plot_scale = TRUE, na_location = "tr", scale_location = "bl", ... )
ch_wbt_catchment_onestep( wd, in_dem, pp_sf, sink_method = "breach_leastcost", dist = NULL, check_catchment = TRUE, threshold = NULL, snap_dist = NULL, cb_colour = "red", pp_colour = "red", channel_colour = "blue", contour_colour = "grey", plot_na = TRUE, plot_scale = TRUE, na_location = "tr", scale_location = "bl", ... )
wd |
Name of working directory. |
in_dem |
File name for original DEM. |
pp_sf |
Vector containing pour points. |
sink_method |
Method for sink removal as used by |
dist |
Maximum search distance for breach paths in cells. Required if |
check_catchment |
If |
threshold |
Threshold for channel initiation. |
snap_dist |
Maximum pour point snap distance in map units. |
cb_colour |
Colour for catchment outline. Default is "red". |
pp_colour |
Colour for catchment pour points. Default is "red". |
channel_colour |
Colour for channel. Default is "blue". |
contour_colour |
Colour for contours Default is "grey". |
plot_na |
If |
plot_scale |
If |
na_location |
Location for the north arrow. Default is tr, i.e. top-right. |
scale_location |
Location for the scale bar. Default is bl, i.e. bottom-left. |
... |
Extra parameters for |
Returns an sp object of the delineated catchment.
Dan Moore and Kevin Shook
# Not tested automatically as requires installation of Whitebox library(raster) test_raster <- ch_volcano_raster() dem_raster_file <- tempfile(fileext = c(".tif")) # write test raster to file writeRaster(test_raster, dem_raster_file, format = "GTiff") wd <- tempdir() pourpoint_file <- tempfile("volcano_pourpoints", fileext = ".shp") pourpoints <- ch_volcano_pourpoints(pourpoint_file) catchment <- ch_wbt_catchment_onestep(wd = wd, in_dem = dem_raster_file, pp_sf = pourpoints, sink_method = "fill", threshold = 1, snap_dist = 10)
# Not tested automatically as requires installation of Whitebox library(raster) test_raster <- ch_volcano_raster() dem_raster_file <- tempfile(fileext = c(".tif")) # write test raster to file writeRaster(test_raster, dem_raster_file, format = "GTiff") wd <- tempdir() pourpoint_file <- tempfile("volcano_pourpoints", fileext = ".shp") pourpoints <- ch_volcano_pourpoints(pourpoint_file) catchment <- ch_wbt_catchment_onestep(wd = wd, in_dem = dem_raster_file, pp_sf = pourpoints, sink_method = "fill", threshold = 1, snap_dist = 10)
Generate stream network
ch_wbt_channels( fn_flowacc, fn_flowdir, fn_channel_ras, fn_channel_vec, threshold = NULL, ... )
ch_wbt_channels( fn_flowacc, fn_flowdir, fn_channel_ras, fn_channel_vec, threshold = NULL, ... )
fn_flowacc |
File name for flow accumulation grid. |
fn_flowdir |
File name for flow direction grid. |
fn_channel_ras |
File name for raster version of channel network. |
fn_channel_vec |
File name for vector version of channel networks. |
threshold |
Threshold for channel initiation. |
... |
Other parameters for whitebox function |
Returns a sf vector object of the stream channels.
Dan Moore
# Not tested automatically as requires installation of Whitebox library(raster) test_raster <- ch_volcano_raster() dem_raster_file <- tempfile(fileext = c(".tif")) no_sink_raster_file <- tempfile("no_sinks", fileext = c(".tif")) # write test raster to file writeRaster(test_raster, dem_raster_file, format = "GTiff") # remove sinks removed_sinks <- ch_wbt_removesinks(dem_raster_file, no_sink_raster_file, method = "fill") # get flow accumulations flow_acc_file <- tempfile("flow_acc", fileext = c(".tif")) flow_acc <- ch_wbt_flow_accumulation(no_sink_raster_file, flow_acc_file) # get flow directions flow_dir_file <- tempfile("flow_dir", fileext = c(".tif")) flow_dir <- ch_wbt_flow_direction(no_sink_raster_file, flow_dir_file) channel_raster_file <- tempfile("channels", fileext = c(".tif")) channel_vector_file <- tempfile("channels", fileext = c(".shp")) channels <- ch_wbt_channels(flow_acc_file, flow_dir_file, channel_raster_file, channel_vector_file, 1) plot(channels)
# Not tested automatically as requires installation of Whitebox library(raster) test_raster <- ch_volcano_raster() dem_raster_file <- tempfile(fileext = c(".tif")) no_sink_raster_file <- tempfile("no_sinks", fileext = c(".tif")) # write test raster to file writeRaster(test_raster, dem_raster_file, format = "GTiff") # remove sinks removed_sinks <- ch_wbt_removesinks(dem_raster_file, no_sink_raster_file, method = "fill") # get flow accumulations flow_acc_file <- tempfile("flow_acc", fileext = c(".tif")) flow_acc <- ch_wbt_flow_accumulation(no_sink_raster_file, flow_acc_file) # get flow directions flow_dir_file <- tempfile("flow_dir", fileext = c(".tif")) flow_dir <- ch_wbt_flow_direction(no_sink_raster_file, flow_dir_file) channel_raster_file <- tempfile("channels", fileext = c(".tif")) channel_vector_file <- tempfile("channels", fileext = c(".shp")) channels <- ch_wbt_channels(flow_acc_file, flow_dir_file, channel_raster_file, channel_vector_file, 1) plot(channels)
Creates a list of the files used for inputs and outputs by the
Whitebox functions. This function needs to be called before calling any of the other
Whitebox (i.e. those prefixed by cd_wbt
) functions. If the file names are not specified, default names will
be used. All raster files are TIFF (.tif), all vector files are shapefiles (.shp).
ch_wbt_filenames( wd = NULL, fn_dem = "dem.tif", fn_dem_fsc = "dem_fsc.tif", fn_dem_ns = "dem_ns.tif", fn_flowacc = "flow_acc.tif", fn_flowdir = "flow_dir.tif", fn_channel_ras = "channel.tif", fn_channel_vec = "channel.shp", fn_catchment_ras = "catchment.tif", fn_catchment_vec = "catchment.shp", fn_pp = "pp.shp", fn_pp_snap = "pp_snap.shp" )
ch_wbt_filenames( wd = NULL, fn_dem = "dem.tif", fn_dem_fsc = "dem_fsc.tif", fn_dem_ns = "dem_ns.tif", fn_flowacc = "flow_acc.tif", fn_flowdir = "flow_dir.tif", fn_channel_ras = "channel.tif", fn_channel_vec = "channel.shp", fn_catchment_ras = "catchment.tif", fn_catchment_vec = "catchment.shp", fn_pp = "pp.shp", fn_pp_snap = "pp_snap.shp" )
wd |
Required. Name of working directory. |
fn_dem |
File name of input DEM. Default is dem.tif. |
fn_dem_fsc |
File name for dem after filling single-cell pits. Default is dem_fsc.tif. |
fn_dem_ns |
File name for dem removing sinks. Default is dem_ns.tif. |
fn_flowacc |
File name for DEM flow accumulation grid Default is flow_acc.tif. |
fn_flowdir |
File name for DEM flow direction grid. Default is flow_dir.tif. |
fn_channel_ras |
File name for raster version of channel network. Default is channel.tif. |
fn_channel_vec |
File name for vector version of channel networks. Default is channel.shp. |
fn_catchment_ras |
File name for raster version of catchment. Default is catchment.tif. |
fn_catchment_vec |
File name for vector version of catchment. Default is catchment.shp. |
fn_pp |
File name for pour points (input). Vector file. Default is pp.shp. |
fn_pp_snap |
File name for pour points after snapping to channel network. Vector file. Default is pp.shp. |
Returns a list of the input and output file names
Dan Moore
wbt_file_names <- ch_wbt_filenames(getwd())
wbt_file_names <- ch_wbt_filenames(getwd())
Creates flow accumulation grid file
ch_wbt_flow_accumulation(fn_dem_ns, fn_flowacc, return_raster = TRUE)
ch_wbt_flow_accumulation(fn_dem_ns, fn_flowacc, return_raster = TRUE)
fn_dem_ns |
File name of dem with sinks removed. |
fn_flowacc |
File name for flow accumulation grid to be created. |
return_raster |
If |
If return_raster = TRUE
, the flow accumulation
grid will be returned as a raster object, otherwise NULL
is returned.
Dan Moore
# Not tested automatically as requires installation of Whitebox library(raster) test_raster <- ch_volcano_raster() dem_raster_file <- tempfile(fileext = c(".tif")) no_sink_raster_file <- tempfile("no_sinks", fileext = c(".tif")) # write test raster to file writeRaster(test_raster, dem_raster_file, format = "GTiff") # remove sinks removed_sinks <- ch_wbt_removesinks(dem_raster_file, no_sink_raster_file, method = "fill") # get flow accumulations flow_acc_file <- tempfile("flow_acc", fileext = c(".tif")) flow_acc <- ch_wbt_flow_accumulation(no_sink_raster_file, flow_acc_file) plot(flow_acc)
# Not tested automatically as requires installation of Whitebox library(raster) test_raster <- ch_volcano_raster() dem_raster_file <- tempfile(fileext = c(".tif")) no_sink_raster_file <- tempfile("no_sinks", fileext = c(".tif")) # write test raster to file writeRaster(test_raster, dem_raster_file, format = "GTiff") # remove sinks removed_sinks <- ch_wbt_removesinks(dem_raster_file, no_sink_raster_file, method = "fill") # get flow accumulations flow_acc_file <- tempfile("flow_acc", fileext = c(".tif")) flow_acc <- ch_wbt_flow_accumulation(no_sink_raster_file, flow_acc_file) plot(flow_acc)
Creates flow direction grid file
ch_wbt_flow_direction(fn_dem_ns, fn_flowdir, return_raster = TRUE)
ch_wbt_flow_direction(fn_dem_ns, fn_flowdir, return_raster = TRUE)
fn_dem_ns |
File name of dem with sinks removed. |
fn_flowdir |
File name for flow direction grid to be created. |
return_raster |
Should a raster object be returned? |
If return_raster = TRUE
(the default), the flow direction
grid will be returned as a raster object, in addition to being written to
fn_flowdir. If return_raster = FALSE
, the output file will still be created
but a NULL
value is returned.
Dan Moore
# Not tested automatically as requires installation of Whitebox library(raster) test_raster <- ch_volcano_raster() dem_raster_file <- tempfile(fileext = c(".tif")) no_sink_raster_file <- tempfile("no_sinks", fileext = c(".tif")) # write test raster to file writeRaster(test_raster, dem_raster_file, format = "GTiff") # remove sinks removed_sinks <- ch_wbt_removesinks(dem_raster_file, no_sink_raster_file, method = "fill") # get flow directions flow_dir_file <- tempfile("flow_dir", fileext = c(".tif")) flow_dir <- ch_wbt_flow_direction(no_sink_raster_file, flow_dir_file) plot(flow_dir)
# Not tested automatically as requires installation of Whitebox library(raster) test_raster <- ch_volcano_raster() dem_raster_file <- tempfile(fileext = c(".tif")) no_sink_raster_file <- tempfile("no_sinks", fileext = c(".tif")) # write test raster to file writeRaster(test_raster, dem_raster_file, format = "GTiff") # remove sinks removed_sinks <- ch_wbt_removesinks(dem_raster_file, no_sink_raster_file, method = "fill") # get flow directions flow_dir_file <- tempfile("flow_dir", fileext = c(".tif")) flow_dir <- ch_wbt_flow_direction(no_sink_raster_file, flow_dir_file) plot(flow_dir)
Pour points describe the outlets of sub-basins within a DEM. To use the pour points to delineate catchments, they must align with the drainage network. This function snaps (forces the locations) of pour points to the channels.
ch_wbt_pourpoints( pp_sf = NULL, fn_flowacc, fn_pp, fn_pp_snap, check_crs = TRUE, snap_dist = NULL, ... )
ch_wbt_pourpoints( pp_sf = NULL, fn_flowacc, fn_pp, fn_pp_snap, check_crs = TRUE, snap_dist = NULL, ... )
pp_sf |
sf object containing pour points. These must be supplied by the user. See
the code in |
fn_flowacc |
Name of file containing flow accumulations. |
fn_pp |
File name to create un-snapped pour points. |
fn_pp_snap |
File name for snapped pour points. |
check_crs |
If |
snap_dist |
Maximum snap distance in map units. |
... |
Additional parameters for whitebox function |
Returns a sf object of the specified pour points snapped to the channel network.
Dan Moore
# Not tested automatically as requires installation of Whitebox library(raster) test_raster <- ch_volcano_raster() dem_raster_file <- tempfile(fileext = c(".tif")) no_sink_raster_file <- tempfile("no_sinks", fileext = c(".tif")) # write test raster to file writeRaster(test_raster, dem_raster_file, format = "GTiff") # remove sinks removed_sinks <- ch_wbt_removesinks(dem_raster_file, no_sink_raster_file, method = "fill") # get flow accumulations flow_acc_file <- tempfile("flow_acc", fileext = c(".tif")) flow_acc <- ch_wbt_flow_accumulation(no_sink_raster_file, flow_acc_file) # get pour points pourpoint_file <- tempfile("volcano_pourpoints", fileext = c(".shp")) pourpoints <- ch_volcano_pourpoints(pourpoint_file) snapped_pourpoint_file <- tempfile("snapped_pourpoints", fileext = c(".shp")) snapped_pourpoints <- ch_wbt_pourpoints(pourpoints, flow_acc_file, pourpoint_file, snapped_pourpoint_file, snap_dist = 10)
# Not tested automatically as requires installation of Whitebox library(raster) test_raster <- ch_volcano_raster() dem_raster_file <- tempfile(fileext = c(".tif")) no_sink_raster_file <- tempfile("no_sinks", fileext = c(".tif")) # write test raster to file writeRaster(test_raster, dem_raster_file, format = "GTiff") # remove sinks removed_sinks <- ch_wbt_removesinks(dem_raster_file, no_sink_raster_file, method = "fill") # get flow accumulations flow_acc_file <- tempfile("flow_acc", fileext = c(".tif")) flow_acc <- ch_wbt_flow_accumulation(no_sink_raster_file, flow_acc_file) # get pour points pourpoint_file <- tempfile("volcano_pourpoints", fileext = c(".shp")) pourpoints <- ch_volcano_pourpoints(pourpoint_file) snapped_pourpoint_file <- tempfile("snapped_pourpoints", fileext = c(".shp")) snapped_pourpoints <- ch_wbt_pourpoints(pourpoints, flow_acc_file, pourpoint_file, snapped_pourpoint_file, snap_dist = 10)
Sinks are removed from a DEM using one of several methods. The raster file
types supported are listed in Spatial_hydrology_functions
.
ch_wbt_removesinks( in_dem, out_dem, method = "breach_leastcost", dist = NULL, fn_dem_fsc = NULL, ... )
ch_wbt_removesinks( in_dem, out_dem, method = "breach_leastcost", dist = NULL, fn_dem_fsc = NULL, ... )
in_dem |
File path for original dem. Required. |
out_dem |
File path for dem after removing sinks. |
method |
Method for removing sinks. Default method is breach_leastcost. Other methods include breach, fill, fill_pd (Planchon and Darboux), and fill_wl (Wang and Liu). |
dist |
Maximum search distance for breach paths in cells. Required if |
fn_dem_fsc |
File path for dem after removing single-cell pits. |
... |
Additional arguments to be passed to functions to remove sinks. |
Returns a raster object containing the processed dem.
Dan Moore
# Not tested automatically as requires installation of Whitebox ch_wbt_check_whitebox() library(raster) test_raster <- ch_volcano_raster() dem_raster_file <- tempfile(fileext = c(".tif")) no_sink_raster_file <- tempfile("no_sinks", fileext = c(".tif")) # write test raster to file writeRaster(test_raster, dem_raster_file, format = "GTiff") # remove sinks removed_sinks <- ch_wbt_removesinks(dem_raster_file, no_sink_raster_file, method = "fill")
# Not tested automatically as requires installation of Whitebox ch_wbt_check_whitebox() library(raster) test_raster <- ch_volcano_raster() dem_raster_file <- tempfile(fileext = c(".tif")) no_sink_raster_file <- tempfile("no_sinks", fileext = c(".tif")) # write test raster to file writeRaster(test_raster, dem_raster_file, format = "GTiff") # remove sinks removed_sinks <- ch_wbt_removesinks(dem_raster_file, no_sink_raster_file, method = "fill")
Display water year
ch_wtr_yr(dates, start_month = 10)
ch_wtr_yr(dates, start_month = 10)
dates |
A vector of dates with actual year |
start_month |
Month in which the year starts (defaults to October) |
Year starting in start_month
http://stackoverflow.com/questions/27626533/r-create-function-to-add-water-year-column
date <- seq(as.Date("1910/1/1"), as.Date("1912/1/1"), "days") wtr_yr_date <- ch_wtr_yr(dates=date, start_month=10) data.frame(wtr_yr_date, date)
date <- seq(as.Date("1910/1/1"), as.Date("1912/1/1"), "days") wtr_yr_date <- ch_wtr_yr(dates=date, start_month=10) data.frame(wtr_yr_date, date)
Contains the annual maxima of 45 hydrometric stations found in the region '01' of Water Survey of Canada. In additional to the annual maxima, the output list includes catchment descriptors (longitude, latitude, basin area, mean annual precipitation) and the geographical distance between each station.
flowAtlantic
flowAtlantic
An object of class list
of length 2.
Martin Durocher
A dataframe of station information, as extracted from HYDAT using ECDataExplorer.
HYDAT_list
HYDAT_list
A dateframe with a row for each station and 20 columns.
Variables:
StationID
Station Name
Active or Discontinued
Province
km
Number of years with data
Start Year
End Year
Regulated
If TRUE/Yes
If TRUE/Yes
If TRUE/Yes
Continuous or Seasonal
If TRUE/Yes
If TRUE/Yes the station is in the reference hydrologic basin network
ECCC Region
Reference datum
Operator
Water Survey of Canada
These functions perform spatial analyses important in hydrology. All
of the functions with the prefix ch_wbt
require the installation of the
package Whitebox. The functions include:
Removes sinks from a DEM by deepening drainage network
Removes sinks from a DEM by filling them
Generates catchment boundaries for a conditioned DEM based on specified points of interest
Generates a drainage network from DEM
Accumulates flows downstream in a cathcment
Calculated flow directions for each cell in DEM
Snaps pour points to channel
Performs all catchment delineations in a single function
Creates contour lines from DEM
Provides a simple map to check the outputs from ch_saga_catchment
Provides a simple map to check the outputs from ch_saga_channels
Returns a raster object of land surface elevations
The Whitebox functions support the following file types for raster data:
extension
*.tif, *.tiff
*.tif, *.tiff
*.txt, *.asc
*.flt, *.hdr
*.txt, *.asc
*.rdc, *.rst
*.sdat, *.sgrd
*.grd
*.grd
*.tas, *.dep
These functions perform statistical analyses
Compares two time periods of data using Mann-Whitney test
Finds flow exceedence probabilities
Finds peak flows over a specified threshold
These functions are primarily intended for graphing, although some analyses may also be done.
Plot of peaks over a threshold
Raster plot of streamflows
Raster plot of streamflows with WSC quality flags
Raster plot and simple trends of observed streamflows
Plots hydrographs and/or precipitation
Polar plot of daily streamflows
Plots the regime of daily streamflows