Writing Custom Evalscripts for On-the-Fly Cloud Raster Processing
Execute pixel-by-pixel band arithmetic, multi-temporal compositing, and custom masks on remote servers before transferring a single byte.
How Server-Side Evalscripts Eliminate Scene Downloads
Traditional remote sensing workflows force teams to download entire 800 MB Sentinel-2 SAFE archives only to crop a 500-hectare farm and discard ninety-eight percent of the pixels. Evalscripts invert that model by shipping lightweight JavaScript functions straight to the cloud data store, where distributed workers read only the requested spatial tiles and spectral bands.
Every evalscript defines two core parts: a setup specification declaring required input bands, sample types, and temporal mosaicking mode, and an evaluatePixel function that transforms each pixel array into RGB visualizations, floating-point indices, or multi-band scientific GeoTIFF tensors.
- Request only the exact bands needed (e.g., B04, B08, SCL) to minimize I/O latency
- Choose SIMPLE mosaicking for single-date renders or ORBIT/TILE mosaicking for temporal composites
- Output UINT8 for web PNG previews or FLOAT32 for unquantized scientific GeoTIFF rasters
- Embed dataMask band handling so no-data margins render cleanly as transparent or NaN
Choosing SampleType and Output Quantization Safely
Mixing up sampleType settings is one of the most common bugs when prototyping evalscripts. AUTO or UINT8 scales numbers between 0 and 255—great for browser previews—but silently truncates negative NDVI or decibel radar values unless values are linearly stretched beforehand.
For analytical pipelines feeding Python NumPy arrays, zonal statistics, or machine learning inference, explicitly declare FLOAT32 in the output block and return raw floating-point numbers alongside a separate 1-bit or UINT8 validity mask so downstream logic never confuses zero reflectance with missing satellite coverage.
Multi-Temporal Compositing Inside EvaluatePixel
Switching mosaicking from SIMPLE to ORBIT passes an array of chronological observations for each pixel rather than a single pre-selected scene. Within evaluatePixel, the script loops over timestamps, filters out pixels flagged as cloud or shadow in the Scene Classification Layer, and computes a cloud-free median, maximum greenness, or linear trend slope.
Sorting valid observations in memory and taking the median effectively suppresses residual thin haze and outlier shadows that single-threshold cloud masks miss, producing clean seasonal mosaics across persistently cloudy tropical or coastal watersheds.
- Filter samples using sample.dataMask === 1 before reading optical reflectance
- Exclude SCL classes 3, 8, 9, 10, and 11 to reject shadows, clouds, cirrus, and snow
- Return a fallback sentinel value such as -9999 or NaN when zero clear observations exist
Debugging, Unit Testing, and Performance Tuning
Because evalscripts execute across millions of pixels per API request, small inefficiencies multiply rapidly across large areas. Avoid allocating temporary arrays or nested helper objects inside evaluatePixel, precompute lookup thresholds outside the pixel callback, and profile execution times on a compact 256x256 bounding box in EO Browser before scaling to provincial batch requests.
Using updateOutputMetadata hooks to attach band names, units, and acquisition timestamps inside output JSON or GeoTIFF tags creates self-documenting data products ready for automated archival. Maintaining version-controlled evalscript files alongside unit test fixtures for edge cases—such as empty scenes, snow cover, or zero denominators—prevents silent regressions when rolling out updated remote sensing formulas.
- Precompute constants outside evaluatePixel to avoid per-pixel object allocation overhead
- Test edge cases including empty tiles, zero reflectance sums, and 100% cloud cover
- Version-control evalscripts alongside API request templates for reproducible outputs
Evalscript SampleType and Mosaicking Configuration Guide
| Setting | Option | Numeric Range | Recommended Scenario |
|---|---|---|---|
| sampleType | UINT8 | 0 to 255 integer | True-color PNGs, color-ramped web map tiles |
| sampleType | UINT16 | 0 to 65535 integer | Scaled reflectance (x10000) for compact GeoTIFF storage |
| sampleType | FLOAT32 | IEEE 754 float | Unscaled NDVI/NDWI, SAR decibels, ML feature stacks |
| mosaicking | SIMPLE | Single best pixel | Fast low-overhead RGB or single-date API tiles |
| mosaicking | ORBIT | Array of orbit dates | Cloud-free median composites and temporal change detection |
Always match the requested HTTP Accept/format (image/tiff vs. image/png) to the declared sampleType.
Worked Illustration: Evaluating a 4-Observation Cloud-Free Median Pixel
This worked illustration traces how an ORBIT-mode evalscript filters four Sentinel-2 timestamps at one pixel location to output a clean NDVI value.
- Receive four observations for the pixel: Date 1 (NDVI=0.12, SCL=9 thick cloud), Date 2 (NDVI=0.64, SCL=4 vegetation), Date 3 (NDVI=0.68, SCL=4 vegetation), Date 4 (NDVI=0.66, SCL=4 vegetation).
- Apply SCL filter rejecting classes {3, 8, 9, 10}; Date 1 is discarded, leaving [0.64, 0.66, 0.68].
- Sort the remaining valid observations in ascending order: [0.64, 0.66, 0.68].
- Select the middle median element: 0.660, completely immune to the Day 1 cloud contamination.
Worked Illustration Summary: Filtering and taking the median reduces cloud contamination error from a distorted 4-date mean (0.525) back to a representative 0.660 canopy score.
Evalscript Production Readiness Checklist
- Declare only the exact required input bands in the setup() function to reduce read latency
- Check sample.dataMask === 1 before performing any arithmetic on pixel samples
- Set output sampleType to FLOAT32 whenever returning negative or fractional indices
- Handle empty valid-observation arrays gracefully with an explicit nodata flag
- Validate script output on a small AOI in EO Browser before running batch or statistical jobs
- Document band order and scaling factors in repository metadata alongside the script
Frequently Asked Questions
Why does my FLOAT32 evalscript fail when requesting image/png output?
Standard PNG images only support 8-bit or 16-bit integer channels, not IEEE 754 floating-point values. Switch the response format to image/tiff when using FLOAT32, or scale values to 0–255 for UINT8 PNG output.
What is the difference between SIMPLE and ORBIT mosaicking?
SIMPLE merges scenes server-side according to mosaicking order (e.g., leastCC) and passes one sample per pixel. ORBIT passes an array containing one sample per satellite overpass date so your script can compute medians or trends.
How do I prevent division-by-zero NaN bugs in normalized difference formulas?
Use a helper function that checks if (a + b === 0) return [0]; or returns an explicit nodata sentinel before dividing (a - b) / (a + b).
Does adding unused bands to setup() cost more processing units?
Yes. Reading extra bands increases I/O and processing load. Keep input band arrays strictly limited to the channels referenced inside evaluatePixel().
Primary Standards & Technical References
- OpenEO & Evalscript Processing Model Documentation — Server-Side Raster UDF Concepts
- OGC API — Processes Part 1: Core Standard (OGC 18-062r2, Open Geospatial Consortium)
- IEEE 754 Standard for Floating-Point Arithmetic (GeoTIFF 32-bit Raster Encoding)