Project

General

Profile

Download (4.48 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
from subprocess import call
16

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

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

    
24
ulx = float(sys.argv[2])
25
uly = float(sys.argv[3])
26
lrx = float(sys.argv[4])
27
lry = float(sys.argv[5])
28
year = int(sys.argv[7])
29
month = int(sys.argv[9])
30
regionname = str(sys.argv[11])
31

    
32
#```
33
#ulx=-159
34
#uly=20
35
#lrx=-154.5
36
#lry=18.5
37
#year=2001
38
#month=6
39
#```
40
## Define output filename
41
output=regionname+'_'+str(year)+'_'+str(month)
42

    
43
## set working directory (where files will be downloaded)
44
os.chdir('/mnt/data2/projects/cloud/mod09')
45

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

    
49
ee.Initialize(ee.ServiceAccountCredentials(MY_SERVICE_ACCOUNT, MY_PRIVATE_KEY_FILE))
50

    
51
## set map center to speed up viewing
52
#ee.mapclient.centerMap(-121.767, 46.852, 11)
53

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

    
59
#////////////////////////////////////////////////////
60

    
61
      # output filename
62
unzippedfilename=output+".mod09.tif"
63

    
64
      # Check if file already exists and continue if so...
65
if(os.path.exists(unzippedfilename)):
66
    sys.exit("File exists:"+output)    
67

    
68

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

    
82
## define region for download
83
region=[ulx,lry], [ulx, uly], [lrx, uly], [lrx, lry]  #h11v08
84
strregion=str(list(region))
85
# Next few lines for testing only
86
# print info to confirm there is data
87
print(data.getInfo())
88

    
89
## print a status update
90
print(output+' Processing....      Coords:'+strregion)
91

    
92

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

    
97
# TODO:  
98
#  use MODIS projection
99

    
100
      # build the URL and name the object (so that when it's unzipped we know what it is!)
101
path =mod09a.getDownloadUrl({
102
        'name': output,  # name the file (otherwise it will be a uninterpretable hash)
103
        'scale': 926,                              # resolution in meters
104
        'crs': 'EPSG:4326', #4326                         #  projection
105
        'region': strregion                        # region defined above
106
        });
107

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

    
112
#if(not(os.path.exists(output+".tif"))):
113
    # download with wget
114
print("Downloading "+output) 
115
wget.download(path)
116
#call(["wget"+path,shell=T])
117
        # try to unzip it
118
print("Unzipping "+output)
119
zipstatus=call("unzip "+output+".zip",shell=True)
120
         # if file doesn't exists or it didn't unzip, remove it and try again      
121
if(zipstatus==9):
122
    sys.exit("File exists:"+output)    
123
#        print("ERROR: "+output+" unzip-able")
124
#        os.remove(output+".zip")
125

    
126
## delete the zipped file (the unzipped version is kept)
127
os.remove(output+".zip")
128
       
129
print(output+' Finished!')
130

    
131

    
(45-45/50)