Google Earth Engine(GEE)的map&function和iterate条件迭代替代if

GEE的map&function和iterate条件迭代替代ee.Algorithms.If()

宗旨1:需要条件conditions,不要用if,用map和function替代

1.1 function&map的理解

// 设置图像中心
Map.setCenter(-72.6978, 41.6798, 8);
// 加载州数据集
var countyData = ee.FeatureCollection('TIGER/2018/Counties');
// 筛选数据集
var countyConnect = countyData.filter(ee.Filter.eq('STATEFP', '09'));
// 显示图像并设置颜色图名
Map.addLayer(countyConnect, {color: 'red'}, 'Original Collection');
//实现函数 performMap
function performMap(feature) {
 var simple = feature.simplify(10000);//先简化定点
 var center = simple.centroid(100);//找到每个要素geometry的中心
 return center.buffer(5000, 100);//每个点做缓冲
}
var mappedCentroid = countyConnect.map(performMap);//countyConnect矢量数据集的每一个要素都遍历performMap
//var result =performMap (input);函数调用
Map.addLayer(mappedCentroid, {color: 'blue'}, 'Mapped buffed centroids');

在这里插入图片描述

1.2 function&map的计算NDVI

// This function gets NDVI from Landsat 8 imagery.
var addNDVI = function(image) {
   var NDVI=image.normalizedDifference(['B5', 'B4']).rename('NDVI');
   return image.addBands(NDVI);
};

// Load the Landsat 8 TOA data, filter by location and date.
var collection = ee.ImageCollection('LANDSAT/LC08/C02/T1_TOA')
  .filterBounds(ee.Geometry.Point(-122.262, 37.8719))
  .filterDate('2014-06-01', '2014-10-01');
// Map the function over the collection.
var ndviCollection = collection.map(addNDVI);

在这里插入图片描述

1.3 function和属性结合

// This function creates a new property that is the sum of two existing properties.创建新属性sum=属性1+属性2
var addField = function(feature) {
  var sum = ee.Number(feature.get('property1')).add(feature.get('property2'));
  return feature.set({'sum': sum});
};
// 创建要素集并且每个要素有两个属性
var features = ee.FeatureCollection([
  ee.Feature(ee.Geometry.Point(-122.4536, 37.7403),
    {property1: 100, property2: 100}),
    ee.Feature(ee.Geometry.Point(-118.2294, 34.039),
    {property1: 200, property2: 300}),
]);
// Map the function over the collection.
var featureCollection = features.map(addField);
// Print a selected property of one Feature.
print(featureCollection.first().get('sum'));
// Print the entire FeatureCollection.
print(featureCollection);
print(features);

在这里插入图片描述

function写法1

var applyfunction=function(datasat){
//operate 
return... ;}
var result=input.map(applyfunction)

function写法2

function applyfunction(datasat) {
/
return... ;}
var result=input.map(applyfunction)

function写法3

var result=input.map(function(dataset){return...)})
var data=ee.List.sequence(1, 5);
var result=data.map(function(dataset){
  return ee.Number(dataset).divide(2);
//没有ee.List(dataset).divide(2);ee.List(dataset).add是追加的意思,所以进行向量运算要用ee.Number

宗旨2:map和condition 解决不了用.iterate迭代

iterate()函数可以用来遍历给定集合中的每个元素,并对每个元素执行指定的操作。其基本语法为:
ee.List().iterate(function(item, previous) { … }, first)
其中,function(item, previous)是对每个元素执行的函数,item表示当前遍历到的元素,previous表示上一个元素的输出结果;而first表示在第一次迭代时传递给函数的参数。

2.1 iterate中的function(current,previous)

current:代表当前 iterator 所迭代的数据集合中的每个元素。current 可以是一个 Image、Feature 或 FeatureCollection 对象,具体取决于 iterate() 方法的第一个参数所传入的类型。
previous:代表前一个 iterator 所执行的函数的返回值。 回调函数中的两个参数可以根据需求进行修改,例如可以将 previous 参数用作中间结果,以便在 iterate() 中每次迭代时更新和累积结果。
在回调函数完成后,iterate() 方法会返回最终结果。
需要注意的是,在 iterate() 中使用回调函数时,函数必须返回一个对象,该对象将成为下一次 iterate() 方法执行时的 previous 参数。

// 创建一个数字列表,并对其中每个数字进行平方操作
var nums = ee.List([1, 2, 3, 4, 5])
var squaredNums = nums.iterate(function(num, prev) {
  return ee.List(prev).add(ee.Number(num).multiply(num))
}, ee.List([ ]))

print(squaredNums)  // 输出 [1, 4, 9, 16, 25]

//在上面的代码中,我们首先创建了一个包含数字1到5的列表nums,然后使用其iterate()方法遍历这个列表。
//对于每个数字num,我们定义一个函数来将其平方,并将结果添加到以前的结果列表prev中。
//在第一次迭代时,我们将一个空列表[]作为previous参数传递给该函数。
//最后,我们通过输出squaredNums的结果来查看平方后的数字列表。

2.2 Map和iterate的区别

iterate()是指遍历集合中的每个元素,并将其传递给用户定义的函数进行处理。在iterate()中,用户必须定义一个用于处理每个元素的函数,并指定初始值和一个累加器。
map()操作是将一个函数应用于集合中的每个元素,并返回一个包含结果的新集合。与iterate()不同的是,map()不需要累加器或初始值。
因此,主要的区别在于iterate()需要自己定义累加器和初始值,而map()不需要这些参数。另外,iterate()可以处理更多的场景,比如需要在处理每个元素时存储一些中间结果,并在最后返回一个累加结果的操作。

(1)iterate求NDVI

var collection = ee.ImageCollection('LANDSAT/LC08/C02/T1_TOA')
  .filterBounds(ee.Geometry.Point(-122.262, 37.8719))
  .filterDate('2014-06-01', '2014-10-01');
//在这个例子中,我们首先通过筛选得到一个LAI的图像集合,
然后定义了一个计算NDVI的函数并通过iterate()函数遍历整个集合,并将NDVI图像存储在一个列表中。
最终得到的是由NDVI图像组成的图像集合。在这种情况下,
我们需要一个累加器 ee.List([]) 和一个中间结果(即每个图像的NDVI值),以便在迭代过程中保留每个图像的结果
var ndviCollection = collection.iterate(add_ndvi, ee.List([]))
function add_ndvi(collection, startlist) {
  var ndvi =collection.normalizedDifference(['B5', 'B4']).rename('ndvi')
  return ee.List( startlist).add(ndvi)
}
print('NDVI Image Collection', ee.ImageCollection(ndviCollection))

(2) Map求NDVI

//iterate只有计算过程NDVI的波段,而map()方法更加直观,并且我们不需要处理额外的累加器和中间结果
var ndviCollection = collection.map(add_ndvi)
// 定义求NDVI的函数
function add_ndvi(image) {
  var ndvi = image.normalizedDifference(['B5', 'B4']).rename('ndvi')
  return image.addBands(ndvi)
}

print('NDVI Image Collection', ndviCollection)

example1-迭代循环求和

var list1= ee.List.sequence(1,100,1)
//求1-100的和,初值为0 ,function累加器,返回给num2
function Do(num1, num2){
  return ee.Number(num1).add(num2)
//num2 只初始值和过程值,num1是现值list1,并依次遍历取出先将初值0加上list1第一个值并返回给num2
}
var list2 = list1.iterate(Do, 0)
print( list2)
//5050

example 2-前两项和等于后一项

var algorithm = function(current, previous) {
  previous = ee.List(previous);
  var n1 = ee.Number(previous.get(-1));
  //get(-1)是获得导数第一个数
  var n2 = ee.Number(previous.get(-2));
  return previous.add(n1.add(n2));
  //previous是list,list.add是追加的意思,即第一个数一定是previous初始值,后面计算值追加。个数一共是初始值加上当前个数
};

// Compute 10 iterations.
var numIteration = ee.List.repeat(1, 10);
//当前列表数值没有意义,个数是计算的次数
print(numIteration)//[1,1,1,1,1,1,1,1,1,1]
var start = [0, 1];//迭代初始值
var sequence = numIteration.iterate(algorithm, start);
//当前列表.iterate(函数,初始值)
print(sequence);  // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

在这里插入图片描述

example 3-.iterate迭代进阶

// This example uses the ee.List.iterate function to generate a series of
// sequentially halved values.生成前一个数的一半值

// Declare a list that will hold the series of sequentially halved values,
// initialize it with the starting quantity.
var quantityList = [1000];//初始值即第一个数

// Define the number of iterations as a list sequence.
var nSteps = ee.List.sequence(1, 10);//没有用到当前数值,所以仅代表运算10次加上初始值一共11个数

// Declare a function that takes the current element of the iteration list and
// the returned result of the previous iteration as inputs. In this case, the
// the function is returning an accumulating list of quantities that are reduced
// by half at each iteration.

var halfOfPrevious = function(currentElement, previousResult) {
  var previousQuantity = ee.Number(ee.List(previousResult).get(-1));
  // 没有ee.list报错 previousResult.get is not a function因为.get(-1)是list才能使用
  // 没有get(-1)报错 Number.divide, argument 'left': Invalid type. Expected type: Number. Actual type: List<Integer>. Actual value: [1000]
 //number的运算只能是对于单数或array,向量可以用ee.Array。即使是单个的list也要在运算时换成number
  var currentQuantity = previousQuantity.divide(2);
  return ee.List(previousResult).add(currentQuantity);
};
// Apply the function to the nSteps list, each element is an iteration.
quantityList = ee.List(nSteps.iterate(halfOfPrevious, quantityList));

// Display the results. Note that step 0 is included for the initial value.
print('Steps in the iteration of halved quantities', nSteps);
print('Series of sequentially halved quantities', quantityList);
//图表绘制 ui.Chart.array.values(array(array/list), axis(沿轴生成几维向量序列), xLabels(在图表的x轴上标记刻度))
print(ui.Chart.array.values({
  array: quantityList,
  axis: 0,
  xLabels: ee.List([0]).cat(nSteps)
// List.cat(other) ,将other的内容连接到列表上,开头补上0
}));

在这里插入图片描述

补充 List&Number&Array区别

//列表list可以将任何数据放入列表,且元素之间没有任何关系,不可以进行数学四则运算;包括array
//数组array,是同类型数据的有限集合,可以进行数学四则运算。var list1= ee.List.sequence(1,100,1)
//求1-100的和,将1和2加和后赋给0 ,再与下一个数相加
var a=ee.Number(list1)
function Do(num2){
  return ee.Number(num2).divide(2)//Number和Array都可以因为function是在map里一个个循环计算
}
var list2 = list1.map(Do)
print(list2)
var previousQuantity = ee.Number(ee.List(list1));//报错,因为这里即使ee.Number输出还是list类型不能计算
var previousQuantity2 = ee.Array(ee.List(list1));//改为数组Array可以计算
var currentQuantity = previousQuantity.divide(2);
print( currentQuantity)
var a=ee.List([1,"w"])
print(a)

iterate参考

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值