Practical Course 14

Mangrove Loss Detection with GFC and DeepSeek

Learn to detect mangrove loss in North Morocco using the Hansen Global Forest Change dataset and DeepSeek AI for enhanced analysis.
North Morocco ~2 hours Master - Climate Change and GeoAI
Dataset: UMD/hansen/global_forest_change_2022_v1_10 Hansen Global Forest Change v1.10 (2000-2022)

📖 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
MangroveMangrove ForestSalt-tolerant coastal woodland ecosystems.
DeforestationDeforestationThe clearing of forests for other land uses.
Remote SensingRemote SensingAcquiring information about an object or area from a distance.
GEEGoogle Earth EngineA cloud-based platform for geospatial analysis.
GFCGlobal Forest ChangeA dataset mapping global forest cover change from 2000 to present.
BandSpectral BandA specific range of wavelengths in the electromagnetic spectrum.
ThresholdThresholdA value used to separate data into different categories.
ClassificationImage ClassificationThe process of assigning pixels to different categories based on their spectral characteristics.
PixelPicture ElementThe smallest addressable element in an image.
Cloud MaskingCloud MaskingThe process of removing clouds from satellite imagery.
Time SeriesTime Series AnalysisA sequence of data points indexed in time order.
DeepSeekDeepSeek LLMLarge Language Model for code generation and analysis.
Image CollectionImage CollectionA stack or time series of images in GEE.
Region of InterestROIA specific geographic area selected for analysis.

Contents

  1. Introduction to Mangroves and Deforestation
  2. Introduction to Hansen GFC Data
  3. Setting up Google Earth Engine
  4. Visualizing Forest Cover
  5. Detecting Forest Loss
  6. Using DeepSeek for Refinement
  7. Analyzing Mangrove Loss in North Morocco
  8. Validating Results
  9. Exporting Results
  10. Further Exploration
1
Introduction
10 min

Mangrove forests are vital ecosystems that provide numerous benefits. This course will guide you through the process of detecting mangrove loss using the Hansen Global Forest Change dataset in Google Earth Engine. You will learn how to use DeepSeek AI to refine your analysis and gain deeper insights into deforestation patterns in North Morocco.

GEE Asset ID
UMD/hansen/global_forest_change_2022_v1_10
Dataset Name
Hansen Global Forest Change v1.10 (2000-2022)
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 Mangrove Loss Detection with GFC 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 Course14_Mangrove Loss Detection with GFC 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
Generate a Google Earth Engine script to detect mangrove forest loss in the North Morocco region (Rif Mountains and Middle Atlas) between 2010 and 2020 using the 'UMD/hansen/global_forest_change_2022_v1_10' dataset. Focus on areas with treecover2000 greater than 30%. Calculate the total area of mangrove loss in hectares. Use the 'lossyear' band to identify the year of loss. Create a map visualization showing the location of mangrove loss. Use Landsat 8 imagery to validate the mangrove loss. Provide code comments explaining each step.
✨
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 Hansen GFC 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 Hansen GFC Data
// Define the region of interest (North Morocco).
var roi = ee.Geometry.Rectangle([-5.5, 33.5, -2.0, 35.5]);

// Import the Hansen Global Forest Change dataset.
var gfc2022 = ee.Image('UMD/hansen/global_forest_change_2022_v1_10');

// Select the tree cover, loss year, and gain bands.
var treecover2000 = gfc2022.select('treecover2000');
var lossyear = gfc2022.select('lossyear');
var gain = gfc2022.select('gain');

// Filter the data to areas with tree cover greater than 30% in 2000.
var treecoverThreshold = 30;
var initialCover = treecover2000.gte(treecoverThreshold);

// Filter the lossyear data to the period between 2010 and 2020 (lossyear values are 0-indexed).
var lossStartYear = 10; // Represents 2010
var lossEndYear = 20;   // Represents 2020
var loss = lossyear.gte(lossStartYear).and(lossyear.lte(lossEndYear)).and(initialCover);
🔑
Beginner note: This code block imports the Hansen GFC dataset and filters it to focus on areas with significant tree cover in 2000 and loss between 2010 and 2020. `ee.Geometry.Rectangle` defines the study area. `ee.Image` imports the GFC dataset. `select` chooses specific bands. `gte` and `lte` are used to filter data based on thresholds. `and` combines the filters.

5
Visualize Forest Loss
10 min

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

Visualize Forest Loss
// Create a visualization of the forest loss.
var lossVisualization = {
  palette: ['FF0000'], // Red color for loss
  min: 0,
  max: 1
};

// Add the loss layer to the map.
Map.addLayer(loss.clip(roi), lossVisualization, 'Forest Loss 2010-2020');

// Calculate the area of forest loss in hectares.
var lossAreaImage = loss.multiply(ee.Image.pixelArea());
var lossArea = lossAreaImage.reduceRegion({
  reducer: ee.Reducer.sum(),
  geometry: roi,
  scale: 30, // Resolution of the Hansen GFC data
  maxPixels: 1e13
});

// Print the area of forest loss to the console.
print('Area of Forest Loss (Hectares):', lossArea.get('lossyear'));
🔑
Beginner note: This block visualizes the detected forest loss and calculates the total area of loss. `palette` sets the color for the visualization. `Map.addLayer` adds the loss layer to the Earth Engine map. `ee.Image.pixelArea` calculates the area of each pixel. `reduceRegion` calculates the sum of the loss area within the ROI. `ee.Reducer.sum` specifies that we want the sum of the pixel areas. `print` displays the result in the console.

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 loss image to Google Drive.
Export.image.toDrive({
  image: loss.clip(roi),
  description: 'forest_loss_2010_2020',
  folder: 'GEE_Exports',
  scale: 30,
  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.

Change the Time Period

  1. Modify the `lossStartYear` and `lossEndYear` variables to analyze a different time period, such as 2005-2015.
  2. Observe how the area of detected forest loss changes.

Adjust the Tree Cover Threshold

  1. Change the `treecoverThreshold` variable to a different value (e.g., 50 or 70).
  2. Examine how this affects the amount of forest loss detected.

Explore Different Visualization Palettes

  1. Modify the `lossVisualization` palette to use different colors.
  2. Experiment with different color combinations to highlight the forest loss more effectively.

Calculate Loss by Year

  1. Modify the code to calculate the area of forest loss for each individual year between 2010 and 2020.
  2. Display the results in a chart or table.

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 IDUMD/hansen/global_forest_change_2022_v1_10
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 14 - Mangrove Loss Detection with GFC and DeepSeek | GeoAI for Climate Change | Dr. Ayoub Lahlouh | UM6P/CUS | 2025/2026