[javascript] dawdw

Viewer

  1. ///////////////////////////////////
  2.  
  3. // Define user inputs
  4. var farmName = prompt("Enter your farm name:");
  5. var diversifyYear = parseInt(prompt("Enter the year of diversification:"));
  6. var treeSpeciesCount = parseInt(prompt("Enter the number of tree species on the farm:"));
  7.  
  8.  
  9.  
  10. // Create a map to display your results
  11. var map = ui.Map();
  12. map.setCenter(-73.76354, 42.14825, 24);
  13.  
  14.  
  15.  
  16. map.setOptions({ style: 'SATELLITE' });
  17.  
  18.  
  19.  
  20. // User inputs for each tree species
  21. var treeSpeciesData = [];
  22. var totalNumTrees = 0; // Initialize total number of trees
  23.  
  24.  
  25.  
  26. for (var i = 0; i < treeSpeciesCount; i++) {
  27. var speciesName = prompt("Enter tree species name:");
  28. var plantingDate = prompt("Enter planting date for " + speciesName + ":");
  29. var numTrees = parseInt(prompt("Enter the number of trees planted for " + speciesName + ":"));
  30. treeSpeciesData.push({
  31. name: speciesName,
  32. datePlanted: plantingDate,
  33. numTrees: numTrees
  34. });
  35. totalNumTrees += numTrees; // Update total number of trees
  36. }
  37.  
  38. var farmBoundary = geometry;
  39.  
  40.  
  41.  
  42. // Calculate farm area
  43. // Assuming you have farmBoundary defined elsewhere
  44. var mergedFarmBoundary = farmBoundary.dissolve(1);
  45.  // Use an error margin of 1 (you can adjust this value as needed)
  46.  
  47.  
  48.  
  49. // Calculate the area of the merged farm boundary in hectares with 2 decimal places
  50. var farmArea = ee.Number(mergedFarmBoundary.area().divide(10000)).format('%.2f'); // in hectares (as a string with 2 decimal places)
  51.  
  52.  
  53.  
  54. // Calculate Shannon Index
  55. var shannonIndexValue = 0; // Initialize Shannon Index value
  56.  
  57.  
  58.  
  59. for (var i = 0; i < treeSpeciesCount; i++) {
  60. var relativeAbundance = treeSpeciesData[i].numTrees / totalNumTrees; // Calculate p_i
  61. if (relativeAbundance > 0) {
  62. shannonIndexValue -= relativeAbundance * Math.log(relativeAbundance); // Calculate p_i ln(p_i)
  63. }
  64. }
  65. shannonIndexValue = shannonIndexValue.toFixed(4); // Round Shannon Index to 4 decimal places
  66.  
  67.  
  68.  
  69. // Calculate Simpson Index
  70. var simpsonIndexValue = 0; // Initialize Simpson Index value
  71.  
  72.  
  73.  
  74. for (var i = 0; i < treeSpeciesCount; i++) {
  75. var relativeAbundance = treeSpeciesData[i].numTrees / totalNumTrees; // Calculate p_i
  76. simpsonIndexValue += relativeAbundance * (relativeAbundance - 1); // Calculate Σ(ni (ni - 1))
  77.  // Calculate Σ(ni (ni - 1))
  78. }
  79. simpsonIndexValue = (1 / simpsonIndexValue).toFixed(4); // Calculate Simpson Index as 1 / Σ(ni * (ni - 1)) and round to 4 decimal places
  80.  
  81.  
  82.  
  83. // Descriptions of Simpson Index values
  84. var simpsonDescription = "";
  85. if (simpsonIndexValue < 0.7) {
  86. 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.";
  87. } else if (simpsonIndexValue <= 0.7 && simpsonIndexValue < 1) {
  88. 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.";
  89. } else {
  90. 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.";
  91. }
  92.  
  93.  
  94.  
  95. // Calculate Species Richness
  96. var speciesRichnessValue = treeSpeciesCount;
  97.  
  98.  
  99.  
  100. // Convert the diversifyYear to a timestamp in milliseconds
  101. var diversifyYearMillis = ee.Date.fromYMD(diversifyYear, 1, 1).millis();
  102.  
  103.  
  104.  
  105. // Filter Sentinel-2 imagery by date and location
  106. var sentinelCollection = ee.ImageCollection('COPERNICUS/S2')
  107. .filterBounds(mergedFarmBoundary)
  108. .filterDate(diversifyYearMillis, Date.now()) // Use the converted timestamp
  109. .filterMetadata('CLOUDY_PIXEL_PERCENTAGE', 'less_than', 20); // Optionally, filter by cloud cover percentage
  110.  
  111.  
  112.  
  113. // Print the number of images in the collection to check
  114. print("Number of Images in Collection:", sentinelCollection.size());
  115.  
  116.  
  117.  
  118. // Check the first image's properties to verify 'system:time_start' is available
  119. var firstImage = sentinelCollection.first();
  120. print("First Image Properties:", firstImage);
  121.  
  122.  
  123.  
  124. // Calculate NDVI for each image in the collection
  125. var ndviCollection = sentinelCollection.map(function (image) {
  126. var ndvi = image.normalizedDifference(['B8', 'B4']); // Calculate NDVI using Sentinel-2 bands B8 (NIR) and B4 (Red)
  127. return ndvi.set('system:time_start', image.get('system:time_start'));
  128. });
  129.  
  130.  
  131.  
  132. // Calculate the mean NDVI for the farm area
  133. var meanNdvi = ndviCollection.mean()
  134. .clip(mergedFarmBoundary); // Clip to the farm boundary
  135.  
  136.  
  137.  
  138. // Visualize the NDVI
  139. map.addLayer(meanNdvi, {
  140. min: -1,
  141. max: 1,
  142. palette: ['blue', 'white', 'green']
  143. }, 'Mean NDVI');
  144.  
  145.  
  146.  
  147. // Display the Shannon Index as a text label on the map
  148. var shannonIndexLabel = ui.Label('Shannon Index: ' + shannonIndexValue);
  149. shannonIndexLabel.style().set({
  150. position: 'top-right',
  151. fontWeight: 'bold',
  152. fontSize: '16px',
  153. padding: '10px'
  154. });
  155. map.add(shannonIndexLabel);
  156.  
  157.  
  158.  
  159. // Descriptions of Shannon Index values
  160. var shannonDescription = "";
  161. if (shannonIndexValue < 1) {
  162. 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.";
  163. } else if (shannonIndexValue >= 1 && shannonIndexValue <= 2) {
  164. 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.";
  165. } else {
  166. 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.";
  167. }
  168.  
  169.  
  170.  
  171. // Compute Normalized Difference Vegetation Index over S2-L2 product.
  172.  
  173.  
  174.  
  175. // Define the start and end dates for NDVI calculation (from diversifyYear to today)
  176. var startDate = ee.Date.fromYMD(diversifyYear, 1, 1);
  177. var endDate = ee.Date(Date.now());
  178.  
  179.  
  180.  
  181. // Step 1: Access the Sentinel-2 Level-2A data and filter it for all the images within the geometry's boundaries.
  182. var s2a = ee.ImageCollection('COPERNICUS/S2_SR')
  183. .filterBounds(mergedFarmBoundary)
  184. .filterDate(startDate, endDate) // Filter by the specified date range
  185. .select('B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8', 'B8A', 'B9', 'B11', 'B12')
  186. .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 10));
  187.  
  188.  
  189.  
  190. // Print your ImageCollection to your console tab to inspect it
  191. print(s2a, 'Image Collection');
  192.  
  193.  
  194.  
  195. // Adjust the map view to be approximately 2x the size of farmBoundary
  196. map.centerObject(mergedFarmBoundary, 13); // You can adjust the zoom level (e.g., change 13 to another value) to control the zoom level
  197.  
  198.  
  199.  
  200. // Step 2: Create a single Image by reducing by Median and clip it to the extent of the geometry
  201. var s2a_median = s2a.median()
  202. .clip(mergedFarmBoundary);
  203.  
  204.  
  205.  
  206. // Print your Image to your console tab to inspect it
  207. print(s2a_median, 'Median reduced Image');
  208.  
  209.  
  210.  
  211. // Add your Image as a map layer
  212. var visParams = {
  213. 'min': 400,
  214. 'max': [4000, 3000, 3000],
  215. 'bands': 'B8,B4,B3'
  216. };
  217. // Map.addLayer(s2a_median, visParams, 'S2 Median Image');
  218.  
  219.  
  220.  
  221. // Step 3: Calculate the NDVI
  222. var ndvi_3 = s2a_median.normalizedDifference(['B8', 'B4'])
  223. .rename('NDVI');
  224.  
  225.  
  226.  
  227. var new_ndvi_3 = s2a.map(function (img) {
  228. var date = img.get("system:time_start");
  229. var ndvi_3 = img.normalizedDifference(['B8', 'B4'])
  230. .rename('NDVI');
  231. return ndvi_3.set("system:time_start", date);
  232. });
  233.  
  234.  
  235.  
  236. // Plot a time series of NDVI at a single location.
  237. Map.centerObject(mergedFarmBoundary, 11);
  238. Map.addLayer(ndvi_3, {
  239. bands: 'NDVI',
  240. min: 0.1,
  241. max: 0.9,
  242. palette: ['white', 'green']
  243. }, 'NDVI Mosaic');
  244.  
  245.  
  246.  
  247. print(ndvi_3);
  248.  
  249.  
  250.  
  251. var S2Chart = ui.Chart.image.series(new_ndvi_3, mergedFarmBoundary, ee.Reducer.mean(), 250)
  252. //.setChartType('line')
  253. .setOptions({
  254. title: 'Sentinel-2 NDVI Time Series at ROI',
  255. trendlines: {
  256. 0: { color: 'CC0000' }
  257. },
  258. lineWidth: 1,
  259. pointSize: 3,
  260. });
  261. print(S2Chart);
  262. // NDVI CODE ENDS HERE
  263. // Convert the diversifyYear to a timestamp in milliseconds
  264. var diversifyYearMillis = ee.Date.fromYMD(diversifyYear, 1, 1).millis();
  265.  
  266.  
  267.  
  268. // Filter Sentinel-2 imagery by date and location
  269. var sentinelCollection = ee.ImageCollection('COPERNICUS/S2')
  270. .filterBounds(mergedFarmBoundary)
  271. .filterDate(diversifyYearMillis, Date.now()) // Use the converted timestamp
  272. .filterMetadata('CLOUDY_PIXEL_PERCENTAGE', 'less_than', 20); // Optionally, filter by cloud cover percentage
  273.  
  274.  
  275.  
  276. // Define the GIF parameters
  277. var gifParams = {
  278. 'region': mergedFarmBoundary.bounds(1).buffer(0.1), // Minimum bounding rectangle with a 10% buffer
  279. 'dimensions': 800,
  280. 'crs': 'EPSG:3857',
  281. 'framesPerSecond': 1,
  282. 'format': 'gif'
  283. };
  284.  
  285.  
  286.  
  287. // Create a GIF by taking monthly snapshots
  288. var gif = sentinelCollection.map(function (image) {
  289. var date = image.date();
  290. return image.visualize({
  291. min: 0,
  292. max: 3000,
  293. bands: ['B4', 'B3', 'B2']
  294. }).set('system:time_start', date);
  295. });
  296.  
  297. // Export the GIF to Google Drive
  298. Export.video.toDrive({
  299.     collection: gif,
  300.     description: 'MyGifAnimation',
  301.     dimensions: 800,
  302.     framesPerSecond: 1,
  303.     region: mergedFarmBoundary.bounds(1).buffer(0.1).getInfo().coordinates
  304. });
  305.  
  306.  
  307. // Display the GIF on the map
  308. // var gifImage = ee.ImageCollection(gif).toBands().rename(['R', 'G', 'B']);
  309. // Map.addLayer(gifImage, {bands: ['R', 'G', 'B'], min: 0, max: 3000}, 'GIF Image');
  310.  
  311.  
  312.  
  313. // Create a list of image properties
  314. var imagePropertiesList = sentinelCollection.map(function(image) {
  315. var date = image.date();
  316. return ee.Feature(null, {
  317. 'Image Date': date.format("YYYY-MM-dd"),
  318. // Add more properties or information you want to include
  319. });
  320. });
  321.  
  322.  
  323.  
  324. // Convert the list of properties to a feature collection and print
  325. var propertyCollection = ee.FeatureCollection(imagePropertiesList);
  326. print("Image Properties:", propertyCollection);
  327.  
  328.  
  329.  
  330. // Display outputs
  331. print("Farm Name: " + farmName);
  332. print("Diversification Year: " + diversifyYear);
  333. print("Total Farm Area (Hectares): " + farmArea.getInfo()); // Display the farm area as a single number
  334. print("Shannon Index: " + shannonIndexValue);
  335. print("Simpson Index: " + simpsonIndexValue);
  336. print("Species Richness: " + speciesRichnessValue);
  337. print("Simpson Index Description: " + simpsonDescription);
  338. print("Shannon Index Description: " + shannonDescription);

Editor

You can edit this paste and save as new:


File Description
  • dawdw
  • Paste Code
  • 03 Oct-2023
  • 10.62 Kb
You can Share it: