
\documentclass{article}
% \VignetteIndexEntry{Watersheds: spatial watershed aggregation and drainage-network analysis}
% \VignetteDepends{Watersheds, sp, sf}
% \VignetteKeyword{watersheds}
% \VignetteEngine{utils::Sweave}
% \VignetteEncoding{UTF-8}

\usepackage{amsmath}
\usepackage{amscd}
\usepackage[tableposition=top]{caption}
\usepackage{ifthen}
\usepackage[utf8]{inputenc}
\usepackage[top=3.0cm, bottom=2.5cm, left=3.0cm, right=3.0cm]{geometry} %define margins
\bibliographystyle{plain}
\usepackage{amsfonts}
\usepackage{lmodern}


\begin{document}
\SweaveOpts{concordance=TRUE}
\sloppy

\title{\bf Watersheds: spatial watershed aggregation and drainage-network analysis}
\author{Jairo A. Torres-Matallana\\
{\small \it Climate Service Center Germany (GERICS), Helmholtz-Zentrum Hereon GmbH,}\
{\small \it Hamburg, Germany}\\
\small jairo.torres@hereon.de}
\maketitle

% --------------------- question 1 ------------------------------
% cdir="/Users/Arturo/Desktop/writesummary/vignettes"

\section{Introduction}

This vignette introduces {\tt Watersheds}, an R package for following a drainage network upstream from a location of interest \cite{Ihaka&Gentleman(1996), RDCoreTeam(2013)}. Given a station, the package finds the hydrological unit containing it, identifies the local inlet and outlet nodes, and then traces its first- and second-order tributaries.

The public interface uses {\tt sp} spatial classes \cite{Pebesma&Bivand(2012)}. Geometry predicates and measurements are performed internally with {\tt sf}, so existing workflows based on {\tt sp} can continue to use the package.

\subsection{Workflow}

The examples follow the same sequence used with a new hydrographic network:
\begin{enumerate}
\item choose a station and assemble the required basin, hydrological-unit, river and node layers in a {\tt Watershed} object;
\item use {\tt Watershed.Order} to find the focal unit, its connected river stretches, and its inlet and outlet nodes;
\item use {\tt Watershed.Order2} when tributary catchments need to be expanded one level further; and
\item apply {\tt Watershed.IOR1}--{\tt Watershed.IOR4} according to the number of connected inlet/outlet river stretches.
\end{enumerate}

\section{The data: river Weser basin, Germany}

The package includes an ECRINS v1.1 example for the river Weser basin, Germany. Its aggregation and drainage-network logic was developed specifically for the topology and attributes of the 2012 European Environment Agency (EEA) Catchments and Rivers Network System (ECRINS). ECRINS is based on previous work by the Joint Research Centre (JRC) Catchment Characterisation and Modelling (CCM) and the EEA's European Lakes, Dams and Reservoirs Database (Eldred2) and European Rivers and Catchments (ERICA) datasets \cite{EEA(2012)}. Applying the package to another hydrographic network requires checking that its topology and required attributes are analogous.

\subsection{Subsets}

The dataset contains the following subsets:
\begin{itemize}
\item {\tt basin}: an object {\tt SpatialPolygonsDataFrame} as is defined in package {\tt sp} that represents the river Weser basin. The {\tt data} slot contains 6 variables as attributes of 1 observation.\\
	
\item {\tt ctry}: an object {\tt SpatialPolygonsDataFrame} as is defined in package {\tt sp} that represents the administrative boundary of Germany. The {\tt data} slot contains 6 variables as attributes of 1 observation.\\
	
\item {\tt node:} an object {\tt SpatialPointsDataFrame} as is defined in package {\tt sp} that represents the nodes of the ECRINS river network of the river Weser basin. The {\tt data} slot contains 13 variables as attributes of 3882 observations.\\
	
\item {\tt rAller} an object {\tt SpatialLinesDataFrame} as is defined in package {\tt sp} that represents the basin of the river Aller, a major tributary of the river Weser. The {\tt data} slot contains 74 variables as attributes of 88 observations.\\
	
\item {\tt rDiemel} an object {\tt SpatialLinesDataFrame} as is defined in package {\tt sp} that represents the basin of the river Diemel, a major tributary of the river Weser. The {\tt data} slot contains 74 variables as attributes of 39 observations.\\
	
\item {\tt rFulda} an object {\tt SpatialLinesDataFrame} as is defined in package {\tt sp} that represents the basin of the river Fulda, a major tributary of the river Weser. The {\tt data} slot contains 74 variables as attributes of 82 observations.\\
	
\item {\tt rHunte} an object {\tt SpatialLinesDataFrame} as is defined in package {\tt sp} that represents the basin of the river Hunte, a major tributary of the river Weser. The {\tt data} slot contains 74 variables as attributes of 34 observations.\\
	
\item {\tt river} an object {\tt SpatialLinesDataFrame} as is defined in package {\tt sp} that represents the ECRINS river network of the river Weser basin. The {\tt data} slot contains 52 variables as attributes of 3874 observations.\\
	
\item {\tt rWerra} an object {\tt SpatialLinesDataFrame} as is defined in package {\tt sp} that represents the basin of the river Werra, a major tributary of the river Weser. The {\tt data} slot contains 74 variables as attributes of 120 observations.\\

\item {\tt rWeser} an object {\tt SpatialLinesDataFrame} as is defined in package {\tt sp} that represents the basin of the river Weser. The {\tt data} slot contains 74 variables as attributes of 104 observations.\\

\item {\tt rWiumme} an object {\tt SpatialLinesDataFrame} as is defined in package {\tt sp} that represents the basin of the river Wiumme, a major tributary of the river Weser. The {\tt data} slot contains 74 variables as attributes of 18 observations.\\

\item {\tt station} an object {\tt SpatialPoints} as is defined in package {\tt sp} that represents a point of interest for which the watershed will be aggregated an ordered. Could be a point with the coordinates of a measurement station.\\

\item {\tt subbasin} an object {\tt SpatialPolygonsDataFrame} as is defined in package {\tt sp} that represents the subbasins of the tributaries of the river Weser. The {\tt data} slot contains 4 variables as attributes of 4 observations.\\

\item {\tt zhyd} an object {\tt SpatialPolygonsDataFrame} as is defined in package {\tt sp} that contains the primary hydrological units of the river Weser basin accordingly with ECRINS. The {\tt data} slot contains 50 variables as attributes and 915 observations.\\
\end{itemize}

The maps below move from the whole Weser basin to its tributary basins, elementary hydrological units and river network. They establish the spatial context for the analysis that follows.

<<c1, eval = TRUE, include = TRUE, echo = FALSE, results = hide, fig = TRUE>>=
	library(sp)
	library(Watersheds)
	data(WatershedsData)
	sp_intersects <- function(x, y) {
		t(as.matrix(sf::st_intersects(sf::st_as_sf(x), sf::st_as_sf(y), sparse = FALSE)))
	}
	sp_boundary <- function(x) {
		sf::as_Spatial(sf::st_boundary(sf::st_geometry(sf::st_as_sf(x))))
	}
	sp_distance <- function(x, y) {
		d <- sf::st_distance(sf::st_as_sf(x), sf::st_as_sf(y))
		t(matrix(as.numeric(d), nrow = nrow(d), ncol = ncol(d)) )
	}
	#ls()
	#str(WatershedsData)
	#str(WatershedsData["basin"])


	# plotting river Weser basin
	plot(WatershedsData["ctry"][[1]], col="gray60")
	plot(WatershedsData["basin"][[1]], col="gray30", add=TRUE)
	title("River Weser basin, Germany")

	# plotting subbasins river Weser basin
	plot(WatershedsData["basin"][[1]])
	plot(WatershedsData["subbasin"][[1]], col="gray60",add=TRUE)
	plot(WatershedsData["rWeser"][[1]],col="blue",lwd=2,add=TRUE)
	plot(WatershedsData["rAller"][[1]],col="blue",lwd=1,add=TRUE)
	plot(WatershedsData["rDiemel"][[1]],col="blue",lwd=1,add=TRUE)
	plot(WatershedsData["rFulda"][[1]],col="blue",lwd=1,add=TRUE)
	plot(WatershedsData["rHunte"][[1]],col="blue",lwd=1,add=TRUE)
	plot(WatershedsData["rWerra"][[1]],col="blue",lwd=1,add=TRUE)
	plot(WatershedsData["rWiumme"][[1]],col="blue",lwd=1,add=TRUE)
	title("Subbasins River Weser")

	# plotting primary zhyd watersheds and drainage network inside river Werra subbasin
	# subsetting the river Werra subbasin
id = list(sp_intersects(
  WatershedsData["rWerra"][[1]],
  WatershedsData["subbasin"][[1]]
))
	subbasin_rWerra = SpDF_Subset(id,WatershedsData["subbasin"][[1]])
	
	# subsetting the river Werra zhyd watersheds
	id = list(sp_intersects(WatershedsData["rWerra"][[1]], WatershedsData["zhyd"][[1]]))
	zhyd_rWerra = SpDF_Subset(id,WatershedsData["zhyd"][[1]])
	plot(subbasin_rWerra, col="grey60")
	plot(zhyd_rWerra,col="grey50",add=TRUE)
	plot(WatershedsData["rWerra"][[1]],col="blue",lwd=1,add=TRUE)
	title("Subbasin River Weser and primary zhyd watersheds")

	# subsetting the river Werra river drainage watersheds
	id = list(sp_intersects(subbasin_rWerra, WatershedsData["river"][[1]]))
	river_rWerra = SpDF_Subset(id,WatershedsData["river"][[1]])
	plot(subbasin_rWerra,col="grey60")
	plot(WatershedsData["rWerra"][[1]],col="blue",lwd=3,add=TRUE)
	plot(river_rWerra,col="blue1",add=TRUE)
	title("Subbasin River Weser and drainage network")
@

\section{The {\tt Watersheds} objects}

A {\tt Watershed} object brings together the station with the layers needed by the algorithms. The station must use the same projected coordinate reference system as the spatial layers. The short setup below creates an object for the bundled example; the remaining maps use the same pattern with different station locations.

<<c2, eval = TRUE, include = TRUE>>=
	station1 = WatershedsData["station"][[1]]
	subbasin1 = WatershedsData["subbasin"][[1]]
	zhyd1 = WatershedsData["zhyd"][[1]]
	river1 = WatershedsData["river"][[1]]
	node1 = WatershedsData["node"][[1]]
	
	station1 = SpatialPoints(station1, 
		proj4string=slot(subbasin1,"proj4string"))
	watershed = new("Watershed",station=station1,subbasin=subbasin1,
		zhyd=zhyd1,river=river1,c1=subbasin1,node=node1)
	class(watershed)
@

\section{The {\tt Watersheds.Order} method}

{\tt Watershed.Order} is the main entry point. It finds the subbasin containing the station, selects the focal {\tt zhyd} unit, identifies its river stretches and candidate inlet/outlet nodes, and returns the first-order tributary units.

In the map, the dark polygon is the focal unit, lighter polygons are first-order tributaries, blue lines are river stretches, the blue triangle is the station, and green and red points mark the inlet and outlet. This is the key diagnostic plot: it lets the analyst check that the topology selected by the method agrees with the intended drainage direction.

<<c3, eval = TRUE, include = TRUE, echo = FALSE, results = hide, warning=FALSE, fig = TRUE>>=
	station1 = WatershedsData["station"][[1]]
	subbasin1 = WatershedsData["subbasin"][[1]]
	zhyd1 = WatershedsData["zhyd"][[1]]
	river1 = WatershedsData["river"][[1]]
	node1 = WatershedsData["node"][[1]]	

	station1 = SpatialPoints(coords=cbind(4328448.74, 3118576.86), 
		proj4string=slot(subbasin1,"proj4string"))
	watershed = new("Watershed",station=station1,subbasin=subbasin1,
		zhyd=zhyd1,river=river1,c1=subbasin1,node=node1)

	a = Watershed.Order(watershed)
	c1 = a[[1]]
	c1_inlet = a[[2]]
	c1_outlet = a[[3]]
	c2 = a[[4]]
	c3 = a[[5]]
	node_trib = a[[6]]
	sb1 = a[[7]]
	riverIO = a[[8]]
	nodeIO = a[[9]]			
	c1_river = a[[10]]
	c1_node = a[[11]]	

	bbox1 = slot(c1, "bbox")
	bbox = matrix(0,2,2)
	bbox[,1] = bbox1[,1]*.998
	bbox[,2] = bbox1[,2]*1.002
	
	plot(c1, xlim=bbox[1,], ylim=bbox[2,],col="gray50")			
	plot(c2, col="gray75", add=TRUE)
	plot(c3, col="gray85", add=TRUE)
	plot(slot(watershed,"station"),pch=24, bg="blue",add= TRUE)
	plot.PolyLineAttribute(c1, "order", 450, 0.8)
	plot.PolyLineAttribute(c2, "order", 450, 0.8)
	plot.PolyLineAttribute(c3, "order", 450, 0.8)				
	plot(c1_river, col="blue", add=TRUE)
	plot(c1_node,pch=21,bg="blue",cex=.5,add=TRUE)
	plot(nodeIO,pch=21,bg="blue",cex=.5,add=TRUE)
	plot(c1_inlet, pch=21, bg="green",add= TRUE)
	plot(c1_outlet,pch=21, bg="red",add= TRUE)
	plot.PointAttribute(nodeIO,"ELEV",600,0.7)
	title(main="Current zhyd watershed (1)",
		sub="First order tributary watersheds (1.1, 1.2)")
@

\section{The {\tt Watersheds.Order2} method}

{\tt Watershed.Order2} expands the analysis to the tributaries of a focal unit. When {\tt Watershed.Order} returns two tributary nodes, this method applies the ordering procedure at each node and returns the two results. The resulting map shows the focal unit together with its first- and second-order tributaries, making the upstream structure easier to inspect.

<<c4, eval = TRUE, include = TRUE, echo = FALSE, results = hide, warning=FALSE, fig = TRUE>>=
	station1 = SpatialPoints(coords=cbind(4328650,3174450), 
		proj4string=slot(subbasin1,"proj4string"))
	watershed = new("Watershed",station=station1,subbasin=subbasin1,
		zhyd=zhyd1,river=river1,c1=subbasin1,node=node1)

	a = Watershed.Order(watershed)
	c1 = a[[1]]
	node_trib = a[[6]]
	c1_river = a[[10]]

watershed2 = new(
  "Watershed", station = node_trib, subbasin = subbasin1,
  zhyd = zhyd1, river = river1, c1 = c1, node = node1
)
	c23 = Watershed.Order2(watershed2)
	c2 = c23[[1]]
	c3 = c23[[2]]	
	
	c2.0 = c2[[1]]
	c2_inlet = c2[[2]]
	c2_outlet = c2[[3]]
	c2.1 = c2[[4]]
	c2.2 = c2[[5]]
	c2_node_trib = c2[[6]]
	c2_sb1 = c2[[7]]
	c2_riverIO = c2[[8]]
	c2_nodeIO = c2[[9]]			
	c2_river = c2[[10]]
	c2_node = c2[[11]]	
			
	c3.0 = c3[[1]]
	c3_inlet = c3[[2]]
	c3_outlet = c3[[3]]
	c3.1 = c3[[4]]
	c3.2 = c3[[5]]
	c3_node_trib = c3[[6]]
	c3_sb1 = c3[[7]]
	c3_riverIO = c3[[8]]
	c3_nodeIO = c3[[9]]			
	c3_river = c3[[10]]
	c3_node = c3[[11]]	
	
	# subsetting river networks
	id = list(sp_intersects(c2.1, WatershedsData$river))
	c21_river = SpDF_Subset(id,WatershedsData$river)

	id = list(sp_intersects(c2.2, WatershedsData$river))
	c22_river = SpDF_Subset(id,WatershedsData$river)
	
	id = list(sp_intersects(c3.1, WatershedsData$river))
	c31_river = SpDF_Subset(id,WatershedsData$river)

	id = list(sp_intersects(c3.2, WatershedsData$river))
	c32_river = SpDF_Subset(id,WatershedsData$river)
	
	# plots
	bbox1 = slot(c3.2, "bbox")
	bbox = matrix(0,2,2)
	bbox[,1] = bbox1[,1]*.995
	bbox[,2] = bbox1[,2]*1.005
							
	plot(c1, col="gray50", xlim=bbox[1,], ylim=bbox[2,])	
	plot(c2.0, col = "gray95", add=TRUE)
	plot(c3.0, col="gray79", add=TRUE)
	plot(c2.1, col="gray78", add=TRUE)
	plot(c2.2, col="gray85", add=TRUE)
	plot(c3.1, col="gray53", add=TRUE)
	plot(c3.2, col="gray63", add=TRUE)

	plot(c1_river, col="blue",add=TRUE)		
	plot(c2_river, col="blue",add=TRUE)		
	plot(c3_river, col="blue",add=TRUE)			
	plot(c21_river, col="blue",add=TRUE)			
	plot(c22_river, col="blue",add=TRUE)			
	plot(c31_river, col="blue",add=TRUE)			
	plot(c32_river, col="blue",add=TRUE)	
	
	title(main="Current zhyd watershed and \n 1st and 2nd order tributary watersheds")
@

\section{The {\tt Watersheds.IOR1} function}

The IOR functions resolve the inlet and outlet nodes after {\tt Watershed.Order} has identified the connected river stretches. Case I applies when there is a single connected stretch. There is only an outlet in this situation, shown in red in the map.

<<c5, eval = TRUE, include = TRUE, echo = FALSE, results = hide, warning=FALSE, fig = TRUE>>=
station1 = SpatialPoints(coords=cbind(4232972,3327634), 
		proj4string=slot(subbasin1,"proj4string"))
	watershed = new("Watershed",station=station1,subbasin=subbasin1,
		zhyd=zhyd1,river=river1,c1=subbasin1,node=node1)

	a = Watershed.Order(watershed)
	c1 = a[[1]]
	nodeIO = a[[9]]			
	c1_river = a[[10]]
			
	# determining inlet and outlet watershed nodes
		# determining distances of nodeIO to c1
		boundary = sp_boundary(c1)
		dist = sp_distance(nodeIO, boundary)
		a = Watershed.IOR1(x=nodeIO, dist=dist)
		c1_inlet = a["inlet"][[1]]; c1_inlet
		c1_outlet = a["outlet"][[1]]; c1_outlet
		
	plot(c1,col="gray50")			
	plot(station1,pch=24, bg="blue",add= TRUE)
	plot(c1_river, col="blue", add=TRUE)
	plot(c1_outlet,pch=21, bg="red",add= TRUE)
	plot.PointAttribute(c1_outlet,"ELEV",700,0.8)
	title(main="Watershed outlet, case I")
@

\section{The {\tt Watersheds.IOR2} function}
Case II applies when two connected river stretches are present. The function uses the candidate nodes and their distances to the watershed boundary to determine the outlet shown in red.

<<c6, eval = TRUE, include = TRUE, echo = FALSE, results = hide, warning=FALSE, fig = TRUE>>=
	station1 = SpatialPoints(coords=cbind(4330341.36,3284797.06), 
			proj4string=slot(subbasin1,"proj4string"))
		watershed = new("Watershed",station=station1,subbasin=subbasin1,
			zhyd=zhyd1,river=river1,c1=subbasin1,node=node1)
	
		a = Watershed.Order(watershed)
		c1 = a[[1]]
		nodeIO = a[[9]]			
		c1_river = a[[10]]
		c1_node = a[[11]]	
				
		# determining inlet and outlet watershed nodes
			# determining distances of nodeIO to c1
			boundary = sp_boundary(c1)
			dist = sp_distance(nodeIO, boundary)
			a = Watershed.IOR2(x=nodeIO, dist=dist, node=c1_node)	
		c1_inlet = a["inlet"][[1]]; c1_inlet
		c1_outlet = a["outlet"][[1]]; c1_outlet
			
		plot(c1,col="gray60")			
		plot(station1,pch=24, bg="blue",add= TRUE)
		plot(c1_river, col="blue", add=TRUE)
		plot(c1_outlet,pch=21, bg="red",add= TRUE)
		plot.PointAttribute(c1_outlet,"ELEV",700,0.8)
		title(main="Watershed outlet, case II")
@

\section{The {\tt Watersheds.IOR3} function}
Case III applies when three connected river stretches are present. The method distinguishes one outlet (red) from the inlet (green) using the river topology and the node distances to the watershed boundary.

<<c7, eval = TRUE, include = TRUE, echo = FALSE, results = hide, warning=FALSE, fig = TRUE>>=
	station1 = SpatialPoints(coords=cbind(4217199.42,3353511.83), 
		proj4string=slot(subbasin1,"proj4string"))
	watershed = new("Watershed",station=station1,subbasin=subbasin1,
		zhyd=zhyd1,river=river1,c1=subbasin1,node=node1)

	a = Watershed.Order(watershed)
	c1 = a[[1]]
	riverIO = a[[8]]
	nodeIO = a[[9]]			
	c1_river = a[[10]]
			
	# determining inlet and outlet watershed nodes
		# determining distances of nodeIO to c1
		boundary = sp_boundary(c1)
		dist = sp_distance(nodeIO, boundary)
		a = Watershed.IOR3(x=nodeIO, y=riverIO, dist=dist)	
		c1_inlet = a["inlet"][[1]]; c1_inlet
		c1_outlet = a["outlet"][[1]]; c1_outlet
		
	plot(c1,col="gray60")			
	plot(station1,pch=24, bg="blue",add= TRUE)
	plot(c1_river, col="blue", add=TRUE)
	plot(c1_outlet,pch=21, bg="red",add= TRUE)
	plot(c1_inlet,pch=21, bg="green",add= TRUE)
	plot.PointAttribute(c1_outlet,"ELEV",1000,0.8)
	plot.PointAttribute(c1_inlet,"ELEV",1000,0.8)
	title(main="Watershed outlet and inlet, case III")	
@

\section{The {\tt Watersheds.IOR4} function}
Case IV is the most connected example in the vignette: four river stretches meet the focal watershed. {\tt Watersheds.IOR4} combines their topology and boundary distances to identify the inlet (green) and outlet (red). This final plot is Figure 9 in the vignette.

<<c8, eval = TRUE, include = TRUE, echo = FALSE, results = hide, warning=FALSE, fig = TRUE>>=
		station1 = SpatialPoints(coords=cbind(4357947,3284525), 
			proj4string=slot(subbasin1,"proj4string"))
		watershed = new("Watershed",station=station1,subbasin=subbasin1,
			zhyd=zhyd1,river=river1,c1=subbasin1,node=node1)
	
		a = Watershed.Order(watershed)
		c1 = a[[1]]
		riverIO = a[[8]]
		nodeIO = a[[9]]			
		c1_river = a[[10]]
				
		# determining inlet and outlet watershed nodes
			# determining distances of nodeIO to c1
			boundary = sp_boundary(c1)
			dist = sp_distance(nodeIO, boundary)
			a = Watershed.IOR4(x=nodeIO, y=riverIO, dist=dist)
		c1_inlet = a["inlet"][[1]]; c1_inlet
		c1_outlet = a["outlet"][[1]]; c1_outlet
			
		plot(c1,col="gray60")			
		plot(station1,pch=24, bg="blue",add= TRUE)
		plot(c1_river, col="blue", add=TRUE)
		plot(c1_outlet,pch=21, bg="red",add= TRUE)
		plot(c1_inlet,pch=21, bg="green",add= TRUE)
		plot.PointAttribute(c1_outlet,"ELEV",1000,0.8)
		plot.PointAttribute(c1_inlet,"ELEV",1000,0.8)
		title(main="Watershed outlet and inlet, case IV")
@


%\begin{figure}[h!]
%	\begin{center}
%		<<label=fig:plot, echo=FALSE>>=
%			<<fig:plotExtra>>
%		@
%	\end{center}
%	\caption{Plot of {\sf mytracExtra} an object of class {\sf TrajectoryExtra}}
%	\label{fig:plot}
%\end{figure}

%%------------------- Bibliography ----------------------


%\bibliography{/Users/Arturo/Documents/00_PhD_Research/PhD}
\bibliography{bibliografia}
\end{document}
