Project

General

Profile

Download (5.84 KB) Statistics
| Branch: | Revision:
1
#!/usr/bin/env python
2

    
3
## 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
import sys
15
import subprocess
16
import time
17

    
18
import logging
19
logging.basicConfig(filename='error.log',level=logging.DEBUG)
20

    
21
def Usage():
22
    print('Usage: ee.MOD9.py -projwin  ulx uly urx ury lrx lry llx lly -year year -month month -regionname 1') 
23
    sys.exit( 1 )
24

    
25
ulx = float(sys.argv[2])
26
uly = float(sys.argv[3])
27
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
#```
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

    
47
## set working directory (where files will be downloaded)
48
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

    
55
      # 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
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
ee.Initialize(ee.ServiceAccountCredentials(MY_SERVICE_ACCOUNT, MY_PRIVATE_KEY_FILE))
65

    
66
## set map center to speed up viewing
67
#ee.mapclient.centerMap(-121.767, 46.852, 11)
68

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

    
74
#////////////////////////////////////////////////////
75
#####################################################
76
# Processing Function
77
# MOD09 internal cloud flag for this year-month
78
      # to filter by a date range:  filterDate(datetime.datetime(yearstart,monthstart,1),datetime.datetime(yearstop,monthstop,31))
79
mod09 = ee.ImageCollection("MOD09GA").filter(ee.Filter.calendarRange(year,year,"year")).filter(ee.Filter.calendarRange(month,month,"month")).map(getmod09);
80
#      myd09 = ee.ImageCollection("MYD09GA").filter(ee.Filter.calendarRange(year,year,"year")).filter(ee.Filter.calendarRange(month,month,"month")).map(getmod09);
81
      # calculate mean cloudiness (%), rename band, multiply by 100, and convert to integer
82
mod09a=mod09.mean().select([0], ['mod09']).multiply(ee.Image(1000)).int16();
83
#      myd09a=myd09.mean().select([0], ['MYD09_'+str(year)+'_'+str(month)]).multiply(ee.Image(100)).int8();
84
## Set data equal to whatver you want downloaded
85
data=mod09a
86
######################################################
87

    
88
## define region for download
89
region=[llx, lly],[lrx, lry],[urx, ury],[ulx,uly]  #h11v08
90
strregion=str(list(region))
91

    
92
# add to plot to confirm it's working
93
#ee.mapclient.addToMap(data, {'range': '0,100'}, 'MOD09')
94

    
95
      # build the URL and name the object (so that when it's unzipped we know what it is!)
96
path =mod09a.getDownloadUrl({
97
        'crs': 'SR-ORG:6974',          # MODIS Sinusoidal
98
        'scale': '926.625433055833',   # MODIS ~1km
99
        'name': output,  # name the file (otherwise it will be a uninterpretable hash)
100
        'region': strregion                        # region defined above
101
        });
102

    
103
# print info to confirm there is data
104
#print(data.getInfo())
105
print(' Processing.... '+output+'     Coords:'+strregion)
106

    
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
print('download sucess for'+output+':   '+str(test))
110

    
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

    
156
## delete the zipped file (the unzipped version is kept)
157
os.remove("mod09.zip")
158
sys.exit("Zip Error for:  "+output)    
159

    
160

    
(45-45/50)