调试

您在 Earth Engine 中创建的算法在 Google Cloud 中运行,并分布在多台计算机上。调试可能具有挑战性,因为错误可能发生在客户端代码或编码指令的服务器端执行中,并且可能是由扩缩问题以及语法或逻辑错误引起的。除非您提出请求,否则无法检查在云端某处运行的程序。本文档介绍了调试策略、工具和解决方案,可帮助您解决常见错误并调试 Earth Engine 脚本。

语法错误

当代码违反编程语言(Earth Engine 中的 JavaScript 或 Python)的规则时,就会发生语法错误。这些错误会导致代码无法运行,通常会在执行前被捕获。如果您遇到语法错误,请仔细查看突出显示的行或出错提示,并查阅 Python 语言参考或 Google JavaScript 样式指南等资源。代码 linter 还可以帮助识别和解决这些问题。

客户端错误

尽管代码在语法上正确无误,但可能存在与脚本的一致性或逻辑相关的错误。以下示例演示了使用不存在的变量和方法时出现的错误。

错误 - 此代码无效!

代码编辑器 (JavaScript)

// Load a Sentinel-2 image.
var image = ee.Image('NASA/NASADEM_HGT/001');

// Error: "bandNames" is not defined in this scope.
var display = image.visualize({bands: bandNames, min: 0, max: 9000});

// Error: image.selfAnalyze is not a function
var silly = image.selfAnalyze();

Python 设置

如需了解 Python API 和如何使用 geemap 进行交互式开发,请访问 Python 环境页面。

import ee
import geemap.core as geemap

Colab (Python)

# Load a Sentinel-2 image.
image = ee.Image('NASA/NASADEM_HGT/001')

# NameError: name 'band_names' is not defined.
display = image.visualize(bands=band_names, min=0, max=9000)

# AttributeError: 'Image' object has no attribute 'selfAnalyze'.
silly = image.selfAnalyze()

第一个错误会告知您,bandNames 变量未在引用它的范围内定义。作为解决方案,请设置变量,或为 bands 参数提供列表实参。第二个错误演示了调用不存在的 selfAnalyze() 函数时会发生什么情况。由于这不是图片上的实际方法,因此错误会提示您这不是一个函数。在这两种情况下,错误都会描述问题。

未知对象类型转换

“...is not a function”错误可能是由于 Earth Engine 不知道变量的类型而导致的。此问题的常见表现形式由以下原因导致:

  • 对 first() 返回的对象执行操作(集合中元素的类型未知)。
  • 对 get() 返回的对象执行操作(存储在属性中的元素类型未知)。
  • 在参数类型未知时,对函数参数(在函数中)执行某些操作。

以下是前一种情况的示例:

错误 - 此代码无效!

代码编辑器 (JavaScript)

var collection = ee.FeatureCollection('USDOS/LSIB_SIMPLE/2017');

// Error: collection.first(...).area is not a function
var area = collection.first().area();

Python 设置

如需了解 Python API 和如何使用 geemap 进行交互式开发,请访问 Python 环境页面。

import ee
import geemap.core as geemap

Colab (Python)

collection = ee.FeatureCollection('USDOS/LSIB_SIMPLE/2017')

# AttributeError: 'Element' object has no attribute 'area'.
area = collection.first().area()

在所有情况下,解决方案都是使用已知类型的构造函数对未知类型的对象进行类型转换。继续前面的示例,解决方案是转换为 ee.Feature:

解决方案 - 使用类型转换!

代码编辑器 (JavaScript)

var area = ee.Feature(collection.first()).area();

Python 设置

如需了解 Python API 和如何使用 geemap 进行交互式开发,请访问 Python 环境页面。

import ee
import geemap.core as geemap

Colab (Python)

area = ee.Feature(collection.first()).area()

(值得注意的是,您可以在此处安全地调用 Element 上的任何方法,因为 Earth Engine 认为它就是该类型)。

避免混用客户端和服务器函数

以下示例不太明显:

错误 - 此代码无法实现您想要的效果

代码编辑器 (JavaScript)

// Don't mix EE objects and JavaScript objects.
var image = ee.Image('NASA/NASADEM_HGT/001');
var nonsense = image + 2;

// You can print this, but it's not what you were hoping for.
print(nonsense);

// Error: g.eeObject.name is not a function
Map.addLayer(nonsense);

Python 设置

如需了解 Python API 和如何使用 geemap 进行交互式开发,请访问 Python 环境页面。

import ee
import geemap.core as geemap

Colab (Python)

# Don't mix EE objects and Python objects.
image = ee.Image('NASA/NASADEM_HGT/001')
nonsense = image + 2

# TypeError: unsupported operand type(s) for +: 'Image' and 'int'.
display(nonsense)

# TypeError: unsupported operand type(s) for +: 'Image' and 'int'.
m = geemap.Map()
m.add_layer(nonsense)
m

假设此代码的作者打算为图片中的每个像素添加 2,那么这种做法是不正确的。具体而言,此代码错误地将服务器端对象 (image) 与客户端运算符 (+) 混合在一起。结果可能会令人惊讶。在第一种情况下,在 JavaScript 代码编辑器中输出 nonsense 将通过以下方式执行请求的操作 (+):将 image 和 2 都转换为字符串,然后将它们串联起来。生成的字符串并非预期结果(在 Python 中会抛出 TypeError)。 在第二种情况(将 nonsense 添加到地图)中,JavaScript 代码编辑器中会显示神秘的 g.eeObject.name is not a function 错误,因为添加到地图的对象 nonsense 是字符串,而不是 EE 对象(在 Python 中会抛出 TypeError)。为避免可能出现的意外结果和无意义的错误,请勿将服务器对象和函数与客户端对象、基元或函数混合使用。此示例中的解决方案是使用服务器函数。

解决方案 - 使用服务器函数!

代码编辑器 (JavaScript)

Map.addLayer(image.add(2));

Python 设置

如需了解 Python API 和如何使用 geemap 进行交互式开发,请访问 Python 环境页面。

import ee
import geemap.core as geemap

Colab (Python)

m = geemap.Map()
m.add_layer(image.add(2))
m

如需了解详情,请参阅客户端与服务器页面。

JavaScript 代码编辑器浏览器锁定

如果客户端中运行的 JavaScript 耗时过长,或者在等待 Earth Engine 的响应,则可能会发生浏览器冻结或锁定。导致此错误的两个常见原因是 JavaScript 代码编辑器代码中的 for 循环和/或 getInfo(),最糟糕的情况是 for 循环内有 getInfo()。For 循环可能会导致浏览器锁定,因为代码是在您的机器上运行的。另一方面,getInfo() 会同步向 Earth Engine 请求计算结果,并会一直阻塞,直到收到结果。如果计算耗时较长,阻塞可能会导致浏览器锁定。在代码编辑器中工作时,请避免使用 for 循环和 getInfo()。如需了解详情,请参阅客户端与服务器页面。

服务器端错误

尽管客户端代码在逻辑上保持一致,但可能存在仅在服务器运行时才会显现的 bug。以下示例演示了尝试获取不存在的乐队时会发生的情况。

错误 - 此代码无效!

代码编辑器 (JavaScript)

// Load a Sentinel-2 image.
var s2image = ee.Image(
    'COPERNICUS/S2_HARMONIZED/20160625T100617_20160625T170310_T33UVR');

// Error: Image.select: Pattern 'nonBand' did not match any bands.
print(s2image.select(['nonBand']));

Python 设置

如需了解 Python API 和如何使用 geemap 进行交互式开发,请访问 Python 环境页面。

import ee
import geemap.core as geemap

Colab (Python)

# Load a Sentinel-2 image.
s2image = ee.Image(
    'COPERNICUS/S2_HARMONIZED/20160625T100617_20160625T170310_T33UVR'
)

# EEException: Image.select: Band pattern 'non_band' did not match any bands.
print(s2image.select(['non_band']).getInfo())

在此示例中,错误消息会告知您没有名为 nonBand 的波段。显而易见的解决方案是指定一个确实存在的波段名称。您可以通过打印图片并在控制台中检查图片,或通过打印 image.bandNames() 返回的波段名称列表来发现波段名称。

不变性

您在 Earth Engine 中创建的服务器端对象是不可变的。(任何 ee.Object 都是服务器端 Object)。这意味着,如果您想更改对象,则必须将更改后的状态保存到新变量中。例如,以下方法无法在 Sentinel-2 图像上设置属性:

错误 - 此代码无法实现您想要的效果!

代码编辑器 (JavaScript)

var s2image = ee.Image(
    'COPERNICUS/S2_HARMONIZED/20160625T100617_20160625T170310_T33UVR');
s2image.set('myProperty', 'This image is not assigned to a variable');

// This will not result in an error, but will not find 'myProperty'.
print(s2image.get('myProperty')); // null

Python 设置

如需了解 Python API 和如何使用 geemap 进行交互式开发,请访问 Python 环境页面。

import ee
import geemap.core as geemap

Colab (Python)

s2image = ee.Image(
    'COPERNICUS/S2_HARMONIZED/20160625T100617_20160625T170310_T33UVR'
)
s2image.set('my_property', 'This image is not assigned to a variable')

# This will not result in an error, but will not find 'my_property'.
display(s2image.get('my_property'))  # None

在此示例中,s2image.set() 会返回具有新属性的图片副本,但存储在 s2image 变量中的图片保持不变。您需要将 s2image.set() 返回的图片保存在新变量中。例如:

解决方案 - 将结果捕获到变量中!

代码编辑器 (JavaScript)

s2image = s2image.set('myProperty', 'OK');
print(s2image.get('myProperty')); // OK

Python 设置

如需了解 Python API 和如何使用 geemap 进行交互式开发,请访问 Python 环境页面。

import ee
import geemap.core as geemap

Colab (Python)

s2image = s2image.set('my_property', 'OK')
display(s2image.get('my_property'))  # OK

映射的函数

客户端和服务器函数不混合的另一种情况是映射函数。具体而言,映射函数指定的操作在云端运行,因此客户端函数(例如 getInfo 和 Export,以及 JavaScript 代码编辑器中 Map 和 Chart 上的 print 和方法)在映射函数中不起作用。例如:

错误 - 此代码无效!

代码编辑器 (JavaScript)

var collection = ee.ImageCollection('MODIS/061/MOD44B');

// Error: A mapped function's arguments cannot be used in client-side operations
var badMap3 = collection.map(function(image) {
  print(image);
  return image;
});

Python 设置

如需了解 Python API 和如何使用 geemap 进行交互式开发,请访问 Python 环境页面。

import ee
import geemap.core as geemap

Colab (Python)

collection = ee.ImageCollection('MODIS/061/MOD44B')

# Error: A mapped function's arguments cannot be used in client-side operations.
bad_map_3 = collection.map(lambda image: print(image.getInfo()))

这个有点神秘的错误源于 Earth Engine 将此代码转换为可在 Google 服务器上运行的一组指令的过程。客户端函数和控制结构不能用于对传递给映射函数的参数图片进行操作。为避免此错误,请避免在映射函数中使用客户端函数。 如需详细了解客户端和服务器功能之间的区别,请参阅客户端与服务器页面。

映射函数有额外要求。例如,映射的函数必须返回一些内容:

错误 - 此代码无效!

代码编辑器 (JavaScript)

var collection = ee.ImageCollection('MODIS/061/MOD44B');

// Error: User-defined methods must return a value.
var badMap1 = collection.map(function(image) {
  // Do nothing.
});

Python 设置

如需了解 Python API 和如何使用 geemap 进行交互式开发,请访问 Python 环境页面。

import ee
import geemap.core as geemap

Colab (Python)

collection = ee.ImageCollection('MODIS/061/MOD44B')

# Error: User-defined methods must return a value.
bad_map_1 = collection.map(lambda image: None)

显而易见的解决方案是返回一些内容。但它不能返回任何类型的内容。具体而言,映射到 ImageCollection 或 FeatureCollection 的函数必须返回 Image 或 Feature。例如,您无法从映射到 ImageCollection 的函数返回日期:

错误 - 此代码无效!

代码编辑器 (JavaScript)

var collection = ee.ImageCollection('MODIS/061/MOD44B');

var badMap2 = collection.map(function(image) {
  return image.date();
});

// Error: Collection.map: A mapped algorithm must return a Feature or Image.
print(badMap2);

Python 设置

如需了解 Python API 和如何使用 geemap 进行交互式开发,请访问 Python 环境页面。

import ee
import geemap.core as geemap

Colab (Python)

collection = ee.ImageCollection('MODIS/061/MOD44B')

bad_map_2 = collection.map(lambda image: image.date())

# EEException: Collection.map:
# A mapped algorithm must return a Feature or Image.
print(bad_map_2.getInfo())

为避免这种情况,请返回设置了新属性的输入图片。然后,如果您需要集合中图片的日期列表,可以使用 aggregate_array():

解决方案 - 设置属性!

代码编辑器 (JavaScript)

var collection = ee.ImageCollection('MODIS/061/MOD44B');

var okMap2 = collection.map(function(image) {
  return image.set('date', image.date());
});
print(okMap2);

// Get a list of the dates.
var datesList = okMap2.aggregate_array('date');
print(datesList);

Python 设置

如需了解 Python API 和如何使用 geemap 进行交互式开发,请访问 Python 环境页面。

import ee
import geemap.core as geemap

Colab (Python)

collection = ee.ImageCollection('MODIS/061/MOD44B')

ok_map_2 = collection.map(lambda image: image.set('date', image.date()))
print(ok_map_2.getInfo())

# Get a list of the dates.
dates_list = ok_map_2.aggregate_array('date')
print(dates_list.getInfo())

程序错误

对没有波段的图片应用了模式

"Pattern 'my_band' was applied to an Image with no bands" 错误表示对具有空波段列表的 Image 进行了 ee.Image.select() 调用。您可以采取以下措施来解决此问题:

  • 如果图片是通过 ImageCollection 使用 reducer 或 first() 或 toBands() 调用生成的,请确保源集合不为空。
  • 如果图片是使用 ee.Dictionary().toImage() 从字典生成的,请确保字典不为空。
  • 如果图片是独立的,请确保它包含数据(而不仅仅是 ee.Image(0))。

扩缩错误

虽然脚本可能在语法上正确,没有逻辑错误,并且代表服务器的一组有效指令,但在并行化和执行计算时,生成的对象可能太大、太多或计算时间太长。在这种情况下,您会收到一条错误消息,指出算法无法扩缩。这些错误通常最难诊断和解决。此类错误的示例包括:

  • 计算超时
  • 并发聚合过多
  • 已超出用户记忆功能上限
  • 发生内部错误

提高代码的扩缩能力不仅能让您更快地获得结果,还能提高所有用户的计算资源可用性。以下各部分将讨论每种类型的错误,并简要介绍 reduceRegion(),这是一种常用的(广告技术提供商)函数,因能够导致各种类型的扩缩错误而臭名昭著。

reduceRegion()

虽然 reduceRegion() 会贪婪地消耗足够的像素来触发各种令人兴奋的错误,但也有一些参数旨在控制计算,以便您克服这些错误。例如,请考虑以下不建议的归约:

错误 - 此代码无效!

代码编辑器 (JavaScript)

var absurdComputation = ee.Image(1).reduceRegion({
  reducer: 'count',
  geometry: ee.Geometry.Rectangle([-180, -90, 180, 90], null, false),
  scale: 100,
});

// Error: Image.reduceRegion: Too many pixels in the region.
//        Found 80300348117, but only 10000000 allowed.
print(absurdComputation);

Python 设置

如需了解 Python API 和如何使用 geemap 进行交互式开发,请访问 Python 环境页面。

import ee
import geemap.core as geemap

Colab (Python)

absurd_computation = ee.Image(1).reduceRegion(
    reducer='count',
    geometry=ee.Geometry.Rectangle([-180, -90, 180, 90], None, False),
    scale=100,
)

# EEException: Image.reduceRegion: Too many pixels in the region.
#        Found 80300348117, but only 10000000 allowed.
print(absurd_computation.getInfo())

这个简单的示例仅用于演示。此错误旨在询问您是否真的要减少 80300348117(即 800 亿)个像素。如果未显示,请相应地增加 scale(以米为单位的像素大小),或将 bestEffort 设置为 true,以自动重新计算更大的比例。如需详细了解这些参数,请参阅 reduceRegion() 页面。

计算超时

假设您在计算中需要所有这些像素。如果是,您可以增加 maxPixels 参数,以使计算成功。不过,Earth Engine 需要一些时间才能完成计算。因此,系统可能会抛出“计算超时”错误:

不当做法 - 请勿这样做!

代码编辑器 (JavaScript)

var ridiculousComputation = ee.Image(1).reduceRegion({
  reducer: 'count',
  geometry: ee.Geometry.Rectangle([-180, -90, 180, 90], null, false),
  scale: 100,
  maxPixels: 1e11
});

// Error: Computation timed out.
print(ridiculousComputation);

Python 设置

如需了解 Python API 和如何使用 geemap 进行交互式开发,请访问 Python 环境页面。

import ee
import geemap.core as geemap

Colab (Python)

ridiculous_computation = ee.Image(1).reduceRegion(
    reducer='count',
    geometry=ee.Geometry.Rectangle([-180, -90, 180, 90], None, False),
    scale=100,
    maxPixels=int(1e11),
)

# Error: Computation timed out.
print(ridiculous_computation.getInfo())

此错误表示 Earth Engine 在等待大约 5 分钟后停止了计算。通过导出,Earth Engine 可以在允许运行时间更长(但内存不会更多)的环境中执行计算。由于 reduceRegion() 的返回值是一个字典,因此您可以使用该字典来设置具有 null 几何图形的地图项的属性:

良好 - 使用 Export!

代码编辑器 (JavaScript)

Export.table.toDrive({
  collection: ee.FeatureCollection([
    ee.Feature(null, ridiculousComputation)
  ]),
  description: 'ridiculousComputation',
  fileFormat: 'CSV'
});

Python 设置

如需了解 Python API 和如何使用 geemap 进行交互式开发,请访问 Python 环境页面。

import ee
import geemap.core as geemap

Colab (Python)

task = ee.batch.Export.table.toDrive(
    collection=ee.FeatureCollection([ee.Feature(None, ridiculous_computation)]),
    description='ridiculous_computation',
    fileFormat='CSV',
)
# task.start()

并发聚合过多

此错误中的“聚合”部分是指分布在多台机器上的操作(例如跨多个图块的缩减)。Earth Engine 设有相关限制,以防止同时运行过多此类聚合。在此示例中,“并发聚合过多”错误是由映射中的缩减触发的:

不当做法 - 请勿这样做!

代码编辑器 (JavaScript)

var collection = ee.ImageCollection('LANDSAT/LT05/C02/T1')
    .filterBounds(ee.Geometry.Point([-123, 43]));

var terribleAggregations = collection.map(function(image) {
  return image.set(image.reduceRegion({
    reducer: 'mean',
    geometry: image.geometry(),
    scale: 30,
    maxPixels: 1e9
  }));
});

// Error: Quota exceeded: Too many concurrent aggregations.
print(terribleAggregations);

Python 设置

如需了解 Python API 和如何使用 geemap 进行交互式开发,请访问 Python 环境页面。

import ee
import geemap.core as geemap

Colab (Python)

collection = ee.ImageCollection('LANDSAT/LT05/C02/T1').filterBounds(
    ee.Geometry.Point([-123, 43])
)


def apply_mean_aggregation(image):
  return image.set(
      image.reduceRegion(
          reducer='mean',
          geometry=image.geometry(),
          scale=30,
          maxPixels=int(1e9),
      )
  )


terrible_aggregations = collection.map(apply_mean_aggregation)

# EEException: Computation timed out.
print(terrible_aggregations.getInfo())

假设此代码的目的是获取每个图片的图片统计信息,一种可能的解决方案是 Export 结果。例如,利用 ImageCollection 也是 FeatureCollection 这一事实,可以将与图片关联的元数据导出为表:

良好 - 使用 Export!

代码编辑器 (JavaScript)

Export.table.toDrive({
  collection: terribleAggregations,
  description: 'terribleAggregations',
  fileFormat: 'CSV'
});

Python 设置

如需了解 Python API 和如何使用 geemap 进行交互式开发,请访问 Python 环境页面。

import ee
import geemap.core as geemap

Colab (Python)

task = ee.batch.Export.table.toDrive(
    collection=terrible_aggregations,
    description='terrible_aggregations',
    fileFormat='CSV',
)
# task.start()

已超出用户记忆功能上限

在 Earth Engine 中,算法并行化的一种方式是将输入拆分为图块,在每个图块上分别运行相同的计算,然后合并结果。因此,计算输出图块所需的所有输入都必须适合内存。例如,如果输入是包含多个波段的图片,并且所有波段都用于计算,则最终可能会占用大量内存。为了进行演示,此示例通过强制(不必要地)将整个图片集合放入一个图块中,从而使用了过多内存:

不当做法 - 请勿这样做!

代码编辑器 (JavaScript)

var bands = ['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7'];
var memoryHog = ee.ImageCollection('LANDSAT/LT05/C02/T1').select(bands)
  .toArray()
  .arrayReduce(ee.Reducer.mean(), [0])
  .arrayProject([1])
  .arrayFlatten([bands])
  .reduceRegion({
    reducer: 'mean',
    geometry: ee.Geometry.Point([-122.27, 37.87]).buffer(1000),
    scale: 1,
    bestEffort: true,
  });

// Error: User memory limit exceeded.
print(memoryHog);

Python 设置

如需了解 Python API 和如何使用 geemap 进行交互式开发,请访问 Python 环境页面。

import ee
import geemap.core as geemap

Colab (Python)

bands = ['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7']
memory_hog = (
    ee.ImageCollection('LANDSAT/LT05/C02/T1')
    .select(bands)
    .toArray()
    .arrayReduce(ee.Reducer.mean(), [0])
    .arrayProject([1])
    .arrayFlatten([bands])
    .reduceRegion(
        reducer=ee.Reducer.mean(),
        geometry=ee.Geometry.Point([-122.27, 37.87]).buffer(1000),
        scale=1,
        bestEffort=True,
    )
)

# EEException: User memory limit exceeded.
print(memory_hog.getInfo())

这段非常糟糕的代码说明了除非确实需要,否则不要使用数组的一个原因(另请参阅“避免不必要地转换类型”部分)。将该集合转换为一个庞大的数组时,必须一次性将该数组加载到内存中。由于这是一个长时间序列的图片,因此数组很大,无法放入内存中。

一种可能的解决方案是将 tileScale 参数设置为更高的值。tileScale 的值越高,图块越小,缩放比例为 tileScale^2。例如,以下代码可使计算成功:

代码编辑器 (JavaScript)

var bands = ['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7'];
var smallerHog = ee.ImageCollection('LANDSAT/LT05/C02/T1').select(bands)
  .toArray()
  .arrayReduce(ee.Reducer.mean(), [0])
  .arrayProject([1])
  .arrayFlatten([bands])
  .reduceRegion({
    reducer: 'mean',
    geometry: ee.Geometry.Point([-122.27, 37.87]).buffer(1000),
    scale: 1,
    bestEffort: true,
    tileScale: 16
  });

print(smallerHog);

Python 设置

如需了解 Python API 和如何使用 geemap 进行交互式开发,请访问 Python 环境页面。

import ee
import geemap.core as geemap

Colab (Python)

bands = ['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7']
smaller_hog = (
    ee.ImageCollection('LANDSAT/LT05/C02/T1')
    .select(bands)
    .toArray()
    .arrayReduce(ee.Reducer.mean(), [0])
    .arrayProject([1])
    .arrayFlatten([bands])
    .reduceRegion(
        reducer=ee.Reducer.mean(),
        geometry=ee.Geometry.Point([-122.27, 37.87]).buffer(1000),
        scale=1,
        bestEffort=True,
        tileScale=16,
    )
)

print(smaller_hog.getInfo())

不过,更可取的解决方案是避免不必要地使用数组,这样您就完全不需要使用 tileScale:

良好 - 避免使用数组!

代码编辑器 (JavaScript)

var bands = ['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7'];
var okMemory = ee.ImageCollection('LANDSAT/LT05/C02/T1').select(bands)
  .mean()
  .reduceRegion({
    reducer: 'mean',
    geometry: ee.Geometry.Point([-122.27, 37.87]).buffer(1000),
    scale: 1,
    bestEffort: true,
  });

print(okMemory);

Python 设置

如需了解 Python API 和如何使用 geemap 进行交互式开发,请访问 Python 环境页面。

import ee
import geemap.core as geemap

Colab (Python)

bands = ['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7']
ok_memory = (
    ee.ImageCollection('LANDSAT/LT05/C02/T1')
    .select(bands)
    .mean()
    .reduceRegion(
        reducer=ee.Reducer.mean(),
        geometry=ee.Geometry.Point([-122.27, 37.87]).buffer(1000),
        scale=1,
        bestEffort=True,
    )
)

print(ok_memory.getInfo())

除非有必要解决内存错误,否则不应设置 tileScale,因为较小的图块也会导致较大的并行化开销。

内部错误

您可能会遇到如下所示的错误:

如果您遇到此错误,请点击 JavaScript 代码编辑器控制台中显示的“报告错误”链接。您还可以通过帮助按钮发送反馈。此错误可能是由脚本中的逻辑错误(仅在运行时变得明显)或 Earth Engine 内部工作原理问题引起的。无论哪种情况,错误都无法提供有用信息,应报告错误以便进行修复。

内部错误包含 request ID,如下所示:

这些字符串用作唯一标识符,可帮助 Earth Engine 团队识别特定问题。请在 bug 报告中包含此字符串。

调试方法

您编写了分析代码,运行了代码,但收到了错误。接下来该怎么办?本部分介绍了用于找出并解决问题的一般调试方法。

检查变量和地图图层

假设您有一个非常复杂的分析,该分析会产生错误。如果错误来源不明显,一个不错的初始策略是输出或直观呈现中间对象,并检查这些对象,以确保对象的结构与脚本中的逻辑一致。具体而言,您可以使用代码编辑器或 geemap 检查器工具检查添加到地图中的图层的像素值。如果您打印了某些内容,请务必使用 zippy (▶) 展开其属性。需要检查的事项包括:

  • 频段名称。图片波段名称是否与代码一致?
  • 像素值。数据范围是否正确?是否进行了适当的遮盖?
  • Null。是否有任何不应为 null 的值却为 null?
  • 尺寸。大小是否不应为零?

aside()

将分析中的每个中间步骤都放入一个变量中,以便打印和检查,这可能会很繁琐。如需从长函数调用链中输出中间值,您可以使用 aside() 方法。例如:

代码编辑器 (JavaScript)

var image = ee.Image(ee.ImageCollection('COPERNICUS/S2_HARMONIZED')
    .filterBounds(ee.Geometry.Point([-12.29, 168.83]))
    .aside(print)
    .filterDate('2011-01-01', '2016-12-31')
    .first());

Python 设置

如需了解 Python API 和如何使用 geemap 进行交互式开发,请访问 Python 环境页面。

import ee
import geemap.core as geemap

Colab (Python)

image = ee.Image(
    ee.ImageCollection('COPERNICUS/S2_HARMONIZED')
    .filterBounds(ee.Geometry.Point([-12.29, 168.83]))
    .aside(display)
    .filterDate('2011-01-01', '2016-12-31')
    .first()
)

请注意,aside(print)(JavaScript 代码编辑器)和 aside(display) (Python geemap) 会调用客户端函数,但在映射函数中仍会失败。您还可以将 aside 与用户定义的函数搭配使用。例如:

代码编辑器 (JavaScript)

var composite = ee.ImageCollection('LANDSAT/LC08/C02/T1_TOA')
    .filterBounds(ee.Geometry.Point([106.91, 47.91]))
    .map(function(image) {
      return image.addBands(image.normalizedDifference(['B5', 'B4']));
    })
    .aside(Map.addLayer, {bands: ['B4', 'B3', 'B2'], max: 0.3}, 'collection')
    .qualityMosaic('nd');

Map.setCenter(106.91, 47.91, 11);
Map.addLayer(composite, {bands: ['B4', 'B3', 'B2'], max: 0.3}, 'composite');

Python 设置

如需了解 Python API 和如何使用 geemap 进行交互式开发,请访问 Python 环境页面。

import ee
import geemap.core as geemap

Colab (Python)

m = geemap.Map()
m.set_center(106.91, 47.91, 11)

composite = (
    ee.ImageCollection('LANDSAT/LC08/C02/T1_TOA')
    .filterBounds(ee.Geometry.Point([106.91, 47.91]))
    .map(lambda image: image.addBands(image.normalizedDifference(['B5', 'B4'])))
    .aside(m.add_layer, {'bands': ['B4', 'B3', 'B2'], 'max': 0.3}, 'collection')
    .qualityMosaic('nd')
)

m.add_layer(composite, {'bands': ['B4', 'B3', 'B2'], 'max': 0.3}, 'composite')
m

在 first 上运行函数

打印和可视化在可用时对调试很有用,但如果您要调试映射到集合的函数,则无法在函数中打印,如映射函数部分中所述。在这种情况下,隔离集合中的问题元素并在单个元素上测试映射函数会很有用。在不映射函数的情况下测试函数时,您可以使用 print 语句来了解问题。不妨参考以下示例。

错误 - 此代码无效!

代码编辑器 (JavaScript)

var image = ee.Image(
    'COPERNICUS/S2_HARMONIZED/20150821T111616_20160314T094808_T30UWU');

var someFeatures = ee.FeatureCollection([
  ee.Feature(ee.Geometry.Point([-2.02, 48.43])),
  ee.Feature(ee.Geometry.Point([-2.80, 48.37])),
  ee.Feature(ee.Geometry.Point([-1.22, 48.29])),
  ee.Feature(ee.Geometry.Point([-1.73, 48.65])),
]);

var problem = someFeatures.map(function(feature) {

  var dictionary = image.reduceRegion({
    reducer: 'first',
    geometry: feature.geometry(),
    scale: 10,
  });

  return feature.set({
    result: ee.Number(dictionary.get('B5'))
                .divide(dictionary.get('B4'))
  });
});

// Error in map(ID=2):
//  Number.divide: Parameter 'left' is required.
print(problem);

Python 设置

如需了解 Python API 和如何使用 geemap 进行交互式开发,请访问 Python 环境页面。

import ee
import geemap.core as geemap

Colab (Python)

image = ee.Image(
    'COPERNICUS/S2_HARMONIZED/20150821T111616_20160314T094808_T30UWU'
)

some_features = ee.FeatureCollection([
    ee.Feature(ee.Geometry.Point([-2.02, 48.43])),
    ee.Feature(ee.Geometry.Point([-2.80, 48.37])),
    ee.Feature(ee.Geometry.Point([-1.22, 48.29])),
    ee.Feature(ee.Geometry.Point([-1.73, 48.65])),
])


# Define a function to be mapped over the collection.
def function_to_map(feature):
  dictionary = image.reduceRegion(
      reducer=ee.Reducer.first(), geometry=feature.geometry(), scale=10
  )

  return feature.set(
      {'result': ee.Number(dictionary.get('B5')).divide(dictionary.get('B4'))}
  )


problem = some_features.map(function_to_map)

# EEException: Error in map(ID=2):
#  Number.divide: Parameter 'left' is required.
print(problem.getInfo())

如需调试此问题,请检查错误。幸运的是,这条有用的错误消息会告知您 ID=2 的特征存在问题。为了进一步调查,最好稍微重构一下代码。具体而言,如本部分所述,当函数映射到集合时,函数中不能包含 print 语句。调试目标是找出有问题的特征,并在函数中添加一些 print 语句后运行该函数。使用之前使用的相同图片和特征:

代码编辑器 (JavaScript)

// Define a function to be mapped over the collection.
var functionToMap = function(feature) {

  var dictionary = image.reduceRegion({
    reducer: 'first',
    geometry: feature.geometry(),
    scale: 10,
  });

  // Debug:
  print(dictionary);

  return feature.set({
    result: ee.Number(dictionary.get('B5'))
                .divide(dictionary.get('B4'))
  });
};

// Isolate the feature that's creating problems.
var badFeature = ee.Feature(someFeatures
    .filter(ee.Filter.eq('system:index', '2'))
    .first());

// Test the function with print statements added.
functionToMap(badFeature);

// Inspect the bad feature in relation to the image.
Map.centerObject(badFeature, 11);
Map.addLayer(badFeature, {}, 'bad feature');
Map.addLayer(image, {bands: ['B4', 'B3', 'B2'], max: 3000}, 'image');

Python 设置

如需了解 Python API 和如何使用 geemap 进行交互式开发,请访问 Python 环境页面。

import ee
import geemap.core as geemap

Colab (Python)

# Define a function to be mapped over the collection.
def function_to_map(feature):
  dictionary = image.reduceRegion(
      reducer=ee.Reducer.first(), geometry=feature.geometry(), scale=10
  )

  # Debug:
  display(dictionary)

  return feature.set(
      {'result': ee.Number(dictionary.get('B5')).divide(dictionary.get('B4'))}
  )


# Isolate the feature that's creating problems.
bad_feature = ee.Feature(
    some_features.filter(ee.Filter.eq('system:index', '2')).first()
)

# Test the function with print statements added.
function_to_map(bad_feature)

# Inspect the bad feature in relation to the image.
m = geemap.Map()
m.center_object(bad_feature, 11)
m.add_layer(bad_feature, {}, 'bad feature')
m.add_layer(image, {'bands': ['B4', 'B3', 'B2'], 'max': 3000}, 'image')
m

现在,由于该函数仅在一个地图项上运行,因此您可以在其中添加一个 print(对于 Python geemap,则为 `display`)调用。检查输出的对象,发现(啊哈!)reduceRegion() 返回的对象每个波段都为 null。这就解释了为什么除法运算会失败:因为您无法用 null 除以 null。为什么它一开始是 null? 如需进行调查,请将输入图片和错误地图项添加到地图中,并以错误地图项为中心。在此过程中,您发现问题是由于该点超出了图片边界。根据这一发现,调试后的代码如下:

代码编辑器 (JavaScript)

var functionToMap = function(feature) {
  var dictionary = image.reduceRegion({
    reducer: 'first',
    geometry: feature.geometry(),
    scale: 10,
  });
  return feature.set({
    result: ee.Number(dictionary.get('B5'))
                .divide(dictionary.get('B4'))
  });
};

var noProblem = someFeatures
    .filterBounds(image.geometry())
    .map(functionToMap);

print(noProblem);

Python 设置

如需了解 Python API 和如何使用 geemap 进行交互式开发,请访问 Python 环境页面。

import ee
import geemap.core as geemap

Colab (Python)

def function_to_map(feature):
  dictionary = image.reduceRegion(
      reducer=ee.Reducer.first(), geometry=feature.geometry(), scale=10
  )

  return feature.set(
      {'result': ee.Number(dictionary.get('B5')).divide(dictionary.get('B4'))}
  )


no_problem = some_features.filterBounds(image.geometry()).map(function_to_map)

display(no_problem)

Profiler

性能分析器会提供有关 EECU 时间和内存用量(按算法和资源)的信息,这些信息来自启用性能分析器后执行的计算。在性能分析器顶部查找条目,了解最耗费资源的操作。对于长时间运行或效率低下的脚本,性能分析器顶部的条目可提供有关应重点优化脚本哪些部分的线索。重要提示:性能分析器本身会影响脚本的性能,因此您应仅在必要时运行它。