[javascript] dawdw
Viewer
*** This page was generated with the meta tag "noindex, nofollow". This happened because you selected this option before saving or the system detected it as spam. This means that this page will never get into the search engines and the search bot will not crawl it. There is nothing to worry about, you can still share it with anyone.
- ///////////////////////////////////
- // Define user inputs
- var farmName = prompt("Enter your farm name:");
- var diversifyYear = parseInt(prompt("Enter the year of diversification:"));
- var treeSpeciesCount = parseInt(prompt("Enter the number of tree species on the farm:"));
- // Create a map to display your results
- var map = ui.Map();
- map.setCenter(-73.76354, 42.14825, 24);
- map.setOptions({ style: 'SATELLITE' });
- // User inputs for each tree species
- var treeSpeciesData = [];
- var totalNumTrees = 0; // Initialize total number of trees
- for (var i = 0; i < treeSpeciesCount; i++) {
- var speciesName = prompt("Enter tree species name:");
- var plantingDate = prompt("Enter planting date for " + speciesName + ":");
- var numTrees = parseInt(prompt("Enter the number of trees planted for " + speciesName + ":"));
- treeSpeciesData.push({
- name: speciesName,
- datePlanted: plantingDate,
- numTrees: numTrees
- });
- totalNumTrees += numTrees; // Update total number of trees
- }
- var farmBoundary = geometry;
- // Calculate farm area
- // Assuming you have farmBoundary defined elsewhere
- var mergedFarmBoundary = farmBoundary.dissolve(1);
- // Use an error margin of 1 (you can adjust this value as needed)
- // Calculate the area of the merged farm boundary in hectares with 2 decimal places
- var farmArea = ee.Number(mergedFarmBoundary.area().divide(10000)).format('%.2f'); // in hectares (as a string with 2 decimal places)
- // Calculate Shannon Index
- var shannonIndexValue = 0; // Initialize Shannon Index value
- for (var i = 0; i < treeSpeciesCount; i++) {
- var relativeAbundance = treeSpeciesData[i].numTrees / totalNumTrees; // Calculate p_i
- if (relativeAbundance > 0) {
- shannonIndexValue -= relativeAbundance * Math.log(relativeAbundance); // Calculate p_i ln(p_i)
- }
- }
- shannonIndexValue = shannonIndexValue.toFixed(4); // Round Shannon Index to 4 decimal places
- // Calculate Simpson Index
- var simpsonIndexValue = 0; // Initialize Simpson Index value
- for (var i = 0; i < treeSpeciesCount; i++) {
- var relativeAbundance = treeSpeciesData[i].numTrees / totalNumTrees; // Calculate p_i
- simpsonIndexValue += relativeAbundance * (relativeAbundance - 1); // Calculate Σ(ni (ni - 1))
- // Calculate Σ(ni (ni - 1))
- }
- simpsonIndexValue = (1 / simpsonIndexValue).toFixed(4); // Calculate Simpson Index as 1 / Σ(ni * (ni - 1)) and round to 4 decimal places
- // Descriptions of Simpson Index values
- var simpsonDescription = "";
- if (simpsonIndexValue < 0.7) {
- simpsonDescription = "Low Diversity (Dominance): When the Simpson Index is close to 0, it indicates low diversity, which means that one or a few species dominate the community. In ecological terms, this might suggest a lack of species richness or a situation where a single species predominates.";
- } else if (simpsonIndexValue <= 0.7 && simpsonIndexValue < 1) {
- simpsonDescription = "Medium Diversity: A Simpson Index value between 0 and 0.7 may be considered a moderate level of diversity. It suggests that there is some level of evenness among the species present, but one or a few species may still dominate to some extent.";
- } else {
- simpsonDescription = "High Diversity (Evenness): When the Simpson Index is close to 1, it suggests high diversity and evenness among species. In such cases, there is a relatively equal distribution of individuals among different species, and no single species dominates the community.";
- }
- // Calculate Species Richness
- var speciesRichnessValue = treeSpeciesCount;
- // Convert the diversifyYear to a timestamp in milliseconds
- var diversifyYearMillis = ee.Date.fromYMD(diversifyYear, 1, 1).millis();
- // Filter Sentinel-2 imagery by date and location
- var sentinelCollection = ee.ImageCollection('COPERNICUS/S2')
- .filterBounds(mergedFarmBoundary)
- .filterDate(diversifyYearMillis, Date.now()) // Use the converted timestamp
- .filterMetadata('CLOUDY_PIXEL_PERCENTAGE', 'less_than', 20); // Optionally, filter by cloud cover percentage
- // Print the number of images in the collection to check
- print("Number of Images in Collection:", sentinelCollection.size());
- // Check the first image's properties to verify 'system:time_start' is available
- var firstImage = sentinelCollection.first();
- print("First Image Properties:", firstImage);
- // Calculate NDVI for each image in the collection
- var ndviCollection = sentinelCollection.map(function (image) {
- var ndvi = image.normalizedDifference(['B8', 'B4']); // Calculate NDVI using Sentinel-2 bands B8 (NIR) and B4 (Red)
- return ndvi.set('system:time_start', image.get('system:time_start'));
- });
- // Calculate the mean NDVI for the farm area
- var meanNdvi = ndviCollection.mean()
- .clip(mergedFarmBoundary); // Clip to the farm boundary
- // Visualize the NDVI
- map.addLayer(meanNdvi, {
- min: -1,
- max: 1,
- palette: ['blue', 'white', 'green']
- }, 'Mean NDVI');
- // Display the Shannon Index as a text label on the map
- var shannonIndexLabel = ui.Label('Shannon Index: ' + shannonIndexValue);
- shannonIndexLabel.style().set({
- position: 'top-right',
- fontWeight: 'bold',
- fontSize: '16px',
- padding: '10px'
- });
- map.add(shannonIndexLabel);
- // Descriptions of Shannon Index values
- var shannonDescription = "";
- if (shannonIndexValue < 1) {
- shannonDescription = "Low Diversity: A low Shannon Index value (close to 0) indicates low diversity, which suggests that one or a few species dominate the community, and there is limited species richness. This is similar to the interpretation for the Simpson Index.";
- } else if (shannonIndexValue >= 1 && shannonIndexValue <= 2) {
- shannonDescription = "Medium Diversity: A Shannon Index value between 1 and 2 may be considered a moderate level of diversity. It suggests that there is some diversity in the community, but one or a few species may still be more abundant or dominant.";
- } else {
- shannonDescription = "High Diversity: A high Shannon Index value (greater than 2) suggests high diversity with evenness among species. In this case, there is a wide variety of species present, and they are relatively evenly distributed in terms of abundance.";
- }
- // Compute Normalized Difference Vegetation Index over S2-L2 product.
- // Define the start and end dates for NDVI calculation (from diversifyYear to today)
- var startDate = ee.Date.fromYMD(diversifyYear, 1, 1);
- var endDate = ee.Date(Date.now());
- // Step 1: Access the Sentinel-2 Level-2A data and filter it for all the images within the geometry's boundaries.
- var s2a = ee.ImageCollection('COPERNICUS/S2_SR')
- .filterBounds(mergedFarmBoundary)
- .filterDate(startDate, endDate) // Filter by the specified date range
- .select('B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8', 'B8A', 'B9', 'B11', 'B12')
- .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 10));
- // Print your ImageCollection to your console tab to inspect it
- print(s2a, 'Image Collection');
- // Adjust the map view to be approximately 2x the size of farmBoundary
- map.centerObject(mergedFarmBoundary, 13); // You can adjust the zoom level (e.g., change 13 to another value) to control the zoom level
- // Step 2: Create a single Image by reducing by Median and clip it to the extent of the geometry
- var s2a_median = s2a.median()
- .clip(mergedFarmBoundary);
- // Print your Image to your console tab to inspect it
- print(s2a_median, 'Median reduced Image');
- // Add your Image as a map layer
- var visParams = {
- 'min': 400,
- 'max': [4000, 3000, 3000],
- 'bands': 'B8,B4,B3'
- };
- // Map.addLayer(s2a_median, visParams, 'S2 Median Image');
- // Step 3: Calculate the NDVI
- var ndvi_3 = s2a_median.normalizedDifference(['B8', 'B4'])
- .rename('NDVI');
- var new_ndvi_3 = s2a.map(function (img) {
- var date = img.get("system:time_start");
- var ndvi_3 = img.normalizedDifference(['B8', 'B4'])
- .rename('NDVI');
- return ndvi_3.set("system:time_start", date);
- });
- // Plot a time series of NDVI at a single location.
- Map.centerObject(mergedFarmBoundary, 11);
- Map.addLayer(ndvi_3, {
- bands: 'NDVI',
- min: 0.1,
- max: 0.9,
- palette: ['white', 'green']
- }, 'NDVI Mosaic');
- print(ndvi_3);
- var S2Chart = ui.Chart.image.series(new_ndvi_3, mergedFarmBoundary, ee.Reducer.mean(), 250)
- //.setChartType('line')
- .setOptions({
- title: 'Sentinel-2 NDVI Time Series at ROI',
- trendlines: {
- 0: { color: 'CC0000' }
- },
- lineWidth: 1,
- pointSize: 3,
- });
- print(S2Chart);
- // NDVI CODE ENDS HERE
- // Convert the diversifyYear to a timestamp in milliseconds
- var diversifyYearMillis = ee.Date.fromYMD(diversifyYear, 1, 1).millis();
- // Filter Sentinel-2 imagery by date and location
- var sentinelCollection = ee.ImageCollection('COPERNICUS/S2')
- .filterBounds(mergedFarmBoundary)
- .filterDate(diversifyYearMillis, Date.now()) // Use the converted timestamp
- .filterMetadata('CLOUDY_PIXEL_PERCENTAGE', 'less_than', 20); // Optionally, filter by cloud cover percentage
- // Define the GIF parameters
- var gifParams = {
- 'region': mergedFarmBoundary.bounds(1).buffer(0.1), // Minimum bounding rectangle with a 10% buffer
- 'dimensions': 800,
- 'crs': 'EPSG:3857',
- 'framesPerSecond': 1,
- 'format': 'gif'
- };
- // Create a GIF by taking monthly snapshots
- var gif = sentinelCollection.map(function (image) {
- var date = image.date();
- return image.visualize({
- min: 0,
- max: 3000,
- bands: ['B4', 'B3', 'B2']
- }).set('system:time_start', date);
- });
- // Export the GIF to Google Drive
- Export.video.toDrive({
- collection: gif,
- description: 'MyGifAnimation',
- dimensions: 800,
- framesPerSecond: 1,
- region: mergedFarmBoundary.bounds(1).buffer(0.1).getInfo().coordinates
- });
- // Display the GIF on the map
- // var gifImage = ee.ImageCollection(gif).toBands().rename(['R', 'G', 'B']);
- // Map.addLayer(gifImage, {bands: ['R', 'G', 'B'], min: 0, max: 3000}, 'GIF Image');
- // Create a list of image properties
- var imagePropertiesList = sentinelCollection.map(function(image) {
- var date = image.date();
- return ee.Feature(null, {
- 'Image Date': date.format("YYYY-MM-dd"),
- // Add more properties or information you want to include
- });
- });
- // Convert the list of properties to a feature collection and print
- var propertyCollection = ee.FeatureCollection(imagePropertiesList);
- print("Image Properties:", propertyCollection);
- // Display outputs
- print("Farm Name: " + farmName);
- print("Diversification Year: " + diversifyYear);
- print("Total Farm Area (Hectares): " + farmArea.getInfo()); // Display the farm area as a single number
- print("Shannon Index: " + shannonIndexValue);
- print("Simpson Index: " + simpsonIndexValue);
- print("Species Richness: " + speciesRichnessValue);
- print("Simpson Index Description: " + simpsonDescription);
- print("Shannon Index Description: " + shannonDescription);
Editor
You can edit this paste and save as new: