Project

General

Profile

Download (4.89 KB) Statistics
| Branch: | Revision:
1
## Example script that downloads data from Google Earth Engine using the python API
2
## MODIS MOD09GA data is processed to extract the MOD09 cloud flag and calculate monthly cloud frequency
3

    
4

    
5
## import some libraries
6
import ee
7
from ee import mapclient
8
import ee.mapclient 
9
import datetime
10
import wget
11
import os
12
from subprocess import call
13

    
14
#import logging
15
#logging.basicConfig()
16

    
17
## set working directory (where files will be downloaded)
18
os.chdir('/mnt/data2/projects/cloud/mod09')
19

    
20
MY_SERVICE_ACCOUNT = '511722844190@developer.gserviceaccount.com'  # replace with your service account
21
MY_PRIVATE_KEY_FILE = '/home/adamw/EarthEngine-privatekey.p12'       # replace with you private key file path
22

    
23
#MY_SERVICE_ACCOUNT = '205878743334-4mrtqgu0n5rnsv1vanrvv6atqk6vu8am@developer.gserviceaccount.com'
24
#MY_PRIVATE_KEY_FILE = '/home/adamw/EarthEngine_Jeremy-privatekey.p12'
25

    
26
ee.Initialize(ee.ServiceAccountCredentials(MY_SERVICE_ACCOUNT, MY_PRIVATE_KEY_FILE))
27

    
28
## set map center to speed up viewing
29
#ee.mapclient.centerMap(-121.767, 46.852, 11)
30

    
31
#///////////////////////////////////
32
#// Function to extract cloud flags
33
def getmod09(img): return(img.select(['state_1km']).expression("((b(0)/1024)%2)>0.5")); 
34
# added the >0.5 because some values are coming out >1.  Need to look into this further as they should be bounded 0-1...
35

    
36
#// Date ranges
37
yearstart=2000
38
yearstop=2012
39
monthstart=1
40
monthstop=12
41

    
42
#////////////////////////////////////////////////////
43
# Loop through months and get monthly % missing data
44

    
45
## set a year-month if you don't want to run the loop (for testing)
46
#year=2001
47
#month=2
48
#r=1
49

    
50
## define the regions to be processed
51
regions=['[[-180, -60], [-180, 0], [0, 0], [0, -60]]',  # SW
52
         '[[-180, 0], [-180, 90], [0, 90], [0, 0]]',    # NW
53
         '[[0, 0], [0, 90], [180, 90], [180, 0]]',      # NE
54
         '[[0, 0], [0, -60], [180, -60], [180, 0]]']    # SE
55
## name the regions (these names will be used in the file names
56
## must be same length as regions list above
57
rnames=['SW','NW','NE','SE']
58

    
59
## Loop over regions, years, months to generate monthly timeseries
60
for r in range(0,len(regions)):                                    # loop over regions
61
  for year in range(yearstart,yearstop+1):              # loop over years
62
    for month in range(monthstart,monthstop+1):         # loop over months
63
      print('Processing '+rnames[r]+"_"+str(year)+'_'+str(month))
64

    
65
      # output filename
66
      filename='mod09_'+rnames[r]+"_"+str(year)+"_"+str(month)
67
      unzippedfilename='mod09_'+rnames[r]+"_"+str(year)+"_"+str(month)+".MOD09_"+str(year)+"_"+str(month)+".tif"
68

    
69
      # Check if file already exists and continue if so...
70
      if(os.path.exists(unzippedfilename)):
71
        print("File exists:"+filename)
72
        continue
73

    
74
      # MOD09 internal cloud flag for this year-month
75
      # to filter by a date range:  filterDate(datetime.datetime(yearstart,monthstart,1),datetime.datetime(yearstop,monthstop,31))
76
      mod09 = ee.ImageCollection("MOD09GA").filter(ee.Filter.calendarRange(year,year,"year")).filter(ee.Filter.calendarRange(month,month,"month")).map(getmod09);
77
#      myd09 = ee.ImageCollection("MYD09GA").filter(ee.Filter.calendarRange(year,year,"year")).filter(ee.Filter.calendarRange(month,month,"month")).map(getmod09);
78
      # calculate mean cloudiness (%), rename band, multiply by 100, and convert to integer
79
      mod09a=mod09.mean().select([0], ['MOD09_'+str(year)+'_'+str(month)]).multiply(ee.Image(100)).byte();
80
#      myd09a=myd09.mean().select([0], ['MYD09_'+str(year)+'_'+str(month)]).multiply(ee.Image(100)).byte();
81
      
82
```
83
# Next few lines for testing only
84
# print info to confirm there is data
85
mod09a.getInfo()
86
myd09a.getInfo()
87

    
88
# add to plot to confirm it's working
89
ee.mapclient.addToMap(mod09a, {'range': '0,100'}, 'MOD09')
90
ee.mapclient.addToMap(myd09a, {'range': '0,100'}, 'MOD09')
91
```
92

    
93
      # build the URL and name the object (so that when it's unzipped we know what it is!)
94
      path =mod09a.getDownloadUrl({
95
          'name': filename,  # name the file (otherwise it will be a uninterpretable hash)
96
          'scale': 1000,                              # resolution in meters
97
          'crs': 'EPSG:4326',                         # MODIS sinusoidal
98
          'region': regions[r]                        # region defined above
99
          });
100

    
101
      # Sometimes EE will serve a corrupt zipped file with no error
102
      # to check this, use a while loop that keeps going till there is an unzippable file.  
103
      # This has the potential for an infinite loop...
104

    
105
      while(not(os.path.exists(filename+".zip"))):
106
        # download with wget
107
        print("Downloading "+filename) 
108
        wget.download(path)
109
        # try to unzip it
110
        print("Unzipping "+filename)
111
        zipstatus=call("unzip "+filename+".zip",shell=True)
112
         # if file doesn't exists or it didn't unzip, remove it and try again      
113
        if(zipstatus==9):
114
          print("ERROR: "+filename+" unzip-able")
115
          os.remove(filename)
116

    
117
print 'Finished'
118

    
119

    
(43-43/47)