I am collecting the Kelvin temperature of a field from Landsat imagery for October for a period of 20 years. Due to clouds, there are some images that are being removed by my pruning, leading to certain years containing no images for that month-year. (this is not the problem)
I have a Feature Collection, where each feature has a year
property that tells me which year I should reduceRegion for.
I map a function to "extract" the mean of the temperature from the imageCollection of the year that is contained in the year property. The problem lies when I try to trap with ee.Algorithms.If()
for an empty image collection once it is filtered to the year in question. Using reduceRegion()
on an empty collection creates an error.
However, no matter how I try, the reduceRegion()
always gets evaluated, even if it should be ignored as it is in the area of the function that will not be evaluated if the collection is of .size()
0
.
myBlockCollection
is my Feature Collection containing 20 features with a property of "year" for the year I am interested in filtering my images to.
selectedPass
is my pruned image collection that only contains the October images that pass the "QC" test and will contain no more than 1 image per year, but could contain no images for a specific year.
var addKelvintoFeature = function(myFeature){
var myBlock = ee.Feature(myFeature);
var theYear = ee.Number.parse(myBlock.get("year"));
var thermalBlockThisYearMean = ee.Number(ee.Algorithms.If(selectedPass
.filterDate(ee.Date.fromYMD(theYear,10,1),ee.Date.fromYMD(theYear,11,1)).size(),
selectedPass
.filterDate(ee.Date.fromYMD(theYear,10,1),ee.Date.fromYMD(theYear,11,1)).size()
.reduceRegion(ee.Reducer.mean(),myBlock.geometry())
.getNumber("Kelvin") // if size is not 0, we do this
,-1)); // if size is 0, we assign -1 so that we end with a negative number
var thermalBlockSeriesMin = selectedPass.map(
function(image){
return ee.Feature(null, {meanKelvin:image.reduceRegion(ee.Reducer.mean(),myBlock.geometry()).getNumber("Kelvin")});
})
.aggregate_min("meanKelvin"); //This works fine every time
var th1 = thermalBlockThisYearMean.divide(thermalBlockSeriesMin);
return myBlock.set("th1",th1);
};
return ee.FeatureCollection(myBlockCollection).map(addKelvintoFeature);
};
When I replace the reduceRegion()
with a simple .size()
there is no issue with the If statement, as that does not produce an error.
var yearsAvailable = selectedPass.aggregate_array("system:time_start").map(function(time_start){return ee.Date(time_start).get("year")})
and this is info is added to my features (with only existing features for valid years). However, the error still persists in thereduceRegion()
When I run thesize()
debug I do get a "1" so there is an image..first()
so that it reduced to an image and not a collection with 1 image.... Thanks JonasV. Please give your comment as an answer so that I can credit you for getting me on the right track.