GRID and CHART related: Generate chart for each polygon in a evenly distributed grid in Google Earth Engine - grid

I have created a grid and I want to plot a time series for each of the squares of this evenly distributed grid.
But I keep getting the same error:
Line 20: ImageCollection.fromImages, argument 'images': Invalid type.
Expected type: List<Image<unknown bands>>.
Actual type: List<ImageCollection>.
Actual value: [<ImageCollection>, <ImageCollection>, <ImageCollection>, <ImageCollection>, <ImageCollection>, <ImageCollection>]
If anyone is kind to provide some help, Id really appreciate it.
This is what I got so far:
var grid = ee.FeatureCollection("projects/ee-moreirarmt/assets/grid")
Map.centerObject(grid)
var chirps_col = ee.ImageCollection("UCSB-CHG/CHIRPS/PENTAD")
.select("precipitation")
.filterDate("2020-01-01", "2021-01-01")
var seq = ee.List.sequence(1, ee.Number(grid.size()))
var vizparam = ({bands:"precipitation",min: 13.39358901977539, max: 27.54470443725586,
palette: ['001137', '0aab1e', 'e7eb05', 'ff4a2d', 'e90000']})
var split_by_each_grid = seq.map(function(x){
var fil = grid.filterMetadata('id', 'equals', x)
var split_chirps_col = chirps_col.filterBounds(fil)
return split_chirps_col.set('id', x)})
var splitted_chirps_col = ee.ImageCollection.fromImages(split_by_each_grid)
for(var a = 1; a < splitted_chirps_col.size().getInfo() + 1; a++){
Map.addLayer(splitted_chirps_col.median().filter(ee.Filter.eq('id',a)), vizparam, "Chirps_per_grid"+a)
}
for(var a = 1; a < final_col.size().getInfo() + 1; a++){
var chart = Chart.image.seriesByRegion(splitted_chirps_col.filter(ee.Filter.eq('id',a)), grid, ee.Reducer.mean(), "precipitation", 5500)
print(chart)
}
Here's the code:
https://code.earthengine.google.com/fbdf0b0e9e1f395eaa8435b805bdc809
Thanks in advance and stay safe.

Related

computing the math formula on the mask (google earth engine)

I am about to calculate Chorophyll-a in the water bodies in one region, as I outlined above. I have created a mask, with water=1, land=0(transparent). And I want to calculate quality formula (NDCI, refer to normalized difference chl-a index) over the mask I created in the last step. Here are my code.
function maskS2clouds(image) {
var qa = image.select('QA60')
var cloudBitMask = 1 << 10;
var cirrusBitMask = 1 << 11;
var mask = qa.bitwiseAnd(cloudBitMask).eq(0).and(
qa.bitwiseAnd(cirrusBitMask).eq(0))
return image.updateMask(mask).divide(10000)
.select("B.*")
.copyProperties(image, ["system:time_start"])
}
var tiles = ['29UNV']
var collection = ee.ImageCollection("COPERNICUS/S2_SR")
.filterDate('2020-01-01', '2020-12-31')
.filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 20))
.filter(ee.Filter.inList('MGRS_TILE', tiles))
print(collection)
var minmin = collection.map(maskS2clouds)
print(minmin)
var calndwi = function(image){
//water mask
var NDWI = image.normalizedDifference(['B3', 'B8']).rename('NDWI');
return image.addBands(NDWI).updateMask(NDWI.gt(0));
};
print(minmin.map(calndwi));
//Add NDWI to the clipped image collection
var withNDWI = minmin.map(calndwi).select('NDWI');
print("NDWI collection", withNDWI);
var bb = withNDWI.first();
Map.addLayer(bb,{},'ss');
var addNDCI = function(image) {
var ndci = image.normalizedDifference(['B5', 'B4']).rename('NDCI');
return image.addBands(ndci);
};
var withNDCI = minmin.map(addNDCI).select('NDCI');
print("NDCI collection", withNDCI);
var MASK = function(image) {
var mask = bb.mask(image);
return image.addBands(mask);
};
var maskk = withNDCI.map(MASK).select('mask');
print(maskk)**
and it give me the bug like ImageCollection (Error)
Error in map(ID=20200106T114451_20200106T114531_T29UNV):Image.select: Pattern 'mask' did not match any bands.what should I do? thanks a million
The maskk object does not contain any bands named mask, because your MASK function does not create or add any bands with that name.
What your code does, as you've currently written it, is this:
var MASK = function(image) {
// Apply a mask over the 'bb' image.
var mask = bb.mask(image);
// return 'image' (which was the 'mask' parameter above),
// with ALL bands from the object 'mask', which is now a 'masked' version of bb.
// since mask = bb.mask(image), all the bands from bb will be added.
return image.addBands(mask);
};
var maskk = withNDCI
// Map the 'MASK' function over the 'withNDCI' collection
.map(MASK)
// Attempt to select a band named 'mask' (which does not exist).
.select('mask');
I'm not sure what you're looking for when you try to select the mask 'band' - I assume what you want is the masked NCDI image. That's essentially what you have already - but the band names of the 'maskk' object are "NDWI" and "NDCI", since it is derived from the bb, and those are the bands that bb contains. There is no band named "mask".

Land-use classification using the Random Forest algorithm of the GEE

I am working on a land use classification program using the RS algorithm of the GEE platform. The codes are as the following link.
https://code.earthengine.google.com/7e99f1de58c1251bd9bff0ff7af9368b
Specific codes:
var table = ee.FeatureCollection("users/zongxuli/Jing_Jin_Ji");
//Set up bands and corresponding band names
var inBands = ee.List([1,2,3,4,5,7,6,'pixel_qa'])
var outBands = ee.List(['blue','green','red','nir','swir1','temp', 'swir2','pixel_qa'])
// Get Landsat data
var l8s = ee.ImageCollection("LANDSAT/LC08/C01/T1_SR")
.filterDate(2019-01-01,2019-12-31)
.filterBounds(table)
.select(inBands,outBands)
.filter(ee.Filter.lt("CLOUD_COVER",10))
function getIndexes(image){
// Normalized Difference Vegitation Index(NDWI)
var ndvi = image.normalizedDifference(['nir','red']).rename("ndvi");
image = image.addBands(ndvi);
// Normalized Difference Snow Index(NDWI)
var ndsi = image.normalizedDifference(['green','swir1']).rename("ndsi");
image = image.addBands(ndsi);
// Normalized Difference Water Index(NDWI)
var ndwi = image.normalizedDifference(['nir','swir1']).rename("ndwi");
image = image.addBands(ndwi);
// add Enhanced Vegetation Indexes
var evi = image.expression('2.5 * ((NIR - RED) / (NIR + 6 * RED - 7.5 * BLUE + 1))', {
'NIR' : image.select('nir'),
'RED' : image.select('red'),
'BLUE': image.select('blue') }).float();
image = image.addBands(evi.rename('evi'));
// Add Index-Based Built-Up Index (IBI)
var ibiA = image.expression('2 * SWIR1 / (SWIR1 + NIR)', {
'SWIR1': image.select('swir1'),
'NIR' : image.select('nir')}).rename(['IBI_A']);
var ibiB = image.expression('(NIR / (NIR + RED)) + (GREEN / (GREEN + SWIR1))', {
'NIR' : image.select('nir'),
'RED' : image.select('red'),
'GREEN': image.select('green'),
'SWIR1': image.select('swir1')}).rename(['IBI_B']);
var ibiAB = ibiA.addBands(ibiB);
var ibi = ibiAB.normalizedDifference(['IBI_A', 'IBI_B']);
image = image.addBands(ibi.rename('ibi'));
return(image);
}
function getTopography(image,elevation) {
// Calculate slope, aspect and hillshade
var topo = ee.Algorithms.Terrain(elevation);
// From aspect (a), calculate eastness (sin a), northness (cos a)
var deg2rad = ee.Number(Math.PI).divide(180);
var aspect = topo.select(['aspect']);
var aspect_rad = aspect.multiply(deg2rad);
var eastness = aspect_rad.sin().rename(['eastness']).float();
var northness = aspect_rad.cos().rename(['northness']).float();
// Add topography bands to image
topo = topo.select(['elevation','slope','aspect']).addBands(eastness).addBands(northness);
image = image.addBands(topo);
return(image);
}
// Get an image to train and apply classification to.
var image = ee.ImageCollection('LANDSAT/LC08/C01/T1_SR')
.filterBounds(table)
.first();
// get bands
var bands=image.bandNames();
print(bands);
// integers starting from zero in the training data.
var label = 'lcode';
// Overlay the points on the imagery to get training.
var trainings = image.select(bands).sampleRegions({
collection: l8s, //.filterDate(2019-01-01,2019-12-31),
properties: [label],
scale: 30
});
// The randomColumn() method will add a column of uniform random
// numbers in a column named 'random' by default.
var sample = trainings.randomColumn();
var split = 0.7; // Roughly 70% training, 30% testing.
var training = sample.filter(ee.Filter.lt('random', split));
print(training.size());
// Random forest
var classifier = (ee.Classifier.smileRandomForest(15)
.train({
features: training,
classProperty: label,
inputProperties: bands
}));
var classified = image.classify(classifier);
print(classified);
So far, I always received the wrong message "Number (Error) Empty date ranges not supported for the current operation." when running the program. What am I doing wrong?
There is a quotation problem in image collection date filtering:
// Get Landsat data
var l8s = ee.ImageCollection("LANDSAT/LC08/C01/T1_SR")
.filterDate(2019-01-01,2019-12-31)
.filterBounds(table)
.select(inBands,outBands)
.filter(ee.Filter.lt("CLOUD_COVER",10))
it must be:
// Get Landsat data
var l8s = ee.ImageCollection("LANDSAT/LC08/C01/T1_SR")
.filterDate('2019-01-01','2019-12-31')
.filterBounds(table)
.select(inBands,outBands)
.filter(ee.Filter.lt("CLOUD_COVER",10))
And in training for classifier section:
// Overlay the points on the imagery to get training.
var trainings = image.select(bands).sampleRegions({
collection: l8s, //.filterDate(2019-01-01,2019-12-31),
properties: [label],
scale: 30 });
it must be :
// Overlay the points on the imagery to get training.
var trainings =
image.select(bands).sampleRegions({
collection: table,
properties: [label],
scale: 30 });

How to get the difference image of this month and the previous month in Google Earth Engine with a smart way?

How to get the difference image of this month and the previous month in Google Earth Engine with a smart way?
study area 25E-75E,5S-35N。
// study area 25E-75E,5S-35N。
var geometry =
ee.Geometry.Polygon(
[[[25, 35],
[25, 5],
[75, 5],
[75, 35]]], null, false);
var regions = ee.FeatureCollection([
ee.Feature(geometry)
]);
// imgCol
var now = ee.Date(Date.now());
var NDVICollection=ee.ImageCollection('MODIS/006/MOD13Q1')
.filterDate('2010-01-01',now)
.filterBounds(regions)
.select('NDVI');
var col = NDVICollection.map(function(img){
return img.multiply(0.0001)
.copyProperties(img,['system:time_start','system:time_end']);
});
// grouped by month
var months = ee.List([11,12,1,2]);
var byMonth = ee.ImageCollection.fromImages(
months.map(function (m) {
return col.filterDate('2019-11-01',now).filter(ee.Filter.calendarRange(m, m, 'month'))
.select('NDVI').mean()
.set('month', m);
}));
mask
var meanNDVI = byMonth.reduce(ee.Reducer.mean());
var mask = meanNDVI.gt(0.1);
Create difference image
**var img12 = byMonth.filter(ee.Filter.eq('month', ee.Number(12))).first().updateMask(mask);
var img11 = byMonth.filter(ee.Filter.eq('month', ee.Number(11))).first().updateMask(mask);
var img1 = byMonth.filter(ee.Filter.eq('month', ee.Number(1))).first().updateMask(mask);
var img2 = byMonth.filter(ee.Filter.eq('month', ee.Number(2))).first().updateMask(mask);
var ndviChange_12 = img12.subtract(img11).set('name','ndviChange_12');
var ndviChange_1 = img1.subtract(img12).set('name','ndviChange_1');
var ndviChange_2 = img12.subtract(img1).set('name','ndviChange_2');
var ndviChange = ee.ImageCollection([ndviChange_12,ndviChange_1,ndviChange_2]);**
I want make it much more smart, what should I do? make a function or something else?
Show the image
Map.centerObject(regions);
Map.addLayer(byMonth);
Map.addLayer(ndviChange);
I think the solution is to use iterate on your byMonth collection . Check this example in the documentations.
https://developers.google.com/earth-engine/ic_iterating

.pluck returning undefined in Meteor

Trying to pull a list of ratings from a collection of Reviews and then average them to come up with an aggregated average rating for a Plate. When I look at the data output from the ratings variable I get nothing but "undefined undefined undefined".
averageRating: function() {
var reviews = Reviews.findOne({plateId: this._id});
var ratings = _.pluck(reviews, 'rating');
var sum = ratings.reduce(function(pv, cv){return pv + cv;}, 0);
var avg = sum / ratings.length;
//Testing output
var test = "";
var x;
for (x in reviews) {
text += reviews[x] + ',';
}
return test;
}
Sorry if this is a super newbie question, but I've been at this for hours and cannot figure it out.
I figured out the issue. As listed above var reviews gets set to a cursor which apparently .pluck does not work on. By first converting the cursor to an array of objects I was then able to use .pluck. So updated code looks like this:
averageRating: function() {
var reviewsCursor = Reviews.find({plateId: this._id});
//Converts cursor to an array of objects
var reviews = reviewsCursor.fetch();
var ratings = _.pluck(reviews, 'rating');
var sum = ratings.reduce(function(pv, cv){return pv + cv;}, 0);
var avg = (sum / ratings.length).toPrecision(2);
return avg;
}

Simple line chart in DC and CrossFilter

I have some data like this
var data = [{date:'2013/01/01', claimNo:1},
{date:'2013/01/01', claimNo:2},
{date:'2013/01/02', claimNo:3}]
I want to plot a line chart in DC so that the days are on the X-Axis and the total # of claims are on the Y-Axis.
I have code like this
var ndx = crossfilter(data);
data.forEach(function (e) {
e.dd = dateFormat.parse(e.dd);
e.month = d3.time.month(e.dd);
});
var dateDim = ndx.dimension(function (d) {
return d.dd;
});
var datesClaimsGroup = dateDim.group();
var claimsLineChart = dc.lineChart("#claims-line-chart");
claimsLineChart
.width(200)
.height(40)
.renderArea(true)
.margins({ top: 0, left: -1, right: 2, bottom: 1 })
.group(datesClaimsGroup)
.dimension(dateDim)
.x(d3.time.scale().domain([data[0].dd, data[data.length - 1].dd]))
.title(function (d) {
return d.value;
});
The chart is plotted but the values in Y-Axis are the date occurance counts and not the claim counts. I know I am supposed to use a function to count the claims but I am not getting there.
For datesClaimsGroup you need to provide a reduce function to count the claims. Otherwise just .group() will default to an identity count reduce function as you observed.
var datesClaimsGroup = dateDim.group().reduceSum(...)
or
var datesClaimsGroup = dateDim.group().reduce(...)

Resources