Title: | Optimal Channel Networks |
Version: | 1.2.2 |
Description: | Generate and analyze Optimal Channel Networks (OCNs): oriented spanning trees reproducing all scaling features characteristic of real, natural river networks. As such, they can be used in a variety of numerical experiments in the fields of hydrology, ecology and epidemiology. See Carraro et al. (2020) <doi:10.1002/ece3.6479> for a presentation of the package; Rinaldo et al. (2014) <doi:10.1073/pnas.1322700111> for a theoretical overview on the OCN concept; Furrer and Sain (2010) <doi:10.18637/jss.v036.i10> for the construct used. |
Imports: | fields, spam, rgl, methods, igraph, Rcpp (≥ 1.0.10), adespatial, spdep, terra |
License: | GPL-3 |
Encoding: | UTF-8 |
LazyData: | true |
Depends: | R (≥ 3.6) |
Suggests: | knitr, rmarkdown, bookdown |
VignetteBuilder: | knitr |
URL: | https://lucarraro.github.io/OCNet/ |
BugReports: | https://github.com/lucarraro/OCNet/issues |
LinkingTo: | Rcpp |
NeedsCompilation: | yes |
Packaged: | 2024-04-16 10:42:15 UTC; lucac |
Author: | Luca Carraro [aut, cre], Florian Altermatt [ctb], Emanuel A. Fronhofer [ctb], Reinhard Furrer [ctb], Isabelle Gounand [ctb], Andrea Rinaldo [ctb], Enrico Bertuzzo [aut] |
Maintainer: | Luca Carraro <luca.carraro@hotmail.it> |
Repository: | CRAN |
Date/Publication: | 2024-04-16 11:40:02 UTC |
Create and analyze Optimal Channel Networks.
Description
A package that allows the generation and analysis of synthetic river network analogues, called Optimal Channel Networks (OCNs).
References
Rinaldo, A., Rigon, R., Banavar, J. R., Maritan, A., & Rodriguez-Iturbe, I. (2014). Evolution and selection of river networks: Statics, dynamics, and complexity. Proceedings of the National Academy of Sciences of the United States of America, 111(7), 2417-2424. doi:10.1073/pnas.1322700111
Carraro, L., Bertuzzo, E., Fronhofer, E. A., Furrer, R., Gounand, I., Rinaldo, A., & Altermatt, F. (2020). Generation and application of river network analogues for use in ecology and evolution. Ecology and Evolution, 10(14), 7537-7550. doi:10.1002/ece3.6479
Carraro, L., & Altermatt, F. (2022). Optimal channel networks accurately model ecologically-relevant geomorphological features of branching river networks. Communications Earth and Environment, 3(1) doi:10.1038/s43247-022-00454-1
Author(s)
Luca Carraro (luca.carraro@hotmail.it), Florian Altermatt, Emanuel A. Fronhofer, Reinhard Furrer, Isabelle Gounand, Andrea Rinaldo, Enrico Bertuzzo
See Also
Example of small OCN
Description
A network built on a 20x20 lattice obtained by executing set.seed(1); create_OCN(20,20)
.
Usage
data(OCN_20)
Format
A river
object. See create_OCN
documentation for details.
Example of single-outlet OCN with periodic boundaries
Description
A network built on a 250x250 lattice obtained by executing set.seed(2); create_OCN(250, 250, periodicBoundaries = TRUE)
.
Usage
data(OCN_250_PB)
Format
A river
object. See create_OCN
documentation for details.
Example of single-outlet OCN
Description
A network built on a 250x250 lattice obtained by executing set.seed(2); create_OCN(250, 250, typeInitialState = "T")
.
Usage
data(OCN_250_T)
Format
A river
object. See create_OCN
documentation for details.
Example of multiple-outlet OCN
Description
A network built on a 300x300 lattice obtained by executing set.seed(5); create_OCN(300, 300, nOutlet = 4, outletSide = c("S", "N", "W", "E"), outletPos = c(1, 300, 149, 150), typeInitialState = "V", cellsize = 50)
.
Usage
data(OCN_300_4out)
Format
A river
object. See create_OCN
documentation for details.
Example of multiple-outlet OCN with periodic boundaries
Description
A network built on a 300x300 lattice obtained by executing set.seed(5); create_OCN(300, 300, nOutlet = 4, outletSide = c("S", "N", "W", "E"), outletPos = c(1, 300, 149, 150), typeInitialState = "V", periodicBoundaries = TRUE, cellsize = 50, coolingRate = 0.5, initialNoCoolingPhase = 0.1)
.
Usage
data(OCN_300_4out_PB_hot)
Format
A river
object. See create_OCN
documentation for details.
Example of small OCN
Description
A network built on a 4x4 lattice for illustrative purposes.
Usage
data(OCN_4)
Format
A river
object. See create_OCN
documentation for details.
Details
Despite its name, this network is not an OCN: indeed, it has been generated manually and not via create_OCN
.
Example of OCN with all perimetric pixels as outlets
Description
A network built on a 400x400 lattice obtained by executing set.seed(8); create_OCN(400, 400, nOutlet = "All", cellsize = 50)
.
Usage
data(OCN_400_Allout)
Format
A river
object. See create_OCN
documentation for details.
Construct asymmetric eigenvector maps (AEM) from an OCN
Description
Function that computes asymmetric eigenvector maps from an OCN. These can be used as spatial variables to assess spatial gradients in environmental or ecological data.
Usage
OCN_to_AEM(OCN, level = "AG", weight = NULL, resistance = "length", moranI = FALSE)
Arguments
OCN |
A |
level |
Aggregation level at which AEMs are to be calculated. It
must be equal to either |
weight |
Determines how and if weights should be used to compute the AEMs.
Defaults to |
resistance |
Identifies how resisitance (i.e., the variable negatively related to
the link weight) is calculated. Defaults to |
moranI |
Logical. Should Moran's I statistics be computed and random tests be performed via
|
Details
Possible character strings for weight
are:
"gravity"
w(r) = r_{max}/r
"exponential"
w(r) = \exp(-r/r_{max})
"linear"
w(r) = 1 - r/r_{max}
"parabolic"
w(r) = 1 - (r/r_{max})^2
where w
is the weight value for a given link, r
its resistance value and r_{max}
the maximum resistance value across all links.
Value
A list as produced by a call to aem
. If moranI = TRUE
, a krandtest
resulting from
the call to moran.randtest
is appended to the output list.
See Also
aem
, moran.randtest
Examples
OCN <- aggregate_OCN(landscape_OCN(OCN_20), thrA = 5)
res <- OCN_to_AEM(OCN) # unweighted AEMs
res$values # eigenvectors associates with the AEMs
plot(OCN, res$vectors[,1], drawNodes = TRUE,
colLevels = c(-max(abs(res$vectors[,1])), max(abs(res$vectors[,1])), 100),
colPalette = hcl.colors(100,"Blue-Red 2")) # plot first eigenvector
res_g <- OCN_to_AEM(OCN, weight = "gravity") # weighted AEMs based on gravity model
fn <- function(r) {1 - r^0.5}
res_f <- OCN_to_AEM(OCN, weight = fn) # weighted AEMs based on user-specified weight function
# compute Moran's I and perform permutation test to assess which eigenfunctions should be retained
res_g <- OCN_to_AEM(OCN, weight = "gravity", moranI = TRUE)
selectedAEM <- which(res_g$moranI$pvalue < 0.05)
# selected eigenfunctions are those with significantly positive spatial autocorrelation
# plot selected eigenfunctions
# (these could be e.g. used as spatial covariates in a species distribution model)
par(mfrow=c(3,4))
for (i in selectedAEM){
plot(OCN, res$vectors[,i], drawNodes = TRUE,
colLevels = c(-max(abs(res$vectors[,i])), max(abs(res$vectors[,i])), 100),
colPalette = hcl.colors(100,"Blue-Red 2"))
title(paste0("AEM",i))
}
Transform OCN into SSN object (disabled)
Description
In OCNet
v1.2.0, this function is disabled following the archiving
of the SSN
package from CRAN (due to the retirement of rgdal
).
A new OCN_to_SSN
function will be included in the next release of OCNet
.
Usage
OCN_to_SSN(OCN, ...)
Arguments
OCN |
A |
... |
Further arguments. |
Value
No output is produced.
Examples
OCN_to_SSN(OCN)
Transform OCN into igraph object
Description
Function that transforms an OCN into an igraph object.
Usage
OCN_to_igraph(OCN, level)
Arguments
OCN |
A |
level |
Aggregation level at which the OCN is converted into an igraph object. It
must be equal to either |
Value
An igraph
object.
Examples
# 1) transform a 20x20 OCN, at the AG level, into a graph object
OCN <- aggregate_OCN(landscape_OCN(OCN_20), thrA = 4)
g <- OCN_to_igraph(OCN, level = "AG")
plot(g, layout = matrix(c(OCN$AG$X,OCN$AG$Y), ncol = 2, nrow = OCN$AG$nNodes))
Aggregate an Optimal Channel Network
Description
Function that, given an OCN, builds the network at the river network (RN), aggregated (AG), subcatchment (SC), and catchment (CM) levels.
Usage
aggregate_OCN(OCN, thrA = 0.002 * OCN$FD$nNodes *
OCN$cellsize^2, streamOrderType = "Strahler", maxReachLength = Inf,
equalizeLengths = FALSE, breakpoints = NULL, displayUpdates = FALSE)
Arguments
OCN |
A |
thrA |
Threshold value on drainage area used to derive the aggregated network. If |
streamOrderType |
If |
maxReachLength |
Maximum reach length allowed (in planar units). If the path length between a channel head and the downstream confluence
is higher than |
equalizeLengths |
Logical. Only effective when |
breakpoints |
Indices of additional nodes at the RN level that should be also nodes at the AG level (beyond source, confluence, outlet nodes
and AG nodes determined via |
displayUpdates |
Logical. State if updates are printed on the console while |
Details
Note that each node (and the corresponding edge exiting from it, in the case of non-outlet nodes) at the AG level corresponds to
a subcatchment at the SC level that shares the same index: for instance, SC$toFD[i]
contains all elements of
AG$toFD[i]
(that is, the indices of pixels at FD level that constitute the edge departing from node i
are also part of subcatchment i
).
Value
A river
object that contains all objects contained in OCN
, in addition to the objects listed below.
New sublists RN
, AG
, SC
, containing variables at the corresponding aggregation levels, are created.
Refer to section 4.2 of the vignette for a more detailed explanation on values OCN$XX$toYY
, where XX
and YY
are two random aggregation levels.
FD$toRN |
Vector (of length |
FD$toSC |
Vector (of length |
RN$A |
Vector (of length |
RN$W |
Adjacency matrix ( |
RN$downNode |
Vector (of length |
RN$drainageDensity |
Drainage density of the river network, calculated as total length of the river network divided by area of the lattice. It is expressed in planar units^(-1). |
RN$leng |
Vector (of length |
RN$nNodes |
Number of nodes at the RN level. |
RN$nUpstream |
Vector (of length |
RN$outlet |
Vector (of length |
RN$Slope |
Vector (of length |
RN$toAG |
Vector (of length |
RN$toAGReach |
Vector (of length |
RN$toFD |
Vector (of length |
RN$toCM |
Vector (of length |
RN$upstream |
List (of length |
RN$X , RN$Y |
Vectors (of length |
RN$Z |
Vector (of length |
AG$A |
Vector (of length |
AG$AReach |
Vector (of length |
AG$W |
Adjacency matrix ( |
AG$downNode |
Vector (of length |
AG$leng |
Vector (of length |
AG$nNodes |
Number of nodes resulting from the aggregation process. |
AG$nUpstream |
Vector (of length |
AG$outlet |
Vector (of length |
AG$slope |
Vector (of length |
AG$streamOrder |
Vector (of length |
AG$upstream |
List (of length |
AG$toFD |
Vector of length |
AG$ReachToFD |
List (of length |
AG$toRN |
Vector of length |
AG$ReachToRN |
List (of length |
AG$toCM |
Vector (of length |
AG$X , AG$Y |
Vectors (of length |
AG$XReach , AG$YReach |
Vector (of length |
AG$Z |
Vector (of length |
AG$ZReach |
Vector (of length |
SC$ALocal |
Vector (of length |
SC$W |
Adjacency matrix ( |
SC$nNodes |
Number of subcatchments into which the lattice is partitioned. If |
SC$toFD |
List (of length |
SC$X , SC$Y |
Vectors (of length |
SC$Z |
Vector (of length |
Finally, thrA
is added to the river
object.
Examples
# 1a) aggregate a 20x20 OCN by imposing thrA = 4.
OCN <- aggregate_OCN(landscape_OCN(OCN_20), thrA = 4)
draw_thematic_OCN(OCN, drawNodes = TRUE)
# 1b) same as above, but identify all RN nodes as AG nodes
mrl <- 1.5*OCN_20$cellsize
OCN2 <- aggregate_OCN(landscape_OCN(OCN_20), thrA = 4, maxReachLength = mrl)
draw_thematic_OCN(OCN2, drawNodes = TRUE)
# 2) explore the effects of thrA, maxReachLength and equalizeLengths on a large OCN
OCN <- landscape_OCN(OCN_250_T) # it takes some seconds
OCN_a <- aggregate_OCN(OCN, thrA = 200) # it takes some seconds
OCN_b <- aggregate_OCN(OCN, thrA = 1000) # it takes some seconds
OCN_c <- aggregate_OCN(OCN, thrA = 1000, maxReachLength = 20) # it takes some seconds
OCN_d <- aggregate_OCN(OCN, thrA = 1000, maxReachLength = 20,
equalizeLengths = TRUE) # it takes some seconds
old.par <- par(no.readonly = TRUE)
par(mfrow = c(2,2))
draw_subcatchments_OCN(OCN_a)
points(OCN_a$AG$X, OCN_a$AG$Y, pch = 19, col = "#0044bb")
title(paste("No. AG nodes = ", as.character(OCN_a$AG$nNodes),
sep=""))
draw_subcatchments_OCN(OCN_b)
points(OCN_b$AG$X, OCN_b$AG$Y, pch = 19, col = "#0044bb")
title(paste("No. AG nodes = ", as.character(OCN_b$AG$nNodes),
sep=""))
draw_subcatchments_OCN(OCN_c)
points(OCN_c$AG$X, OCN_c$AG$Y, pch = 19, col = "#0044bb")
title(paste("No. AG nodes = ", as.character(OCN_c$AG$nNodes),
sep=""))
draw_subcatchments_OCN(OCN_d)
points(OCN_d$AG$X, OCN_d$AG$Y, pch = 19, col = "#0044bb")
title(paste("No. AG nodes = ", as.character(OCN_d$AG$nNodes),
sep=""))
par(old.par)
# note the difference between OCN_c and OCN_d at the bottom right corner of the lattice
# 3) use of breakpoints
OCN <- aggregate_OCN(landscape_OCN(OCN_20), thrA = 5)
draw_thematic_OCN(OCN, drawNodes=TRUE)
# add an AG node downstream of node 1 at AG level
new_node_RN <- OCN$RN$downNode[OCN$AG$toRN[1]]
OCN2 <- aggregate_OCN(landscape_OCN(OCN_20), thrA = 5, breakpoints = new_node_RN)
draw_thematic_OCN(OCN2, drawNodes = TRUE)
points(OCN$RN$X[new_node_RN], OCN$RN$Y[new_node_RN],
pch = 19, col = "red") # this node has been added
Perform OCN Search Algorithm on an Existing OCN
Description
Function that performs the OCN search algorithm on an existing OCN.
Usage
continue_OCN(OCN,nNewIter, coolingRate=NULL, initialNoCoolingPhase=0,
displayUpdates=1, showIntermediatePlots=FALSE, thrADraw=NULL,
easyDraw=NULL, nUpdates=50)
Arguments
OCN |
A |
nNewIter |
Number of iterations that the OCN search algorithm performs. |
coolingRate |
Parameter of the function used to describe the temperature of the simulated annealing algorithm. See |
initialNoCoolingPhase |
Parameter of the function used to describe the temperature of the simulated annealing algorithm. See |
nUpdates |
Number of updates given during the OCN search process (only effective if |
showIntermediatePlots |
If |
thrADraw |
Threshold drainage area value used to display the network (only effective when |
easyDraw |
Logical. If |
displayUpdates |
State if updates are printed on the console while the OCN search algorithm runs.
|
Value
A river
object analogous to the input OCN
. Note that, unlike in create_OCN
, OCN$coolingRate
and OCN$initialNoCoolingPhase
are now vectors (of length equal to the number of times continue_OCN
has been performed on the same OCN, plus one) that store the full sequence of coolingRate
, initialNoCoolingPhase
used to generate the OCN. Additionally, the vector OCN$nIterSequence
is provided, with entries equal to the number of iterations performed by each successive application of create_OCN
or continue_OCN
. It is OCN$nIter = sum(OCN$nIterSequence)
.
Examples
set.seed(1)
OCN_a <- create_OCN(20, 20, nIter = 10000)
set.seed(1)
OCN_b <- create_OCN(20, 20, nIter = 5000)
OCN_b <- continue_OCN(OCN_b, nNewIter = 5000)
old.par <- par(no.readonly = TRUE)
par(mfrow=c(1,2))
draw_simple_OCN(OCN_a)
draw_simple_OCN(OCN_b) # the two OCNs are equal
par(old.par)
Create an Optimal Channel Network
Description
Function that performs the OCN search algorithm on a rectangular lattice and creates OCN at the flow direction (FD) level.
Usage
create_OCN(dimX, dimY, nOutlet = 1, outletSide = "S",
outletPos = round(dimX/3), periodicBoundaries = FALSE,
typeInitialState = NULL, flowDirStart = NULL, expEnergy = 0.5,
cellsize = 1, xllcorner = 0.5 * cellsize, yllcorner = 0.5 *
cellsize, nIter = 40 * dimX * dimY, nUpdates = 50,
initialNoCoolingPhase = 0, coolingRate = 1,
showIntermediatePlots = FALSE, thrADraw = 0.002 * dimX * dimY *
cellsize^2, easyDraw = NULL, saveEnergy = FALSE, saveExitFlag = FALSE,
saveN8 = FALSE, saveN4 = FALSE, displayUpdates = 1)
Arguments
dimX |
Longitudinal dimension of the lattice (in number of pixels). |
dimY |
Latitudinal dimension of the lattice (in number of pixels). |
nOutlet |
Number of outlets. If |
outletSide |
Side of the lattice where the outlet(s) is/are placed.
It is a vector of characters, whose allowed values are |
outletPos |
Vector of positions of outlets within the sides specified by |
periodicBoundaries |
If |
typeInitialState |
Configuration of the initial state of the network. Possible values: |
flowDirStart |
Matrix (
|
expEnergy |
Exponent of the functional |
cellsize |
Size of a pixel in planar units. |
xllcorner |
Longitudinal coordinate of the lower-left pixel. |
yllcorner |
Latitudinal coordinate of the lower-left pixel. |
nIter |
Number of iterations for the OCN search algorithm. |
nUpdates |
Number of updates given during the OCN search process (only effective if |
initialNoCoolingPhase , coolingRate |
Parameters of the function used to describe the temperature of the simulated annealing algorithm. See details. |
showIntermediatePlots |
If |
thrADraw |
Threshold drainage area value used to display the network (only effective when |
easyDraw |
Logical. If |
saveEnergy |
If |
saveExitFlag |
If |
saveN8 |
If |
saveN4 |
If |
displayUpdates |
State if updates are printed on the console while the OCN search algorithm runs.
|
Details
Simulated annealing temperature. The function that expresses the temperature of the simulated annealing process is as follows:
- if
i <= initialNoCoolingPhase*nIter
: Temperature[i] = Energy[1]
- if
initialNoCoolingPhase*nIter < i <= nIter
: Temperature[i] = Energy[1]*(-coolingRate*(i - InitialNocoolingPhase*nIter)/nNodes)
where i
is the index of the current iteration and Energy[1] = sum(A^expEnergy)
, with A
denoting
the vector of drainage areas corresponding to the initial state of the network. According to the simulated annealing
principle, a new network configuration obtained at iteration i
is accepted with probability equal to
exp((Energy[i] - Energy[i-1])/Temperature[i])
if Energy[i] < Energy[i-1]
.
To ensure convergence, it is recommended to use coolingRate
values between 0.5 and 10 and initialNoCoolingPhase <= 0.3
.
Low coolingRate
and high initialNoCoolingPhase
values cause the network configuration to depart more significantly from the initial state.
If coolingRate < 0.5
and initialNoCoolingPhase > 0.1
are used, it is suggested to increase nIter
with respect to the default value in order to guarantee convergence.
Initial network state.
If nOutlet > 1
, the initial state is applied with regards to the outlet located at outletSide[1]
, outletPos[1]
.
Subsequently, for each of the other outlets, the drainage pattern is altered within a region of maximum size 0.5*dimX
by 0.25*dimY
for outlets located at the eastern and western borders of the lattice,
and 0.25*dimX
by 0.5*dimY
for outlets located at the southern and northern borders of the lattice. The midpoint of the long size of the regions coincides with the outlet at stake.
Within these regions, an "I"
-type drainage pattern is produced if typeInitialState = "I"
or "T"
; a "V"
-type drainage pattern is produced if typeInitialState = "V"
;
no action is performed if typeInitialState = "H"
. Note that typeInitialState = "H"
is the recommended choice only for large nOutlet
.
Suggestions for creating "fancy" OCNs.
In order to generate networks spanning a realistic, non-rectangular catchment domain (in the "real-shape" view provided by draw_contour_OCN
), it is convenient
to use the option periodicBoundaries = TRUE
and impose at least a couple of diagonally adjacent outlets on two opposite sides, for example nOutlet = 2
, outletSide = c("S", "N")
, outletPos = c(1, 2)
.
See also OCN_300_4out_PB_hot
. Note that, because the OCN search algorithm is a stochastic process, the successful generation of a "fancy" OCN is not guaranteed: indeed, it is possible that the final outcome is a
network where most (if not all) pixels drain towards one of the two outlets, and hence such outlet is surrounded (in the "real-shape" view) by the pixels that it drains. Note that, in order to hinder such occurrence, the two pixels along the lattice perimeter next to each outlet are bound to drain towards such outlet.
In order to create a network spanning a "pear-shaped" catchment (namely where the width of the area spanned in the direction orthogonal to the main stem diminishes downstream, until it coincides with the river width at the outlet),
it is convenient to use the option nOutlet = "All"
(here the value of periodicBoundaries
is irrelevant) and then pick a single catchment (presumably one with rather large catchment area, see value OCN$CM$A
generated by landscape_OCN
) among the many generated. Note that it is not possible to predict the area spanned by such catchment a priori. To obtain a catchment whose size is rather large compared to the size of the lattice where the
OCN was generated, it is convenient to set typeInitialState = "I"
and then pick the catchment with largest area (landscape_OCN
must be run).
The default temperature schedule for the simulated annealing process is generally adequate for generating an OCN that does not resemble the initial network state if the size of the lattice is not too large (say, until dimX*dimY <= 40000
). When dimX*dimY > 40000
, it might be convenient to make use of a "warmer" temperature schedule (for example, by setting coolingRate = 0.5
and initialNoCoolingPhase = 0.1
; see also the package vignette) and/or increase nIter
with respect to its default value. Note that these suggestions only pertain to the aesthetics of the final OCN; the default temperature schedule and nIter
are calibrated to ensure convergence of the OCN (i.e. achievement of a local minimum of Energy
, save for a reasonable threshold) also for lattices larger than dimX*dimY = 40000
.
Value
A river
object. It is de facto a list, whose objects are listed below. Variables that define the network at the FD level are wrapped in the sublist FD
.
Adjacency matrices describing 4- or 8- nearest-neighbours connectivity among pixels are contained in lists N4
and N8
, respectively.
FD$A |
Vector (of length |
FD$W |
Adjacency matrix ( |
FD$downNode |
Vector (of length |
FD$X (FD$Y) |
Vector (of length |
FD$nNodes |
Number of nodes at FD level (equal to |
FD$outlet |
Vector (of length |
FD$perm |
Vector (of length |
energyInit |
Initial energy value. |
energy |
Vector (of length |
exitFlag |
Vector (of length
|
N4$W |
Adjacency matrix ( |
N8$W |
Adjacency matrix ( |
Finally, dimX
, dimY
, cellsize
, nOutlet
, periodicBoundaries
, expEnergy
,
coolingRate
, typeInitialState
, nIter
, xllcorner
, yllcorner
are passed to the river
object as they were included in the input
(except nOutlet = "All"
which is converted to 2*(dimX + dimY - 2))
.
Examples
# 1) creates and displays a single outlet 20x20 OCN with default options
set.seed(1)
OCN_a <- create_OCN(20, 20)
draw_simple_OCN(OCN_a)
# 2) creates and displays a 2-outlet OCNs with manually set outlet location,
# and a 4-outlet OCNs with random outlet position.
set.seed(1)
old.par <- par(no.readonly = TRUE)
par(mfrow=c(1,2))
OCN_b1 <- create_OCN(30, 30, nOutlet = 2, outletSide = c("N", "W"), outletPos = c(15, 12))
OCN_b2 <- create_OCN(30, 30, nOutlet = 4)
draw_simple_OCN(OCN_b1)
title("2-outlet OCN")
draw_simple_OCN(OCN_b2)
title("4-outlet OCN")
par(old.par)
## Not run:
# 3) generate 3 single-outlet OCNs on the same (100x100) domain starting from different
# initial states, and show 20 intermediate plots and console updates.
set.seed(1)
OCN_V <- create_OCN(100, 100, typeInitialState = "V", showIntermediatePlots = TRUE,
nUpdates = 20, displayUpdates = 2)
OCN_T <- create_OCN(100, 100, typeInitialState = "T", showIntermediatePlots = TRUE,
nUpdates = 20, displayUpdates = 2)
OCN_I <- create_OCN(100, 100, typeInitialState = "I", showIntermediatePlots = TRUE,
nUpdates = 20, displayUpdates = 2)
## End(Not run)
## Not run:
# 4) generate a 2-outlet OCN and show intermediate plots. Note that different colors are used
# to identify the two networks (all pixels are colored because thrADraw = 0).
set.seed(1)
OCN <- create_OCN(150, 70, nOutlet = 2, outletPos = c(1, 150), outletSide = c("S", "N"),
typeInitialState = "V", periodicBoundaries = TRUE,
showIntermediatePlots = TRUE, thrADraw = 0)
# The resulting networks have an irregular contour, and their outlets are located on the contour:
draw_contour_OCN(landscape_OCN(OCN))
## End(Not run)
Create an Optimal Channel Network on a general contour
Description
Function that performs the OCN search algorithm on a general contour and creates OCN at the flow direction (FD) level.
Usage
create_general_contour_OCN(flowDirStart, expEnergy = 0.5,
cellsize = 1, xllcorner = 0.5 * cellsize, yllcorner = 0.5 *
cellsize, nIter = NULL, nUpdates = 50,
initialNoCoolingPhase = 0, coolingRate = 1,
showIntermediatePlots = FALSE, thrADraw = NULL,
easyDraw = NULL, saveEnergy = FALSE, saveExitFlag = FALSE,
displayUpdates = 1)
Arguments
flowDirStart |
Matrix with custom initial flow directions. Cells outside the catchment must have value equal to
Note that |
expEnergy |
Exponent of the functional |
cellsize |
Size of a pixel in planar units. |
xllcorner |
Longitudinal (column-wise) coordinate of the lower-left pixel of |
yllcorner |
Latitudinal (row-wise) coordinate of the lower-left pixel of |
nIter |
Number of iterations for the OCN search algorithm. Default is 40 times the number of non- |
nUpdates |
Number of updates given during the OCN search process (only effective if |
initialNoCoolingPhase , coolingRate |
Parameters of the function used to describe the temperature of the simulated annealing algorithm. See details. |
showIntermediatePlots |
If |
thrADraw |
Threshold drainage area value used to display the network (only effective when |
easyDraw |
Logical. If |
saveEnergy |
If |
saveExitFlag |
If |
displayUpdates |
State if updates are printed on the console while the OCN search algorithm runs.
|
Value
A river
object as in create_OCN
, to which the reader is referred for detailed documentation.
However, note that in this case dimX
and dimY
are equal to the number of columns and rows of flowDirStart
, respectively,
while nNodes
is the number of non-NaN
pixels in flowDirStart
. Hence, nNodes
is generally lower than
dimX*dimY
. The additionally exported vector FD$toDEM
identifies the indices of the pixels of the landscape/flow direction matrix
that belong to the catchment (i.e., they are not NaN
).
Examples
OCN1 <- create_general_contour_OCN(flowDir, nIter=0) # initial flow directions
OCN2 <- create_general_contour_OCN(flowDir) # perform OCN algorithm
draw_simple_OCN(OCN1)
draw_simple_OCN(OCN2)
Create Peano network
Description
Function that creates Peano networks on a square lattice.
Usage
create_peano(nIterPeano, outletPos = "NE", xllcorner = 1,
yllcorner = 1, cellsize = 1)
Arguments
nIterPeano |
Number of iteration of the Peano scheme. The resulting network will span a domain
of size |
outletPos |
Corner where the outlet is located, expressed as intercardinal direction.
Possible values are |
xllcorner |
X coordinate of the lower-left pixel (expressed in planar units). |
yllcorner |
Y coordinate of the lower-left pixel (expressed in planar units). |
cellsize |
Size of a pixel (expressed in planar units). |
Value
A river
object that contains the same objects as those produced by create_OCN
.
As such, it can be used as input for all other complementary functions of the package.
Examples
# 1) create a peano network in a 32x32 square,
# use landscape_OCN, aggregate_OCN functions,
# and display subcatchment map and map of drainage area
peano <- create_peano(4)
peano <- aggregate_OCN(landscape_OCN(peano), thrA = 4)
old.par <- par(no.readonly = TRUE)
par(mfrow=c(1,3))
draw_simple_OCN(peano)
title("Peano network")
draw_subcatchments_OCN(peano)
title("Subcatchments")
draw_thematic_OCN(peano$RN$A, peano)
title("Drainage area at RN level")
par(old.par)
Draw Optimal Channel Network with catchment contours
Description
Function that plots real-shaped OCN and catchment contours.
Usage
draw_contour_OCN(OCN, thrADraw = 0.002 * OCN$FD$nNodes *
OCN$cellsize^2, exactDraw = TRUE, drawContours = TRUE, colPalRiver = NULL,
colPalCont = "#000000", drawOutlets = 0, pch = 15, colPalOut = "#000000",
min_lwd = 0.5, max_lwd = 5, contour_lwd = 2, add = FALSE)
Arguments
OCN |
A |
thrADraw |
Threshold drainage area value used to display the network. |
exactDraw |
If |
drawContours |
If |
colPalRiver |
Color palette used to plot the river network(s). Default is a rearranged version of theme |
colPalCont |
Color palette used to plot the catchment contour(s). Details as in |
drawOutlets |
If equal to |
pch |
Shape of the outlet points (if |
colPalOut |
Color palette used to plot the outlet points (if |
min_lwd , max_lwd |
Minimum and maximum values of line width used to display the OCN (actual line width is proportional to the square root of drainage area). |
contour_lwd |
Line width value for catchment contour plotting. |
add |
Logical. If |
Details
For not too large networks (i.e. if OCN$FD$nNodes <= 40000
, corresponding to a 200x200 lattice),
pixels whose drainage area OCN$FD$A
is lower than thrADraw
are drawn with a light grey stroke.
If OCN$FD$nNodes > 40000
, in order to speed up the execution of this function, only the network constituted
by pixels such that OCN$FD$A > thrADraw
is drawn.
Value
No output is returned.
Examples
# 1) draw contour of a 20x20 single-outlet OCN
# (for single-outlet OCNs without periodic boundaries, the output
# of draw_contour_OCN is very similar to that of draw_simple_OCN)
draw_contour_OCN(landscape_OCN(OCN_20), thrADraw = 4)
## Not run:
# 2a) plot real shape of multiple-outlet OCN created with periodic boundaries
# add outlets on top of the rivers
OCN <- landscape_OCN(OCN_300_4out_PB_hot, displayUpdates = 2) # it takes around one minute
draw_contour_OCN(OCN, drawOutlets = 2)
# 2b) same as before, but use same color palette for rivers and contours
draw_contour_OCN(OCN, colPalCont = 0)
# 2c) draw contours of catchments obtained from an OCN with nOutlet = "All"
OCN <- landscape_OCN(OCN_400_Allout, displayUpdates = 2) # it takes some minutes
draw_contour_OCN(OCN)
# 2d) same as above, but do not plot contours, and plot outlets
# with same color palette as rivers
draw_contour_OCN(OCN, drawContours = FALSE, drawOutlets = TRUE,
colPalOut = 0)
## End(Not run)
Plot 2D map of elevation generated by an OCN
Description
Function that plots the 2D elevation map generated by an OCN.
Usage
draw_elev2D_OCN(OCN, colPalette = terrain.colors(1000, alpha = 1),
addLegend = TRUE, drawRiver = FALSE, thrADraw = 0.002*OCN$FD$nNodes*OCN$cellsize^2,
riverColor = "#00BFFF", min_lwd = 0.5, max_lwd = 5, args_imagePlot = list())
Arguments
OCN |
A |
colPalette |
Color palette used for the plot. |
addLegend |
Logical. If |
drawRiver |
Logical. If |
thrADraw |
Threshold drainage area value used to display the network. |
riverColor |
Color used to display the OCN (only effective if |
min_lwd , max_lwd |
Minimum and maximum values of line width used to display the OCN (actual line width is proportional to the square root of drainage area). |
args_imagePlot |
List of arguments passed to |
Value
No output is returned.
Examples
# 1) draw 2D map of a 20x20 OCN with default settings
draw_elev2D_OCN(landscape_OCN(OCN_20))
Plot 3D map of elevation generated by an OCN
Description
Function that plots the 3D elevation map generated by an OCN.
Usage
draw_elev3D_OCN(OCN, coarseGrain = c(1,1), colPalette = terrain.colors(1000, alpha = 1),
addColorbar = TRUE, drawRiver = TRUE, thrADraw = 0.002 *
OCN$FD$nNodes * OCN$cellsize^2, riverColor = "#00CCFF",
theta = -20, phi = 30, expand = 0.05, shade = 0.5, min_lwd = 0.5, max_lwd = 5,
args_imagePlot = list())
Arguments
OCN |
A |
coarseGrain |
2x1 vector (only effective if |
colPalette |
Color palette used for the plot. |
addColorbar |
If |
drawRiver |
If |
thrADraw |
Threshold drainage area value used to display the network. |
riverColor |
Color used to plot the river. |
theta , phi , expand , shade |
Additional parameters passed to the perspective plotting
function |
min_lwd , max_lwd |
Minimum and maximum values of line width used to display the OCN (actual line width is proportional to the square root of drainage area). |
args_imagePlot |
Only effective if |
Value
No output is returned.
Examples
# draw 3D representation of a 20x20 OCN with default options
draw_elev3D_OCN(landscape_OCN(OCN_20))
## Not run:
# 1a) draw the 3D representation of the OCN (without displaying the river
# and the colorbar) and enhance the aspect ratio of Z coordinates
# with respect to the default value (the final result will be ugly):
OCN <- landscape_OCN(OCN_400_Allout, displayUpdates = 2) # this takes some minutes
draw_elev3D_OCN(OCN, expand = 0.2, addColorbar = FALSE, drawRiver = FALSE)
# 1b) same as above, but operate coarse graining and modify shade for better aesthetics:
draw_elev3D_OCN(OCN, coarseGrain = c(5,5), expand = 0.2,
shade = 0.25, addColorbar = FALSE, drawRiver = FALSE)
## End(Not run)
Plot 3D map of elevation generated by an OCN via rgl rendering
Description
Function that plots the 3D elevation map generated by an OCN.
Usage
draw_elev3Drgl_OCN(OCN, coarseGrain = c(1, 1), chooseCM = FALSE,
addColorbar = FALSE, drawRiver = FALSE, thrADraw = 0.002 *
OCN$FD$nNodes* OCN$cellsize^2, riverColor = "#00CCFF",
min_lwd = 1, max_lwd = 8, ...)
Arguments
OCN |
A |
coarseGrain |
2x1 vector (only effective if |
chooseCM |
Index of catchment to display (only effective if |
addColorbar |
If |
drawRiver |
If |
thrADraw |
Threshold drainage area value used to display the network. |
riverColor |
Color used to plot the river. |
min_lwd , max_lwd |
Minimum and maximum values of line width used to display the OCN (actual line width is proportional to the square root of drainage area). |
... |
Further parameters passed to function |
Details
This function makes use of the rgl
rendering system. To export the figure in raster format, use rgl.snapshot
.
To export in vectorial format, use rgl.postscript
(but note that this might produce rendering issues, see rgl
for details).
The function will attempt at drawing a contour of the plotted entity (i.e. the lattice or a catchment, depending on chooseCM
) at null elevation, and drawing polygons connecting this contour with the lattice/catchment contour at the real elevation. If chooseCM != FALSE
, this might result in errors owing to failure of polygon3d
in triangulating the polygons.
Value
No output is returned.
Examples
## Not run:
draw_elev3Drgl_OCN(landscape_OCN(OCN_20))
## End(Not run)
## Not run:
# 1a) draw the 3D representation of a single catchment within an OCN
# generated with nOutlet = "All" and add draw the river on top of it
OCN <- landscape_OCN(OCN_400_Allout, displayUpdates = 2) # this takes some minutes
draw_elev3Drgl_OCN(OCN, chooseCM = 983, drawRiver = TRUE)
# 1b) draw the 3D representation of the largest catchment within the OCN
# (here polygon3d may fail at plotting the polygon at zero elevation)
draw_elev3Drgl_OCN(OCN, chooseCM = TRUE)
# 1c) draw the 3D representation of the whole OCN
# and enhance the aspect ratio of Z coordinates
# with respect to the default value (the final result will be ugly):
draw_elev3Drgl_OCN(OCN, aspect = c(1, 1, 0.2))
# 1d) same as above, but operate coarse graining for better aesthetics:
draw_elev3Drgl_OCN(OCN, coarseGrain = c(5,5), aspect = c(1, 1, 0.2))
# 2) draw the 3D representation of a single catchment of an OCN generated
# with periodicBoundaries = TRUE
# (note that the real shape of the catchment is drawn)
OCN <- landscape_OCN(OCN_300_4out_PB, displayUpdates = 2) # this takes some minutes
draw_elev3Drgl_OCN(OCN, chooseCM = TRUE)
## End(Not run)
Draw an Optimal Channel Network
Description
Function that plots the non-aggregated OCN as calculated by create_OCN
.
Usage
draw_simple_OCN(OCN, thrADraw = 0.002 * OCN$FD$nNodes *
OCN$cellsize^2, riverColor = "#0066FF", easyDraw = NULL,
min_lwd = 0.5, max_lwd = 5, add = FALSE)
Arguments
OCN |
A |
thrADraw |
Threshold drainage area value used to display the network. |
riverColor |
Color used to plot the river. |
easyDraw |
Logical. If |
min_lwd , max_lwd |
Minimum and maximum values of line width used to display the OCN (actual line width is proportional to the square root of drainage area). |
add |
Logical. If |
Value
No output is returned.
Examples
# 1a) draw OCN with default settings
draw_simple_OCN(OCN_250_T)
# 1b) same as above, but with decreased thrADraw
draw_simple_OCN(OCN_250_T, thrADraw = 0.001 * OCN_250_T$dimX * OCN_250_T$dimY)
# 1c) same as the first example, but include the portion of network
# with drainage area lower than thrADraw
draw_simple_OCN(OCN_250_T, easyDraw = FALSE) # this will take some seconds
Draw subcatchment map from an Optimal Channel Network
Description
Function that draws a map of subcatchments generated by the aggregation process on the OCN. If theme
is NULL
, colormap is such that neighbouring subcatchments have distinguished colors. If theme
is specified, colors reflect the values of theme
across subcatchments, in analogy with draw_thematic_OCN
.
Usage
draw_subcatchments_OCN(OCN, theme = NULL, drawRiver = TRUE,
colPalette = NULL, colLevels = NULL, riverColor = NULL, addLegend = NULL,
min_lwd = 0.5, max_lwd = 5, add = FALSE, args_imagePlot = list(), ...)
Arguments
OCN |
A |
theme |
Vector (of length |
drawRiver |
Logical. If |
colPalette |
Color palette used. |
colLevels |
Number of colors in the palette (only effective if |
riverColor |
Color used to display the OCN (only effective if |
addLegend |
Logical. State if a legend should be displayed (only active if |
min_lwd , max_lwd |
Minimum and maximum values of line width used to display the OCN (actual line width is proportional to the square root of drainage area). |
add |
Logical. If |
args_imagePlot |
Only effective if |
... |
Further arguments to be passed to |
Value
No output is returned.
See Also
Examples
# 1a) aggregate a 20x20 OCN , use thrA = 5 pixels
# and draw subcatchments with default color palette
OCN <- aggregate_OCN(landscape_OCN(OCN_20), thrA = 5)
draw_subcatchments_OCN(OCN, drawRiver = TRUE)
# 1b) same as above, but define color palette with a function
draw_subcatchments_OCN(OCN, drawRiver = TRUE, colPalette = rainbow)
# 1c) same as above, but define color palette with a vector of colors
draw_subcatchments_OCN(OCN, drawRiver = TRUE, colPalette = hcl.colors(6, "Dark 3"))
# 2) Display theme at subcatchment level
draw_subcatchments_OCN(OCN, theme = OCN$AG$A)
Draw thematic map on an Optimal Channel Network
Description
Function that draws OCNs with color of RN or AG nodes depending on an arbitrary theme.
Usage
draw_thematic_OCN(OCN,theme=NA*numeric(OCN$AG$nNodes),
chooseAggregation = NULL,
discreteLevels = FALSE,
colLevels = NULL, cutoff = FALSE,
colPalette = colorRampPalette(c("yellow","red","black")),
exactDraw = FALSE, chooseCM = FALSE, drawNodes = FALSE,
nodeType = "upstream", nanColor = "#00BFFF",
riverColor = "#00BFFF", backgroundColor = "#999999",
addLegend = TRUE, min_lwd = 0.5, max_lwd = 5,
add = FALSE, args_imagePlot = list(), args_legend = list(),
...)
Arguments
OCN |
A |
theme |
Vector (of length |
chooseAggregation |
Only effective if |
discreteLevels |
Logical. If |
colLevels |
Number of colors in the palette. If |
cutoff |
Logical. If |
colPalette |
Color palette used to display theme values. |
chooseCM |
Index of catchment to display (only effective if |
exactDraw |
Logical. If |
drawNodes |
Logical. If |
nodeType |
Only effective if |
nanColor |
Color attributed to RN or AG nodes whose theme value is |
riverColor |
Only effective if |
backgroundColor |
Color used in the background of the figure. It can be either a single value, or a vector with number of components
equal to |
addLegend |
Logical. If |
min_lwd , max_lwd |
Minimum and maximum values of line width used to display the OCN (actual line width is proportional to the square root of drainage area). |
add |
Logical. If |
args_imagePlot |
Only effective if |
args_legend |
Only effective if |
... |
Further arguments to be passed to |
Details
This function can be used to show how a certain spatial field varies along the river network.
Default plot options. By default, it is set asp = 1
, xlab = ""
, ylab = ""
. If at least one between xlim
and ylim
is specified by the user, the default for axes
is TRUE
, and is FALSE
if not. Specifying xlim
and ylim
helps zoom into a portion of the river network; however, due to the default asp = 1
, the displayed region might be larger than what is expected if the ranges of xlim
and ylim
are different. To avoid this, set asp = NA
(at the cost of producing a deformed river network).
Adding scale bar and north arrow. Scale bar and north arrow can be added via terra
's functions sbar
and north
, respectively. However, note that arguments d
and xy
must be specified by the user (because no rast
object is plotted). See example 5.
Value
No output is returned.
Examples
# 1a) Six different ways to display contributing area at the AG level
OCN <- aggregate_OCN(landscape_OCN(OCN_20), thrA = 4)
old.par <- par(no.readonly = TRUE)
par(mfrow=c(2,3), oma = c(0, 0, 3, 0))
draw_thematic_OCN(OCN$AG$A, OCN, colPalette = hcl.colors)
title("Continuous levels \n Colors on edges")
draw_thematic_OCN(OCN$AG$A, OCN, discreteLevels = TRUE,
colPalette = hcl.colors)
title("Discrete, unique levels \n Colors on edges")
draw_thematic_OCN(OCN$AG$A, OCN, discreteLevels = TRUE,
colLevels = c(1, 10, 50, 100, 500),
colPalette = hcl.colors)
title("Discrete, user-defined levels \n Colors on edges")
draw_thematic_OCN(OCN$AG$A, OCN, drawNodes = TRUE,
colPalette = hcl.colors)
title("Continuous levels \n Colors on edges")
draw_thematic_OCN(OCN$AG$A, OCN, discreteLevels = TRUE,
drawNodes = TRUE, colPalette = hcl.colors)
title("Discrete, unique levels \n Colors on nodes")
draw_thematic_OCN(OCN$AG$A, OCN, discreteLevels = TRUE,
drawNodes = TRUE, colLevels = c(1, 10, 50, 100, 500),
colPalette = hcl.colors)
title("Discrete, user-defined levels \n Colors on nodes")
mtext("Six different ways to display contributing area [no. pixels]", outer = TRUE, cex = 1.5)
par(old.par)
# 1b) Same as above, but use different colLevels, cutoff combinations
# with DiscreteLevels = FALSE
old.par <- par(no.readonly = TRUE)
par(mfrow=c(1,2))
draw_thematic_OCN(OCN$AG$A, OCN, drawNodes = TRUE,
colLevels = c(0, 200, 1000), colPalette = hcl.colors)
title("All nodes with A > 200 pixels \n are displayed in yellow")
draw_thematic_OCN(OCN$AG$A, OCN, drawNodes = TRUE,
nanColor = "#00000000", colLevels = c(0, 200, 1000),
cutoff = TRUE, colPalette = hcl.colors)
title("All nodes with A > 200 pixels \n are treated as NaN")
par(old.par)
## Not run:
# 2) Display distance to outlet (at the RN level) along the main stem
# of an OCN
OCN <- aggregate_OCN(landscape_OCN(OCN_250_T)) # this takes some seconds
OCN <- paths_OCN(OCN, includePaths = TRUE) # this takes some seconds
distanceToOutlet <- OCN$RN$downstreamPathLength[,OCN$RN$outlet]
farthestNode <- which(distanceToOutlet == max(distanceToOutlet))
mainStem <- OCN$RN$downstreamPath[[farthestNode]][[OCN$RN$outlet]]
theme <- rep(NaN, OCN$RN$nNodes)
theme[mainStem] <- distanceToOutlet[mainStem]
draw_thematic_OCN(theme, OCN)
title("Distance to outlet along the main stem [pixel units]")
## End(Not run)
# 3) Show an OCN without a theme
OCN <- aggregate_OCN(landscape_OCN(OCN_20), thrA = 4)
draw_thematic_OCN(OCN)
draw_thematic_OCN(OCN, xlim=c(3,8), ylim=c(0,5)) # zoom closer at the outlet
# 4) Adjust legend location
draw_thematic_OCN(OCN, OCN$AG$A,
args_imagePlot = list(smallplot = c(0.1, 0.11, 0.1, 0.3)))
draw_thematic_OCN(OCN, OCN$AG$streamOrder,
discreteLevels = TRUE, args_legend = list(x = -2, y = 1))
# 5) add thematic OCN on top of map and show scale bar and north arrow
draw_elev2D_OCN(OCN)
draw_thematic_OCN(OCN, OCN$AG$slope, backgroundColor = NULL,
add = TRUE, colPalette = hcl.colors(1000, "Grays", rev = TRUE),
args_imagePlot = list(smallplot=c(0.05,0.07,0.1,0.9)))
# now add scale bar and north arrow
library(terra)
# sbar() # this would throw an error
# north()# this would throw an error
sbar(d=1, xy=c(min(OCN$FD$X), min(OCN$FD$Y)-1)) # this works
north(d=1, xy=c(max(OCN$FD$X)+1, max(OCN$FD$Y))) # this works
Find relationship between number of nodes and threshold area in an OCN
Description
Function that calculates relationship between threshold area and number of nodes at RN and AG level for a given OCN.
It can be used prior to application of aggregate_OCN
in order to derive the drainage area threshold
that corresponds to the desired number of nodes of the aggregated network.
It is intended for use with single outlet OCNs, although its use with multiple outlet OCNs is allowed (provided that max(thrValues) <= min(OCN$CM$A)
).
Usage
find_area_threshold_OCN(OCN, thrValues = seq(OCN$cellsize^2,
min(OCN$CM$A), OCN$cellsize^2), maxReachLength = Inf,
streamOrderType = "Strahler", displayUpdates = 0)
Arguments
OCN |
A |
thrValues |
Vector of values of threshold drainage area (in squared planar units) for which the respective number of nodes at the RN and AG levels are computed.
Note that it must be |
maxReachLength |
Maximum reach length allowed (in planar units). If the path length between a channel head and the downstream confluence
is higher than |
streamOrderType |
If |
displayUpdates |
If |
Value
A list whose objects are listed below.
thrValues |
Copy of the input vector with the same name. |
nNodesRN |
Vector (of the same length as |
nNodesAG |
Vector (of the same length as |
drainageDensity |
Vector (of the same length as |
streamOrder |
Vector (of the same length as |
Examples
# 1) derive relationship between threshold area and number of nodes
OCN <- landscape_OCN(OCN_20)
thr <- find_area_threshold_OCN(OCN)
# log-log plot of number of nodes at the AG level versus
# relative threshold area (as fraction of total drainage area)
old.par <- par(no.readonly = TRUE)
par(mai = c(1,1,1,1))
plot(thr$thrValues[thr$nNodesAG > 0]/OCN$CM$A,
thr$nNodesAG[thr$nNodesAG > 0], log = "xy",
xlab = "Relative area threshold", ylab = "Number of AG nodes")
par(old.par)
Example of initial flow direction matrix to be used as input in create_general_contour_OCN
.
Description
An arbitrary initial flow direction matrix.
Usage
data(flowDir)
Format
A matrix. See create_general_contour_OCN
documentation for details.
Generate 3D landscape from an Optimal Channel Network
Description
Function that calculates the elevation field generated by the OCN and the partition of the domain into different catchments.
Usage
landscape_OCN(OCN, slope0 = 1, zMin = 0, optimizeDZ = FALSE,
optimMethod = "BFGS", optimControl = list(maxit = 100 *
length(OCN$FD$outlet), trace = 1), displayUpdates = 0)
Arguments
OCN |
A |
slope0 |
slope of the outlet pixel (in elevation units/planar units). |
zMin |
Elevation of the lowest pixel (in elevation units). |
optimizeDZ |
If |
optimMethod |
Optimization method used by function |
optimControl |
List of control parameters used by function |
displayUpdates |
State if updates are printed on the console while
Note that the display of updates during optimization of elevations (when |
Details
The function features an algorithm (which can be activated via the optional input optimizeDZ
) that, given the network
configuration and a slope0
value, finds the elevation of OCN$nOutlet - 1
outlets relative to the elevation of the first
outlet in vectors outletSide
, outletPos
such that the sum of the absolute differences elevation of neighboring pixels
belonging to different catchments is minimized. Such objective function is minimized by means of function optim
.
The absolute elevation of the outlet pixels (and, consequently, of the whole lattice) is finally attributed by imposing
OCN$FD$Z >= zMin
. Note that, due to the high dimensionality of the problem, convergence of the
optimization algorithm is not guaranteed for large OCN$nOutlet
(say, OCN$nOutlet > 10
).
Value
A river
object that contains all objects contained in OCN
, in addition to the objects listed below.
A new sublist CM
, containing variables at the catchment aggregation levels, is created.
FD$slope |
Vector (of length |
FD$leng |
Vector (of length |
FD$toCM |
Vector (of length |
FD$XDraw |
When |
FD$YDraw |
When |
FD$Z |
Vector (of length |
CM$A |
Vector (of length |
CM$W |
Adjacency matrix ( |
CM$XContour (CM$Y_contour) |
List with number of objects equal to |
CM$XContourDraw (CM$YContourDraw) |
List with number of objects equal to |
OptList |
List of output parameters produced by the optimization function |
Finally, slope0
and zMin
are passed to the river
as they were included in the input.
Examples
# 1) draw 2D elevation map of a 20x20 OCN with default options
OCN2 <- landscape_OCN(OCN_20)
## Not run:
# 2) generate a 100x50 OCN; assume that the pixel resolution is 200 m
# (the total catchment area is 20 km2)
set.seed(1)
OCN <- create_OCN(100, 50, cellsize = 200,
displayUpdates = 0) # this takes about 40 s
# use landscape_OCN to derive the 3D landscape subsumed by the OCN
# by assuming that the elevation and slope at the outlet are 200 m
# and 0.0075, respectively
OCN <- landscape_OCN(OCN, zMin = 200, slope0 = 0.0075)
# draw 2D and 3D representations of the landscape
draw_elev2D_OCN(OCN)
draw_elev3D_OCN(OCN)
draw_elev3Drgl_OCN(OCN)
## End(Not run)
## Not run:
# 3) generate a 100x50 OCN with 4 outlets
set.seed(1)
OCN <- create_OCN(100, 50, cellsize = 200,
nOutlet = 4, displayUpdates = 0) # this takes about 40 s
# use landscape_OCN and optimize elevation of outlets
OCN <- landscape_OCN(OCN, slope0 = 0.0075,
optimizeDZ = TRUE)
# display elevation of outlets and 2D elevation map
OCN$FD$Z[OCN$FD$outlet]
draw_elev2D_OCN(OCN)
## End(Not run)
Calculate paths between nodes in an Optimal Channel Network
Description
Function that determines upstream and downstream paths and path lengths between any nodes of the network at the aggregated level.
Usage
paths_OCN(OCN, level = c("RN","AG"), whichNodes = NULL, includePaths = FALSE,
includeDownstreamNode = FALSE, includeUnconnectedPaths = FALSE, displayUpdates = FALSE)
Arguments
OCN |
A |
level |
Character vector. At which level should paths be calculated? Possible values are |
whichNodes |
List. It allows specifying a subset of nodes for which paths are computed. In the case of large rivers, this could
speed up the function execution substantially. It must contain objects named |
includePaths |
Logical. If |
includeDownstreamNode |
Logical. If |
includeUnconnectedPaths |
Logical. If |
displayUpdates |
Logical. State if updates are printed on the console while |
Value
A river
object that contains all objects contained in OCN
, in addition to the objects listed below.
RN$downstreamPath |
List (of length |
RN$downstreamPathLength |
Sparse matrix ( |
RN$downstreamLengthUnconnected |
Matrix ( |
AG$downstreamPath |
List (of length |
AG$downstreamPathLength |
Sparse matrix ( |
AG$downstreamLengthUnconnected |
Matrix ( |
Examples
# 1) Calculate paths between nodes of an OCN
OCN <- paths_OCN(aggregate_OCN(landscape_OCN(OCN_20), thrA = 4))
# 2) Display distance to outlet (at the RN level) along the main stem
# of an OCN
OCN <- aggregate_OCN(landscape_OCN(OCN_250_T)) # this takes some seconds
OCN <- paths_OCN(OCN, includePaths = TRUE) # this takes some seconds
distanceToOutlet <- OCN$RN$downstreamPathLength[,OCN$RN$outlet]
farthestNode <- which(distanceToOutlet == max(distanceToOutlet))
mainStem <- OCN$RN$downstreamPath[[farthestNode]][[OCN$RN$outlet]]
theme <- rep(NaN, OCN$RN$nNodes)
theme[mainStem] <- distanceToOutlet[mainStem]
draw_thematic_OCN(theme, OCN)
title("Distance to outlet along the main stem [pixel units]")
# 3) use whichNodes to compute distance between two non flow-connected nodes
OCN <- aggregate_OCN(landscape_OCN(OCN_250_T)) # this takes some seconds
RNnodes <- c(483, 516)
plot(OCN)
points(OCN$RN$X[RNnodes], OCN$RN$Y[RNnodes], pch = 19) # nodes 483 and 516 are not flow-connected
OCN <- paths_OCN(OCN, whichNodes = list(RN=RNnodes), includePaths = TRUE,
includeUnconnectedPaths = TRUE)
OCN$RN$downstreamPath[[RNnodes[1]]][[OCN$RN$outlet]]
# the outlet node has been added to whichNodes$RN
OCN$RN$downstreamLengthUnconnected[RNnodes[1], RNnodes[2]]
# distance from node 1 to the common downstream confluence
OCN$RN$downstreamLengthUnconnected[RNnodes[2], RNnodes[1]]
# distance from node 2 to the common downstream confluence
Plot a river
Description
Plots a river
object
Usage
## S4 method for signature 'river,numeric'
plot(x, y, type, ...)
## S4 method for signature 'numeric,river'
plot(x, y, type, ...)
## S4 method for signature 'river,missing'
plot(x, type, ...)
Arguments
x |
A |
y |
A numeric vector to be displayed (or a river if |
type |
Optional argument. If |
... |
Arguments passed to the plotting functions |
Details
This is an interface to the plotting functions draw_simple_OCN
, draw_elev2D_OCN
, draw_contour_OCN
, draw_subcatchments_OCN
,
draw_thematic_OCN
. If the river
object does not have an elevation field (i.e., it has been generated
by create_OCN
or create_general_contour_OCN
, but landscape_OCN
has not
been run), the plotting function used is draw_simple_OCN
. If the elevation field is present, but the river
has not been aggregated (via aggregate_OCN
or aggregate_river
), the default plotting function used is
draw_contour_OCN
. If the river has been aggregated, draw_subcatchments_OCN
or draw_thematic_OCN
are used depending on type
.
Elevation maps can be produced with type = "elev2D"
, regardless of whether the river has been aggregated.
Adding scale bar and north arrow. Scale bar and north arrow can be added via terra
's functions sbar
and north
, respectively.
However, note that arguments d
and xy
must be specified by the user (because no rast
object is plotted). See example.
See Also
draw_simple_OCN
, draw_elev2D_OCN
, draw_contour_OCN
, draw_subcatchments_OCN
, draw_thematic_OCN
Examples
set.seed(1)
OCN <- OCN_20
plot(OCN) # equivalent to draw_simple_OCN
OCN <- landscape_OCN(OCN)
plot(OCN) # equivalent to draw_contour_OCN
plot(OCN, type = "elev2D") # equivalent to draw_elev2D_OCN
OCN <- aggregate_OCN(OCN, thrA = 4)
plot(OCN) # equivalent to draw_thematic_OCN (with no theme specified)
plot(OCN, OCN$AG$A) # equivalent to draw_thematic_OCN (with theme specified)
plot(OCN, type = "contour") # equivalent to draw_contour_OCN
plot(OCN, type = "SC") # equivalent to draw_subcatchments_OCN (with no theme specified)
plot(OCN, OCN$AG$A, type = "SC") # equivalent to draw_subcatchments_OCN (with theme specified)
# now add scale bar and north arrow
library(terra)
# sbar() # this would throw an error
# north()# this would throw an error
sbar(d=1, xy=c(min(OCN$FD$X), min(OCN$FD$Y)-1)) # this works
north(d=1, xy=c(max(OCN$FD$X)+1, max(OCN$FD$Y))) # this works
river class
Description
A river
object contains information on river attributes at different aggregation levels. It can represent a real river network
(obtained via rivnet::extract_river
) or an optimal channel network (obtained via create_OCN
).
The content of a river
object can be treated as a list, hence its objects and sublists can be accessed with both the $
and @
operators.
For information on the aggregation levels and on the content of a
river
object, see OCNet-package
.
Examples
show(OCN_20)
names(OCN_20)
# extract or replace parts of a river object
OCN_20$dimX
OCN_20@dimX
dim <- OCN_20[["dimX"]]
OCN_20$dimX <- 1
OCN_20[["dimX"]]
OCN_20[["dimX"]] <- dim
River geometry of an Optimal Channel Network
Description
Function that calculates river width, depth and water velocity by applying Leopold's scaling relationships to nodes at the RN and AG levels.
Usage
rivergeometry_OCN(OCN, widthMax = 1, depthMax = 1,
velocityMax = 1, expWidth = NaN, expDepth = NaN,
expVelocity = NaN)
Arguments
OCN |
A |
widthMax |
Maximum river width allowed. If |
depthMax |
Maximum river depth allowed. If |
velocityMax |
Maximum water velocity allowed. If |
expWidth , expDepth , expVelocity |
Exponents for the power law relationship between river width, depth, water velocity
and contributing area. If none of |
Details
The values of contributing area used to evaluate river geometry at the AG level are equal to 0.5*(OCN$AG$A + OCN$AG$AReach)
. See also aggregate_OCN
.
See also Leopold, L. B., & Maddock, T. (1953). The hydraulic geometry of stream channels and some physiographic implications (Vol. 252). US Government Printing Office.
Value
AA river
object that contains all objects contained in OCN
, in addition to the objects listed below.
RN$width |
Vector (of length |
RN$depth |
Vector (of length |
RN$velocity |
Vector (of length |
AG$width |
Vector (of length |
AG$depth |
Vector (of length |
AG$velocity |
Vector (of length |
Finally, widthMax
, depthMax
, velocityMax
, expWidth
, expDepth
, expVelocity
are added to the list.
Examples
# 1) Compute river geometry of a 20x20 OCN with default options
# and display river width at the RN level
OCN <- rivergeometry_OCN(aggregate_OCN(landscape_OCN(OCN_20)))
draw_thematic_OCN(OCN$RN$width,OCN)