Evalscript V3

Start your evalscript with //VERSION=3 so the system will interpret it as such.

For evalscript V3 you need to specify two functions (described in detail below):

  • setup - where you specify inputs and outputs.
  • evaluatePixel - which calculates the output values for each pixel.

This is an example of a simple V3 evalscript which returns a true color image:

//VERSION=3
function setup() {
return {
input: ["B02", "B03", "B04"],
output: { bands: 3 }
};
}
function evaluatePixel(sample) {
return [2.5 * sample.B04, 2.5 * sample.B03, 2.5 * sample.B02];
}

setup function

This function is required as it sets up the input and output settings.

Specifics

Setup needs to return a javascript object with the following properties:

Input object properties

  • bands - an array of strings representing band names
  • units (optional) - a string (all bands will use this unit) or an array of strings listing the units of each band. For a description of units see the documentation of the collection you are querying. Defaults to the default units for each band.

Output object properties

  • id (optional) - any string of your choosing. Must be unique if multiple output objects are defined. Defaults to default.
  • bands - the number of bands in this output.
  • sampleType (optional) - sets the SampleType constant defining the returned raster sample type. Defaults to AUTO.

Note that the number of bands represent the number of components in the output image. JPEG and PNG, for example, can only support 1 or 3 color components (plus an alpha channel for PNG, if set). The sampleType also needs to be compatible with the output raster format.

Mosaicking

Mosaicking defines how the source data is mosaicked. Not all collections support all these mosaicking types as it depends on how the source data is distributed. See the collection information pages to determine which ones are supported. It is a constant which is specified by a string. To use, for example, set: mosaicking: "SIMPLE".

  • SIMPLE (default) - the simplest method, it flattens the mosaicked image so only a single sample is passed to evaluation.
  • ORBIT - the mosaicked image is flattened for each orbit so that there is only one sample per pixel per orbit. Multiple samples can therefore be present if there is more than one orbit for the selected time range at the pixel location.
  • TILE - this is essentially the unflattened mosaic. It contains all data available for the selected time range. Multiple samples can be present as each sample comes from a single scene. What a scene is is defined by the datasource.

Note: ORBIT mosaicking currently does not work exactly as described but generates a single scene for each day containing satellite data. For most requests this should not be an issue, however high latitude regions may have more than one acquisition per day. For these consider using TILE mosaicking if getting all available data is paramount. This will be corrected in future releases.

SampleType

SampleType defines the sample type of the output raster. This needs to be compatible with the raster format (e.g. JPEG cannot be FLOAT32). It is a constant which is specified by a string. To use, for example, set: sampleType: "AUTO".

  • UINT8 - unsigned 8-bit integer (values should range from 0-255)
  • UINT16 - unsigned 16-bit integer (values should range from 0-65535)
  • FLOAT32 - 32-bit floating point (values should range from 0-1)
  • AUTO (default) - values should range from 0-1, which will then automatically be stretched from the interval [0, 1] to [0, 255] and written into an UINT8 raster. Values below 0 and above 1 will be clamped to 0 and 255, respectively. This is the default if sampleType is not set in the output object.

Note: Sentinel Hub currently only supports unsigned integer values, therefore requesting INT8 or INT16 will return the same as UINT8 or UINT16, respectively.

Handling SampleType in an Evalscript

It is the responsibility of the evalscript to return the values in the interval expected for the chosen sampleType. If no sampleType is specified, AUTO is selected and the evalscript should return values ranging from 0-1. If sampleType is UINT8, the evalscript should return values ranging from 0-255, and so on.

In case of input data provided as reflectance values ranging 0-1 (e.g., Sentinel and Landsat), no scaling is needed when AUTO or FLOAT32 sampleType are specified.

Examples

This simple Sentinel-2 setup() function gets bands B02, B03, B04 and returns (UINT16) 16 bit unsigned raster values.

function setup() {
return {
input: [{
bands: ["B02", "B03", "B04"], // this sets which bands to use
units: "DN" // here we optionally set the units. All bands will be in this unit (in this case Digital numbers)
}],
output: { // this defines the output image type
bands: 3, // the output of this evalscript will have RGB colors
sampleType: "UINT16" // raster format will be UINT16
}
};
}

This Sentinel-2 setup() function gets bands B02, B03, B04 and returns a single raster with 8-bit integer values. To return values in the correct interval for the UINT8 sampleType, the evaluatePixel() function multiplies the reflectance values by 255. A true color image is returned.

function setup() {
return {
input: [{
bands: ["B02", "B03", "B04"], // this sets which bands to use
}],
output: {
bands: 3,
sampleType: "UINT8" // raster format will be UINT8
}
};
}
function evaluatePixel(sample) {
return [sample.B04 * 255, sample.B03 * 255, sample.B02 * 255]; // bands need to be multiplied by 255
}

In case of UINT16, the multiplication factor in evaluatePixel() would be 65535 instead of 255.

The following example uses bands with different units and produces two rasters:

function setup() {
return {
input: [{
bands: ["B02", "B03", "B04", "B08"],
units: ["reflectance", "reflectance", "reflectance", "DN"] // B08 will be in digital numbers, the rest reflectance
}],
output: [{ // this is now an array since there are multiple output objects
id: "rgb"
bands: 3
}, {
id: "falseColor"
bands: 3
}]
}
}

evaluatePixel function

The evaluatePixel function is a mapping which maps the input bands in their input units to the values in the output raster(s). The function parameters depend on the mosaicking value.

Parameters

When mosaicking is SIMPLE, only a single mosaicked sample exists.

These are the full parameters of the evaluatePixel function:

function evaluatePixel(sample, scene, inputMetadata, customData, outputMetadata)
  • sample - an object containing the band values of the single mosaicked sample, in the specified units, as its properties. The property names equal the names of all the input bands (e.g. sample.B02 gives pixel values of band B02). Input bands values correspond to the bands' physical quantities. For example, if a band represents reflectance, its values will typically be in the interval [0 1].
  • scene - an object containing scene metadata
  • inputMetadata - an object containing input metadata
  • customData - an object containing custom data
  • outputMetadata - an object containing output metadata

When mosaicking is TILE or ORBIT, the function gets an array of samples as defined in the SIMPLE case. For different pixels it may get different number of samples, and may get an empty array, if no data is available for the given request.

function evaluatePixel(samples, scenes, inputMetadata, customData, outputMetadata)
  • samples - an array of samples as defined in the SIMPLE case. When mosaicking technique applied is ORBIT or TILE, multiple samples can therefore be present if there is more than one orbit/tile for the selected time range at the pixel location. Each sample can then be accessed as an item in the array (e.g samples[0].B04). The array length can be 0, 1 or more.

  • scenes - an array of objects containing scene metadata. scenes are therefore equal in number to samples. Each object's properties include:

    • date (type Date) -- the datetime of the product/tile
    • idx (type Number) -- the order (index) of this scene within all scenes of this timerange starting with 0 to (number of scenes - 1)
    • tileOriginalId (type String) -- the original name of the tile/product used
    • orbitId (type Number) -- the orbit ID of the product/tile
    • Some properties vary depending on whether mosaicking is ORBIT or TILE. See this metadata example for more details.

The remaining parameters are the same as in the SIMPLE case.

Returns

The evaluatePixel function can return:

  • An object whose keys are the output ids and its values are arrays of numbers. The length of the array is bound by the output object bands number and the values by sampleType.
  • An array of numbers with the same rules as above. This option can be used only when a single image output is defined.
  • Nothing; the return statement is not specified. This is useful when only information in outputMetadata.userData is needed.

Input Units and Output Values

The values of each sample is the units specified in the input object. See the input object documentation for more information. How the output values are written to the output raster depends on the sample type. AUTO will stretch values in the interval [0, 1] to [0, 255] and then write those values into an UINT8 raster. The remaining sample types expect values within the range of the sample format.

Examples

Example evaluatePixel script returns a simple True Color image based on bands B04, B03, B02:

function evaluatePixel(sample) {
return [2.5 * sample.B04, 2.5 * sample.B03, 2.5 * sample.B02];
}

When we have multiple outputs in the setup function we can provide them as such:

function evaluatePixel(sample) {
return {
trueColor: [2.5 * sample.B04, 2.5 * sample.B03, 2.5 * sample.B02],
falseColor: [2.5 * sample.B08, 2.5 * sample.B04, 2.5 * sample.B03]
};
}

Calculate the average value of band B04 when using ORBIT or TILE mosaicking:

function evaluatePixel(samples) {
var sum = 0;
var nonZeroSamples = 0;
for (var i = 0; i < samples.length; i++) {
var value = samples[i].B04;
if (value != 0) {
sum += value;
nonZeroSamples++;
}
}
return [sum / nonZeroSamples];
}

updateOutputMetadata function (optional)

This function is optional and if present is called at the end of evalscript evaluation. It provides a convenient way to forward information pertaining to the returned data as a whole (as opposed to evaluatePixel which is run for each pixel) into an output object. Do this by setting the userData property of the outputMetadata parameter to any value you require.

Parameters

These are the full parameters of the updateOutputMetadata function:

function updateOutputMetadata(scenes, inputMetadata, outputMetadata)
  • scenes - an object containing scene metadata
  • inputMetadata - an object containing input metadata
  • outputMetadata - an object containing output metadata

outputMetadata object properties

  • userData - is a generic object and can contain any data. This can be pushed to the API response by adding a userdata identified output response object to your API request (see this for details or an example here).

filterScenes function (optional)

This function is optional, and if present is called at the beginning of the script evaluation before the actual satellite data is processed. Use it when mosaicking is set to ORBIT. It provides additional filtering functionality for scenes, after the constraints set in the request parameters are already applied. This is useful, for example, to reduce the number of scenes needed, thereby reducing processing time and the number of processing units for the request.

Parameters

These are the full parameters of the filterScenes function:

function filterScenes(availableScenes, inputMetadata)
  • availableScenes - an array of objects where each of them represents one available scene for a given request. Each object has two properties:
    • date (type Date) -- the date and time of the scene
    • idx (type Number) -- the order (index) of this scene within the availableScenes array
  • inputMetadata - an object with properties:
    • from (type Date) -- the value given as timeRange.from in the body of the request, representing the start of the search interval
    • to (type Date) -- the value given as timeRange.to in the body of the request, representing the end of the search interval
    • scenes -- the array equal to availableScenes

Returns

The filterScenes function must return an array of objects of the same type as contained in an availableScenes array. Most often, a sub-set of the availableScenes array will be returned:

function filterScenes(availableScenes, inputMetadata){
return availableScenes.filter(function (scene) {
return scene.date.getTime() < new Date("2019-02-01T00:00:00Z")
});
}

Examples

Filter scenes by particular days

In this example, we use filterScenes function to select images acquired on two particular dates within the requested timeRange. This example was taken (and adopted) from the evalscript for delineation of burned areas, based on the comparison of Sentinel-2 images acquired before (i.e. on "2017-05-15") and after (i.e. on "2017-06-24") the event.

function filterScenes (availableScenes, inputMetadata) {
var allowedDates = ["2017-05-15", "2017-06-24"]; //before and after Knysna fires
return availableScenes.filter(function (scene) {
var sceneDateStr = scene.date.toISOString().split("T")[0]; //converting date and time to string and rounding to day precision
return allowedDates.includes(sceneDateStr);
});
}

Filter scenes by time interval

Here, we filter out (= remove) all the scenes acquired between the two selected dates, which both fall within the requested time range.

function filterScenes(availableScenes, inputMetadata) {
return availableScenes.filter(function (scene) {
return (scene.date.getTime() < new Date("2019-01-31T00:00:00Z")) ||
(scene.date.getTime() >= new Date("2019-06-01T00:00:00Z"))
});
}

Combining this with the timeRange set in the body of the request as:

{
"from": "2019-01-01T00:00:00Z",
"to": "2019-06-30T23:59:59Z"
}

we end up only with scenes acquired in January and June 2019. In the evaluatePixel function, we could then e.g., calculate the average NDVI index for each of the months and compare them.

Specify the number of months taken into account

Values of timeRange.from and timeRange.to parameters as given in the request, are available in the filterScenes function as iputMetadata.to and inputMetadata.from, respectively. These can be used to e.g. filter out scenes acquired more than 3 months before the given to date and time:

function filterScenes (availableScenes, inputMetadata) {
return availableScenes.filter(function (scene) {
return scene.date.getTime()>=(inputMetadata.to.getTime()-3*31*24*3600*1000);
});
}

The 3*31*24*3600*1000 represents the 3 months converted to milliseconds. This is needed, so that a 3-month time span can be compared to scene.date and inputMetadata.to, which are all returned as milliseconds since 1970-1-1 by the getTime() function. Note: The result is the same as if the timeRange.from parameter in the body of the request is set to 3 months prior to the timeRange.to.

Select one image per month

In this example, we filter the available scenes, so that only the first scene acquired in each month is sent to the evaluatePixel function:

function filterScenes(availableScenes, inputMetadata){
availableScenes.sort((s1, s2) => s1.date - s2.date); // sort the scenes by dates in ascending order
previousSceneMonth = availableScenes[0].date.getMonth()-1
return availableScenes.filter(function (scene) {
if (scene.date.getMonth() != previousSceneMonth ){
previousSceneMonth=scene.date.getMonth();
return true;
} else return false;
});
}

OGC services specifics

There are some specifics when using evalscript V3 with WMS, WTS, WCS services:

  • These services return only the default output. Only one image can be returned with each request and it is not possible to request metadata in JSON format.
  • TRANSPARENCY and BGCOLOR parameters are ignored. You can use dataMask band in evalscript V3 to handle transparency, as described above.
  • Bit depth, which is given as the part of a FORMAT parameter (e.g. FORMAT=image/tiff;depth=8) is ignored. You can use sampleType in evalscript V3 to request the bit depth of your choice.