Project

General

Profile

Download (5.74 KB) Statistics
| Branch: | Revision:
1 f5ef0596 Adam M. Wilson
#!/usr/bin/env python
2
3 58d05081 Adam M. Wilson
## Example script that downloads data from Google Earth Engine using the python API
4
## MODIS MOD09GA data is processed to extract the MOD09 cloud flag and calculate monthly cloud frequency
5
6
7
## import some libraries
8
import ee
9
from ee import mapclient
10
import ee.mapclient 
11
import datetime
12
import wget
13
import os
14 f5ef0596 Adam M. Wilson
import sys
15 41d291a6 Adam M. Wilson
import subprocess
16
import time
17 58d05081 Adam M. Wilson
18 f5ef0596 Adam M. Wilson
import logging
19
logging.basicConfig(filename='error.log',level=logging.DEBUG)
20
21
def Usage():
22 41d291a6 Adam M. Wilson
    print('Usage: ee.MOD9.py -projwin  ulx uly urx ury lrx lry llx lly -year year -month month -regionname 1') 
23 f5ef0596 Adam M. Wilson
    sys.exit( 1 )
24
25
ulx = float(sys.argv[2])
26
uly = float(sys.argv[3])
27 41d291a6 Adam M. Wilson
urx = float(sys.argv[4])
28
ury = float(sys.argv[5])
29
lrx = float(sys.argv[6])
30
lry = float(sys.argv[7])
31
llx = float(sys.argv[8])
32
lly = float(sys.argv[9])
33
year = int(sys.argv[11])
34
month = int(sys.argv[13])
35
regionname = str(sys.argv[15])
36 f5ef0596 Adam M. Wilson
#```
37
#ulx=-159
38
#uly=20
39
#lrx=-154.5
40
#lry=18.5
41
#year=2001
42
#month=6
43
#```
44
## Define output filename
45
output=regionname+'_'+str(year)+'_'+str(month)
46 58d05081 Adam M. Wilson
47
## set working directory (where files will be downloaded)
48 41d291a6 Adam M. Wilson
cwd='/mnt/data2/projects/cloud/mod09/'
49
## Wget always starts with a temporary file called "download", so move to a subdirectory to
50
## prevent overwrting when parallel downloading 
51
if not os.path.exists(cwd+output):
52
    os.makedirs(cwd+output)
53
os.chdir(cwd+output)
54 58d05081 Adam M. Wilson
55 41d291a6 Adam M. Wilson
      # output filename
56
unzippedfilename=output+".mod09.tif"
57
      # Check if file already exists and continue if so...
58
if(os.path.exists(unzippedfilename)):
59
    sys.exit("File exists:"+output)    
60
61
## initialize GEE
62 15936a3e Adam M. Wilson
MY_SERVICE_ACCOUNT = '511722844190@developer.gserviceaccount.com'  # replace with your service account
63
MY_PRIVATE_KEY_FILE = '/home/adamw/EarthEngine-privatekey.p12'       # replace with you private key file path
64 58d05081 Adam M. Wilson
ee.Initialize(ee.ServiceAccountCredentials(MY_SERVICE_ACCOUNT, MY_PRIVATE_KEY_FILE))
65
66
## set map center to speed up viewing
67 15936a3e Adam M. Wilson
#ee.mapclient.centerMap(-121.767, 46.852, 11)
68 58d05081 Adam M. Wilson
69
#///////////////////////////////////
70
#// Function to extract cloud flags
71 ba7057c4 Adam M. Wilson
def getmod09(img): return(img.select(['state_1km']).expression("((b(0)/1024)%2)").gte(1)); 
72 bce95cb5 Adam M. Wilson
73 58d05081 Adam M. Wilson
#////////////////////////////////////////////////////
74 f5ef0596 Adam M. Wilson
#####################################################
75
# Processing Function
76
# MOD09 internal cloud flag for this year-month
77 15936a3e Adam M. Wilson
      # to filter by a date range:  filterDate(datetime.datetime(yearstart,monthstart,1),datetime.datetime(yearstop,monthstop,31))
78 f5ef0596 Adam M. Wilson
mod09 = ee.ImageCollection("MOD09GA").filter(ee.Filter.calendarRange(year,year,"year")).filter(ee.Filter.calendarRange(month,month,"month")).map(getmod09);
79 d7dc526e Adam M. Wilson
#      myd09 = ee.ImageCollection("MYD09GA").filter(ee.Filter.calendarRange(year,year,"year")).filter(ee.Filter.calendarRange(month,month,"month")).map(getmod09);
80 15936a3e Adam M. Wilson
      # calculate mean cloudiness (%), rename band, multiply by 100, and convert to integer
81 f5ef0596 Adam M. Wilson
mod09a=mod09.mean().select([0], ['mod09']).multiply(ee.Image(1000)).int16();
82
#      myd09a=myd09.mean().select([0], ['MYD09_'+str(year)+'_'+str(month)]).multiply(ee.Image(100)).int8();
83
## Set data equal to whatver you want downloaded
84
data=mod09a
85
######################################################
86
87
## define region for download
88 41d291a6 Adam M. Wilson
region=[llx, lly],[lrx, lry],[urx, ury],[ulx,uly]  #h11v08
89 f5ef0596 Adam M. Wilson
strregion=str(list(region))
90 d7dc526e Adam M. Wilson
91
# add to plot to confirm it's working
92 f5ef0596 Adam M. Wilson
#ee.mapclient.addToMap(data, {'range': '0,100'}, 'MOD09')
93 15936a3e Adam M. Wilson
94
      # build the URL and name the object (so that when it's unzipped we know what it is!)
95 f5ef0596 Adam M. Wilson
path =mod09a.getDownloadUrl({
96 41d291a6 Adam M. Wilson
        'crs': 'SR-ORG:6974',          # MODIS Sinusoidal
97
        'scale': '926.625433055833',   # MODIS ~1km
98 f5ef0596 Adam M. Wilson
        'name': output,  # name the file (otherwise it will be a uninterpretable hash)
99
        'region': strregion                        # region defined above
100
        });
101 15936a3e Adam M. Wilson
102 41d291a6 Adam M. Wilson
# print info to confirm there is data
103 ba7057c4 Adam M. Wilson
print(data.getInfo())
104 41d291a6 Adam M. Wilson
print(' Processing.... '+output+'     Coords:'+strregion)
105 ba7057c4 Adam M. Wilson
print(path)
106 41d291a6 Adam M. Wilson
107
#test=wget.download(path)
108
test=subprocess.call(['-c','-q','--timeout=0','--ignore-length','--no-http-keep-alive','-O','mod09.zip',path],executable='wget')
109 ba7057c4 Adam M. Wilson
print('download sucess for tile '+output+':   '+str(test))
110 41d291a6 Adam M. Wilson
111
## Sometimes EE will serve a corrupt zipped file with no error
112
# try to unzip it
113
zipstatus=subprocess.call("unzip -o mod09.zip",shell=True)
114
115
if zipstatus==0:  #if sucessful, quit
116
    os.remove("mod09.zip")
117
    sys.exit("Finished:  "+output)
118
119
# if file doesn't exists or it didn't unzip, try again      
120
if zipstatus!=0:
121
    print("Zip Error for:  "+output+"...         Trying again (#2)")    
122
    time.sleep(15)
123
    test=subprocess.call(['-c','-q','--timeout=0','--ignore-length','--no-http-keep-alive','-O','mod09.zip',path],executable='wget')
124
125
zipstatus=subprocess.call("unzip -o mod09.zip",shell=True)
126
127
if zipstatus==0:  #if sucessful, quit
128
    os.remove("mod09.zip")
129
    sys.exit("Finished:  "+output)
130
131
# if file doesn't exists or it didn't unzip, try again      
132
if zipstatus!=0:
133
    print("Zip Error for:  "+output+"...         Trying again (#3)")    
134
    time.sleep(30)
135
    test=subprocess.call(['-c','-q','--timeout=0','--ignore-length','--no-http-keep-alive','-O','mod09.zip',path],executable='wget')
136
137
# try again #4
138
zipstatus=subprocess.call("unzip -o mod09.zip",shell=True)
139
140
if zipstatus==0:  #if sucessful, quit
141
    os.remove("mod09.zip")
142
    sys.exit("Finished:  "+output)
143
144
# if file doesn't exists or it didn't unzip, try again      
145
if zipstatus!=0:
146
    print("Zip Error for:  "+output+"...         Trying again (#4)")    
147
    time.sleep(30)
148
    test=subprocess.call(['-c','-q','--timeout=0','--ignore-length','--no-http-keep-alive','-O','mod09.zip',path],executable='wget')
149
150
zipstatus=subprocess.call("unzip -o mod09.zip",shell=True)
151
152
if zipstatus==0:  #if sucessful, quit
153
    os.remove("mod09.zip")
154
    sys.exit("Finished:  "+output)
155 f5ef0596 Adam M. Wilson
156
## delete the zipped file (the unzipped version is kept)
157 41d291a6 Adam M. Wilson
os.remove("mod09.zip")
158
sys.exit("Zip Error for:  "+output)    
159 58d05081 Adam M. Wilson