Summary
- Summary
-
Algotithms
- Acquisition
-
CSqueeze
- landParsing
- landParsingTurf
- extractShoreLine
- extractShoreLineTurf
- landCoversIntersections
- landCoversIntersectionsTurf
- filterElevation
- applyScaleFactors
- getMapBiomasClassificationsList
- getMapBiomasClassificationYear
- getLandCoverLabelMapBiomas
- maskCloudLandsat
- maskCloudSentinel
- getImageCSqueezeInfos
- applySaviBand
- applyEviBand
- applyNdviBand
- applyMndwiBand
- trainAndClassify
- getMangroves
- Geodesy
- Imagery
- Satellite-Landsat
- Satellite-Sentinel
- Satellite-LandsatTOA
- Shoreline
- Utils
Algotithms
Acquisition
The given code is a JavaScript module that contains several functions related to acquiring and processing satellite imagery data.
- The `sliceByRevisit` function takes a collection of satellite images, a starting date, and a number of days as input. It filters the collection by the specified date and duration, and returns the filtered collection.
- The `acquireFromDate` function takes a specific date, a satellite image collection, and a geometry (region of interest) as input. It uses the `sliceByRevisit` function to filter the collection based on the specified date and a fixed number of days (16 days in this case). It then applies a mosaic operation to the filtered collection and clips the resulting mosaic to the specified geometry. The function sets additional properties to the mosaic image using the `mergeProperties` function. It retrieves the selected satellite type from the session storage and determines the appropriate QA band name. Finally, it calls the `scoreClouds` function with the mosaic image, geometry, and QA band name to calculate a cloud score for the image.
- The `processCollection` function takes a satellite type and a geometry as input. It retrieves the satellite image collection for the specified type using the `getSatelliteCollection` function. It then retrieves the earliest and latest dates from the collection using the `retrieveExtremes` function. The function adds grid positions to each image in the collection and sorts them in ascending order. It retrieves the northeasternmost grid position within the specified geometry. It filters the images in the collection based on the northeastern position. It again retrieves the earliest and latest dates from the filtered collection. The function calculates the difference in days between the earliest image in the northeastern position and the globally earliest image. It computes the remainder of the difference divided by the fixed number of days (16 days). It then calculates the step (number of days to go back) by subtracting the remainder from the fixed number of days. The function computes the date of the earliest possible image in the northeastern position by going back in time using the calculated step. It calculates the number of complete orbital cycles between the earliest and latest possible dates of the images in the northeastern position. It generates slices of 16 days for each complete cycle. For each slice, it creates an empty image and sets metadata related to the corresponding orbital cycle. It keeps only the images whose combined geometries contain the region of interest. Finally, it returns a list of dates from the valid images.
- The `generateCloudMap` function takes a list of dates, a satellite image collection, and a geometry as input. It maps over the list of dates and calls the `acquireFromDate` function to acquire the cloud score image for each date. It retrieves the cloud score from each image and returns a list of cloud scores.
sliceByRevisit
The `sliceByRevisit` function filters a collection of satellite images based on a starting date and a number of days.
const sliceByRevisit = (collection, startingDate, days) => {
const start = ee.Date(startingDate).update(null, null, null, 0, 0, 0);
const end = start.advance(days, "day");
return collection.filterDate(start, end);
};
Inputs:
- collection: A collection of satellite images. - startingDate: The starting date for filtering the collection. - days: The number of days for filtering the collection.
Output:
- Returns a filtered collection of satellite images.
Use
To use the `sliceByRevisit` function, follow these steps: - Call the function `sliceByRevisit` and provide the collection of satellite images, starting date, and number of days as inputs. - The function will filter the collection based on the specified starting date and number of days. - The filtered collection will be returned as the output.
const filteredCollection = sliceByRevisit(satelliteImages, "2021-01-01", 16);
acquireFromDate
The `acquireFromDate` function retrieves satellite images from a given date onwards, filters them based on a geometry, and calculates cloud scores for the filtered images.
export const acquireFromDate = (date, collection, geometry) => {
const slice = sliceByRevisit(
ee.ImageCollection(collection).filterBounds(geometry),
date,
REVISIT_DAYS
);
const mosaicked = slice.mosaic().clip(geometry);
const image = mosaicked.set(mergeProperties(slice));
let satellite = window.sessionStorage.getItem("selectedSatellite");
let qaBand = satellite= "Landsat" ? "QA_PIXEL" : "QA60";
console.log("QA BAND AQUI", qaBand)
return scoreClouds(image, geometry, qaBand);
};
Inputs:
- date: The starting date to retrieve satellite images from. - collection: The collection of satellite images to retrieve from. - geometry: The geometry to filter the satellite images by.
Output:
- Returns a cloud score for the filtered satellite image.
Use
To use the `acquireFromDate` function, follow these steps: - Call the function `acquireFromDate` and provide the starting date, collection of satellite images, and geometry as inputs. - The function will filter the satellite images based on the provided geometry and starting date. - It will calculate the cloud score for the filtered image. - The cloud score will be returned as the output.
const cloudScore = acquireFromDate("2021-01-01", satelliteImages, geometry);
acquireFromDate
The `acquireFromDate` function retrieves satellite images from a given date onwards, filters them based on a geometry, and calculates cloud scores for the filtered images.
export const acquireFromDate = (date, collection, geometry) => {
const slice = sliceByRevisit(
ee.ImageCollection(collection).filterBounds(geometry),
date,
REVISIT_DAYS
);
const mosaicked = slice.mosaic().clip(geometry);
const image = mosaicked.set(mergeProperties(slice));
let satellite = window.sessionStorage.getItem("selectedSatellite");
let qaBand = satellite= "Landsat" ? "QA_PIXEL" : "QA60";
console.log("QA BAND AQUI", qaBand)
return scoreClouds(image, geometry, qaBand);
};
Inputs:
- date: The starting date to retrieve satellite images from. - collection: The collection of satellite images to retrieve from. - geometry: The geometry to filter the satellite images by.
Output:
- Returns a cloud score for the filtered satellite image.
Use
To use the `acquireFromDate` function, follow these steps: - Call the function `acquireFromDate` and provide the starting date, collection of satellite images, and geometry as inputs. - The function will filter the satellite images based on the provided geometry and starting date. - It will calculate the cloud score for the filtered image. - The cloud score will be returned as the output.
const cloudScore = acquireFromDate("2021-01-01", satelliteImages, geometry);
processCollection
The `processCollection` function performs a series of operations on a satellite image collection based on the selected satellite and a specified geometry.
export const processCollection = (satellite, geometry) => {
const query = getSatelliteCollection(satellite).filterBounds(geometry);
const global = retrieveExtremes(query);
const enhanced = query
.map(addGridPosition(satellite))
.sort(Metadata.GRID_POSITION);
const northeasternPosition = ee
.Image(enhanced.toList(1).get(0))
.get(Metadata.GRID_POSITION);
const filtered = enhanced.filter(
ee.Filter.eq(Metadata.GRID_POSITION, northeasternPosition)
);
const northeastern = retrieveExtremes(filtered);
const difference = northeastern.earliest
.difference(global.earliest, "day")
.abs();
const remainder = ee.Number(difference).mod(REVISIT_DAYS);
const step = ee.Number(REVISIT_DAYS).subtract(remainder);
const earliestDate = global.earliest.advance(step.multiply(-1), "day");
const completeCycles = ee
.Number(earliestDate.difference(global.latest, "day").abs())
.divide(REVISIT_DAYS)
.ceil();
const additions = ee.List.sequence(0, null, REVISIT_DAYS, completeCycles);
const carriers = additions.map((increment) => {
const startingDate = earliestDate.advance(increment, "day");
const collection = sliceByRevisit(query, startingDate, REVISIT_DAYS);
const empty = ee.Algorithms.IsEqual(collection.size(), 0);
const properties = ee.Algorithms.If(empty, {}, mergeProperties(collection));
return ee.Image(0).set(properties);
});
const valid = ee.ImageCollection.fromImages(carriers).filter(
ee.Filter.contains(Metadata.FOOTPRINT, geometry)
);
return ee.List(valid.toList(valid.size()).map(getDate));
};
Inputs:
- satellite: The selected satellite for processing the image collection. - geometry: The geometry to filter the image collection by.
Output:
- Returns a list of dates corresponding to the processed images in the collection.
Use
To use the `processCollection` function, follow these steps: - Call the function `processCollection` and provide the satellite and geometry as inputs. - The function will filter the image collection based on the provided satellite and geometry. - It will perform various operations on the filtered collection, including retrieving extremes, sorting by grid position, and filtering by northeastern position. - The function will generate slices of images based on complete orbital cycles and add metadata to the slices. - It will filter the slices based on the geometry and return a list of dates corresponding to the valid images.
const dates = processCollection("Landsat", geometry);
generateCloudMap
The `generateCloudMap` function takes a list of dates, an image collection, and a geometry as inputs. It generates a list of cloud values corresponding to the provided dates and collection.
export const generateCloudMap = (dates, collection, geometry) => {
const cloudList = ee.List(dates).map((date) => {
const image = ee.Image(acquireFromDate(date, collection, geometry));
return image.get("CLOUDS");
});
return cloudList;
};
Inputs:
- dates: A list of dates for which to generate the cloud values. - collection: The image collection from which to acquire images. - geometry: The geometry to filter the image collection by.
Output:
- Returns a list of cloud values corresponding to the provided dates and collection.
Use
To use the `generateCloudMap` function, follow these steps: - Call the function `generateCloudMap` and provide the dates, collection, and geometry as inputs. - The function will iterate over the provided dates and acquire the corresponding image from the collection based on the date and geometry. - It will extract the cloud value from each image and create a list of these values. - The function will return the generated list of cloud values.
const cloudValues = generateCloudMap(dates, imageCollection, geometry);
CSqueeze
The given code is used for geospatial analysis. It primarily analyses land cover and shorelines using Google Earth Engine (imported as 'ee') and Turf.js (imported as 'turf'), two powerful libraries for geospatial analysis. The code contains the functions bellow:
-
landParsing
: This function takes in four parameters: landcover, sidesCoords, centerCoord, and shoreline. It checks if the given landcover is water, calculates the intersection of the sides of the landcover with its geometry, and then calculates the length and coordinates of these intersections. It also calculates the distance of the intersections from the center and shoreline. It then determines which side of the landcover is larger and if the landcover is water, it notes the side and intersection point. Finally, it returns an object containing details about the landcover, including its name, class, length of sides, biggest side, intersection points, distances from the baseline and shoreline, and information related to water. -
landParsingTurf
: This function is similar tolandParsing
but uses the Turf.js library for geospatial operations instead of Google Earth Engine. It takes the same parameters and performs similar operations but uses Turf.js methods liketurf.point
,turf.lineString
,turf.buffer
,turf.feature
,turf.intersect
,turf.length
,turf.getCoords
,turf.distance
, andturf.nearestPointOnLine
. 3.extractShoreLine
: This function takes in two parameters: baseLineCoords and waterGeometry. It creates a geometry for the baseline and water body, then calculates the intersection of the baseline with the water body. This intersection represents the shoreline. The code also imports and uses a list of landcovers and a 'satellite' object from other modules. The landcovers list is used to assign names and classes to the landcover based on its id. -
extractShoreLineTurf(baseLine, waterGeometry)
: This function takes a base line and a water geometry as inputs. It converts the water geometry into a turf feature, intersects it with the base line, and then converts the intersection into a line, which represents the shoreline. -
landCoversIntersections(transect, landcoversdata, shoreLine, year)
: This function takes a transect, land cover data, a shoreline, and a year as inputs. It then calculates the intersections of the transect with the land cover data. The function also determines which side of the transect intersects with the water body. -
landCoversIntersectionsTurf(transect, landcoversdata, shoreLine, year)
: This function is similar to the previous one, but it uses Turf.js functions for the calculations. -
filterElevation(image, elevation, type, satellite)
: This function takes an image, an elevation value, a type, and a satellite as inputs. It filters the image based on the elevation value, using different methods depending on the type and satellite provided. It returns the filtered image. 5.applyScaleFactors(image)
: This function takes an image as input and applies scale factors to the optical and thermal bands of the image. It returns the image with the adjusted bands. 6.getMapBiomasClassificationsList()
: This function retrieves a list of band IDs from a specific image in the MapBiomas project on Google Earth Engine. It returns this list. Overall, these functions are used for processing and analyzing geographical data, likely as part of a larger application for environmental or geographical studies. -
getMapBiomasClassificationYear(AOI, year, elevation = 10)
: This function retrieves a classification image from the MapBiomas database for a specific year and area of interest (AOI). The image is then clipped to the AOI and filtered by elevation. -
getLandCoverLabelMapBiomas(value)
: This function returns a label for a given land cover value. It maps the input value to one of four categories: mangrove, vegetation, water, or human. -
maskCloudLandsat(image, qa_band)
andmaskCloudSentinel(image)
: These two functions are used to mask cloud cover from Landsat and Sentinel satellite images, respectively. They both use bitwise operations to filter out pixels that are flagged as clouds or cloud shadows. -
getImageCSqueezeInfos(missionName)
: This function retrieves metadata for a given satellite mission name. -
applySaviBand(image, bands)
,applyEviBand(image, bands)
,applyNdviBand(image, bands)
,applyMndwiBand(image, bands)
,applyUiBand(image, bands)
: These functions calculate various vegetation indices (SAVI, EVI, NDVI, MNDWI, UI) from an image using specific band combinations. -
trainAndClassify(image, classificationAreas, bands, AOICoords)
: This function trains a random forest classifier using the provided image, classification areas, and bands. The trained classifier is then used to classify the image. -
getMangroves()
: This function retrieves a global mangrove map from the ESA WorldCover database, masks out all non-mangrove areas, calculates the slope of the mangrove areas, and returns an overlay of the slope map.
landParsing
This function takes several inputs and performs calculations to determine various properties related to land cover and water bodies.
function landParsing(landcover, sidesCoords, centerCoord, shoreline) {
var isWater = landcover.id === 2;
var center = ee.Geometry.Point(centerCoord);
var intersectionSideOne = ee.Geometry.LineString(sidesCoords[0]).intersection(landcover.geometry, 1);
var intersectionSideTwo = ee.Geometry.LineString(sidesCoords[1]).intersection(landcover.geometry, 1);
var intersectionData = ee.Dictionary({
intersectionSideOneLength: intersectionSideOne.length(),
intersectionSideTwoLength: intersectionSideTwo.length(),
intersectionSideOneCoordinatesFlatten: intersectionSideOne.coordinates().flatten(),
intersectionSideTwoCoordinatesFlatten: intersectionSideTwo.coordinates().flatten()
}).getInfo()
var lengthSide = [0, 0]
var distancesFromBaseLine = [0, 0];
var distancesFromShoreLine = [0, 0];
var landCoverIntersectPoint = [null, null];
var landCoverBiggestSide = -1;
var waterSide = -1;
var waterIntersectPoint = [0, 0];
var oneCoordsFlatten = intersectionData.intersectionSideOneCoordinatesFlatten.reverse()
var twoCoordsFlatten = intersectionData.intersectionSideTwoCoordinatesFlatten.reverse()
if (oneCoordsFlatten.length > 0 && twoCoordsFlatten.length > 0) {
lengthSide[0] = intersectionData.intersectionSideOneLength;
lengthSide[1] = intersectionData.intersectionSideTwoLength;
landCoverIntersectPoint[0] = [oneCoordsFlatten[1], oneCoordsFlatten[0]];
landCoverIntersectPoint[1] = [twoCoordsFlatten[1], twoCoordsFlatten[0]];
distancesFromBaseLine[0] = landCoverIntersectPoint[0] !== null ? ee.Geometry.Point(landCoverIntersectPoint[0]).distance(center, 1).getInfo() : null;
distancesFromBaseLine[1] = landCoverIntersectPoint[1] !== null ? ee.Geometry.Point(landCoverIntersectPoint[1]).distance(center, 1).getInfo() : null;
distancesFromShoreLine[0] = landCoverIntersectPoint[0] !== null ? ee.Geometry.Point(landCoverIntersectPoint[0]).distance(shoreline, 1).getInfo() : null;
distancesFromShoreLine[1] = landCoverIntersectPoint[1] !== null ? ee.Geometry.Point(landCoverIntersectPoint[1]).distance(shoreline, 1).getInfo() : null;
if (lengthSide[0] > lengthSide[1]) landCoverBiggestSide = 0;
else landCoverBiggestSide = 1;
}
else if (twoCoordsFlatten.length > 0) {
lengthSide[1] = intersectionData.intersectionSideTwoLength;
landCoverIntersectPoint[1] = [twoCoordsFlatten[1], twoCoordsFlatten[0]];
distancesFromBaseLine[1] = landCoverIntersectPoint[1] !== null ? ee.Geometry.Point(landCoverIntersectPoint[1]).distance(center, 1).getInfo() : null;
distancesFromShoreLine[1] = landCoverIntersectPoint[1] !== null ? ee.Geometry.Point(landCoverIntersectPoint[1]).distance(shoreline, 1).getInfo() : null;
landCoverBiggestSide = 1;
}
else if (oneCoordsFlatten.length > 0) {
lengthSide[0] = intersectionData.intersectionSideOneLength;
landCoverIntersectPoint[0] = [oneCoordsFlatten[1], oneCoordsFlatten[0]];
distancesFromBaseLine[0] = landCoverIntersectPoint[0] !== null ? ee.Geometry.Point(landCoverIntersectPoint[0]).distance(center, 1).getInfo() : null;
distancesFromShoreLine[0] = landCoverIntersectPoint[0] !== null ? ee.Geometry.Point(landCoverIntersectPoint[0]).distance(shoreline, 1).getInfo() : null;
landCoverBiggestSide = 0;
}
if (isWater) {
waterSide = landCoverBiggestSide;
waterIntersectPoint = landCoverIntersectPoint[landCoverBiggestSide];
}
var name = landcovers[landcover.id];
var classe = landcovers[landcover.id];
return {
label: landcover.id,
name: name,
classe: classe,
lengthSide: lengthSide,
biggestSide: landCoverBiggestSide,
intersectPoint: landCoverIntersectPoint,
baseLineDistance: distancesFromBaseLine,
shoreLineDistance: distancesFromShoreLine,
waterSide: waterSide,
waterIntersectPoint: waterIntersectPoint
};
}
'Inputs:'
- landcover: The land cover object. - sidesCoords: An array containing the coordinates of the two sides. - centerCoord: The coordinate of the center point. - shoreline: The shoreline geometry.
'Output:'
- label: The ID of the land cover. - name: The name of the land cover. - classe: The class of the land cover. - lengthSide: An array containing the lengths of the two sides. - biggestSide: The index of the biggest side. - intersectPoint: An array containing the intersection points of the land cover with the sides. - baseLineDistance: An array containing the distances from the base line. - shoreLineDistance: An array containing the distances from the shoreline. - waterSide: The index of the water side. - waterIntersectPoint: The intersection point of the water side.
'Use'
- Create an instance of the land cover object. - Define the coordinates of the two sides. - Specify the center coordinate. - Provide the shoreline geometry. - Call the function landParsing with the inputs mentioned above. - Retrieve the desired properties from the output.
var landcover = ...; // create the land cover object
var sidesCoords = [...]; // define the coordinates of the sides
var centerCoord = ...; // specify the center coordinate
var shoreline = ...; // provide the shoreline geometry
var result = landParsing(landcover, sidesCoords, centerCoord, shoreline);
landParsingTurf
This function parses a given landcover to determine its attributes and the relationships to other geographical features. It takes in four parameters: landcover, sidesCoords, centerCoord, and shoreline. The function uses the Turf.js library to perform various geographical operations, including creating points and lines, buffering lines, intersecting shapes, and calculating distances. It checks if the landcover is water, calculates the intersection of the landcover with two sides, and determines the length and coordinates of the intersections. It then calculates the distances from the baseline and shoreline for each side, determines the biggest side, and if the landcover is water, it assigns the water side and intersection point. Finally, it returns an object with all the calculated attributes and measurements.
function landParsingTurf(landcover, sidesCoords, centerCoord, shoreline) {
var isWater = landcover.id === 2;
var center = turf.point(centerCoord);
var sideOneTurf = turf.lineString(sidesCoords[0])
var sideOne = turf.buffer(sideOneTurf, 1, options);
var sideTwoTurf = turf.lineString(sidesCoords[1])
var sideTwo = turf.buffer(sideTwoTurf, 1, options);
var landcoverTurf = turf.feature(landcover.geometry)
// if (landcover.geometry.type === "MultiPolygon") {
// landcoverTurf = turf.multiPolygon(landcover.geometry.coordinates)
// } else {
// landcoverTurf = turf.polygon(landcover.geometry.coordinates)
// }
var intersectionSideOne = turf.intersect(sideOne, landcoverTurf);
var intersectionSideTwo = turf.intersect(sideTwo, landcoverTurf);
var intersectionData = {
intersectionSideOneLength: intersectionSideOne ? turf.length(intersectionSideOne, options) : 0,
intersectionSideTwoLength: intersectionSideTwo ? turf.length(intersectionSideTwo, options) : 0,
intersectionSideOneCoordinatesFlatten: intersectionSideOne ? turf.getCoords(intersectionSideOne).flat(Infinity) : [],
intersectionSideTwoCoordinatesFlatten: intersectionSideTwo ? turf.getCoords(intersectionSideTwo).flat(Infinity) : []
};
var lengthSide = [0, 0]
var distancesFromBaseLine = [0, 0];
var distancesFromShoreLine = [0, 0];
var landCoverIntersectPoint = [null, null];
var landCoverBiggestSide = -1;
var waterSide = -1;
var waterIntersectPoint = [0, 0];
var oneCoordsFlatten = intersectionData.intersectionSideOneCoordinatesFlatten.reverse()
var twoCoordsFlatten = intersectionData.intersectionSideTwoCoordinatesFlatten.reverse()
if (oneCoordsFlatten.length > 0 && twoCoordsFlatten.length > 0) {
lengthSide[0] = intersectionData.intersectionSideOneLength;
lengthSide[1] = intersectionData.intersectionSideTwoLength;
landCoverIntersectPoint[0] = [oneCoordsFlatten[1], oneCoordsFlatten[0]];
landCoverIntersectPoint[1] = [twoCoordsFlatten[1], twoCoordsFlatten[0]];
distancesFromBaseLine[0] = landCoverIntersectPoint[0] !== null ? turf.distance(turf.point(landCoverIntersectPoint[0]), center, options) : null;
distancesFromBaseLine[1] = landCoverIntersectPoint[1] !== null ? turf.distance(turf.point(landCoverIntersectPoint[1]), center, options) : null;
var pontoShoreLineProximo0 = turf.nearestPointOnLine(shoreline, turf.point(landCoverIntersectPoint[0]), options);
distancesFromShoreLine[0] = landCoverIntersectPoint[0] !== null ? turf.distance(turf.point(landCoverIntersectPoint[0]), pontoShoreLineProximo0, options) : null;
var pontoShoreLineProximo1 = turf.nearestPointOnLine(shoreline, turf.point(landCoverIntersectPoint[1]), options);
distancesFromShoreLine[1] = landCoverIntersectPoint[1] !== null ? turf.distance(turf.point(landCoverIntersectPoint[1]), pontoShoreLineProximo1, options) : null;
if (lengthSide[0] > lengthSide[1]) landCoverBiggestSide = 0;
else landCoverBiggestSide = 1;
}
else if (twoCoordsFlatten.length > 0) {
lengthSide[1] = intersectionData.intersectionSideTwoLength;
landCoverIntersectPoint[1] = [twoCoordsFlatten[1], twoCoordsFlatten[0]];
distancesFromBaseLine[1] = landCoverIntersectPoint[1] !== null ? turf.distance(turf.point(landCoverIntersectPoint[1]), center, options) : null;
var pontoShoreLineProximo1 = turf.nearestPointOnLine(shoreline, turf.point(landCoverIntersectPoint[1]), options);
distancesFromShoreLine[1] = landCoverIntersectPoint[1] !== null ? turf.distance(turf.point(landCoverIntersectPoint[1]), pontoShoreLineProximo1, options) : null;
landCoverBiggestSide = 1;
}
else if (oneCoordsFlatten.length > 0) {
lengthSide[0] = intersectionData.intersectionSideOneLength;
landCoverIntersectPoint[0] = [oneCoordsFlatten[1], oneCoordsFlatten[0]];
distancesFromBaseLine[0] = landCoverIntersectPoint[0] !== null ? turf.distance(turf.point(landCoverIntersectPoint[0]), center, options) : null;
var pontoShoreLineProximo0 = turf.nearestPointOnLine(shoreline, turf.point(landCoverIntersectPoint[0]), options);
distancesFromShoreLine[0] = landCoverIntersectPoint[0] !== null ? turf.distance(turf.point(landCoverIntersectPoint[0]), pontoShoreLineProximo0, options) : null;
landCoverBiggestSide = 0;
}
if (isWater) {
waterSide = landCoverBiggestSide;
waterIntersectPoint = landCoverIntersectPoint[landCoverBiggestSide];
}
var name = landcovers[landcover.id];
var classe = landcovers[landcover.id];
return {
label: landcover.id,
name: name,
classe: classe,
lengthSide: lengthSide,
biggestSide: landCoverBiggestSide,
intersectPoint: landCoverIntersectPoint,
baseLineDistance: distancesFromBaseLine,
shoreLineDistance: distancesFromShoreLine,
waterSide: waterSide,
waterIntersectPoint: waterIntersectPoint
};
}
function landParsingTurf(landcover, sidesCoords, centerCoord, shoreline) {...}
Inputs:
- landcover: The landcover object to be parsed. - sidesCoords: An array containing the coordinates of the two sides. - centerCoord: The coordinates of the center point. - shoreline: The shoreline object.
Output:
An object containing the following properties: - label: The ID of the landcover. - name: The name of the landcover. - classe: The class of the landcover. - lengthSide: The lengths of the two sides. - biggestSide: The biggest side. - intersectPoint: The intersection points of the landcover with the two sides. - baseLineDistance: The distances from the baseline for each side. - shoreLineDistance: The distances from the shoreline for each side. - waterSide: The water side, if the landcover is water. - waterIntersectPoint: The water intersection point, if the landcover is water.
Use
- Call the function landParsingTurf with the required parameters: landcover, sidesCoords, centerCoord, and shoreline. - The function will perform various geographical operations and calculations using the Turf.js library. - It will return an object with the calculated attributes and measurements.
landParsingTurf(landcover, sidesCoords, centerCoord, shoreline);
extractShoreLine
This function takes in the baseLineCoords and waterGeometry as input parameters and returns the intersection of the base line geometry and the water geometry lines.
export const extractShoreLine = (baseLineCoords, waterGeometry) => {
var baseLineGeometry = ee.Geometry(baseLineCoords.geometry);
var waterGeometryLines = ee.FeatureCollection(waterGeometry.coordinates.map(function (l) {
return ee.Feature(ee.Geometry.MultiLineString(l))
})).geometry();
return baseLineGeometry.intersection(waterGeometryLines, ee.ErrorMargin(1));
}
Inputs:
- baseLineCoords: The coordinates of the base line geometry. This should be in a format that can be converted to an ee.Geometry object. - waterGeometry: The geometry of the water. This should be in a format that can be converted to an ee.FeatureCollection object.
Output:
- Intersection: The intersection of the base line geometry and the water geometry lines.
Use
- Create a base line geometry using the desired coordinates. - Create a water geometry using the desired coordinates. - Call the extractShoreLine function, passing in the base line geometry and water geometry as input parameters. - The function will return the intersection of the base line geometry and the water geometry lines.
extractShoreLine(baseLineCoords, waterGeometry);
extractShoreLineTurf
This function takes in the baseLine and waterGeometry as input parameters and returns the shoreline as a line geometry.
export const extractShoreLineTurf = (baseLine, waterGeometry) => {
var waterTurf = turf.feature(waterGeometry);
var intersection = turf.intersect(baseLine, waterTurf);
var shoreLine = turf.polygonToLine(intersection);
return shoreLine;
}
Inputs:
- baseLine: The base line geometry. This should be in a format that can be converted to a turf feature object. - waterGeometry: The geometry of the water. This should be in a format that can be converted to a turf feature object.
Output:
- shoreLine: The shoreline as a line geometry.
Use
- Create a base line geometry using the desired coordinates. - Create a water geometry using the desired coordinates. - Call the extractShoreLineTurf function, passing in the base line geometry and water geometry as input parameters. - The function will return the shoreline as a line geometry.
extractShoreLineTurf(baseLine, waterGeometry);
landCoversIntersections
This function takes in the transect, landcoversdata, shoreLine, and year as input parameters and returns an object containing various outputs related to land cover intersections.
export const landCoversIntersections = (transect, landcoversdata, shoreLine, year) => {
var sideOneCoords = transect.sides[0].coords.map(arr => Object.values(arr));
var sideTwoCoords = transect.sides[1].coords.map(arr => Object.values(arr));
var sideOne = sideOneCoords;
var sideTwo = sideTwoCoords;
var completeLine = [sideOne, sideTwo];
var lineCenter = transect.center;
// // var landcoversCodes = ee.Algorithms.If(filter, filter, landcovers.distinct('label').aggregate_array('label'))
var waterSide = -1;
var waterIntersectPoint = [0, 0];
var landcoversOutput = [];
var waters = landcoversdata.filter(function (l) { return l.id === 2 })
var outputwater = waters.map(function (water) {
return landParsing(water, [sideOne, sideTwo], lineCenter, shoreLine)
})[0]
waterSide = outputwater.waterSide;
waterIntersectPoint = outputwater.waterIntersectPoint;
if (waterSide > -1) {
if (waterSide === 0) {
sideOne = sideTwoCoords
sideTwo = [lineCenter, waterIntersectPoint]
completeLine = [sideOne, sideTwo]
}
if (waterSide === 1) {
sideOne = sideOneCoords
sideTwo = [lineCenter, waterIntersectPoint]
completeLine = [sideOne, sideTwo]
}
}
landcoversOutput = landcoversdata.map(landcover => {
return landParsing(landcover, [sideOne, sideTwo], lineCenter, shoreLine)
});
var saida = {
id: transect.transect,
year,
center: lineCenter,
completeLine,
sides: transect.sides,
waterSide: waterSide,
waterIntersectPoint: waterIntersectPoint,
landCoversIntersections: landcoversOutput
};
return saida;
}
Inputs:
- transect: The transect object containing information about the transect line. - landcoversdata: The land cover data used for intersection analysis. This should be an array of land cover objects. - shoreLine: The shoreline as a line geometry. This should be in a format that can be used for intersection analysis. - year: The year associated with the analysis.
Output:
- saida: An object containing various outputs related to land cover intersections. The properties of saida include:
- id: The transect ID.
- year: The year associated with the analysis.
- center: The center point of the transect line.
- completeLine: The complete line geometry of the transect.
- sides: An array containing the two sides of the transect line.
- waterSide: The side of the transect line where water is intersected (-1 if no water intersection).
- waterIntersectPoint: The coordinates of the point where the transect line intersects with water.
- landCoversIntersections: An array containing the intersection results for each land cover object in the landcoversdata array.
Use
- Create a transect object containing information about the transect line. - Prepare the land cover data for intersection analysis. - Create the shoreline as a line geometry. - Specify the year associated with the analysis. - Call the landCoversIntersections function, passing in the transect, landcoversdata, shoreLine, and year as input parameters. - The function will return an object containing various outputs related to land cover intersections.
landCoversIntersections(transect, landcoversdata, shoreLine, year);
landCoversIntersectionsTurf
This function takes in the transect, landcoversdata, shoreLine, and year as input parameters and returns an object containing various outputs related to land cover intersections using the Turf library.
export const landCoversIntersectionsTurf = (transect, landcoversdata, shoreLine, year) => {
var sideOneCoords = transect.sides[0].coords.map(arr => Object.values(arr));
var sideTwoCoords = transect.sides[1].coords.map(arr => Object.values(arr));
var sideOne = sideOneCoords;
var sideTwo = sideTwoCoords;
var completeLine = [sideOne, sideTwo];
var lineCenter = transect.center;
// // var landcoversCodes = ee.Algorithms.If(filter, filter, landcovers.distinct('label').aggregate_array('label'))
var waterSide = -1;
var waterIntersectPoint = [0, 0];
var landcoversOutput = [];
var waters = landcoversdata.filter(function (l) { return l.id === 2 })
var outputwater = waters.map(function (water) {
return landParsingTurf(water, [sideOne, sideTwo], lineCenter, shoreLine)
})[0]
waterSide = outputwater.waterSide;
waterIntersectPoint = outputwater.waterIntersectPoint;
if (waterSide > -1) {
if (waterSide === 0) {
sideOne = sideTwoCoords
sideTwo = [lineCenter, waterIntersectPoint]
completeLine = [sideOne, sideTwo]
}
if (waterSide === 1) {
sideOne = sideOneCoords
sideTwo = [lineCenter, waterIntersectPoint]
completeLine = [sideOne, sideTwo]
}
}
landcoversOutput = landcoversdata.map(landcover => {
return landParsingTurf(landcover, [sideOne, sideTwo], lineCenter, shoreLine)
});
var saida = {
id: transect.transect,
year,
center: lineCenter,
completeLine,
sides: transect.sides,
waterSide: waterSide,
waterIntersectPoint: waterIntersectPoint,
landCoversIntersections: landcoversOutput
};
return saida;
}
Inputs:
- transect: The transect object containing information about the transect line. - landcoversdata: The land cover data used for intersection analysis. This should be an array of land cover objects. - shoreLine: The shoreline as a line geometry. This should be in a format that can be used for intersection analysis. - year: The year associated with the analysis.
Output:
- saida: An object containing various outputs related to land cover intersections. The properties of saida include:
- id: The transect ID.
- year: The year associated with the analysis.
- center: The center point of the transect line.
- completeLine: The complete line geometry of the transect.
- sides: An array containing the two sides of the transect line.
- waterSide: The side of the transect line where water is intersected (-1 if no water intersection).
- waterIntersectPoint: The coordinates of the point where the transect line intersects with water.
- landCoversIntersections: An array containing the intersection results for each land cover object in the landcoversdata array.
Use
- Create a transect object containing information about the transect line. - Prepare the land cover data for intersection analysis. - Create the shoreline as a line geometry. - Specify the year associated with the analysis. - Call the landCoversIntersectionsTurf function, passing in the transect, landcoversdata, shoreLine, and year as input parameters. - The function will return an object containing various outputs related to land cover intersections using the Turf library.
landCoversIntersectionsTurf(transect, landcoversdata, shoreLine, year);
filterElevation
This function takes in the image, elevation, type, and satellite as input parameters and returns an image with an elevation mask applied.
export const filterElevation = (image, elevation, type = null, satellite = "LANDSAT") => {
var elevationMask;
// Digital Elevation Model (DEM)
// var dem = ee.Image("USGS/SRTMGL1_003").lte(elevation);
// ALOS DSM: Global 30m v3.2
// var dem = ee.ImageCollection('JAXA/ALOS/AW3D30/V3_2').select('DSM').mosaic().lte(elevation);
var dataset = ee.ImageCollection('JAXA/ALOS/AW3D30/V3_2').select(0).mosaic().lte(elevation);
// var dem = ee.Image("users/nlang/ETH_GlobalCanopyHeightSD_2020_10m_v1").lte(elevation)
// NADA ELEVATION
// var nasa = ee.Image('NASA/NASADEM_HGT/001').select(0).lte(elevation);
if (type === "mapbiomas") {
// Reprojeta e redimensiona a imagem DSM para a mesma projeção e resolução espacial da imagem classification
var dataset_reproj = dataset.reproject({
crs: image.projection(),
scale: image.projection().nominalScale(),
});
// Subtrai a imagem DSM da imagem classification
var classification_minus_dataset = image.subtract(dataset_reproj);
// Define a máscara para excluir a área do DSM
var mask = dataset_reproj.eq(0).not();
// Aplica a máscara à imagem classification_minus_dsm
elevationMask = classification_minus_dataset.updateMask(mask);
return image.updateMask(elevationMask)
} else {
if (satellite === "S2") {
dataset = ee.Image('USGS/SRTMGL1_003');
elevationMask = dataset.lte(elevation);
} else {
elevationMask = dataset.subtract(image.select(0));
}
}
return image.updateMask(elevationMask);
}
Inputs:
- image: The image to be filtered based on elevation. - elevation: The elevation threshold used for filtering. - type: The type of filter to apply ("mapbiomas" or null). - satellite: The satellite used for the filter ("LANDSAT" or "S2").
Output:
- image: The filtered image with an elevation mask applied.
Use
- Prepare the image to be filtered based on elevation. - Specify the elevation threshold for filtering. - Optional: Specify the type of filter to apply ("mapbiomas" or null). - Optional: Specify the satellite used for the filter ("LANDSAT" or "S2"). - Call the filterElevation function, passing in the image, elevation, type, and satellite as input parameters. - The function will return the filtered image with an elevation mask applied.
filterElevation(image, elevation, type, satellite);
applyScaleFactors
This function takes in an image as input and applies scale factors to the optical and thermal bands. It then adds the scaled bands to the input image and returns the modified image.
export const applyScaleFactors = (image) => {
var opticalBands = image.select('SR_B.').multiply(0.0000275).add(-0.2);
var thermalBand = image.select('ST_B.*').multiply(0.00341802).add(149.0);
return image.addBands(opticalBands, null, true)
.addBands(thermalBand, null, true);
}
Inputs:
- image: The input image to which scale factors will be applied.
Output:
- image: The modified image with scaled bands added.
Use
- Prepare the image to which scale factors will be applied. - Call the applyScaleFactors function, passing in the image as an input parameter. - The function will apply scale factors to the optical and thermal bands of the image and add the scaled bands to the input image. - The modified image with scaled bands added will be returned.
applyScaleFactors(image);
getMapBiomasClassificationsList
This function retrieves the list of classifications from the MapBiomas dataset. It fetches the MapBiomas image and extracts the band IDs to create a list of classifications.
export const getMapBiomasClassificationsList = () => {
var mapbiomas = ee.Image("projects/mapbiomas-workspace/public/collection7/mapbiomas_collection70_integration_v2").getInfo();
var list = mapbiomas.bands.map((m) => m.id);
return list;
}
Inputs:
No input parameters for this function.
Output:
- list: The list of classifications from the MapBiomas dataset.
Use
- Call the getMapBiomasClassificationsList function. - The function will retrieve the list of classifications from the MapBiomas dataset. - The list of classifications will be returned.
getMapBiomasClassificationsList();
getMapBiomasClassificationYear
This function retrieves the MapBiomas classification image for a specific year within a given Area of Interest (AOI). It selects the classification band corresponding to the specified year and clips the image to the AOI. The function also applies an optional elevation filter before returning the classified image.
export const getMapBiomasClassificationYear = (AOI, year, elevation = 10) => {
let classified = ee
.Image(
"projects/mapbiomas-workspace/public/collection7/mapbiomas_collection70_integration_v2"
)
.select("classification_" + year)
.clip(ee.Geometry.Polygon(AOI));
classified = filterElevation(classified, elevation, "mapbiomas")
return classified;
}
Inputs:
- AOI: The Area of Interest (AOI) for which the MapBiomas classification image will be retrieved. - year: The specific year for which the MapBiomas classification image will be retrieved. - elevation (optional): The elevation threshold for filtering the classification image. Default value is 10.
Output:
- classified: The MapBiomas classification image for the specified year and AOI.
Use
- Define the Area of Interest (AOI) and the specific year for which the MapBiomas classification image is needed. - Call the getMapBiomasClassificationYear function, passing in the AOI and year as input parameters. - The function will retrieve the MapBiomas classification image for the specified year and AOI. - If an elevation threshold is provided, the function will apply the elevation filter to the classification image. - The classified image will be returned.
getMapBiomasClassificationYear(AOI, year, elevation);
getLandCoverLabelMapBiomas
This function returns the label for a given land cover value based on the MapBiomas land cover types. It takes a land cover value as input and checks if it belongs to any of the predefined land cover types. If a match is found, the corresponding label is returned. If no match is found, a default label of 3 is returned.
export function getLandCoverLabelMapBiomas(value) {
let landcoverstypes = {
mangrove: {
label: 0,
types: [5]
},
vegetation: {
label: 1,
types: [1, 3, 4, 5, 49, 10, 11, 12, 32, 29, 50, 13]
},
water: {
label: 2,
types: [26, 33]
},
human: {
label: 3,
types: [14, 15, 18, 19, 39, 20, 40, 62, 41, 36, 46, 47, 48, 9, 21, 22, 23, 24, 30, 25, 31, 27]
},
}
for (const type of Object.entries(landcoverstypes)) {
if (type[1].types.includes(value)) {
return type[1].label;
}
}
return 3;
}
Inputs:
- value: The land cover value for which the label will be determined.
Output:
- label: The label corresponding to the given land cover value. If no match is found, a default label of 3 is returned.
Use
- Define the land cover value for which the label is needed. - Call the getLandCoverLabelMapBiomas function, passing in the land cover value as an input parameter. - The function will determine the label based on the land cover value. - The label will be returned.
getLandCoverLabelMapBiomas(value);
maskCloudLandsat
This function masks cloud and cloud shadow pixels in a Landsat image using the quality assessment (QA) band. It takes an input image and the QA band name as parameters. The function applies bitwise operations to create a mask that identifies cloud and cloud shadow pixels based on specific bit masks. The image is then updated with the mask, effectively masking out the cloud and cloud shadow pixels.
export function maskCloudLandsat(image, qa_band) {
var cloudShadowBitMask = (1 << 3);
var cloudsBitMask = (1 << 5);
var qa = image.select(qa_band);
var mask = qa.bitwiseAnd(cloudShadowBitMask).eq(0).and(qa.bitwiseAnd(cloudsBitMask).eq(0));
return image.updateMask(mask);
}
Inputs:
- image: The Landsat image to be masked. - qa_band: The name of the quality assessment (QA) band in the Landsat image.
Output:
- image: The input Landsat image with cloud and cloud shadow pixels masked out.
Use
- Provide an input Landsat image and the name of the quality assessment (QA) band. - Call the maskCloudLandsat function, passing in the image and qa_band as input parameters. - The function will create a mask based on the QA band to identify cloud and cloud shadow pixels. - The input image will be updated with the mask, masking out the cloud and cloud shadow pixels. - The updated image will be returned.
maskCloudLandsat(image, qa_band);
maskCloudSentinel
This function masks cloud and cirrus pixels in a Sentinel-2 image using the quality assessment (QA) band. It takes an input image as a parameter. The function applies bitwise operations to create a mask that identifies cloud and cirrus pixels based on specific bit masks. The image is then updated with the mask, effectively masking out the cloud and cirrus pixels and dividing the image by 10000.
export function maskCloudSentinel(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);
}
Inputs:
- image: The Sentinel-2 image to be masked.
Output:
- image: The input Sentinel-2 image with cloud and cirrus pixels masked out and divided by 10000.
Use
- Provide an input Sentinel-2 image. - Call the maskCloudSentinel function, passing in the image as an input parameter. - The function will create a mask based on the QA band to identify cloud and cirrus pixels. - The input image will be updated with the mask, masking out the cloud and cirrus pixels and dividing the image by 10000. - The updated image will be returned.
maskCloudSentinel(image);
getImageCSqueezeInfos
This function retrieves metadata information for a given mission name. It takes a missionName parameter as input. The function checks if the missionName includes the string "LANDSAT". If true, it retrieves the metadata from the second satellite object in the satellite array. Otherwise, it retrieves the metadata from the first satellite object. The function returns an object containing the metadata.
export const getImageCSqueezeInfos = (missionName) => {
let metadata;
if (missionName.includes("LANDSAT")) {
metadata = satellite[1].get(missionName);
} else {
metadata = satellite[0].get(missionName);
}
return { metadata }
}
Inputs:
- missionName: The name of the mission for which metadata information is to be retrieved.
Output:
- metadata: The metadata information for the given mission name.
Use
- Provide a mission name as input. - Call the getImageCSqueezeInfos function, passing in the missionName as an input parameter. - The function will check if the missionName includes the string "LANDSAT". - If true, it will retrieve the metadata from the second satellite object in the satellite array. - If false, it will retrieve the metadata from the first satellite object. - The function will return an object containing the metadata information.
getImageCSqueezeInfos(missionName);
applySaviBand
This function applies the Soil-Adjusted Vegetation Index (SAVI) to an input image using the specified bands. It takes two parameters: image and bands. The function calculates the SAVI using the formula: 1.5 * (NIR - RED) / (NIR + RED + 5000), where NIR represents the Near-Infrared band and RED represents the Red band. The result is then renamed as "SAVI".
export const applySaviBand = (image, bands) => image
.expression("1.5 * (NIR - RED) / (NIR + RED + 5000)", {
NIR: image.select(bands.nir),
RED: image.select(bands.red),
})
.rename("SAVI");
Inputs:
- image: The input image to which SAVI will be applied. - bands: An object containing the names of the NIR and RED bands used in the SAVI calculation.
Output:
- image: The input image with the SAVI band applied and renamed as "SAVI".
Use
- Provide an input image and a bands object with the names of the NIR and RED bands. - Call the applySaviBand function, passing in the image and bands as input parameters. - The function will calculate the SAVI using the NIR and RED bands from the input image. - The result will be a new image with the SAVI band applied and renamed as "SAVI".
applySaviBand(image, bands);
applyEviBand
This function applies the Enhanced Vegetation Index (EVI) to an input image using the specified bands. It takes two parameters: image and bands. The function calculates the EVI using the formula: (2.5 * ((NIR - RED)) / (NIR + 6 * RED - 7.5 * BLUE + 1)), where NIR represents the Near-Infrared band, RED represents the Red band, and BLUE represents the Blue band. The result is then renamed as "EVI".
export const applyEviBand = (image, bands) => image
.expression(
"(2.5 * ((NIR - RED)) / (NIR + 6 * RED - 7.5 * BLUE + 1))",
{
NIR: image.select(bands.nir),
RED: image.select(bands.red),
BLUE: image.select(bands.blue),
}
)
.rename("EVI");
Inputs:
- image: The input image to which EVI will be applied. - bands: An object containing the names of the NIR, RED, and BLUE bands used in the EVI calculation.
Output:
- image: The input image with the EVI band applied and renamed as "EVI".
Use
- Provide an input image and a bands object with the names of the NIR, RED, and BLUE bands. - Call the applyEviBand function, passing in the image and bands as input parameters. - The function will calculate the EVI using the NIR, RED, and BLUE bands from the input image. - The result will be a new image with the EVI band applied and renamed as "EVI".
applyEviBand(image, bands);
applyNdviBand
This function applies the Normalized Difference Vegetation Index (NDVI) to an input image using the specified bands. It takes two parameters: image and bands. The function calculates the NDVI using the formula: (NIR - RED) / (NIR + RED), where NIR represents the Near-Infrared band and RED represents the Red band. The result is then renamed as "NDVI".
export const applyNdviBand = (image, bands) =>
image.expression('(NIR - RED) / (NIR + RED)', {
'NIR': image.select(bands.nir),
'RED': image.select(bands.red),
}).rename('NDVI')
Inputs:
- image: The input image to which NDVI will be applied. - bands: An object containing the names of the NIR and RED bands used in the NDVI calculation.
Output:
- image: The input image with the NDVI band applied and renamed as "NDVI".
Use
- Provide an input image and a bands object with the names of the NIR and RED bands. - Call the applyNdviBand function, passing in the image and bands as input parameters. - The function will calculate the NDVI using the NIR and RED bands from the input image. - The result will be a new image with the NDVI band applied and renamed as "NDVI".
applyNdviBand(image, bands);
applyMndwiBand
This function applies the Modified Normalized Difference Water Index (MNDWI) to an input image using the specified bands. It takes two parameters: image and bands. The function calculates the MNDWI using the formula: (GREEN - SWIR) / (GREEN + SWIR), where GREEN represents the Green band and SWIR represents the Shortwave Infrared band. The result is then renamed as "MNDWI".
export const applyMndwiBand = (image, bands) =>
image.expression('(GREEN - SWIR) / (GREEN + SWIR)', {
'GREEN': image.select(bands.green),
'SWIR': image.select(bands.swir),
}).rename('MNDWI')
Inputs:
- image: The input image to which MNDWI will be applied. - bands: An object containing the names of the Green and Shortwave Infrared (SWIR) bands used in the MNDWI calculation.
Output:
- image: The input image with the MNDWI band applied and renamed as "MNDWI".
Use
- Provide an input image and a bands object with the names of the Green and SWIR bands. - Call the applyMndwiBand function, passing in the image and bands as input parameters. - The function will calculate the MNDWI using the Green and SWIR bands from the input image. - The result will be a new image with the MNDWI band applied and renamed as "MNDWI".
applyMndwiBand(image, bands);
trainAndClassify
This function trains a classifier using the provided image and classification areas, and then classifies the image based on the trained classifier. It takes four parameters: image, classificationAreas, bands, and AOICoords. The function performs the following steps:
1. Selects the specified bands from the input image.
2. Samples regions within the classification areas using the selected bands and the "LandCover" property. 3. Trains a random forest classifier using the sampled training data, with the "LandCover" property as the class property and the selected bands as the input properties. 4. Classifies the input image using the trained classifier. 5. Returns the classified image.
export const trainAndClassify = (image, classificationAreas, bands, AOICoords) => {
let trainingData = image
.select(bands)
.sampleRegions({
collection: classificationAreas,
properties: ["LandCover"],
scale: 30,
});
let classifier = ee.Classifier.smileRandomForest(30).train({
features: trainingData,
classProperty: "LandCover",
inputProperties: bands,
});
let classified = image
.select(bands)
.classify(classifier);
return classified;
}
Inputs:
- image: The input image to be classified. - classificationAreas: The collection of areas used for training the classifier. - bands: The names of the bands to be used for training and classification. - AOICoords: The coordinates of the area of interest (AOI).
Output:
- classified: The classified image.
Use
- Provide an input image, a collection of classification areas, the names of the bands, and the coordinates of the AOI. - Call the trainAndClassify function, passing in the required parameters. - The function will train a classifier using the image and classification areas. - It will then classify the image based on the trained classifier. - The result will be the classified image.
trainAndClassify(image, classificationAreas, bands, AOICoords);
getMangroves
This function retrieves the mangrove areas from the "ESA/WorldCover/v200" dataset. It performs the following steps: 1. Retrieves the first image from the "ESA/WorldCover/v200" dataset. 2. Creates a mask to keep only the mangrove areas (value 95 represents mangroves). 3. Applies the mask to the original image, resulting in an image with only the mangrove areas. 4. Sets the visualization parameters for the mangrove areas, including the minimum and maximum values and the color palette. 5. Calculates the slope of the mangrove areas using the ee.Terrain.slope function. 6. Retrieves the map ID and creates an Earth Engine TileSource using the visualization parameters. 7. Creates an ImageOverlay using the TileSource. 8. Returns the ImageOverlay.
export const getMangroves = function () {
var dataset = ee.ImageCollection("ESA/WorldCover/v200").first();
var mangroveMask = dataset.select('Map').eq(95);
var mangroves = dataset.updateMask(mangroveMask);
var visualization = {
min: 95,
max: 95,
palette: ['000000', 'red']
};
var slope = ee.Terrain.slope(mangroves);
var mapId = slope.getMap(visualization);
var tileSource = new ee.layers.EarthEngineTileSource(mapId);
var overlay = new ee.layers.ImageOverlay(tileSource);
return overlay;
}
Inputs:
No input parameters for this function.
Output:
- overlay: An ImageOverlay containing the mangrove areas.
Use
- Call the getMangroves function. - The function will retrieve the mangrove areas from the "ESA/WorldCover/v200" dataset and create an ImageOverlay. - The ImageOverlay can be used to display the mangrove areas on a map.
getMangroves();
Geodesy
This code is a module that provides functions for computing displacement and bearing between two geographic coordinates using Earth Engine.
- The code begins by importing the "ee" module from the "../../services/earth-engine" directory. Next, the constant variable "EARTHS_RADIUS" is defined with a value of 6371000, which represents the radius of the Earth in meters.
- The code then defines two helper functions: "toDegrees" and "toRadians". The "toDegrees" function takes longitude and latitude values as input and converts them from radians to degrees. It multiplies the latitude and longitude values by 180 divided by Math.PI to convert them to degrees. It then returns an array containing the converted longitude and latitude values.
- The "toRadians" function takes a value in degrees as input and converts it to radians. It multiplies the input value by Math.PI divided by 180 and returns the result as an ee.Number object. Next, the code exports two functions: "computeDisplacement" and "computeBearing".
- The "computeDisplacement" function takes longitude, latitude, theta (bearing angle), and distance as input. It first converts the latitude and longitude values to radians using the "toRadians" function. The theta and distance values are converted to ee.Number objects.
- The function then calculates the delta value by dividing the distance by the Earth's radius.
- It then calculates the latitude components of the new coordinates using trigonometric functions. The latitude left component is obtained by multiplying the sine of latitude by the cosine of delta. The latitude right component is obtained by multiplying the cosine of latitude by the sine of delta and the cosine of theta. The latitude components are added together and passed through the arcsine function to obtain the new latitude value.
- Next, the function calculates the longitude components of the new coordinates. The longitude Y component is obtained by multiplying the sine of theta by the sine of delta and the cosine of latitude. The longitude X component is obtained by subtracting the sine of latitude multiplied by the sine of the new latitude from the cosine of delta. The longitude components are then used to calculate the new longitude value using the atan2 function.
- Finally, the function calls the "toDegrees" function to convert the new longitude and latitude values from radians to degrees and returns the result.
- The "computeBearing" function takes four arguments: the longitude and latitude values of two points. It first converts the latitude and longitude values to radians using the "toRadians" function.
- The function then calculates the delta longitude by subtracting the first longitude from the second longitude.
- Next, the function calculates the y component of the bearing vector by multiplying the sine of the delta longitude by the cosine of the second latitude.
- The function then calculates the x component of the bearing vector using trigonometric functions. It subtracts the product of the sine of the first latitude and the cosine of the second latitude multiplied by the cosine of the delta longitude from the product of the cosine of the first latitude and the sine of the second latitude.
- Finally, the function uses the atan2 function to calculate the
bearing angle from the x and y components and returns the result.
computeDisplacement
This function calculates the displacement between two geographic coordinates using Earth Engine.
const computeDisplacement = (lng, lat, theta, distance) => {
lat = toRadians(lat);
lng = toRadians(lng);
theta = ee.Number(theta);
distance = ee.Number(distance);
const delta = distance.divide(EARTHS_RADIUS);
const latLeft = lat.sin().multiply(delta.cos());
const latRight = lat.cos().multiply(delta.sin()).multiply(theta.cos());
const newLat = latLeft.add(latRight).asin();
const lngY = theta.sin().multiply(delta.sin()).multiply(lat.cos());
const lngX = delta.cos().subtract(lat.sin().multiply(newLat.sin()));
const newLng = lng.add(lngX.atan2(lngY));
return toDegrees(newLng, newLat);
};
Inputs:
- lng: The longitude of the starting point. - lat: The latitude of the starting point. - theta: The bearing angle in degrees. - distance: The distance to travel in meters.
Output:
- An array containing the longitude and latitude of the new location.
Use
- Call the function with the starting longitude, latitude, bearing angle, and distance as inputs. - The function will return an array with the longitude and latitude of the new location.
computeDisplacement(10, 20, 45, 1000);
computeBearing
This function calculates the bearing angle between two geographic coordinates using Earth Engine.
const computeBearing = (lng1, lat1, lng2, lat2) => {
lat1 = toRadians(lat1);
lat2 = toRadians(lat2);
lng1 = toRadians(lng1);
lng2 = toRadians(lng2);
const deltaLng = lng2.subtract(lng1);
const y = deltaLng.sin().multiply(lat2.cos());
const rightTerm = lat1.sin().multiply(lat2.cos()).multiply(deltaLng.cos());
const x = lat1.cos().multiply(lat2.sin()).subtract(rightTerm);
return x.atan2(y);
};
Inputs:
- lng1: The longitude of the first point. - lat1: The latitude of the first point. - lng2: The longitude of the second point. - lat2: The latitude of the second point.
Output:
- The bearing angle in radians.
Use
- Call the function with the longitude and latitude values of the two points as inputs. - The function will return the bearing angle between the two points.
computeBearing(10, 20, 30, 40);
Imagery
The code is written in JavaScript and appears to be part of a larger application related to geospatial analysis, specifically for analyzing satellite imagery. It uses Google Earth Engine (GEE) for processing and analyzing geospatial data. Here is a step-by-step explanation of the code:
- The `scoreCloudRatio` function calculates the ratio of cloud coverage in a given region. It takes a masked image with pixel values indicating cloud presence (1 for cloud, 0 for no cloud), a band name, and a geometry representing the region of interest. It also takes optional parameters for scale and maximum pixels. It first multiplies the masked image by the pixel area to get the cloudy area, then it reduces the region by adding pixel values and divides it by the pixel count to get the cloud ratio.
- The `scoreClouds` function calculates the ratio of cloud coverage in an image. It takes an image, a geometry, and a quality assurance (qa) band. It creates expressions for cloud and shadow based on bit shifting operations, applies these expressions to the image, and calculates the ratio of cloudy area to total area. The function then sets this ratio as a property "CLOUDS" on the image and returns the image.
- The `generateLayer` function creates a new layer from a given image, mission, name, and optional parameters. If parameters are undefined, it generates visualization parameters based on the mission.
- The `createThumbnail` and `createThumbnailCSqueeze` functions generate a thumbnail for the given image. The functions take an image, a geometry, parameters, and a callback function as arguments. They apply different scaling factors and visualization parameters based on the satellite type (Landsat or Sentinel-2) stored in the session storage. The functions then return the thumbnail URL.
- The `cumulativeWindow` function calculates the cumulative window of a histogram by removing up to a certain percentile of pixels in each side of the histogram's buckets. It takes a full histogram and a percentile as arguments and returns the bounds (min/max) of the cumulative window.
Overall, the code is designed to process and analyze satellite imagery, specifically for cloud coverage and creating thumbnails of the images.
scoreCloudRatio
This function calculates the ratio of the sum of cloud pixels to the total area of a given geometry.
export const scoreCloudRatio = (
masked,
bandName,
geometry,
scale = 30,
maxPixels = 1e12
) => {
const cloudyArea = masked.multiply(ee.Image.pixelArea());
const cloudClassSum = cloudyArea.reduceRegion({
reducer: ee.Reducer.sum(),
scale: scale,
maxPixels: maxPixels,
geometry: geometry,
});
return ee.Number(cloudClassSum.get(bandName)).divide(geometry.area());
};
Inputs:
- masked: The input image with cloud masking applied. - bandName: The name of the band to calculate the cloud sum for. - geometry: The geometry to calculate the cloud sum within. - scale (optional): The scale at which to reduce the image. Default is 30. - maxPixels (optional): The maximum number of pixels to reduce. Default is 1e12.
Output:
- A number representing the ratio of the sum of cloud pixels to the total area of the geometry.
Use
To use the scoreCloudRatio function, follow these steps: - Provide the required input parameters: masked, bandName, and geometry. - Optionally, specify the scale and maxPixels parameters if needed. - Call the function by passing the input parameters. - The function will return the calculated cloud ratio.
scoreCloudRatio(masked, bandName, geometry);
scoreClouds
This function calculates the ratio of cloudy pixels to the total area of a given geometry in an input image. It takes three parameters: image, geometry, and qa. The function uses the specified quality assessment (QA) band to filter out cloudy and shadow pixels using the C2 algorithm. It then calculates the area of the remaining cloudy pixels and divides it by the area of the input geometry to obtain the cloudy pixel ratio. The function returns the input image with the cloudy pixel ratio added as a property named "CLOUDS".
export const scoreClouds = (image, geometry, qa) => {
const cloud = "((b(0) >> 3) & 1)"; //C2
const shadow = "((b(0) >> 4) & 1)"; //C2
const expr = `(${cloud} || ${shadow})` ;
const filtered = image.select(qa).expression(expr);
const imageArea = filtered.multiply(ee.Image.pixelArea());
const res = imageArea.reduceRegion({
reducer: ee.Reducer.sum(),
scale: 1000,
maxPixels: 1e9,
geometry: geometry,
});
const cloudyArea = res.get(qa);
const ratio = ee.Number(cloudyArea).divide(geometry.area(1));
return image.set("CLOUDS", ratio);
};
Inputs:
- image: The input image to calculate the cloudy pixel ratio for. - geometry: The geometry to calculate the cloudy pixel ratio within. - qa: The name of the quality assessment (QA) band to use for filtering cloudy and shadow pixels.
Output:
- An image with the cloudy pixel ratio added as a property named "CLOUDS".
Use
To use the scoreClouds function, follow these steps: - Provide the required input parameters: image, geometry, and qa. - Call the function by passing the input parameters. - The function will calculate the cloudy pixel ratio using the C2 algorithm and the specified QA band. - The result will be an image with the cloudy pixel ratio added as a property named "CLOUDS".
scoreClouds(image, geometry, qa);
generateLayer
This function generates a layer using an input image, mission, name, and parameters. If the params parameter is undefined, the function calls the generateVisualizationParams function to generate default visualization parameters based on the mission. The function then creates a new Layer object using the input image, name, and params, and returns it.
export const generateLayer = (image, mission, name, params) => {
if (params=== undefined) {
console.log("params is undefined", params);
params = generateVisualizationParams(mission);
}
return new Layer(image, name, params);
};
Inputs:
- image: The input image to generate the layer from. - mission: The mission associated with the layer. - name: The name of the layer. - params: Optional visualization parameters for the layer. If not provided, default parameters will be generated based on the mission.
Output:
- layer: A new Layer object generated using the input image, name, and params.
Use
To use the generateLayer function, follow these steps: - Provide the required input parameters: image, mission, and name. - Optionally provide the params parameter for custom visualization parameters. - Call the function by passing the input parameters. - If the params parameter is not provided, the function will generate default visualization parameters based on the mission. - The function will create a new Layer object using the input image, name, and params (or default parameters). - The result will be the generated layer.
generateLayer(image, mission, name, params);
createThumbnail
This function is used to create a thumbnail image based on the input image, geometry, parameters, and callback function. The function first checks the selected satellite from the session storage. If the satellite is "Landsat", it applies scaling factors to the image using the applyScaleFactors function. It then defines a visualization object with the specified bands, minimum value, and maximum value. The function visualizes the image using the visualization parameters and returns the thumbnail URL. If the selected satellite is not "Landsat", the function generates a thumbnail using generic code for LANDSAT COL1 and SENTINEL satellites. The generation parameters are defined based on the input geometry, format, dimensions, and additional parameters. The function checks the date of the image and applies specific generation parameters if the image belongs to the Sentinel-2 satellite and the date is after February 1, 2022. The function then returns the thumbnail URL.
export const createThumbnail = (image, geometry, params, callback) => {
//code for LANDSAT COLLECTION 2
let satellite = window.sessionStorage.getItem("selectedSatellite");
if (satellite === "Landsat") {
//if(image.getInfo().bands[0].id.indexOf("SR") != -1){
// Applies scaling factors.
function applyScaleFactors(image) {
var opticalBands = image.select('SR_B.').multiply(0.0000275).add(-0.2);
var thermalBands = image.select('ST_B.*').multiply(0.00341802).add(149.0);
return image.addBands(opticalBands, null, true).addBands(thermalBands, null, true);
}
// image = applyScaleFactors(image);
console.log("bands thumbnail", params.bands, "image", image, image.getInfo());
var visualization = {
bands: params.bands,//['SR_B4', 'SR_B3', 'SR_B2']
min: 0.0,
max: 0.4, //0.3
};
console.log("IMG::", "param", params, "bands", params.bands, image.getInfo(), "Id()", image.id(), "Id().getInfo()", image.id, image.id().getInfo(), "properties", image.propertyNames().getInfo());
//LANDSAT- 5 (3,2,1)
var outImg = image.visualize(visualization);
//console.log("createThumbnail", "visualization", outImg.getThumbURL({region: geometry,dimensions: 512, format: 'png'}))
return outImg.getThumbURL({ region: geometry, dimensions: 512, format: 'png' }, callback);
} else {
//generic code (LANDSAT COL1, SENTINEL)
const generationParams = {
region: geometry,
format: "jpg",
dimensions: 512,
...params,
};
if (satellite === "Sentinel-2") {
let dt = new Date(image.getInfo().properties["system:time_start"].value);
let dtThreshold = new Date(2022, 1, 1);// 01.02.2022
if (dt > dtThreshold) {
generationParams.max = 4000;
generationParams.min = 1000;
return image.getThumbURL(generationParams, callback);
}
}
return image.getThumbURL(generationParams, callback);
}
};
};
Inputs:
- image: The input image to create a thumbnail from. - geometry: The geometry to define the region of interest for the thumbnail. - params: Additional parameters for thumbnail generation. - callback: The callback function to handle the thumbnail URL.
Output:
- thumbnailURL: The URL of the generated thumbnail image.
Use
To use the createThumbnail function, follow these steps: - Provide the required input parameters: image, geometry, params, and callback. - Optionally provide additional parameters for customizing the thumbnail generation. - Call the function by passing the input parameters. - The function will generate a thumbnail image based on the input image, geometry, and parameters. - The result will be the URL of the generated thumbnail image.
createThumbnail(image, geometry, params, callback);
createThumbnailCSqueeze
This function is used to create a thumbnail image based on the given parameters.
export const createThumbnailCSqueeze = (image, geometry, params, callback) => {
console.log("CREATING CSQUEEZE THUMBNAIL", params, geometry)
//code for LANDSAT COLLECTION 2
let satellite = window.sessionStorage.getItem("selectedSatellite");
if (satellite === "Landsat") {
//if(image.getInfo().bands[0].id.indexOf("SR") != -1){
// Applies scaling factors.
function applyScaleFactors(image) {
var opticalBands = image.select('SR_B.').multiply(0.0000275).add(-0.2);
var thermalBands = image.select('ST_B.*').multiply(0.00341802).add(149.0);
return image.addBands(opticalBands, null, true).addBands(thermalBands, null, true);
}
image = applyScaleFactors(image);
console.log("bands thumbnail", params.bands, "image", image, image.getInfo());
var visualization = {
bands: params.bands,//['SR_B4', 'SR_B3', 'SR_B2']
min: 0.0,
max: 0.3, //0.3
};
// console.log("IMG::", "param", params, "bands", params.bands, image.getInfo(), "Id()", image.id(), "Id().getInfo()", image.id, image.id().getInfo(), "properties", image.propertyNames().getInfo());
//LANDSAT- 5 (3,2,1)
var outImg = image.visualize(visualization);
//console.log("createThumbnail", "visualization", outImg.getThumbURL({region: geometry,dimensions: 512, format: 'png'}))
return outImg.getThumbURL({ region: geometry, dimensions: 512, format: 'png' }, callback);
} else {
//generic code (LANDSAT COL1, SENTINEL)
const generationParams = {
region: geometry,
format: "jpg",
dimensions: 512,
...params,
};
// if (satellite === "Sentinel-2") {
// let dt = new Date(image.getInfo().properties["system:time_start"].value);
// let dtThreshold = new Date(2022, 1, 1);// 01.02.2022
// if (dt > dtThreshold) {
// generationParams.max = 4000;
// generationParams.min = 1000;
// return image.getThumbURL(generationParams, callback);
// }
// }
return image.getThumbURL(generationParams, callback);
}
};
Inputs:
- image: The image to create a thumbnail from. - geometry: The geometry of the thumbnail. - params: Additional parameters for creating the thumbnail. - callback: The callback function to be executed after the thumbnail is created.
Output:
- The URL of the created thumbnail image.
Use
- Call the function with the required inputs to create a thumbnail image.
createThumbnailCSqueeze(image, geometry, params, callback);
cumulativeWindow
Calculates the cumulative window of the *fullHistogram* by removing up to *percentile* pixels in each side of the histogram's buckets.
export const cumulativeWindow = (fullHistogram, percentile) => {
/* Cast to dictionary and retrieve histogram and buckets */
const cast = ee.Dictionary(fullHistogram);
const histogram = ee.List(cast.get("histogram"));
const buckets = ee.List(cast.get("bucketMeans"));
const pixelCount = ee.Number(histogram.reduce(ee.Reducer.sum()));
const cumulativeCut = pixelCount.multiply(percentile);
/*
* lowerBound returns the min level where cumulative sum
* would have exceeded the percentile threshold
*/
const lowerBound = (histogram, buckets) => {
const cumulativeMin = ee.List.sequence(
0,
buckets.size().subtract(1)
).iterate(
(idx, acc) => {
const ctx = ee.Dictionary(acc);
const sum = ctx.getNumber("sum").add(histogram.getNumber(idx));
const min = ee.Algorithms.If(
sum.gt(cumulativeCut),
ctx.getNumber("min"),
buckets.getNumber(idx)
);
return ee.Dictionary({ min, sum });
},
{ min: buckets.getNumber(0), sum: 0 }
);
return ee.Dictionary(cumulativeMin).getNumber("min");
};
/* Calculate the bound of each side */
const lower = lowerBound(histogram, buckets);
const upper = lowerBound(histogram.reverse(), buckets.reverse());
return ee.List([lower, upper]);
};
Inputs:
- fullHistogram: An ee.Dictionary representing the full histogram. - percentile: A number or ee.Number representing the percentile to remove from each side of the histogram.
Output:
- An ee.List representing the cumulative window bounds (min/max).
Use
- Call the function with the required inputs to calculate the cumulative window.
cumulativeWindow(fullHistogram, percentile);
Satellite-Landsat
The code provided is a collection of functions related to acquiring and processing satellite imagery data. Here is a step-by-step explanation of the code:
- The code imports necessary modules and functions from other files.
- The function `addGridPosition` takes an image element as input and adds a property called "GRID_POSITION" to the image. The "GRID_POSITION" is computed based on the "WRS_PATH" and "WRS_ROW" properties of the image.
- The function `sliceByRevisit` takes a collection, a starting date, and a number of days as input. It filters the collection based on the date range specified by the starting date and the number of days.
- The function `acquireFromDate` takes a date, a mission, and a geometry as input. It uses the `sliceByRevisit` function to filter the image collection based on the mission and geometry. It then creates a mosaic of the filtered images and clips it to the specified geometry. The resulting image is then passed to the `scoreClouds` function along with the geometry and the mission's QA bands to compute a cloud score for the image.
- The function `processCollection` takes a mission and a geometry as input. It retrieves the image collection for the mission and filters it based on the geometry. It then performs several operations on the filtered collection, including retrieving the globally extreme dates, computing the grid position of each image, filtering images based on the northeasternmost grid position, computing the difference in days between the earliest image in the northeastern position and the globally earliest image, and generating slices of images based on complete orbital cycles. Finally, it returns a list of valid dates within the region.
- The function `generateCloudMap` takes a list of dates, a mission, and a geometry as input. It iterates over the list of dates and calls the `acquireFromDate` function to acquire the corresponding image for each date. It then retrieves the "CLOUDS" property of each image and returns a list of cloud values.
- The function `queryAvailable` takes a mission as input and returns a function that takes a geometry as input. It calls the `processCollection` function to retrieve the image collection for the mission and filters it based on the geometry. It then formats the dates as ISO standard formatting and UTC and generates a cloud map using the `generateCloudMap` function. Finally, it returns a dictionary with the dates as keys and the corresponding cloud values as values.
- The functions `getAvailable` and `acquire` are placeholders and currently do not have any implementation.
- The function `format` takes a dictionary of properties as input and returns a formatted string that includes the "system:time_start" and "cloud" properties.
- The code exports an object with several functions as properties, including `queryAvailable` , `getAvailable` , `acquire` , and `format` .
addGridPosition
This function adds the grid position to an element. It takes an element as input and returns an image with the grid position added.
const addGridPosition = (element) => {
const image = ee.Image(element);
const rawPosition = {
path: image.get("WRS_PATH"),
row: image.get("WRS_ROW"),
};
const position = ee
.Number(rawPosition.path)
.multiply(100)
.add(ee.Number(rawPosition.row));
return image.set({ [Metadata.GRID_POSITION]: position });
};
Inputs:
- element: The element to which the grid position will be added.
Output:
- image: The image with the grid position added.
Use
To use this function, follow these steps: - Call the addGridPosition function and pass the element as an argument. - The function will create an image from the element. - It will retrieve the WRS_PATH and WRS_ROW properties from the image. - The function will calculate the grid position by multiplying the path by 100 and adding the row. - Finally, it will set the grid position as a property on the image and return the updated image.
addGridPosition(element);
sliceByRevisit
This function slices a collection of images based on a starting date and a number of days. It takes three parameters: collection, startingDate, and days. The function filters the collection to include only the images within the specified date range.
const sliceByRevisit = (collection, startingDate, days) => {
const start = ee.Date(startingDate).update(null, null, null, 0, 0, 0);
const end = start.advance(days, "day");
return collection.filterDate(start, end);
};
Inputs:
- collection: The collection of images to be sliced. - startingDate: The starting date of the slice. - days: The number of days to include in the slice.
Output:
- collection: The sliced collection of images.
Use
- Provide a collection of images, a starting date, and the number of days. - Call the sliceByRevisit function, passing in the collection, startingDate, and days as input parameters. - The function will convert the startingDate to an ee.Date object and set the time to 00:00:00. - It will then calculate the end date by advancing the startingDate by the specified number of days. - The function will filter the collection to include only the images within the specified date range. - The sliced collection will be returned as the output.
sliceByRevisit(collection, startingDate, days);
acquireFromDate
This function acquires an image from a specific date and mission, within a given geometry. It takes three parameters: date, mission, and geometry. The function first slices the image collection based on the provided date and mission using the sliceByRevisit function. It then mosaics the sliced images and clips the result to the specified geometry. The function sets the properties of the mosaicked image by merging the properties of the sliced images. Finally, it applies the scoreClouds function to the image using the provided geometry and mission bands.qa, and returns the resulting image.
export const acquireFromDate = (date, mission, geometry) => {
const slice = sliceByRevisit(
ee.ImageCollection(mission.name).filterBounds(geometry),
date,
mission.cycle
);
const mosaicked = slice.mosaic().clip(geometry);
const image = mosaicked.set(mergeProperties(slice));
return scoreClouds(image, geometry, mission.bands.qa);
};
Inputs:
- date: The specific date from which to acquire the image. - mission: An object containing information about the mission, including its name, cycle, and bands.qa. - geometry: The geometry within which to acquire the image.
Output:
- image: The acquired image with clouds scored, clipped to the specified geometry, and with merged properties from the sliced images.
Use
- Provide a specific date, a mission object, and a geometry. - Call the acquireFromDate function, passing in the date, mission, and geometry as input parameters. - The function will filter the image collection based on the mission name and the provided geometry. - It will then slice the collection using the sliceByRevisit function, with the date and mission cycle as parameters. - The function will mosaic the sliced images and clip the result to the specified geometry. - It will set the properties of the mosaicked image by merging the properties of the sliced images. - The function will apply the scoreClouds function to the image using the provided geometry and mission bands.qa. - The resulting image, with clouds scored and clipped to the geometry, will be returned as the output.
acquireFromDate(date, mission, geometry);
processCollection
This function processes an image collection for a specific mission and geometry. It takes two parameters: mission and geometry. The function first filters the image collection based on the provided mission name and geometry using the ee.ImageCollection().filterBounds() method. It then defines a process function that performs several operations on the filtered image collection. The process function retrieves the globally extreme dates (earliest and latest) using the retrieveExtremes() function. It computes the grid position of each image in the collection and sorts them in ascending order. The function retrieves the northeasternmost grid position within the specified bounds. It keeps the images in the slice where the satellite passed first (northeast) using the filter() method. The function retrieves the extremes in the northeastern position using the retrieveExtremes() function. It computes the difference in days between the earliest image in the northeastern position and the globally earliest image. The function computes the amount of complete orbital cycles between the earliest and latest possible dates of the images in the northeastern position. It generates slices of 16, one for each complete cycle. The function transforms each slice into an empty image and adds metadata related to the corresponding orbital cycle. It keeps only the images whose combined geometries contain the AOI using the filter() method. Finally, the function returns a list of the dates of the valid images.
export const processCollection = (mission, geometry) => {
const query = ee.ImageCollection(mission.name).filterBounds(geometry);
const process = (available) => {
const global = retrieveExtremes(available);
const enhanced = available
.map(addGridPosition)
.sort(Metadata.GRID_POSITION);
const northeasternPosition = ee
.Image(enhanced.toList(1).get(0))
.get(Metadata.GRID_POSITION);
const filtered = enhanced.filter(
ee.Filter.eq(Metadata.GRID_POSITION, northeasternPosition)
);
const northeastern = retrieveExtremes(filtered);
const difference = northeastern.earliest
.difference(global.earliest, "day")
.abs();
const remainder = ee.Number(difference).mod(mission.cycle);
const step = ee.Number(mission.cycle).subtract(remainder);
const earliestDate = global.earliest.advance(step.multiply(-1), "day");
const completeCycles = ee
.Number(earliestDate.difference(global.latest, "day").abs())
.divide(mission.cycle)
.ceil();
const additions = ee.List.sequence(0, null, mission.cycle, completeCycles);
const carriers = additions.map((increment) => {
const startingDate = earliestDate.advance(increment, "day");
const collection = sliceByRevisit(available, startingDate, mission.cycle);
const empty = ee.Algorithms.IsEqual(collection.size(), 0);
const properties = ee.Algorithms.If(
empty,
{},
mergeProperties(collection)
);
return ee.Image(0).set(properties);
});
const valid = ee.ImageCollection.fromImages(carriers).filter(
ee.Filter.contains(Metadata.FOOTPRINT, geometry)
);
return ee.List(valid.toList(valid.size()).map(getDate));
};
return ee.List(
ee.Algorithms.If(query.size().gt(0), process(query), ee.List([]))
);
};
Inputs:
- mission: An object containing information about the mission, including its name. - geometry: The geometry within which to process the image collection.
Output:
- A list of dates corresponding to the valid images in the processed image collection.
Use
- Provide a mission object and a geometry. - Call the processCollection function, passing in the mission and geometry as input parameters. - The function will filter the image collection based on the mission name and the provided geometry. - It will then perform several operations on the filtered image collection, including retrieving extreme dates, computing grid positions, and filtering images based on the northeastern position. - The function will generate slices and transform them into empty images with metadata related to the orbital cycle. - It will keep only the images whose combined geometries contain the AOI. - The function will return a list of dates corresponding to the valid images in the processed image collection.
processCollection(mission, geometry);
generateCloudMap
This function generates a cloud map based on the given dates, mission, and geometry.
export const generateCloudMap = (dates, mission, geometry) => {
const cloudList = ee.List(dates).map((date) => {
const image = ee.Image(acquireFromDate(date, mission, geometry));
return image.get("CLOUDS");
});
return cloudList;
};
Inputs:
- dates: An array of dates. - mission: The mission name. - geometry: The geometry of the area.
Output:
- cloudList: A list of cloud values.
Use
- Call the function with the desired inputs to generate a cloud map.
generateCloudMap(dates, mission, geometry);
queryAvailable
This function queries the availability of data for a given mission and geometry. It takes the mission as a parameter and returns a function that takes the geometry as a parameter. The returned function processes the collection based on the mission and geometry, and then generates a dictionary with dates and corresponding cloud values.
const queryAvailable = (mission) => (geometry) => {
const query = processCollection(mission, geometry);
const process = (available) => {
const datesQuery = available.map((date) =>
// Format Data as ISO standart formating and and UTC
ee.Date(date).format(null, 'UTC')
);
const cloudQuery = generateCloudMap(datesQuery, mission, geometry);
return ee.Dictionary.fromLists(datesQuery, cloudQuery);
};
return ee.Dictionary(
ee.Algorithms.If(query.size().gt(0), process(query), ee.Dictionary({}))
);
};
Inputs:
- mission: The name of the mission. - geometry: The geometry of the area.
Output:
- A dictionary containing the dates and corresponding cloud values.
Use
- Call the queryAvailable function with the desired mission as the input. - The function will return another function that takes the geometry as the input. - Call the returned function with the desired geometry. - The function will query the availability of data for the given mission and geometry. - It will generate a dictionary with dates formatted in ISO standard and UTC, and corresponding cloud values.
queryAvailable(mission)(geometry);
acquire
This function is used to acquire data for a specific mission, date, and geometry. It takes the mission as a parameter and returns a function that takes the date and geometry as parameters. The returned function calls the acquireFromDate function to acquire data for the specified date, mission, and geometry.
const acquire = (mission) => (date, geometry) => {
return acquireFromDate(date, mission, geometry);
};
Inputs:
- mission: The name of the mission. - date: The specific date for which data needs to be acquired. - geometry: The geometry of the area.
Output:
- Data acquired for the specified mission, date, and geometry.
Use
- Call the acquire function with the desired mission as the input. - The function will return another function that takes the date and geometry as inputs. - Call the returned function with the desired date and geometry. - The function will acquire data for the specified mission, date, and geometry using the acquireFromDate function. - The acquired data will be returned as the output.
acquire(mission)(date, geometry);
format
This function takes a properties object as input and returns a formatted string. The formatted string is created by concatenating the values of the "system:time_start" and "cloud" properties of the input object, separated by " -- ".
const format = (properties) => {
return properties["system:time_start"] + " -- " + properties["cloud"];
};
Inputs:
- properties: An object containing the properties of the data.
Output:
- A formatted string created by concatenating the values of the "system:time_start" and "cloud" properties, separated by " -- ".
Use
- Provide an object with the desired properties. - Call the format function, passing in the properties object as an input parameter. - The function will return a formatted string that combines the values of the "system:time_start" and "cloud" properties.
format(properties);
Satellite-Sentinel
This code is a collection of functions that are used to process satellite imagery data from Google Earth Engine. It performs various operations such as masking clouds, acquiring images from a specific date, and retrieving a list of valid dates for image retrieval.
Here is a step-by-step explanation:
1. The code starts by importing necessary dependencies and utility functions from different modules.
2. `addGridPosition` function is defined, which adds the grid position as metadata to an image.
3. `sliceByRevisit` function is defined, which filters the image collection based on the given date and the number of days.
4. `maskS2Clouds` function is defined, which creates a mask for clouds in the image.
5. `acquireFromDate` function is defined, which retrieves an image from a specific date, calculates the cloud ratio, and sets it as metadata.
6. `processCollection` function is defined, which computes a list of valid dates for image retrieval. It retrieves the earliest and latest dates, filters images based on grid position, calculates the difference in days between the earliest images, and generates slices for each complete cycle.
7. `generateCloudMap` function is defined, which maps the list of dates to their respective cloud ratio.
8. `queryAvailable` and `getAvailable` functions are defined, which process the image collection and create a dictionary mapping the dates to their respective cloud ratio.
9. `acquire` function is defined, which acquires an image from a specific date if the current URL does not contain "bathymetry".
10. `format` function is defined, which formats the properties of an image.
11. Finally, the functions are exported in an object at the end.
addGridPosition
This function takes an element as input and returns an image with a grid position property set. The grid position property is obtained from the "MGRS_TILE" property of the input image.
const addGridPosition = (element) => {
const image = ee.Image(element);
return image.set({ [Metadata.GRID_POSITION]: image.get("MGRS_TILE") });
};
Inputs:
- element: The element to be processed.
Output:
- image: The input image with the grid position property set.
Use
To use this function, follow these steps: - Call the function with an element as input. - The function will return an image with the grid position property set.
addGridPosition(element);
sliceByRevisit
This function filters a collection of images based on a starting date and a number of days. It returns the filtered collection.
const sliceByRevisit = (collection, startingDate, days) => {
const start = ee.Date(startingDate).update(null, null, null, 0, 0, 0);
const end = start.advance(days, "day");
return collection.filterDate(start, end);
};
Inputs:
- collection: The collection of images to be filtered. - startingDate: The starting date for filtering. - days: The number of days to include in the filtered collection.
Output:
- collection: The filtered collection of images.
Use
To use this function, follow these steps: - Call the function with the collection, starting date, and number of days as inputs. - The function will return the filtered collection.
sliceByRevisit(collection, startingDate, days);
maskS2Clouds
This function masks out clouds in a Sentinel-2 image using the QA60 band.
Inputs:
- image: The Sentinel-2 image to be processed.
Output:
- image: The input image with clouds masked out.
Use
To use this function, follow these steps: - Call the function with the Sentinel-2 image as input. - The function will return the input image with clouds masked out.
maskS2Clouds(image);
acquireFromDate
This function acquires an image from a specific date, mission, and geometry. It filters an image collection based on the mission name and geometry, selects the image with the closest revisit date to the specified date, and clips it to the geometry. It also calculates the cloud ratio and adds it as a property to the image.
Inputs:
- date: The date for acquiring the image. - mission: The mission object containing the mission name and cycle. - geometry: The geometry to clip the acquired image.
Output:
- image: The acquired image with cloud ratio property added.
Use
To use this function, follow these steps: - Call the function with the date, mission, and geometry as inputs. - The function will return the acquired image with the cloud ratio property added.
acquireFromDate(date, mission, geometry);
processCollection
This function computes a list of valid dates in the region to be retrieved with acquireFromDate.
Inputs:
- mission: The mission object containing the name of the image collection to be processed. - geometry: The geometry object representing the region of interest.
Output:
- A list of valid dates in the specified region.
Use:
1. Call the function by providing the mission object and the geometry object as inputs. 2. The function filters the image collection based on the specified region. 3. It retrieves the globally extreme dates (earliest and latest) from the filtered collection. 4. The function computes the grid position of each image and sorts them in ascending order. 5. It retrieves the northeasternmost grid position within the specified bounds. 6. The function keeps the images in the slice where the satellite passed first (northeast). 7. It retrieves the extremes in the northeastern position. 8. The function computes the difference in days between the earliest image in the northeastern position and the globally earliest image. 9. It computes the remainder of the difference divided by the mission cycle. 10. The amount of days to go back is given by subtracting the remainder from the mission cycle. 11. The function computes the date of the earliest possible image in the northeastern position by going back in time. 12. It computes the amount of complete orbital cycles between the earliest and latest possible dates of the images in the northeastern position. 13. The function generates slices of 5, one for each complete cycle. 14. It transforms each slice into an empty image and adds metadata related to the correspondent orbital cycle. 15. The function keeps only the images whose combined geometries contain the region of interest. 16. It returns a list of valid dates.
Use`` ``example:
const mission = { name: 'exampleMission' }; const geometry = ee.Geometry.Point([-122.084, 37.42]);
const validDates = processCollection(mission, geometry);
print(validDates);
generateCloudMap
This function generates a cloud map for a given list of dates, mission, and geometry.
Inputs:
- dates: A list of dates for which the cloud map needs to be generated. - mission: The mission object containing the name of the image collection to be processed. - geometry: The geometry object representing the region of interest.
Output:
- A list of cloud maps corresponding to the input dates.
Use:
1. Call the function by providing the dates, mission, and geometry as inputs. 2. The function creates a list of cloud maps by acquiring the cloud information for each date using the acquireFromDate function. 3. It returns the list of cloud maps.
Use`` ``example:
const dates = ['2021-01-01', '2021-02-01', '2021-03-01']; const mission = { name: 'exampleMission' }; const geometry = ee.Geometry.Point([-122.084, 37.42]);
const cloudMaps = generateCloudMap(dates, mission, geometry);
print(cloudMaps);
queryAvailable
This function queries the availability of data for a given mission and geometry.
Inputs:
- mission: The mission object containing the name of the image collection to be processed.
Output:
- A dictionary with dates as keys and corresponding cloud maps as values.
Use:
1. Call the function by providing the mission object. 2. The function returns a function that takes the geometry object as an input. 3. Call the returned function by providing the geometry object. 4. The function processes the collection for the given mission and geometry. 5. It formats the data as ISO standard formatting and UTC. 6. The function generates the cloud maps using the generateCloudMap function. 7. It returns a dictionary with dates as keys and corresponding cloud maps as values.
Use`` ``example:
const mission = { name: 'exampleMission' }; const geometry = ee.Geometry.Point([-122.084, 37.42]);
const availability = queryAvailable(mission)(geometry);
print(availability);
getAvailable
This function returns a dictionary of available dates and cloud cover values for a given mission and geometry.
const getAvailable = (mission) => (geometry) => {
const query = processCollection(mission, geometry);
// Format Data as ISO standart formating and and UTC
const datesQuery = query.map((date) => ee.Date(date).format(null, 'UTC'));
const cloudQuery = generateCloudMap(datesQuery, mission, geometry);
return ee.Dictionary.fromLists(datesQuery, cloudQuery);
};
Inputs:
- mission: The mission for which the available dates and cloud cover values are requested. - geometry: The geometry object representing the area of interest.
Output:
- A dictionary where the keys are ISO-formatted dates and the values are the corresponding cloud cover values.
Use
- Call the function with the desired mission and geometry to retrieve the available dates and cloud cover values.
getAvailable('mission')(geometry);
acquire
This function acquires data for a specific date, mission, and geometry.
const acquire = (mission) => (date, geometry) => {
if(window.location.href.indexOf("bathymetry") !== -1) return false;
console.log("PARAMS", date, mission, geometry);
return acquireFromDate(date, mission, geometry);
};
Inputs:
- mission: The mission for which the data is requested. - date: The specific date for which the data is requested. - geometry: The geometry object representing the area of interest.
Output:
- The acquired data for the specified date, mission, and geometry.
Use
1. Check if the current URL contains "bathymetry". If it does, return false. 2. Print the parameters (date, mission, geometry) to the console. 3. Call the acquireFromDate function with the specified date, mission, and geometry to acquire the data.
acquire('mission')('date', geometry);
format
This function formats the properties of a data object.
const format = (properties) => {
return properties["system:time_start"] + " -- " + properties["cloud"];
};
Inputs:
- properties: The properties object of a data object.
Output:
- A formatted string containing the "system:time_start" property value followed by a dash and the "cloud" property value.
Use
- Call the function with the properties object to format the properties.
format(properties);
Satellite-LandsatTOA
This code is written in JavaScript and uses the Google Earth Engine (EE) library to analyze satellite imagery. It provides a series of functions to process and analyze satellite images based on their metadata, such as their geographical location, date, and cloud coverage.
Here's a step-by-step explanation:
1. `addGridPosition` : This function adds a grid position to an image based on its 'WRS_PATH' and 'WRS_ROW' properties. It multiplies the path by 100 and adds the row to it, setting the result as the 'GRID_POSITION' metadata.
2. `sliceByRevisit` : This function filters the image collection by date, returning only the images captured within a specified number of days starting from a specific date.
3. `maskTOAClouds` : This function masks the clouds in an image. It uses bitwise operations to create a mask that identifies areas in the image where there are clouds, cloud shadows, or cirrus clouds.
4. `acquireFromDate` : This function retrieves an image from a specified date, mission, and geometry. It mosaics the images, clips them to the specified geometry, and calculates a cloud ratio score.
5. `processCollection` : This function processes the images in a specified mission and geometry. It retrieves the extreme dates (earliest and latest), sorts the images by their grid position, filters the images by their grid position, calculates the difference in days, and generates slices of images for each complete cycle.
6. `generateCloudMap` : This function generates a list of cloud ratios for a list of dates.
7. `queryAvailable` : This function queries the available images for a specified mission and geometry. It processes the collection, formats the dates, and generates a cloud map. It returns a dictionary with dates as keys and cloud ratios as values.
8. `getAvailable` and `acquire` : These are placeholders for functions that should return available images and acquire an image from a specific date and geometry, respectively.
9. `format` : This function formats the properties of an image.
10. The `export default` statement exports the `queryAvailable` , `getAvailable` , `acquire` , and `format` functions so they can be used in other modules.
addGridPosition
The function 'addGridPosition' is used to add a grid position to an image object. It retrieves the path and row properties from the image metadata, multiplies the path by 100 and adds the row number to create a unique position identifier.
const addGridPosition = (element) => {
const image = ee.Image(element);
const rawPosition = {
path: image.get("WRS_PATH"),
row: image.get("WRS_ROW"),
};
const position = ee
.Number(rawPosition.path)
.multiply(100)
.add(ee.Number(rawPosition.row));
return image.set({ [Metadata.GRID_POSITION]: position });
};
Inputs:
- element: The image element that needs a grid position added.
Output:
- It returns the image with the added grid position metadata.
Use
This function is used to add a grid position to an image object. This grid position is calculated by multiplying the path by 100 and adding the row number. This unique position identifier is then added to the image metadata.
addGridPosition(image);
sliceByRevisit
The function 'sliceByRevisit' filters an image collection by a given date range. It takes in a collection of images, a starting date and a number of days, and returns a subset of the collection that falls within this date range.
const sliceByRevisit = (collection, startingDate, days) => {
const start = ee.Date(startingDate).update(null, null, null, 0, 0, 0);
const end = start.advance(days, "day");
return collection.filterDate(start, end);
};
Inputs:
- collection: The collection of images to be filtered.
- startingDate: The start date for the date range.
- days: The number of days for the date range.
Output:
- It returns a subset of the image collection that falls within the specified date range.
Use
This function is used to filter an image collection by a given date range. The starting date and the number of days form the date range. The function returns a subset of the image collection that falls within this date range.
sliceByRevisit(collection, '2022-01-01', 30);
maskTOAClouds
This function masks out clouds in an image based on the specified band.
export const maskTOAClouds = (image, bandName) => {
const band = image.select(bandName);
const cloudMask = 1 << 4,
cloudConf = 3 << 5,
shadowConf = 3 << 7,
cirrusConf = 3 << 11;
return band
.bitwiseAnd(cloudMask)
.and(
band
.bitwiseAnd(cloudConf)
.gt(1)
.or(band.bitwiseAnd(shadowConf).gt(1))
.or(band.bitwiseAnd(cirrusConf).gt(1))
);
};
Inputs:
- image: The image to be processed. - bandName: The name of the band to be used for masking.
Output:
- A masked image with clouds removed.
Use
- Select an image and specify the band name to be used for masking. - Call the function with the image and band name as inputs. - The function will return a masked image with clouds removed.
maskTOAClouds(image, "qa");
acquireFromDate
This function acquires an image from a specific date, mission, and geometry.
export const acquireFromDate = (date, mission, geometry) => {
const slice = sliceByRevisit(
ee.ImageCollection(mission.name).filterBounds(geometry),
date,
mission.cycle
);
const mosaicked = slice.mosaic().clip(geometry);
const image = mosaicked.set(mergeProperties(slice));
const ratio = scoreCloudRatio(
maskTOAClouds(image, mission.bands.qa),
mission.bands.qa,
geometry
);
return image.set("CLOUDS", ratio);
};
Inputs:
- date: The date of the image to be acquired. - mission: The mission object containing the name, cycle, and bands information. - geometry: The geometry to filter the image collection.
Output:
- An acquired image with clouds masked and additional metadata.
Use
- Specify the date, mission, and geometry for acquiring the image. - Call the function with the specified inputs. - The function will return an acquired image with clouds masked and additional metadata.
acquireFromDate("2022-01-01", missionObject, geometryObject);
processCollection
This function processes a collection of satellite images based on the given mission and geometry.
export const processCollection = (mission, geometry) => {
const query = ee.ImageCollection(mission.name).filterBounds(geometry);
// Retrieve the globally extreme dates (earliest and latest)
const global = retrieveExtremes(query);
// Compute the grid position of each image and sort in ascending order
const enhanced = query.map(addGridPosition).sort(Metadata.GRID_POSITION);
// Retrieve the northeasternmost grid position within the specified bounds
const northeasternPosition = ee
.Image(enhanced.toList(1).get(0))
.get(Metadata.GRID_POSITION);
// Keep images in the slice where the satellite passed first (northeast)
const filtered = enhanced.filter(
ee.Filter.eq(Metadata.GRID_POSITION, northeasternPosition)
);
// Retrieve the extremes in the northeastern position
const northeastern = retrieveExtremes(filtered);
// Compute the difference in days between the earliest image in the
// northeastern position and the globally earliest image
const difference = northeastern.earliest
.difference(global.earliest, "day")
.abs();
const remainder = ee.Number(difference).mod(mission.cycle);
// The amount of days we need to go back is given by the reverse of the
// difference, in terms of the duration of an orbit
const step = ee.Number(mission.cycle).subtract(remainder);
// Compute the date of the earliest possible image in the northeastern
// position (whether or not it exists) by going back in time
const earliestDate = global.earliest.advance(step.multiply(-1), "day"); // 1.21 gigawatts!
// Compute the amount of complete orbital cycles between the earliest and
// latest possible dates of the images in the northeastern position (whether
// or not they exist)
const completeCycles = ee
.Number(earliestDate.difference(global.latest, "day").abs())
.divide(mission.cycle)
.ceil();
// Generate slices of 16 (0, 16, 32, 48, ...), one for each complete cycle
const additions = ee.List.sequence(0, null, mission.cycle, completeCycles);
// Transform each slice into an empty image. If the slice contains at least
// one image, we add metadata related to the correspondent orbital cycle,
// to allow for filtering later
const carriers = additions.map((increment) => {
const startingDate = earliestDate.advance(increment, "day");
const collection = sliceByRevisit(query, startingDate, mission.cycle);
const empty = ee.Algorithms.IsEqual(collection.size(), 0);
const properties = ee.Algorithms.If(empty, {}, mergeProperties(collection));
return ee.Image(0).set(properties);
});
// Keep only the images whose combined geometries contain the AOI
const valid = ee.ImageCollection.fromImages(carriers).filter(
ee.Filter.contains(Metadata.FOOTPRINT, geometry)
);
if(valid.size()===0){
console.log("Valid size is 0");
return null;
}
// For now only the date of the slice is important.
return ee.List(valid.toList(valid.size()).map(getDate));
};
Inputs:
- mission: The mission object containing the name of the satellite mission. - geometry: The geometry object defining the area of interest.
Output:
- A list of dates representing the slices of satellite images within the specified bounds.
Use
- Create a mission object specifying the name of the satellite mission. - Create a geometry object defining the area of interest. - Call the processCollection function with the mission and geometry as inputs. - The function will process the collection of satellite images based on the given mission and geometry. - The function will return a list of dates representing the slices of satellite images within the specified bounds.
processCollection(mission, geometry);
generateCloudMap
This function generates a cloud map based on the provided dates, mission, and geometry.
export const generateCloudMap = (dates, mission, geometry) => {
const cloudList = ee.List(dates).map((date) => {
const image = ee.Image(acquireFromDate(date, mission, geometry));
return image.get("CLOUDS");
});
return cloudList;
};
Inputs:
- dates: A list of dates. - mission: The mission name. - geometry: The geometry for the cloud map.
Output:
- cloudList: A list of cloud maps.
Use
- Call the function with the desired inputs to generate a cloud map.
generateCloudMap(dates, mission, geometry);
queryAvailable
This function queries the availability of data for a given mission and geometry. It takes two parameters: mission and geometry. The function first processes the collection using the processCollection function. If the query is null, it logs a message and returns null. Otherwise, it logs the query and its information, formats the dates in ISO standard format and UTC, generates a cloud map using the generateCloudMap function, and returns a dictionary with the dates and corresponding cloud maps.
const queryAvailable = (mission) => (geometry) => {
const query = processCollection(mission, geometry);
if(query===null){
console.log("query is null");
return null;
}
console.log("query", query, query.getInfo());
const datesQuery = query.map((date) => ee.Date(date).format(null, 'UTC')); // Format Data as ISO standart formating and and UTC
console.log("datesQuery", datesQuery,datesQuery.getInfo());
const cloudQuery = generateCloudMap(datesQuery, mission, geometry);
return ee.Dictionary.fromLists(datesQuery, cloudQuery);
};
Inputs:
- mission: The mission name. - geometry: The geometry for the query.
Output:
- A dictionary containing the dates as keys and the corresponding cloud maps as values.
Use
- Provide a mission name and a geometry for the query. - Call the queryAvailable function, passing in the mission and geometry as input parameters. - The function will process the collection, log the query and its information, format the dates in ISO standard format and UTC, generate a cloud map, and return a dictionary with the dates and corresponding cloud maps.
queryAvailable(mission)(geometry);
getAvailable
This function retrieves the available data for a given mission and geometry. It takes two parameters: mission and geometry. The function is currently empty and does not have any functionality implemented.
const getAvailable = (mission) => (geometry) => {};
Inputs:
- mission: The mission name. - geometry: The geometry for the query.
Output:
- No output parameters for this function.
Use
- Provide a mission name and a geometry for the query. - Call the getAvailable function, passing in the mission and geometry as input parameters. - Currently, the function does not have any functionality implemented.
getAvailable(mission)(geometry);
acquire
This function acquires data for a given mission, date, and geometry. It takes three parameters: mission, date, and geometry. The function calls the acquireFromDate function, passing in the date, mission, and geometry, and returns the result.
const acquire = (mission) => (date, geometry) => {
return acquireFromDate(date, mission, geometry);
};
Inputs:
- mission: The mission name. - date: The date for which to acquire the data. - geometry: The geometry for the acquisition.
Output:
- The result of the acquireFromDate function.
Use
- Provide a mission name, a date, and a geometry for the acquisition. - Call the acquire function, passing in the mission, date, and geometry as input parameters. - The function will call the acquireFromDate function with the provided parameters and return the result.
acquire(mission)(date, geometry);
format
This function takes a properties object as input and returns a formatted string. The formatted string consists of the value of the "system:time_start" property concatenated with the value of the "cloud" property, separated by "--".
const format = (properties) => {
return properties["system:time_start"] + " -- " + properties["cloud"];
};
Inputs:
- properties: The properties object to be formatted.
Output:
- A formatted string.
Use
- Provide a properties object as input. - Call the format function, passing in the properties object. - The function will return a formatted string, concatenating the values of the "system:time_start" and "cloud" properties with "--" in between.
format(properties);
queryAvailable
This function is exported as part of the default export object. It is not defined in the given code snippet.
export default {
queryAvailable,
getAvailable,
acquire,
format,
};
Inputs:
- No input parameters for this function.
Output:
- No output parameters for this function.
Use
- This function is part of the default export object. - It can be accessed by importing the default export and using the "queryAvailable" property. - The function is not defined in the given code snippet, so its usage is not provided.
import myFunctions from 'myFunctions.js';
| code = myFunctions.queryAvailable();
getAvailable
This function is exported as part of the default export object. It is not defined in the given code snippet.
export default {
queryAvailable,
getAvailable,
acquire,
format,
};
Inputs:
- No input parameters for this function.
Output:
- No output parameters for this function.
Use
- This function is part of the default export object. - It can be accessed by importing the default export and using the "getAvailable" property. - The function is not defined in the given code snippet, so its usage is not provided.
import myFunctions from 'myFunctions.js';
| code = myFunctions.getAvailable();
acquire
This function is exported as part of the default export object. It is not defined in the given code snippet.
export default {
queryAvailable,
getAvailable,
acquire,
format,
};
Inputs:
- No input parameters for this function.
Output:
- No output parameters for this function.
Use
- This function is part of the default export object. - It can be accessed by importing the default export and using the "acquire" property. - The function is not defined in the given code snippet, so its usage is not provided.
import myFunctions from 'myFunctions.js';
| code = myFunctions.acquire();
Shoreline
This JavaScript code is part of a larger application that uses Google Earth Engine to analyze satellite imagery. Specifically, this script is designed to identify, analyze, and extract shorelines from the images.
Here's a step-by-step breakdown:
- The code starts by importing various modules and functions from other parts of the application. These include Earth Engine service, geodesy computations, metadata handling, utility functions, and Material UI icons.
- The `identifyWaterFeature` function is defined. This function partitions a raster image using a water index and a threshold function, then reduces the output raster to a vector, which corresponds to the water body in the image.
- The `removeShorelineNoise` function is defined. This function removes noises from the shoreline by keeping only the polygons that have the most intersections with the transects.
- The `gaussianKernel` function is defined. This function creates a Gaussian kernel controlled by size, mean, and sigma.
- The `linearGaussianFilter` function is defined. This function applies a linear Gaussian filter to a list of coordinates, producing local averages weighted by a Gaussian kernel.
- The `thresholdingAlgorithm` function is defined.
- The function `expandCoastline` takes in the `coordinates` and `distance` parameters.
- The `coordinates` parameter is converted to an `ee.List` object.
- The `neighbors` variable is created by extracting all elements from the `coordinates` list except the first one.
- The `displacedSegments` variable is created by mapping over the `coordinates` and `neighbors` lists. For each pair of coordinates, the function `computeBearing` is called to calculate the bearing between the current and neighbor coordinates. Then, the function `computeDisplacement` is called twice to calculate the new displaced points ( `p1` and `p2` ) based on the bearing and distance.
- The `rectifyJunctions` function is called with the `displacedSegments` and `coordinates` as parameters. This function normalizes the junctions of the segments by calculating the angles and lengths between adjacent segments.
- The `combined` variable is created by reversing the `coordinates` list, splicing the `displacedSegments` at the beginning, and creating a new list.
- Finally, the function returns an `ee.Feature` object with a `Polygon` geometry created from the `combined` list.
The `rectifyJunctions` function performs the following steps:
- The function takes in the `segments` and `originalCoordinates` parameters.
- The `segments` parameter is converted to an `ee.List` object.
- The `originalCoordinates` parameter is sliced to remove the first element.
- The `neighbors` variable is created by extracting all elements from the `segments` list except the first one.
- The `processed` variable is created by mapping over the indices of the `neighbors` list. For each index, the function calculates the angles and lengths between the current segment, neighbor segment, and original coordinates. The centroid of the displacement is then calculated using the `computeDisplacement` function.
- The first and last coordinates of the segments are extracted and added to the `processed` list.
- The `processed` list is returned as the result.
identifyWaterFeature
This function identifies water features in an image by performing a thresholding operation. It returns a binary image with water features identified.
Inputs:
No input parameters for this function.
Output:
- Binary image with water features identified.
Use
- Load an image
- Call the identifyWaterFeature() function passing the image as argument.
var image = ee.Image('LANDSAT/LC08/C01/T1_SR/LC08_044034_20140318');
var water = identifyWaterFeature(image);
removeShorelineNoise
This function removes noise from a shoreline geometry by performing morphological closing and simplification.
Inputs:
- Shoreline geometry
- Kernel size for morphological closing
- Tolerance for geometry simplification
Output:
- Shoreline geometry with noise removed
Use
- Obtain a shoreline geometry
- Call the removeShorelineNoise() function passing the geometry and kernel size and tolerance as arguments.
var shoreline = /* Obtain shoreline geometry */;
var cleaned = removeShorelineNoise(shoreline, 3, 10);
gaussianKernel
This function creates a Gaussian kernel.
Inputs:
- Kernel size
- Standard deviation
- Kernel type (square or circle)
Output:
- Gaussian kernel
Use
- Call the gaussianKernel() function passing kernel size, standard deviation and kernel type as arguments.
var kernel = gaussianKernel(5, 2, 'square');
linearGaussianFilter
This function performs Gaussian filtering on a line geometry.
Inputs:
- Line geometry
- Kernel size
- Standard deviation
- Kernel type (square or circle)
Output:
- Smoothed line geometry
Use
- Obtain a line geometry
- Call the linearGaussianFilter() function passing the geometry, kernel size, standard deviation and kernel type as arguments.
var line = /* Obtain line geometry */;
var smoothed = linearGaussianFilter(line, 5, 2, 'square');
thresholdingAlgorithm
This function performs thresholding on an image to extract shorelines. It has options for single thresholding, multi-Otsu thresholding and interactive thresholding.
Inputs:
- Image
- Thresholding method (single, multiOtsu or interactive)
- Threshold value (for single thresholding)
Output:
- Binary image with shorelines extracted
Use
- Load an image
- Call the thresholdingAlgorithm() function passing the image, thresholding method and threshold value (if single thresholding) as arguments.
var image = ee.Image('LANDSAT/LC08/C01/T1_SR/LC08_044034_20140318');
var binary = thresholdingAlgorithm(image, 'single', 0.2);
selectThreshold
This function allows the user to interactively select a threshold value from an image histogram.
Inputs:
- Image
Output:
- Selected threshold value
Use
- Load an image
- Call the selectThreshold() function passing the image as argument.
- The function will display the image histogram and allow the user to select a threshold.
var image = ee.Image('LANDSAT/LC08/C01/T1_SR/LC08_044034_20140318');
var threshold = selectThreshold(image);
extractShoreline
This function extracts the shoreline from an image using the selected thresholding method.
Inputs:
- Image
- Thresholding method (single, multiOtsu or interactive)
- Threshold value (for single thresholding)
- Buffer distance
- Simplification tolerance
Output:
- Shoreline geometry
Use
- Load an image
- Select a threshold value (using selectThreshold() for interactive method)
- Call the extractShoreline() function passing the image, thresholding method, threshold value, buffer distance and simplification tolerance as arguments.
var image = ee.Image('LANDSAT/LC08/C01/T1_SR/LC08_044034_20140318');
var threshold = 0.2; // Selected using selectThreshold()
var shoreline = extractShoreline(image, 'single', threshold, 10, 5);
deriveShoreline
This function derives the shoreline for a single image.
Inputs:
- Image
- Satellite (Landsat or Sentinel-2)
- Region of interest
- Kernel size for morphological closing
- Simplification tolerance
Output:
- Shoreline feature
Use
- Load an image
- Define a region of interest
- Call the deriveShoreline() function passing the image, satellite, region of interest, kernel size and simplification tolerance as arguments.
var image = ee.Image('LANDSAT/LC08/C01/T1_SR/LC08_044034_20140318');
var roi = /* Define region of interest */;
var shoreline = deriveShoreline(image, 'Landsat', roi, 3, 10);
deriveShorelines
This function derives shorelines for multiple images.
Inputs:
- List of images
- Satellite (Landsat or Sentinel-2)
- Region of interest
- Kernel size for morphological closing
- Simplification tolerance
Output:
- FeatureCollection containing shorelines for all images
Use
- Load a list of images
- Define a region of interest
- Call the deriveShorelines() function passing the list of images, satellite, region of interest, kernel size and simplification tolerance as arguments.
var images = [/* List of images */];
var roi = /* Define region of interest */;
var shorelines = deriveShorelines(images, 'Landsat', roi, 3, 10);
expandCoastline
This function expands a shoreline by a specified distance.
Inputs:
- Shoreline geometry
- Expansion distance
Output:
- Expanded shoreline geometry
Use
- Obtain a shoreline geometry
- Call the expandCoastline() function passing the shoreline geometry and expansion distance as arguments.
var shoreline = /* Obtain shoreline geometry */;
var expanded = expandCoastline(shoreline, 10);
rectifyJunctions
This function rectifies junctions in a MultiLineString geometry.
Inputs:
- MultiLineString geometry
Output:
- MultiLineString geometry with junctions rectified
Use
- Obtain a MultiLineString geometry
- Call the rectifyJunctions() function passing the geometry as argument.
var mls = /* Obtain MultiLineString geometry */;
var rectified = rectifyJunctions(mls);
Utils
This code contains several utility functions that perform various tasks related to image processing and data manipulation. Here is a step-by-step explanation of each function:
1. `addGridPosition`: This function takes a satellite object and returns a function that adds a grid position property to an image. It computes the grid position using the `computeGridPosition` method of the satellite object and sets it as a property of the image.
2. `getDate`: This function takes an image and returns the date of the image using the `TIME_START` metadata property.
3. `mergeFootprints`: This function takes a collection of images and merges their footprints into a single geometry using the `geometry` method of the `ee.FeatureCollection` class.
4. `retrieveExtremes`: This function takes a collection of images and retrieves the earliest and latest images in the collection based on their start time. It sorts the collection by start time, converts it to a list, and returns the dates of the earliest and latest images.
5. `mergeProperties`: This function takes a collection of images and merges their properties into a single object. It retrieves the date of the earliest image in the collection, merges the footprints of all images, and sets the sensor ID property.
6. `combineReducers`: This function takes multiple reducers and combines them into a single reducer using the `combine` method. It iterates over the reducers and combines them one by one.
7. `serializeList`: This function takes a subject (typically a list) and serializes it into a string representation.
8. `generateVisualizationParams`: This function takes a mission object and generates visualization parameters for the mission. It extracts the red, green, and blue bands from the mission's bands property and combines them with the mission's visualization parameters.
9. `evaluate`: This function takes a query object and returns a function that can be used to evaluate the query.
10. `applyExpression`: This function applies an expression or label to an image. It searches for the corresponding index in the list of available indices and applies the expression to the image using the specified bands.
11. `imageToKey`: This function converts an image object into a string key by picking the "id" and "version" properties and serializing them as a JSON string.
12. `getSatelliteCollection`: This function takes a satellite object and returns the corresponding image collection. If the collection set property is an array, it selects the first element as the image collection.
13. `simplify`: This function takes an amount parameter and returns a function that simplifies a feature geometry by reducing the number of vertices.
These utility functions can be used in various image processing and data manipulation tasks to simplify and streamline the code.
addGridPosition
This function adds a grid position property to each image in a collection.
Inputs:
- satellite: The satellite object used to compute the grid position.
Output:
- Returns a function that takes an element (image) and sets the grid position property on the image.
Use
1. Define the satellite object. 2. Create the addGridPosition function by calling the addGridPosition function and passing the satellite object. 3. Apply the addGridPosition function to a collection of images using the map function.
const satellite = ...
const addGridPositionFunc = addGridPosition(satellite);
const collectionWithGridPosition = imageCollection.map(addGridPositionFunc);
getDate
This function retrieves the date of an image.
Inputs:
- image: The image for which to retrieve the date.
Output:
- Returns the date of the image.
Use
1. Pass an image to the getDate function. 2. The function will return the date of the image.
const image = ...
const date = getDate(image);
mergeFootprints
This function merges the footprints of a collection of features into a single geometry.
Inputs:
- collection: The collection of features whose footprints to merge.
Output:
- Returns a single geometry representing the merged footprints.
Use
1. Pass a collection of features to the mergeFootprints function. 2. The function will return a single geometry representing the merged footprints.
const collection = ...
const mergedFootprints = mergeFootprints(collection);
retrieveExtremes
This function retrieves the earliest and latest dates from a collection of images.
Inputs:
- collection: The collection of images from which to retrieve the extremes.
Output:
- Returns an object with the earliest and latest dates as properties.
Use
1. Pass a collection of images to the retrieveExtremes function. 2. The function will return an object with the earliest and latest dates.
const collection = ...
const extremes = retrieveExtremes(collection);
console.log(extremes.earliest, extremes.latest);
mergeProperties
This function merges properties from the first image in a collection to create a new object.
Inputs:
- collection: The collection of images from which to merge properties.
Output:
- Returns a new object with merged properties.
Use
1. Pass a collection of images to the mergeProperties function. 2. The function will merge properties from the first image and return a new object.
const collection = ...
const mergedProperties = mergeProperties(collection);
console.log(mergedProperties);
combineReducers
This function combines multiple reducers into a single reducer.
Inputs:
- reducers: The reducers to combine.
Output:
- Returns a combined reducer.
Use
1. Pass multiple reducers to the combineReducers function. 2. The function will return a combined reducer.
const reducer1 = ...
const reducer2 = ...
const combinedReducer = combineReducers(reducer1, reducer2);
serializeList
This function serializes a list into a string.
Inputs:
- subject: The list to serialize.
Output:
- Returns a serialized string representation of the list.
Use
1. Pass a list to the serializeList function. 2. The function will return a serialized string representation of the list.
const list = ...
const serialized = serializeList(list);
console.log(serialized);
generateVisualizationParams
This function generates visualization parameters for a mission.
Inputs:
- mission: The mission object containing band information.
Output:
- Returns an object with generated visualization parameters.
Use
1. Pass a mission object to the generateVisualizationParams function. 2. The function will return an object with generated visualization parameters.
const mission = ...
const visualizationParams = generateVisualizationParams(mission);
console.log(visualizationParams);
evaluate
This function returns a function that can be used to evaluate a query.
Inputs:
- query: The query to evaluate.
Output:
- Returns a function that can be used to evaluate the query.
Use
1. Pass a query to the evaluate function. 2. The function will return a function that can be used to evaluate the query.
const query = ...
const evaluateFunc = evaluate(query);
console.log(evaluateFunc());
applyExpression
This function applies an expression or label to an image.
Inputs:
- image: The image to apply the expression or label to. - expressionOrLabel: The expression or label to apply. - bands: An object containing band information.
Output:
- Returns a new image with the applied expression or label.
Use
1. Pass an image, expression or label, and bands object to the applyExpression function. 2. The function will return a new image with the applied expression or label.
const image = ...
const expressionOrLabel = ...
const bands = ...
const result = applyExpression(image, expressionOrLabel, bands);
console.log(result);
imageToKey
This function converts an image to a key string.
Inputs:
- image: The image to convert.
Output:
- Returns a key string representing the image.
Use
1. Pass an image to the imageToKey function. 2. The function will return a key string representing the image.
const image = ...
const key = imageToKey(image);
console.log(key);
getSatelliteCollection
This function retrieves the satellite collection from a satellite object.
Inputs:
- satellite: The satellite object.
Output:
- Returns the satellite collection as an ImageCollection.
Use
1. Pass a satellite object to the getSatelliteCollection function. 2. The function will return the satellite collection as an ImageCollection.
const satellite = ...
const collection = getSatelliteCollection(satellite);
console.log(collection);
simplify
This function simplifies a feature by reducing the number of vertices.
Inputs:
- amount: The amount of simplification to apply.
Output:
- Returns a function that takes a feature and simplifies it.
Use
1. Define the amount of simplification. 2. Create the simplify function by calling the simplify function and passing the amount. 3. Apply the simplify function to a feature using the map function.
const amount = ...
const simplifyFunc = simplify(amount);
const simplifiedFeature = featureCollection.map(simplifyFunc);