Combine MODIS Terra and Aqua Products on GEE

The Moderate Resolution Imaging Spectroradiometer (MODIS) has been providing high temporal resolution images since the first launch of Terra satellite in 1999 followed by the Aqua satellite in 2002. The Terra satellite passes from north to south in the morning at around 10:30 a.m. local time. The Aqua satellite passes from south to north in the afternoon at around 1:30 p.m. Since MODIS has a revisiting time of one or two days, for any given day, there are most likely be images from both Terra and Aqua satellites. Therefore, fusing images from two products together can be useful to mitigate missing value problem due to cloud contaminations because the chance of having cloud at both 10:30 a.m. and 1:30 p.m. is definitely lower than having cloud at either time.

Specifically, for any given pair of images, the combined value is the mean of the two if both have valid values. If any one is missing, then the other one is taken. If both are missing, it remains missing.

On Google Earth Engine (GEE), this can be easily done by doing a math trick:

/**
 * This function combines MODIS Terra and Aqua data to generate one dataset. 
 * Originally written for mitigating missing value problem.
 * 
 * @param {ee.Image} terra - multi-band Terra image, number of bands can be 1 to n.
 * @param {ee.Image} aqua - multi-band Aqua image, number of bands should match terra bands.
 */
function combineModis(terra, aqua) {
    var bandwise_and = terra.and(aqua);

    /**
     * if band-wise-and returns 1, then two bands all have values, take the mean,
     * if not, then at least one band has missing value, add them up as the final value
     */
    var multiplicative = bandwise_and.add(1).pow(-1);   // from [0, 1] -> [1, 2] -> [1, 1/2] 
    var combined = terra.add(aqua).multiply(multiplicative);
    return combined;
}

The trick is by doing bandwise logical and on each pair of bands. The results will be 0 if any band has missing value, and 1 if both have valid values. Then a multiplicative term is calculated by adding 1 to the logical and result and raise to the power of -1. This makes 0 to 1, 1 to 0.5. The mulplicative term is then multiplied by the sum of the band pair. So if any band has missing value, the result will be 1 * (Terra + Aqua) for bands with missing values, and 0.5 * (Terra + Aqua) for bands with no missing values. There, mission accomplished.

Other useful functions for GEE can be found at the my repo.