前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >气象编程 | Google Earth Engine for R——提供250+ 实例

气象编程 | Google Earth Engine for R——提供250+ 实例

作者头像
气象学家
发布2020-07-23 14:47:14
1.6K0
发布2020-07-23 14:47:14
举报
文章被收录于专栏:气象学家

中国第一封电子邮件

之前有推送过关于GEE的文章,后台反馈的情况来看,很多人是想用,但是由于某些众所周知的原因无法使用GEE,还是那句话懂的人自然懂,想使用的人肯定想办法能用得上。就像中国第一封电子邮件富有深意的那句话:“Across the Great Wall we can reach every corner in the world.(越过长城,走向世界)”,今天推荐基于R语言的GEE”工具箱“!

Google Earth Engine for R

rgee is a binding package for calling Google Earth Engine API from within R. Additionally, several functions have been implemented to make simple the connection with the R spatial ecosystem. The current version of rgee has been built considering theearthengine-api 0.1.227.Note that access to Google Earth Engine is only available to registered users.

GitHub:https://github.com/r-spatial/rgee

More than 250+ examples using GEE with R are available here

Quick Start User's Guide for rgee in Portuguese and Spanish.

Created by:

  • POR: Andres Luiz Lima Costa http://amazeone.com.br/index.php
  • SPA: Antony Barja Ingaruca https://barja8.github.io/

What is Google Earth Engine?

Google Earth Engine is a cloud-based platform that allows users to have an easy access to a petabyte-scale archive of remote sensing data and run geospatial analysis on Google’s infrastructure. Currently, Google offers support only for Python and JavaScript. rgee will fill the gap starting to provide support to R!. Below you will find the comparison between the syntax of rgee and the two Google-supported client libraries.

JS (Code Editor)

Python

R

var db = 'CGIAR/SRTM90_V4'var image = ee.Image(db)print(image.bandNames())#> 'elevation'

import eeee.Initialize()db = 'CGIAR/SRTM90_V4'image = ee.Image(db)image.bandNames().getInfo()#> [u'elevation']

library(rgee)ee_Initialize()db <- 'CGIAR/SRTM90_V4'image <- ee$Image(db)image$bandNames()$getInfo()#> [1] "elevation"

Quite similar, isn’t it?. However, there are additional smaller changes should consider when using Google Earth Engine with R. Please check the consideration section before you start coding!

Installation

Install the rgee package from GitHub is quite simple, you just have to run in your R console as follows:

代码语言:javascript
复制
remotes::install_github("r-spatial/rgee")

rgee depends on sf. Therefore, is necessary to install its external libraries, follow the installation steps specified here.

Docker image
代码语言:javascript
复制
docker pull csaybar/rgee
docker run -d -p 8787:8787 -e USER=rgee -e PASSWORD=rgee --name rgee-dev csaybar/rgee

After that, in your preferred browser, run:

代码语言:javascript
复制
127.0.0.1:8787

setup

Prior to using rgee you will need to install a Python version higher than 3.5 in their system. rgee counts with an installation function (ee_install) which helps to setup rgee correctly:

代码语言:javascript
复制
library(rgee)

## It is necessary just once
ee_install()

# Initialize Earth Engine!
ee_Initialize()

Additionally, you might use the functions below for checking the status of rgee dependencies and delete credentials.

代码语言:javascript
复制
ee_check() # Check non-R dependencies
ee_clean_credentials() # Remove credentials of a specific user
ee_clean_pyenv() # Remove reticulate system variables

Also, consider looking at the setup section for more information on customizing your Python installation.

Package Conventions

  • All rgee functions have the prefix ee_. Auto-completion is your friend :).
  • Full access to the Earth Engine API with the prefixee$….
  • Authenticate and Initialize the Earth Engine R API withee_Initialize. It is necessary once by session!.
  • rgee is “pipe-friendly”, we re-exports %>%, but rgee does not require its use.

Quick Demo

1. Compute the trend of night-time lights (JS version)

Authenticate and Initialize the Earth Engine R API.

代码语言:javascript
复制
library(rgee)
ee_Initialize()
#ee_reattach() # reattach ee as a reserve word

Adds a band containing image date as years since 1991.

代码语言:javascript
复制
createTimeBand <-function(img) {
  year <- ee$Date(img$get('system:time_start'))$get('year')$subtract(1991L)
  ee$Image(year)$byte()$addBands(img)
}

Map the time band creation helper over the night-time lights collection.

代码语言:javascript
复制
collection <- ee$
  ImageCollection('NOAA/DMSP-OLS/NIGHTTIME_LIGHTS')$
  select('stable_lights')$
  map(createTimeBand)

Compute a linear fit over the series of values at each pixel, visualizing the y-intercept in green, and positive/negative slopes as red/blue.

代码语言:javascript
复制
col_reduce <- collection$reduce(ee$Reducer$linearFit())
col_reduce <- col_reduce$addBands(
  col_reduce$select('scale'))
ee_print(col_reduce)

Create a interactive visualization!

代码语言:javascript
复制
Map$setCenter(9.08203, 47.39835, 3)
Map$addLayer(
  eeObject = col_reduce,
  visParams = list(
    bands = c("scale", "offset", "scale"),
    min = 0,
    max = c(0.18, 20, -0.18)
  ),
  name = "stable lights trend"
)

rgee_01

2. Extract precipitation values

Install and load tidyverse and sf R package, after that, initialize the Earth Engine R API.

代码语言:javascript
复制
library(tidyverse)
library(rgee)
library(sf)

# ee_reattach() # reattach ee as a reserve word
ee_Initialize()

Read the nc shapefile.

代码语言:javascript
复制
nc <- st_read(system.file("shape/nc.shp", package = "sf"), quiet = TRUE)

Map each image from 2001 to extract the monthly precipitation (Pr) from the Terraclimate dataset

代码语言:javascript
复制
terraclimate <- ee$ImageCollection("IDAHO_EPSCOR/TERRACLIMATE")$
  filterDate("2001-01-01", "2002-01-01")$
  map(function(x) x$reproject("EPSG:4326")$select("pr"))

Extract monthly precipitation values from the Terraclimate ImageCollection through ee_extract. ee_extract works similar to raster::extract, you just need to define: the ImageCollection object (x), the geometry (y), and a function to summarize the values (fun).

代码语言:javascript
复制
ee_nc_rain <- ee_extract(x = terraclimate, y = nc, sf = FALSE)
colnames(ee_nc_rain) <- sprintf("%02d", 1:12)
ee_nc_rain$name <- nc$NAME

Use ggplot2 to generate a beautiful static plot!

代码语言:javascript
复制
ee_nc_rain %>%
  pivot_longer(-name, names_to = "month", values_to = "pr") %>%
  ggplot(aes(x = month, y = pr, group = name, color = pr)) +
  geom_line(alpha = 0.4) +
  xlab("Month") +
  ylab("Precipitation (mm)") +
  theme_minimal()

3. Create an NDVI-animation (JS version)

Install and load sf, after that, initialize the Earth Engine R API.

代码语言:javascript
复制
library(rgee)
library(sf)
ee_Initialize()
# ee_reattach() # reattach ee as a reserve word

Define the regional bounds of animation frames and a mask to clip the NDVI data by.

代码语言:javascript
复制
mask <- system.file("shp/arequipa.shp", package = "rgee") %>% 
  st_read(quiet = TRUE) %>% 
  sf_as_ee()
region <- mask$geometry()$bounds()

Retrieve the MODIS Terra Vegetation Indices 16-Day Global 1km dataset as an ee.ImageCollectionand select the NDVI band.

代码语言:javascript
复制
col <- ee$ImageCollection('MODIS/006/MOD13A2')$select('NDVI')

Group images by composite date

代码语言:javascript
复制
col <- col$map(function(img) {
  doy <- ee$Date(img$get('system:time_start'))$getRelative('day', 'year')
  img$set('doy', doy)
})
distinctDOY <- col$filterDate('2013-01-01', '2014-01-01')

Define a filter that identifies which images from the complete collection match the DOY from the distinct DOY collection.

代码语言:javascript
复制
filter <- ee$Filter$equals(leftField = 'doy', rightField = 'doy');

Define a join; convert the resulting FeatureCollection to an ImageCollection.

代码语言:javascript
复制
join <- ee$Join$saveAll('doy_matches')
joinCol <- ee$ImageCollection(join$apply(distinctDOY, col, filter))

Apply median reduction among matching DOY collections.

代码语言:javascript
复制
comp <- joinCol$map(function(img) {
  doyCol = ee$ImageCollection$fromImages(
    img$get('doy_matches')
  )
  doyCol$reduce(ee$Reducer$median())
})

Define RGB visualization parameters.

代码语言:javascript
复制
visParams = list(
  min = 0.0,
  max = 9000.0,
  bands = "NDVI_median",
  palette = c(
    'FFFFFF', 'CE7E45', 'DF923D', 'F1B555', 'FCD163', '99B718', '74A901',
    '66A000', '529400', '3E8601', '207401', '056201', '004C00', '023B01',
    '012E01', '011D01', '011301'
    )
)

Create RGB visualization images for use as animation frames.

代码语言:javascript
复制
rgbVis <- comp$map(function(img) {
  do.call(img$visualize, visParams) %>% 
    ee$Image$clip(mask)
})

Define GIF visualization parameters.

代码语言:javascript
复制
gifParams <- list(
  region = region,
  dimensions = 600,
  crs = 'EPSG:3857',
  framesPerSecond = 10
)

Render the GIF animation in the console.

代码语言:javascript
复制
print(rgbVis$getVideoThumbURL(gifParams))
browseURL(rgbVis$getVideoThumbURL(gifParams))

How does rgee work?

rgee is not a native Earth Engine API like the Javascript or Python client, to do this would be extremely hard, especially considering that the API is in active development. So, how is it possible to run Earth Engine using R? the answer is reticulate. reticulate is an R package designed to allow a seamless interoperability between R and Python. When an Earth Engine request is created in R, reticulate will transform this piece into Python. Once the Python code is obtained, the Earth Engine Python API transform the request to a JSON format. Finally, the request is received by the Google Earth Engine Platform thanks to a Web REST API. The response will follow the same path.

workflow

Code of Conduct

Please note that the rgee project is released with a Contributor Code of Conduct. By contributing to this project, you agree to abide by its terms.

Contributing Guide

? Thanks for taking the time to contribute! ?? Please review our Contributing Guide.

Share the love ❤️

Think rgee is useful? Let others discover it, by telling them in person via Twitter or a blog post.

Using rgee for a paper you are writing? Consider citing it

代码语言:javascript
复制
citation("rgee")
To cite rgee in publications use:

  C Aybar, Q Wu, L Bautista, R Yali and A Barja (2020) rgee: An R
  package for interacting with Google Earth Engine Journal of Open
  Source Software URL https://github.com/r-spatial/rgee/.

A BibTeX entry for LaTeX users is

  @Article{,
    title = {rgee: An R package for interacting with Google Earth Engine},
    author = {Cesar Aybar and Quisheng Wu and Lesly Bautista and Roy Yali and Antony Barja},
    journal = {Journal of Open Source Software},
    year = {2020},
  }

Credits :bow:

First off, we would like to offer an special thanks :raised_hands: :clap: to Justin Braaten for his wise and helpful comments in the whole development of rgee. As well, we would like to mention the following third-party R/Python packages for contributing indirectly to the develop of rgee:

  • gee_asset_manager - Lukasz Tracewski
  • geeup - Samapriya Roy
  • geeadd - Samapriya Roy
  • cartoee - Kel Markert
  • geetools - Rodrigo E. Principe
  • landsat-extract-gee - Loïc Dutrieux
  • earthEngineGrabR - JesJehle
  • sf - Edzer Pebesma
  • stars - Edzer Pebesma
  • gdalcubes - Marius Appel
Readme template obtained from dbparser

参考资料

[1]

文章链接: https://r-spatial.github.io/rgee/index.html

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-07-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 气象学家 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Google Earth Engine for R
    • More than 250+ examples using GEE with R are available here
      • What is Google Earth Engine?
        • Installation
          • setup
            • Package Conventions
              • Quick Demo
                • 1. Compute the trend of night-time lights (JS version)
                • 2. Extract precipitation values
                • 3. Create an NDVI-animation (JS version)
              • How does rgee work?
                • Code of Conduct
                  • Contributing Guide
                    • Share the love ❤️
                      • Credits :bow:
                      相关产品与服务
                      容器服务
                      腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
                      领券
                      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档