Practical Course 11

Water Quality Monitoring with Sentinel-2 and DeepSeek

Learn to assess water quality in North Morocco using Sentinel-2 satellite imagery and the DeepSeek AI model within Google Earth Engine.
North Morocco ~2 hours Master - Climate Change and GeoAI
Dataset: COPERNICUS/S2_SR Sentinel-2 Surface Reflectance

📖 Key Terms for Beginners

Before starting, make sure you understand these terms. They appear throughout all code blocks in this course.

TermFull NameWhat it means in simple words
TurbidityTurbidityA measure of water cloudiness caused by suspended particles.
Chlorophyll-aChlorophyll-aA pigment found in plants and algae, used as an indicator of phytoplankton biomass.
NDWINormalized Difference Water IndexAn index used to identify water bodies.
EutrophicationEutrophicationExcessive richness of nutrients in a lake or other body of water, frequently due to runoff from the land, which causes a dense growth of plant life and death of animal life from lack of oxygen.
ReflectanceReflectanceThe proportion of incident light or radiation that is reflected by a surface.
Sentinel-2Sentinel-2An Earth observation mission from the Copernicus Programme that systematically acquires optical imagery at high spatial resolution.
GEEGoogle Earth EngineA cloud-based platform for planetary-scale geospatial analysis.
AIArtificial IntelligenceThe theory and development of computer systems able to perform tasks that normally require human intelligence.
Deep LearningDeep LearningA type of machine learning based on artificial neural networks with multiple layers.
Water Quality IndexWater Quality IndexA single number that represents the overall water quality at a certain location and time, based on several water quality parameters.
Remote SensingRemote SensingThe science of obtaining information about an object or area from a distance, typically from aircraft or satellites.
Spectral BandsSpectral BandsSpecific ranges of wavelengths in the electromagnetic spectrum that are used to collect data in remote sensing.

Contents

  1. Introduction to Water Quality Monitoring
  2. Sentinel-2 Data Access in GEE
  3. NDWI Calculation
  4. Visualizing Water Bodies
  5. Introduction to DeepSeek AI
  6. DeepSeek Prompt Engineering
  7. Water Quality Parameter Estimation with DeepSeek
  8. Accuracy Assessment
  9. Mapping Water Quality
  10. Exporting Results
1
Introduction
10 min

Water quality is crucial for human health and ecosystem well-being. This course introduces the use of Sentinel-2 satellite imagery and the DeepSeek AI model within Google Earth Engine to monitor water quality in North Morocco. You will learn to process satellite data, calculate water indices, and leverage AI for parameter estimation.

GEE Asset ID
COPERNICUS/S2_SR
Dataset Name
Sentinel-2 Surface Reflectance
Study Area
North Morocco
AI Tool
DeepSeek (free, no API key needed)
🌍
What you will build: By the end of this course you will have a working GEE script that analyzes Water Quality Monitoring with Sentinel-2 and DeepSeek, computes statistics, visualizes results on an interactive map, and exports data to Google Drive.

2
Setup: GEE + DeepSeek
5 min

You need two browser tabs open side by side throughout this course.

1
Open chat.deepseek.com -- free account, no API key needed
2
Open code.earthengine.google.com in a second tab
3
Create a new GEE script named Course11_Water Quality Monitoring with Sentinel-2 and DeepSeek
💡
Workflow: Write a prompt in DeepSeek describing your task with exact dataset IDs and requirements. Copy the generated GEE JavaScript. Paste into GEE code editor. Click Run. Inspect results. Iterate.

3
Crafting the DeepSeek Prompt
15 min

The prompt is the core skill of this course. A good prompt includes the exact dataset ID, band names, study area coordinates, dates, preprocessing steps, and desired outputs.

📋 Main Prompt -- copy and paste this into DeepSeek
Estimate Chlorophyll-a and Turbidity levels in the Al Wahda Dam and surrounding rivers in the Rif Mountains and Middle Atlas of North Morocco, using Sentinel-2 satellite images from June 1, 2023 to September 30, 2023. Consider bands B2 (Blue), B3 (Green), B4 (Red), and B8 (NIR). Output the Chlorophyll-a and Turbidity values as separate GeoTIFF images, with Chlorophyll-a in mg/L and Turbidity in NTU. Include a confidence score for each prediction.
✨
After pasting the prompt: Wait 20-30 seconds for DeepSeek to generate the full GEE script. Copy the entire code block it produces. If the output is cut short, type "Continue the code" to get the rest.

4
Import and Filter Sentinel-2 Data
10 min

Paste the following code into your GEE code editor and click Run. Read the beginner notes below to understand what each line does.

Import and Filter Sentinel-2 Data
// Define region of interest (Rif Mountains and Middle Atlas, Morocco)
var roi = ee.Geometry.Rectangle([-5.5, 34, -3.5, 35]);

// Filter Sentinel-2 SR data for the specified period and region
var dataset = ee.ImageCollection('COPERNICUS/S2_SR')
                  .filterDate('2023-06-01', '2023-09-30')
                  .filterBounds(roi)
                  .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 20));

// Print the number of images found
print('Number of Sentinel-2 images:', dataset.size());

// Function to mask clouds using the QA60 band
var maskS2clouds = function(image) {
  var qa = image.select('QA60');
  // Bits 10 and 11 are clouds and cirrus, respectively.
  var cloudBitMask = 1 << 10;
  var cirrusBitMask = 1 << 11;
  // Both flags should be set to zero, indicating clear conditions.
  var mask = qa.bitwiseAnd(cloudBitMask).eq(0)
      .and(qa.bitwiseAnd(cirrusBitMask).eq(0));
  return image.updateMask(mask).divide(10000);
};
🔑
Beginner note: This code block first defines a region of interest (ROI) encompassing the Rif Mountains and Middle Atlas in Morocco. Then, it filters the Sentinel-2 Surface Reflectance (SR) dataset for images acquired between June 1 and September 30, 2023, within the defined ROI, and with less than 20% cloud cover. The number of images found is printed to the console. Finally, a function `maskS2clouds` is defined to mask clouds using the QA60 band of Sentinel-2, dividing the remaining reflectance values by 10000 to scale them between 0 and 1.

5
NDWI Calculation and Visualization
10 min

Add this block after the previous code. It continues the analysis with additional processing and visualization.

NDWI Calculation and Visualization
// Apply cloud masking
var maskedDataset = dataset.map(maskS2clouds);

// Function to calculate NDWI
var calculateNDWI = function(image) {
  return image.normalizedDifference(['B3', 'B8']).rename('NDWI');
};

// Calculate NDWI for each image in the collection
var ndwiCollection = maskedDataset.map(calculateNDWI);

// Create a composite image (median NDWI over the time period)
var ndwiComposite = ndwiCollection.median();

// Visualization parameters for NDWI
var ndwiVisParams = {
  min: -1,  
  max: 1,  
  palette: ['red', 'white', 'blue']
};

// Add the NDWI composite to the map
Map.addLayer(ndwiComposite, ndwiVisParams, 'NDWI Composite');

// Center the map on the region of interest
Map.centerObject(roi, 9);
🔑
Beginner note: This code block applies the cloud masking function to the Sentinel-2 dataset. It then defines a function `calculateNDWI` to compute the Normalized Difference Water Index (NDWI) using the green (B3) and NIR (B8) bands. The NDWI is calculated for each image in the collection, and a median NDWI composite is created to represent the typical NDWI value over the specified time period. Finally, the NDWI composite is added to the map with a color palette ranging from red (low NDWI) to blue (high NDWI), and the map is centered on the ROI.

6
Export Results to Google Drive
5 min

Add this block at the end of your script to export the final map as a GeoTIFF to your Google Drive. After clicking Run, go to the Tasks tab in GEE and click Run next to each export task.

Export to Google Drive
// Export the Chlorophyll-a estimation to Google Drive
Export.image.toDrive({
  image: /* Chlorophyll-a image from DeepSeek result */,
  description: 'Chlorophyll_a_Estimation',
  folder: 'GEE_Exports',
  scale: 10, // Adjust scale as needed
  region: roi,
  maxPixels: 1e13
});

// Export the Turbidity estimation to Google Drive
Export.image.toDrive({
  image: /* Turbidity image from DeepSeek result */,
  description: 'Turbidity_Estimation',
  folder: 'GEE_Exports',
  scale: 10, // Adjust scale as needed
  region: roi,
  maxPixels: 1e13
});
🔑
Beginner note -- Export.image.toDrive(): This function does not export immediately. It creates a task in the GEE Tasks tab that you must manually start by clicking Run. The file will appear in your Google Drive folder (GEE_Courses) as a GeoTIFF that you can open in QGIS or ArcGIS.

7
Exercises Using DeepSeek Prompts
Homework

Use DeepSeek to extend the script for each exercise below. Write a follow-up prompt describing what you want to add, then copy the generated code and paste it into your GEE script.

Explore Different Time Periods

  1. Modify the start and end dates to analyze water quality changes across different seasons.
  2. Observe how the NDWI values change and relate them to potential environmental factors.

Calculate Other Water Indices

  1. Implement the Normalized Difference Vegetation Index (NDVI) and Enhanced Vegetation Index (EVI).
  2. Compare the spatial patterns of NDVI, EVI, and NDWI to understand the relationship between vegetation and water bodies.

Refine Cloud Masking

  1. Experiment with different cloud masking thresholds to improve the quality of the analysis.
  2. Investigate the impact of cloud cover on the accuracy of water quality parameter estimation.

Apply DeepSeek to other water bodies

  1. Change the ROI to focus on a different lake or river in Morocco.
  2. Run the DeepSeek prompt and compare the results with existing water quality data, if available.

8
Prompt Engineering Tips
Reference

To get the best results from DeepSeek for GEE tasks, always include these elements in your prompts:

ElementExample
Exact dataset IDCOPERNICUS/S2_SR
Band names"select band 'B4' for red, 'B8' for NIR"
Study area"rectangle [-6.5, 33.0, -1.5, 36.0] North Morocco"
Date range"filter from 2020-01-01 to 2023-12-31"
Output format"print area in hectares, add a legend, export to Drive"
Error fixing"The code gives error X. Please fix it."
Iteration"Add a time series chart for each year 2018-2023"
🧠
Best practice: Start with the main prompt, run the code, then send follow-up prompts to add features one at a time. This gives you cleaner, more reliable code than asking for everything at once.
Course 11 - Water Quality Monitoring with Sentinel-2 and DeepSeek | GeoAI for Climate Change | Dr. Ayoub Lahlouh | UM6P/CUS | 2025/2026