Project

General

Profile

Download (4.46 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 15936a3e Adam M. Wilson
from subprocess import call
16 58d05081 Adam M. Wilson
17 f5ef0596 Adam M. Wilson
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 58d05081 Adam M. Wilson
43
## set working directory (where files will be downloaded)
44 d7dc526e Adam M. Wilson
os.chdir('/mnt/data2/projects/cloud/mod09')
45 58d05081 Adam M. Wilson
46 15936a3e Adam M. Wilson
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 58d05081 Adam M. Wilson
49
ee.Initialize(ee.ServiceAccountCredentials(MY_SERVICE_ACCOUNT, MY_PRIVATE_KEY_FILE))
50
51
## set map center to speed up viewing
52 15936a3e Adam M. Wilson
#ee.mapclient.centerMap(-121.767, 46.852, 11)
53 58d05081 Adam M. Wilson
54
#///////////////////////////////////
55
#// Function to extract cloud flags
56 bce95cb5 Adam M. Wilson
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 58d05081 Adam M. Wilson
#////////////////////////////////////////////////////
60 15936a3e Adam M. Wilson
61
      # output filename
62 f5ef0596 Adam M. Wilson
unzippedfilename=output+".mod09.tif"
63 15936a3e Adam M. Wilson
64
      # Check if file already exists and continue if so...
65 f5ef0596 Adam M. Wilson
if(os.path.exists(unzippedfilename)):
66
    sys.exit("File exists:"+output)    
67 15936a3e Adam M. Wilson
68 f5ef0596 Adam M. Wilson
69
#####################################################
70
# Processing Function
71
# MOD09 internal cloud flag for this year-month
72 15936a3e Adam M. Wilson
      # to filter by a date range:  filterDate(datetime.datetime(yearstart,monthstart,1),datetime.datetime(yearstop,monthstop,31))
73 f5ef0596 Adam M. Wilson
mod09 = ee.ImageCollection("MOD09GA").filter(ee.Filter.calendarRange(year,year,"year")).filter(ee.Filter.calendarRange(month,month,"month")).map(getmod09);
74 d7dc526e Adam M. Wilson
#      myd09 = ee.ImageCollection("MYD09GA").filter(ee.Filter.calendarRange(year,year,"year")).filter(ee.Filter.calendarRange(month,month,"month")).map(getmod09);
75 15936a3e Adam M. Wilson
      # calculate mean cloudiness (%), rename band, multiply by 100, and convert to integer
76 f5ef0596 Adam M. Wilson
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 d7dc526e Adam M. Wilson
# Next few lines for testing only
86
# print info to confirm there is data
87 f5ef0596 Adam M. Wilson
#data.getInfo()
88
89
## print a status update
90
print(output+' Processing....      Coords:'+strregion)
91
92 d7dc526e Adam M. Wilson
93
# add to plot to confirm it's working
94 f5ef0596 Adam M. Wilson
#ee.mapclient.addToMap(data, {'range': '0,100'}, 'MOD09')
95
#```
96
97
# TODO:  
98
#  use MODIS projection
99 15936a3e Adam M. Wilson
100
      # build the URL and name the object (so that when it's unzipped we know what it is!)
101 f5ef0596 Adam M. Wilson
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',                         #  projection
105
        'region': strregion                        # region defined above
106
        });
107 15936a3e Adam M. Wilson
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 f5ef0596 Adam M. Wilson
#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 15936a3e Adam M. Wilson
        # try to unzip it
118 f5ef0596 Adam M. Wilson
print("Unzipping "+output)
119
zipstatus=call("unzip "+output+".zip",shell=True)
120 d7dc526e Adam M. Wilson
         # if file doesn't exists or it didn't unzip, remove it and try again      
121 f5ef0596 Adam M. Wilson
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 58d05081 Adam M. Wilson