Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

""" Common functions for dealing with GEE 

""" 

import datetime as dt 

 

import ee 

import shapely.geometry 

 

 

# ============================================================================== 

# Metadata handling 

def object_metadata(obj, keys): 

""" Return metadata from some EE object as dict (not evaluated) 

 

Parameters 

---------- 

image : object 

EarthEngine object (from ``ee``), typically an ``ee.Image`` 

keys : Sequence[str] 

Metadata to retrieve 

 

Returns 

------- 

ee.Dictionary 

Dictionary of metadata 

""" 

d = ee.Dictionary() 

for key in keys: 

d = d.set(key, obj.get(key)) 

return d 

 

 

def collection_metadata(collection, key): 

""" Return a ee.List of metadata from each item in ``collection`` 

 

Parameters 

---------- 

collection : ee.ImageCollection 

GEE collection 

key : str 

Metadata key 

 

Returns 

------- 

ee.List 

List of metadata per item in ``collection`` 

""" 

def inner(img, previous): 

v = ee.Image(img).get(key) 

previous_ = ee.List(previous) 

return ee.List(previous_.add(v)) 

return collection.iterate(inner, ee.List([])) 

 

 

# ============================================================================== 

# Time 

def get_collection_dates(imgcol): 

def inner(image, previous): 

date = ee.Image(image).date().format('YYYY-MM-dd') 

previous_ = ee.List(previous) 

return ee.List(previous_.add(date)) 

dates = imgcol.iterate(inner, ee.List([])).getInfo() 

return [dt.datetime.strptime(d, '%Y-%m-%d') for d in dates] 

 

 

def get_collection_uniq_dates(col): 

return list(sorted(set(get_collection_dates(col)))) 

 

 

def filter_collection_time(col, d_start, d_end): 

# ee.Date should parse from str or datetime 

d_start_ = ee.Date(d_start) 

d_end_ = ee.Date(d_end) 

col_ = col.filterDate(d_start_, d_end_) 

return col_ 

 

 

# ============================================================================= 

# Tile related functions 

def filter_collection_tile(col, tile): 

geom_ee = tile_geom(tile) 

return col.filterBounds(geom_ee) 

 

 

def tile_geom(tile): 

# Buffer slightly inward so we don't get "touching" but not overlapping 

geom = shapely.geometry.mapping(tile.bbox.buffer(-1e-3)) 

geom_ee = ee.Geometry(geom, opt_proj=tile.crs.wkt) 

return geom_ee