LakeRS Demonstrator
R-Package for remote sensing analysis of lakes
2025-05-11: Version 1.0
Malte Zamzow* (Kompetenzzentrum Wasser Berling gGmbH), Michael Rustler (Kompetenzzentrum Wasser Berlin gGmbH)
*Correspnding author: malte.zamzow@kompetenz-wasser.de
lakeRS
lakeRS is an R-Package developed in the European Project ProCleanLakes that calculates a Normalized Difference Trophic Index (NDTrI) based on sentinel-2 data. The Methodology behind the NDTrI was empirically developed by in-situ Trophic state index (TSI) data from about 300 lakes over 5 years in eastern Germany.
lakeRS is available on Github: https://github.com/KWB-R/lakeRS
It was developed in the European Horizon Project ProCleanLakes: https://procleanlakes.eu/
This document is online available: https://procleanlakes.kompetenz-wasser.io/lakeRS_doc/LakeRS Demonstrator.html
The R package is continuously being developed; to reproduce the results in this document exactly, you must download and install version 0.1.0 (see chapter “Install the lakeRS Package”).
Requirements
- Software R (> 4.0.0), suggested: RStudio
- Copernicus Dataspace Account
- R-Package lakeRS (further required Packages: tidyr, geosphere, htmltools, htmlwidgets, leaflet, openeo, terra)
Theoretical Background
Sentinel-2 Data
Sentinel-2 is a European Copernicus mission providing freely available, high-resolution multispectral imagery for global Earth observation. The mission comprises a constellation of satellites carrying a 13-band optical sensor that samples the visible, near-infrared, and shortwave infrared regions at 10 m, 20 m, and 60 m spatial resolution. With a revisit time of about 5 days and a wide swath of 290 km, Sentinel-2 is well suited for monitoring vegetation, land cover, inland waters, coastal areas, and surface change. The data are commonly used as input for further preprocessing and analysis in environmental, agricultural, and geospatial applications.
Further Information:
- A complete description of sentinel-2 Mission and Algorithms: https://docs.sentinel-hub.com/api/latest/data/sentinel-2-l2a/
- Copernicus Browser to get familiar with sentinel-2 Images and Indixes (even without account): https://browser.dataspace.copernicus.eu
Trophic Index
The trophic state index (TSI) is a standardized measure used to describe the biological productivity of lakes and other inland water bodies. It summarizes the nutrient status and algal growth potential of a lake, typically based on indicators such as chlorophyll-a, total phosphorus, and water transparency. Higher TSI values indicate more productive, nutrient-rich, and often more eutrophic conditions, while lower values correspond to clearer, less productive waters. The index is widely used in lake ecology and water quality assessment to compare lakes, track changes over time, and support environmental monitoring and management.
Normalized Difference Trophic Index
The NDTrI was empirically developed by in-situ Trophic state index (TSI) data from about 300 lakes over 5 years in eastern Germany. A high correlation (r 0.9) was found between NDTrI and in-situe values.
The extent to which the relationship with absolute TSIs can be generalized to regions with different environmental conditions (climate, geological background, etc.) must be assessed on a case-by-case basis. However, it is expected that relative changes in the NDTrI within a water body (over time and across space) serve as a good indicator of relative changes in the TSI.
It was developed in the European Horizon Projekt AD4GD to support lake management by increasing the temporal resolution of trophic data per lake and including lakes that are not monitored on a regular basis.
As part of the ProCleanLakes project, the NDTrI data analysis was expanded from a single value per lake per year to a more detailed spatial and temporal assessment. This was done with the aim of evaluating the impact of local nature-based solutions as lake restoration measures.
Further Information:
- Presentation of Methodology and Validation from EGU 2025:
Brates Lake (Example)
Lake Brates is a shallow freshwater lake in eastern Romania, situated near Galați in the lower Danube region and is a Demonstration site in the Europen ProCleanLakes Project. It is one of the largest natural lakes in the country and forms an important aquatic habitat within a highly modified riverine landscape. From a limnological perspective, Lake Brateș is generally regarded as a nutrient-rich system and is therefore often described as eutrophic or even tending toward hypereutrophic conditions. Such conditions are common in shallow lowland lakes influenced by agricultural runoff, reduced water exchange, and long-term human alteration of the catchment. The lake’s relatively rectangula shape is not entirely natural. About a century ago, the lake covered approximately 27,000 hectares; however, from the third decade of the 20th century onward, it underwent major anthropogenic transformations that progressively reduced its extent to a heavily impacted ecosystem of about 2,120 hectares
Install the lakeRS Package
if (! require("remotes")) {
install.packages("remotes", repos = "https://cloud.r-project.org")
}
# Install KWB package 'lakeRS' from GitHub (newest Version)
remotes::install_github("KWB-R/lakeRS")
# Or install KWB package 'lakeRS' from GitHub (v0.1.0)
remotes::install_github("KWB-R/lakeRS@v0.1.0")lakeRS Applications
1) How to Download Data
The Sentinel-2 data is downloaded from the Copernicus Dataspace via the openEO platform. This offers the advantage that preprocessing is already performed on the server. In particular, data can be filtered by spatial extent, time interval, required bands, as well as by tiles or orbit numbers. This ensures that only relevant data is downloaded, and the file size is reduced to the necessary minimum. For very large lakes in particular, it is useful to process the satellite data in segments, e.g., by year or by spatial area.
OpenEO can be directly accessed using the R package “openeo.” To do this, a job is set up in R and the task is sent to OpenEO. Once the job is complete, it can be downloaded and saved locally. In lakeRS, the functions from the openeo package are already integrated in such a way that only the settings required for further analysis need to be adjusted. This simplifies communication with OpenEO, allowing users to download Sentinel-2 data even without in-depth knowledge.
To download data, you need an account in Copernicus Dataspace. The account can be set up at:
The “openeo” package must also be installed in R.
if(!("openeo" %in% installed.packages())){
install.packages("openeo")
}
eodc <- openeo::connect(host = "https://openeo.dataspace.copernicus.eu/openeo/1.2")
openeo::login() # account for copernicus dataspace requiredWhen starting a new processing job, it is a good idea to assign a name and an ID to the project; the combination of both should be unique. The name and ID are passed on to OpenEO and can be found in the OpenEO Editor if needed. The metadata can also be used for the folder name of the locally saved file.
In this example, data for Brates Lake—which is Demonstration Site 2 (DS2) in the ProCleanLakes project—is downloaded.
lakeName <- "Brates Lake"
lakeID <- "DS2"There are three different ways to create a bounding box to spatially filter the satellite data. The coordinates must be specified in the WGS84 coordinate system:
- A bounding box can be created around a defined point. The input variable “meters” creates a square around the point with a side length of 2 x “meters” in meters.
- A bounding box can be specified directly as a rectangle using 4 corner points. Here, too, there is the input variable “meters,” which extends the rectangle outward by a specified number of meters. This can be useful if the bounding box of a lake was derived directly from geodata, but the shoreline deviates slightly—for example, due to water level fluctuations or because the shoreline was surveyed some time ago.
- A polygon can be entered directly via a list of coordinates. Since bounding boxes always run parallel to lines of longitude or latitude, it can sometimes result in too many data points being downloaded if the lake shore runs in other directions or has many irregularities. Another reason for creating a custom polygon may be to exclude other nearby lakes. To define a polygon, the coordinates are entered as lat,lon pairs into an R-list. (The lat,lon pairs can be quickly copied from Google Maps, for example.)
Polygon handling on OpenEO
ℹ️OpenEO can only use bounding boxes to filter data prior to data acquisition. If a polygon is passed as the geometry to the
start_openEO_Job()function, the polygon is subsequently used to crop Sentinel-2 values from the bounding box. The OpenEO data processing steps are thus performed for all pixels in the bounding box, but the download size is reduced.
The selected area can then be reviewed before further processing. To do this, an interactive Leaflet map opens, which you can zoom in and out of.
# 1. Bounding Box from point
geom <- lakeRS::bbox_from_point(
lat = 45.48344,
lon = 28.06878,
meters = 500
)
lakeRS::display_geometry(geom = geom, zoom = 13)
# 2. Bounding Box from Rectangle
geom <- lakeRS::bbox_from_rectangle(
top_lat = 45.505707,
bottom_lat = 45.461176,
left_lon = 28.037879,
right_lon = 28.099677,
meters = 100
)
lakeRS::display_geometry(geom = geom, zoom = 13)
# 3. Polygon
geom <- list(c(45.505754, 28.037929), c(45.504479, 28.102674),
c(45.462632, 28.101410), c(45.460962, 28.086337),
c(45.461727, 28.065711), c(45.467570, 28.045977))
lakeRS::display_geometry(geom = geom, zoom = 13)The observation period is specified in the format “YYYY-mm-dd”. For particularly large lakes (approx. > 10 km in diameter), it is advisable to download the data on an annual basis to make it easier to analyze later.
tBeg <- "2025-01-01"
tEnd <- "2025-12-31"After entering the name, ID, and temporal and spatial boundaries, the job can be submitted to openEO. You can also specify the bands to be downloaded. For the NDTrI, the “B02,” “B05,” and “SCL” bands are theoretically sufficient. However, in lakeRS, indices with additional bands can also be created. To keep this option open, this example requests the reflection of all available wavelengths in addition to the Scene Classification Layer (SCL).
The output format of the data can also be customized within the function. The lakeRS package only processes netCDF files. Saving in a different format (e.g., GTiff) may be useful for other programs or analyses.
Special Case - Tiles and relative orbit number
ℹ️In certain cases, it may be useful to filter Sentinel-2 data by specific tiles or relative orbit numbers. One example of this is when a lake is only partially visible in images from a given orbit number. This often results in the typical stripes in the satellite image, which interfere with a spatial analysis of the lake. If anomalies are detected during the analysis, it is worth evaluating the individual images separately by tile or relative orbit number and, if necessary, adjusting the filter for the data download.
jobTitle <- lakeRS::start_openEO_job(
title = paste(lakeName, lakeID, tBeg, tEnd, sep = "_"),
geom = geom,
bands = list(
"B01", "B02", "B03", "B04", "B05", "B06", "B07", "B08", "B8A", "B09",
"B11", "B12", "SCL"),
tBeg = tBeg,
tEnd = tEnd
)Processing a job on openEO can take some time, depending on its size. Experience has shown that generating the data for medium-sized lakes takes about 10 minutes. The file can only be downloaded once the job has finished. If you try to download the job before it finishes, you will see the message “Job is still running.” In this case, you can try the download function again a little later.
print(getwd()) # see where folder and file will be saved
lakeRS::download_openEO_job(
title = jobTitle,
path = file.path(getwd(), "input")
)The process on openEO can be tracked in the openEO Editor. The Editor is available at https://openeo.dataspace.copernicus.eu/. Additional information is also available there in case an error occurs during data retrieval or processing.
2) How to calculate the Normalized Difference Trophic Index of a lake
The Normalized Difference Trophic Index (NDTrI) is an index that, similar to in-situ measurements, refers to an entire lake over an entire season. The data is available in the netCDF file on a per-image (and thus per-time-step) basis as well as on a per-pixel basis. The data must therefore be aggregated spatially and temporally. The lakeRS package also allows for spatial or temporal analysis of data. This is explained in Chapter 3 and 4.
First, the netCDF file must be opened. If you do not have a netCDF file from openEO on your computer, a netCDF file for the example described above (Lake Brates, year 2025) can be downloaded here (368 MB): https://procleanlakes.kompetenz-wasser.io/lakeRS_example/openEO.nc
File Size
ℹ️The file is already 368 MB in size, even though it covers only one year of data for Lake Brates, which is approximately 5 km wide. This means that very large amounts of data accumulate quickly, and filtering by time, location, and tape is essential to limit network traffic and the amount of storage space required.
All netCDF files downloaded from openEO are named “openEO.nc”. By default, the open_netcdf function searches for the file with exactly this name. To ensure the data is properly organized, the underlying folder structure and folder naming conventions are important. If the files are renamed individually instead, this must be passed as an argument to the function. Otherwise, the only argument is the file path (in R, folder names in a file path are separated by a forward slash “/”) where the netCDF file is located.
filePath <- "" # whereever the openEO.nc file is stored
nc <- lakeRS::open_netcdf(filePath = filePath)Once the connection to netCDF is established, indices can be calculated from the data. The NDTrI is generated using bands 5 and 2. In this example, it is calculated for Lake Brates for the year 2025. Optionally, you can specify which months represent a season before performing the calculation. In Germany, for example, the trophic index is calculated using data from April to October. However, depending on climatic conditions, peak primary production may occur at entirely different times. Setting this to NULL means no monthly filter is applied.
imageIndex <- lakeRS::ndi_per_image(
nc = nc,
year = 2025,
bandNames = c("B05", "B02"),
monthFilter = 1:12
)The index is now available for every pixel at every available point in time, meaning that even pixels that are not actually located in the lake have been evaluated. The first aggregation step involves temporal aggregation. By setting “water_scenes_only” to TRUE, only pixels categorized as water by the SCL band are included in the aggregation. In addition, the “pixelQualityThreshold” argument can be used to specify a threshold percentage by which a pixel must be categorized as water over the entire time period in order to be evaluated. This ensures that questionable pixels (e.g., those very close to the shore) are excluded from the overall evaluation of the lake.
When to turn off “water_scenes_only”
ℹ️Technically, the lakeRS package can also be used to calculate indices that describe the surrounding area. To do this, set “water_scenes_only” to FALSE and “pixelQualityThreshold” to 0.
seasonIndex <- lakeRS::seasonal_index_per_pixel(
imageIndex = imageIndex,
nc = nc,
water_scenes_only = TRUE,
pixelQualityThreshold = 0.8
)The data is then aggregated spatially. The metadata regarding the lake name and the lake ID are optional but are included in the results and recommended from a data management perspective.
lakeIndex <- lakeRS::seasonal_index_per_lake(
seasonIndex = seasonIndex,
lakeName = "Brates Lake",
lakeID = "DS2"
)
lakeIndex$IndexModusBestThe NDTrI of lake Brates in 2025 is 0.257.
Interpretation of NDTrI values
Like any normalized difference index, the NDTrI ranges between -1 and 1. The method for determining the NDTrI was empirically derived from in-situ trophic data from approximately 300 lakes in Brandenburg, Germany [1]. In general, there is a good linear correlation between the in-situ trophic index according to LAWA [2] and the NDTrI (Pearson correlation approx. 0.8–0.9). The following applies: the lower the NDTrI, the more oligotrophic the water body; the higher the NDTrI, the more eutrophic it is. However, the methods for assessing trophic status using satellite data and in-situ data differ significantly, and it would be incorrect to equate the results. While satellite data analyze the entire area, but only the uppermost layer of a water body, in-situ measurements often involve taking vertical composite samples at a fixed location in the lake. Furthermore, satellite images can only assess properties that affect the reflection of the measured wavelengths, which does not apply to all trophic indicators such as phosphorus concentration. However, the value ranges in the following table, which were derived from the assessment of German lakes, can be used as a rough guide. Lake Brates thus falls within the range of polytrophic lakes in 2025.
NDTrI Oligotrophic < -0.4 Mesotrophic -0.4- -0.15 Eutrophic -0.15 - 0.05 Polytrophic 0.05 - 0.35 Hypertrophic > 0.35 [2] LAWA (2014): Trophieklassifikation von Seen. Richtlinie zur Ermittlung des Trophie-Index nach LAWA für natürliche Seen, Baggerseen, Talsperren und Speicherseen. Empfehlungen
Oberirdische Gewässer. Hrsg. LAWA – Bund/Länder Arbeitsgemeinschaft Wasser. Kulturbuch-Verlag Berlin GmbH. 34 S. zzgl. Access-Auswertetool. (Autoren: Riedmüller, U., Hoehn, E., Mischke, U.).
Further methods to return lake-specific NDTrI results
The
lakeIndexresult includes not only the metadata and the overall lake rating, but also the pixel-specific, time-aggregated values. The overall lake rating can be displayed in a table.lakeRS::oneLake_df(lakeIndexList = list(lakeIndex))The table includes columns for the entered metadata, the number of pixels used, the variability among the pixels from which the overall rating was calculated, and two variants that can be used to derive the overall rating. In addition to the median of all pixels, it is possible to select the mode of the density distribution, which is done by default. This parameter is more robust against skewed distributions. However, the two values are often very close to each other.
lakeName lakeID year index_median index_sd index_modusBest nValidPixel QualityThreshold Brates Lake DS2 2025 0.257 0.015 0.257 190528 0.8 To get a better overview of all the assessed pixels, the density distribution can be plotted. Both overall assessment methods are included in the plot. In Lake Brates, the distribution is very symmetrical, and the choice of assessment method makes no difference. However, there can be significant differences, especially in small lakes with a relatively large number of pixels near the shore.
3) How to analyse the trophic index spatial distribution
Starting with the temporally aggregated index, the spatial distribution of the NDTrI—and thus variations within the lake over a given period (usually a season)—can be visualized. First, the index is calculated as described above.
nc <- lakeRS::open_netcdf(filePath = filePath)
imageIndex <- lakeRS::ndi_per_image(
nc = nc,
year = 2025,
bandNames = c("B05", "B02"),
monthFilter = 1:12
)
seasonIndex <- lakeRS::seasonal_index_per_pixel(
imageIndex = imageIndex,
nc = nc,
water_scenes_only = TRUE,
pixelQualityThreshold = 0.8
)
lakeIndex <- lakeRS::seasonal_index_per_lake(
seasonIndex = seasonIndex,
lakeName = "Brates Lake",
lakeID = "DS2"
) There are two ways to plot the data:
- In an interactive Leaflet map that allows you to zoom in and out: This is particularly useful if you want to examine certain areas in detail and use that information to plan further analysis.
- In an R-Base plot without a background map: This is useful for capturing a result in a reproducable way and saving it locally.
Color scale of Trophic Assessment
When plotting the NDTrI layer, you can use the “lakeRS::NDTrIColors” color palette included in the package. The table contains rows with pairs of NDTrI values and colors. The colors reflect the typical representation of trophic status to facilitate quick interpretation. Oligotrophic lakes are shown in dark blue, mesotrophic lakes in yellow/green, eutrophic lakes in orange, and polytrophic to hypertrophic lakes in red to purple.
x <- lakeRS::NDTrIColors$ndtri C <- lakeRS::NDTrIColors$color i <- which(x > -0.6 & x < 0.4) par(mar = c(4.1,0,0,0)) plot(x = x[i], y = rep(0.5, length(i)), ylim = c(0,1), type = "n", col = C[i], xaxs = "i", yaxs = "i", axes = FALSE, ylab = "", xlab = "NDTrI") for(ii in i){ lines(x = c(x[ii], x[ii]), y = c(0,1), col = C[ii]) } axis(side = 1, at = pretty(x[i]), labels = pretty(x[i]))
The NDTrI is distributed very homogeneously in Lake Brates 2025. The map also provides a good way to verify whether the assessment was based on correct pixels that actually reflect the lake. It is evident that some pixels near the shore were not used. These pixels did not meet the specified 80% criterion in the SCL band.
Upon closer inspection, the western side of the lake appears slightly more purple and is thus assessed as being minimally more eutrophic than the eastern side. Such differences are particularly important for evaluating small, local measures. To make small differences visible, there is an additional evaluation and visualization method in which the pixels are ranked according to their NDTrI and then sorted into classes.
Before the evaluation can be done in classes, the results list must first be reformatted, since the subsequent function was designed to process data from multiple years. The discreteClassAssessment() function is used to classify the pixels into classes. For the plotting function, the result must be converted back into a matrix with the original layer dimensions. You can use the package’s internal color scale, but of course you can also use your own color selection.
Classification method
ℹ️By default, the classification is done in 10 classes, for which color values are also stored in the package. However, the number of classes can be changed as needed. All classes except the first and last are exactly the same width in terms of the NDTrI range, meaning that the number of pixels in each class can vary. The boundaries of the first and last classes are defined by the 5th and 95th percentiles of all pixels, respectively. The classes do not provide information about the absolute value of the trophic state; instead, it compares pixels only relative to one another.
yearlyPixels <- lakeRS::combine_years_pixelData(
lakeIndexList = list(lakeIndex)
)
classData <- lakeRS::discreteClassAssessment(
yearly_spread = yearlyPixels$indexTable,
nClass = 10,
proportionExtreme = 0.05
)
classLayer <- matrix(
data = classData$assessment$year_2025_class,
nrow = length(nc$y),
ncol = length(nc$x)
)
lakeRS::map_layer(
ncLayer = classLayer,
nc = nc,
lowerLimits = lakeRS::tenClassColors$class,
classColors = lakeRS::tenClassColors$color,
plotLegend = FALSE
) Classification makes it possible to clearly highlight even small differences. In 2025, the pixels with the highest index were concentrated in a narrow area on the western side of the lake. This analysis should be considered in conjunction with the display of absolute values, which reveals that there is, overall, a small difference between the pixels.
4) Analyse the yearly dynamic of the Indices
Strictly speaking, the trophic index refers to the entire season and is not defined for a specific point in time during the year. However, tracking how the value changes over the course of the year can still be very interesting. How much do certain seasons or months affect the overall assessment of the trophic state? Does it make sense to consider the entire year for the assessment, or just the months of April to October? Where are the peaks, and can these peaks be reduced by taking measures in the lake?
First, again the index is calculated for each pixel.
filePath <- "" # whereever the openEO.nc file is stored
nc <- lakeRS::open_netcdf(filePath = filePath)
imageIndex <- lakeRS::ndi_per_image(
nc = nc,
year = 2025,
bandNames = c("B05", "B02"),
monthFilter = 1:12
)A time series is then created for each pixel. By default, a pixel value is included in the time series only if the pixel is identified as water in the SCL band at that time. If this criterion is disabled, scenes containing clouds and snow are still filtered out. An average value for the entire lake is then calculated for each day of the year based on the selected pixels.
Selection of Pixel by pixelQualityThreshold
ℹ️A pixel is selected if it meets the pixelQualityThreshold criterion. The default setting is 0.8, similar to temporal aggregation (→ the pixel must be identified as water in 80% of the time steps). The “byMedian” option shown in the example below is more stringent. It selects only those pixels that are selected at least as frequently as an average water pixel of the lake. This excludes half of pixels that are less frequently identified, probably located in critical areas (e.g., near the shore) or affected by occasional disturbances. In terms of dynamics, this means that it primarily calculates from undisturbed pixels, often in the middle of the lake.
As not all pixels have data with the same timestamp, the function first calculates a smoothed time series for each pixel using moving averages. The number of days that can be included in the averaging before and after a given time step is specified by the input variable days_around_ma. This variable significantly influences the calculated dynamics. Smaller moving average windows better reflect reality. However, larger time intervals are necessary, especially in areas with frequent cloud or ice cover. In this example, the variable is set to 30 days. The calculated value for August 1 thus includes all satellite images between July 1 and September 1. The number of pixels can be limited using the input variable maxPixels, which is particularly useful for very large lakes. In the Brates example, the processing time is less than one minute.
The dynamics can then be plotted, showing not only the median value at a given point in time in the lake but also the 50th and 95th percentile ranges of all pixels.
indexDynamic <- lakeRS::dynamic_per_pixel(
imageIndex = imageIndex,
nc = nc,
water_scenes_only = TRUE,
maxPixels = Inf,
returnSinglePixels = TRUE,
pixelQualityThreshold = "byMedian",
days_around_ma = 30
)
lakeRS::plot_dynamic(
v_averageList = list(indexDynamic$lakeDynamic$q_0.5),
df_q50List = list(indexDynamic$lakeDynamic[,c("q_0.25", "q_0.75")]),
df_q95List = list(indexDynamic$lakeDynamic[,c("q_0.025", "q_0.975")]),
lakeName = "Brates Lake",
ylab = "NDTrI per timestep"
)The highest NDTrI values occur from late summer in August through November. When the number of days in the moving average is varied, the peaks in the time series are clearly smoothed out. If you are only interested in the general trend, using larger time windows can actually yield better results. However, small peaks, such as the one at the end of March 2025, are no longer visible.
Comparing the dynamics across multiple years is particularly interesting. This isn’t possible with the provided sample file, which covers only one year. The following code shows how two years of data for a lake can be compared (2024 and 2025 for Lake Brates). When comparing two years, it’s important that the time window for the moving average is the same.
#######################################################
# Example not possible with example data of only 1 year
#######################################################
nc1 <- lakeRS::open_netcdf(filePath = filePath1)
nc2 <- lakeRS::open_netcdf(filePath = filePath2)
imageIndex1 <- lakeRS::ndi_per_image(
nc = nc1,
year = "2024",
bandNames = c("B05", "B02")
)
imageIndex2 <- lakeRS::ndi_per_image(
nc = nc2,
year = "2025",
bandNames = c("B05", "B02")
)
DynamicList <- list()
DynamicList[["y_2024"]] <- lakeRS::dynamic_per_pixel(
imageIndex = imageIndex1,
nc = nc1,
maxPixels = Inf,
returnSinglePixels = FALSE,
pixelQualityThreshold = "byMedian",
days_around_ma = 30
)
DynamicList[["y_2025"]] <- lakeRS::dynamic_per_pixel(
imageIndex = imageIndex2,
nc = nc2,
maxPixels = Inf,
returnSinglePixels = FALSE,
pixelQualityThreshold = "byMedian",
days_around_ma = 30
)
x_mean <- lapply(DynamicList, function(x){x$lakeDynamic[,"q_0.5"]})
x_q50 <- lapply(DynamicList, function(x){x$lakeDynamic[,c("q_0.25", "q_0.75")]})
lakeRS::plot_dynamic(
v_averageList = x_mean,
df_q50List = x_q50,
TSnames = c("2024", "2025")
)In both years, the NDTrI value rises steadily from April through August. In 2024, there is a peak lasting about one month before the value returns to April levels in October. A year later, this peak lasts much longer, extending into November.
Why do the end value of year 2024 does not match the starting value of year 2025?
🛠The time series within a given year were calculated separately. Therefore, the values from January 2025 cannot be included in the averages for December 2024. Future versions will allow index data to be combined across years prior to the dynamic analysis, thereby making the analysis more consistent.
Years can also be combined to derive long-term average trends. The trend for a given year can then be compared with the average trend. This is particularly useful for comparing the situation before and after a measure has been implemented. The following code can be used to combine and plot the years shown above.
d <- lakeRS::combine_years_dynamic(
indexDynamicList = DynamicList
)
lakeRS::plot_dynamic(
v_averageList = list(d$mean_of_median),
v_sdList = list(d$sd_over_median),
TSnames = "Years 2024 and 2025"
)As expected, the mean lies between the trends observed in the individual years. The standard deviation is particularly high in the fall, as the two years differ significantly in this period. With only two years of data, it is not possible to determine which trend occurs more frequently and which is more of an anomaly or perhaps even an outlier. The more years that can be included in the analysis, the more reliable the average will be.
Other Indices
ℹ️Unlike trophic status, other water quality parameters that can be measured using satellite data—such as chlorophyll a or turbidity—are easier to interpret on a per-time-step basis. A list of available indices based on Landsat or Sentinel data is provided here, for example: https://awesome-ee-spectral-indices.readthedocs.io/en/latest/list.html#water
In addition to the NDTrI trend shown above, trends can be calculated, for example, for the chlorophyll a index based on the “B05” and “B04” bands, or for the turbidity index based on “B04” and “B03”. (It is not the scope of this demonstrator to further converte the indices into a chlorophyll a concentrations or turbidity values)

Normalized Difference Chlorophyl Index (B05 - B04)/(B05 + B04) [https://doi.org/10.1016/j.rse.2011.10.016] 
Normalized Differenc Turbidity Index (B04 - B03)/(B04 + B03) [https://doi.org/10.1016/j.rse.2006.07.012]
5) How to do a NDTrI cluster analysis
In Chapter 3, pixels are grouped based on their trophic value. It is also possible to group pixels according to their dynamics. To do this, the index must first be calculated for each pixel and time step. The dynamics for each pixel are then calculated.
nc <- lakeRS::open_netcdf(filePath = filePath)
imageIndex <- lakeRS::ndi_per_image(
nc = nc,
year = 2025,
bandNames = c("B05", "B02"),
monthFilter = 1:12
)
indexDynamic <- lakeRS::dynamic_per_pixel(
imageIndex = imageIndex,
nc = nc,
maxPixels = Inf,
returnSinglePixels = TRUE,
days_around_ma = 30
)Subsequently, the cluster analysis is performed based on the calculated pixel-wise dynamics. In addition to the number of clusters created, there is another important setting: correlate_first. This input variable determines whether the index values of the time series are used directly for the cluster analysis or whether a correlation analysis is first performed between the pixels. In the first case, the magnitude of the index has a significant influence on the result of the analysis (the classes are thus closer to the classification in Chapter 3). In the second case, pixels are sorted into different clusters depending on the dynamics. Here, the index value is irrelevant. However, this method is better suited for identifying temporal differences within the lake (e.g., due to temporary discharges).
Note: Cluster analysis can take a very long time for large lakes, especially if a correlation analysis is performed beforehand and many clusters (>3) are to be calculated. In the example of Lake Brates (approx. 190,000 pixels), it can take 10 to 20 minutes, depending on the computing power. If it is not essential to include all pixels in the cluster analysis (for example, for an initial overview), the number of pixels can be reduced beforehand using the dynamic_per_pixel() function.
pClusters <- lakeRS::pixel_clusters(
pixelDynamic = indexDynamic$pixelDynamics,
correlate_first = TRUE,
k = 4
)The results of the cluster analysis can be displayed as a dynamic or spatial distribution. If both plots are created, it is recommended to use the same colors for the clusters in both plots. Possible colors for displaying the clusters are listed in the “tenClusterColors” table, which is part of the “lakeRS” package. The number of clusters is limited to ten. If you want to work with more than 10 clusters, the colors must be passed manually to the plotting functions. Dynamic and spatial visualizations require different steps in data preparation.
# Dynamic Plot
# The available clusters
k_i <- sort(unique(pClusters$clusterVector))
# Create one dynamic table per cluster
DynamicStatList <- lapply(k_i, function(CLUSTER){
lakeRS::dynamic_per_pixel(
imageIndex = imageIndex,
nc = nc,
pixelFilter =
as.integer(
gsub(pattern = "p_", replacement = "", names(pClusters$clusterVector))
)[pClusters$clusterVector == CLUSTER],
returnSinglePixels = FALSE,
days_around_ma = 30)$lakeDynamic
})
# plot dynamic of all clusters
lakeRS::plot_dynamic(
v_averageList = lapply(DynamicStatList, function(x){x$q_0.5}),
df_q50List = lapply(DynamicStatList, function(x){data.frame(x$q_0.25, x$q_0.75)}),
lakeName = lakeName,
TSnames = paste0("C", k_i)
)
# the number of pixels per cluster
summary(as.factor(pClusters$clusterVector))
# 1 2 3 4
# 10972 1936 177185 402 Cluster 3 contains the most pixels and closely matches the average dynamic of the whole lake. The second-largest cluster, C1, is above C3 in the spring but has a significantly shorter peak in late summer. The other two clusters contain significantly fewer pixels. Their spatial distribution can be viewed using the map_layer() or plot_layer() functions. However, a layer with the dimensions of the data cube must first be created from the cluster vector.
clusterLayer <- get_clusterLayer(
clusterVector = pClusters$clusterVector,
nc = nc
)
lakeRS::map_layer(
ncLayer = clusterLayer,
nc = nc, lowerLimits = k_i,
classColors = lakeRS::tenClusterColors$color
)All clusters except C3 are located near the lake’s shore. Cluster 1 extends slightly further into the lake, particularly in the northern part. The visualization reveals a limitation of the clustering algorithm when applied to very homogeneous lakes. Small differences affecting many pixels are not detected; instead, the cluster analysis focuses on large differences affecting only a few pixels. These are typically exceptions, such as pixels near the shore. The causes of these varying dynamics can be diverse. For example, in shallow areas, sediment or vegetation growing on the sediment can influence the results.
Future versions will include hierarchical clustering, in which only clusters above a certain minimum size can be broken down into further clusters.
Cluster analysis wihtout correlation
pClusters <- lakeRS::pixel_clusters( pixelDynamic = indexDynamic$pixelDynamics, correlate_first = FALSE, k = 4 ) k_i <- sort(unique(pClusters$clusterVector)) DynamicStatList <- lapply(k_i, function(CLUSTER){ lakeRS::dynamic_per_pixel( imageIndex = imageIndex, nc = nc, pixelFilter = as.integer( gsub(pattern = "p_", replacement = "", names(pClusters$clusterVector)) )[pClusters$clusterVector == CLUSTER], returnSinglePixels = FALSE, days_around_ma = 30)$lakeDynamic }) summary(as.factor(pClusters$clusterVector)) # 1 2 3 4 # 16915 93744 71337 8499 lakeRS::plot_dynamic( v_averageList = lapply(DynamicStatList, function(x){x$q_0.5}), df_q50List = lapply(DynamicStatList, function(x){data.frame(x$q_0.25, x$q_0.75)}), lakeName = "Brates Lake", TSnames = paste0("C", k_i) ) clusterLayer <- get_clusterLayer( clusterVector = pClusters$clusterVector, nc = nc ) lakeRS::map_layer( ncLayer = clusterLayer, nc = nc, lowerLimits = k_i, classColors = lakeRS::tenClusterColors$color )
6) SCL Layer overview and hydromorphology analysis
There may be unexpected results in certain areas of the lake or at certain points in the time series. This may be due to errors in scene classification or to poor weather conditions (clouds or snow) over an extended period. Or it may be due to the surrounding topography, which consistently casts shadows. In this case, it makes sense to take a closer look at the SCL layer, which forms the basis for pixel selection. An overview of the SCL band output is included as a table in the lakeRS package as data frame sceneIDs.
For each image, coverage can be calculated for water, clouds, snow or shadows. The results can then be plotted over time. First, the SCL data is loaded and evaluated for each pixel and time point.
nc <- lakeRS::open_netcdf(filePath = filePath)
# General information on image and scene classification frequency
# scene argument can be "clouds", "water", "snow" or "shadows"
xScene <- lakeRS::nc_scene_per_image(nc = nc, scene = "clouds")
lakeRS::plot_scene_coverage(
vDate = xScene$date,
vCoverage = xScene$coverage
)
The figures show that conditions are mostly cloudy starting around day 310. Consequently, very few pixels were available for analysis in November and December. This must be taken into account when interpreting the long NDTrI peak described in Chapter 4.
The SCL layer can also be summarized spatially. The input variables lowerLimits and classColors should be adjusted so that they can accurately represent the frequency distribution of the scene.
The calculation of the water scene proportion and the definition of allowed disturbances
Each pixel is classified into one of the 11 scenes: No Data, Defective, Topo Shadows, Cloud Shadows, Vegetation, Bare Soil, Water, Unclassified, Cloud Medium, Cloud High, Thin Cirrus, Snow or Ice.
A pixel of a lake is expected to be classified as water unless there are valid reasons, such as clouds, snow or ice covering the lake, or topographic shadows. Basically, these are all exceptions that do not rule out the presence of water at this location. These exceptions are called allowed disturbances. They are highlighted in the list above with a green background and are not taken into account when calculating the water coverage threshold. Thus, the water scene proportion is actually the ratio of water scenes to the sum of water, vegetation, bare soil and defective scenes.
# Overview of SCL IDs
lakeRS::sceneIDs
sceneProportion <- lakeRS::waterscene_proportion(
scl_image = lakeRS::load_BandLayer(nc = nc, band = "SCL")$band
)
lakeRS::map_layer(
ncLayer = sceneProportion$water,
nc = nc,
lowerLimits = c(0,0.1, 0.3, 0.5, 0.7, 0.8, 0.9),
classColors = c("white","gray80", "gray60", "chartreuse1","chartreuse4",
"dodgerblue", "dodgerblue4"),
legendTitle = "Water Classification Quality"
)Everything shown here in light blue and dark blue was selected using the default pixel selection criterion (>80% water scenes). For index calculation, the use of a quality criterion for selecting a pixel is very important.
The SCL band can also be used to describe the hydromorphology of water bodies and their changes. While pixels in the center of a lake are almost always identified as water, this is less common for pixels near the shoreline. On the other side, some pixels south of the lake are occasionally classified as water. Either these areas are periodically submerged, or there is sporadic interference of wavelength reflactance leading to incorrect classification.
waterPoportionGroups <- hist(
x = sceneProportion$water[sceneProportion$water > 0],
breaks = 10,
col = colorRampPalette(colors = c("white", "blue"))(10),
main = "Water Identification Histogramm", ylab = "Pixels",
xlab = "Proportion of SCL Water Identification"
)
data.frame(
"WaterPoportion" = waterPoportionGroups$breaks[-1],
"n" = waterPoportionGroups$counts
)A histogram of the pixels defined by a percentage classified as water allows us to estimate how many pixels represent permanent water and how many represent only sporadic water. It can be assumed that the right-hand bar, ranging from 90% to 100%, represents permanent water. There are 188,440 pixels in this category. An additional 2,068 pixels are identified as water 80% to 90% of the time and can thus be considered very likely to represent permanent water. A total of 25,622 pixels are identified as water less frequently. The probability that they represent water only temporarily increases as the proportion of SCL water identification decreases. The pixels can be grouped together.
| Group Name | Proportion of SCL water Identification | Pixels |
| Definitely always water | > 90% | 188,440 (1884 ha) |
| Very likely always water | 80% - 90% | 2,068 (21 ha) |
| Water identification sometimes disturbed | 20 - 80% | 10,448 (105 ha) |
| Likely periodically no water | < 20% | 15,174 (152 ha) |
From all the pixels combined, a weighted total water area can be calculated that combines permanent and temporary water bodies. To do this, each pixel representing 100 m² is multiplied by the SCL water identification percentage, and the results are then summed.
sum(sceneProportion$water * 100, na.rm = TRUE) / 10000 # m/haFor Brates Lake, this results in a weighted total water area of 1,962 ha in 2025, which is slightly less than the 2,120 ha cited in the theoretical background chapter. Both the weighted total water area and the individual groups can be compared over the years to identify trends in water availability and morphological developments.
In addition to the water layer, all other scenes can also be plotted. As a rule, the input variable lowerLimits must then be shifted downward. Below are two examples for vegetation (SCL = 4) and unclassified (SCL = 7). The drainage north of the lake often cannot be classified using the SCL algorithm.
lakeRS::map_layer(
ncLayer = sceneProportion$allScenes[[5]],
nc = nc,
lowerLimits = c(0,0.02,0.05,0.1,0.15,0.2,0.25,0.3,0.4,0.5,1) ,
classColors = c("white","gray80","gray60", "aquamarine1", "aquamarine3",
"chartreuse1", "chartreuse3", "darkgreen", "goldenrod1",
"chocolate1", "orangered1"),
legendTitle = paste0("Proportion of '", lakeRS::sceneIDs$name[5],"'")
)7) Including Catchment Properties
The water quality of a lake is strongly influenced by land use, material inputs, hydrological flow paths, soil and slope conditions, and the distance of polluting land uses from the water body. To capture agricultural areas in the catchment, the lake’s surface catchment first need to be delineated, for example using digital elevation models, existing hydrological datasets, or official catchment data. Land-cover and land-use data, such as CORINE Land Cover, Copernicus Land Monitoring products, or national agricultural datasets, can then be intersected with this catchment area.






















