-
Notifications
You must be signed in to change notification settings - Fork 1
/
iteratewcs.py
315 lines (248 loc) · 9.57 KB
/
iteratewcs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
import urllib
import isodate
import time
import netCDF4
from netCDF4 import MFDataset
import sys
from subprocess import PIPE, Popen, STDOUT
from threading import Thread
import json
import os
import shutil
from mkdir_p import *
import zipfile
from xml.sax.saxutils import escape
from xml.dom import minidom
import CGIRunner
import re
import logging;
#logging.basicConfig(level=logging.DEBUG)
def daterange(start_date, end_date, delta):
d = start_date
while d <= end_date:
yield d
d += delta
def which(program):
import os
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
def cleanlog(tmpdir):
try:
os.remove(tmpdir+"/iteratewcs.log")
except:
pass
def dolog(tmpdir, data):
with open(tmpdir+"/iteratewcs.log", "a") as myfile:
myfile.write(str(data)+"\n")
myfile.flush();
def openfile(file):
with open (file, "r") as myfile:
data = myfile.read()
return data
def getlog(tmpdir):
return openfile(tmpdir+"/iteratewcs.log")
def makezip(tmpdir,OUTFILE):
currentpath=os.getcwd()
os.chdir(tmpdir)
""" Otherwise, make a zipfile of all files """
zipf = zipfile.ZipFile(OUTFILE, 'w',zipfile.ZIP_DEFLATED)
for root, dirs, files in os.walk("."):
for file in files:
zipf.write(os.path.join(root, file))
zipf.close()
os.chdir(currentpath)
def callADAGUC(adagucexecutable,tmpdir,LOGFILE,url,filetogenerate):
env = {}
if(LOGFILE != None):
env["ADAGUC_ERRORFILE"]=LOGFILE
try:
os.remove(tmpdir+"/adaguclog.log")
except:
pass
env["ADAGUC_LOGFILE"]=tmpdir+"/adaguclog.log"
return CGIRunner.CGIRunner().run([adagucexecutable],url,out = filetogenerate,extraenv=env, isLocalADAGUC = True)
"""
Describecoverage is done in order to retrieve the avaible dates in the coverage
"""
def describeCoverage(adagucexecutable,tmpdir,LOGFILE,WCSURL,COVERAGE):
filetogenerate = tmpdir+"/describecoverage.xml"
url = WCSURL + "&SERVICE=WCS&REQUEST=DescribeCoverage&";
url = url + "COVERAGE="+COVERAGE+"&";
status = callADAGUC(adagucexecutable,tmpdir,LOGFILE,url,filetogenerate);
if(status != 0):
adaguclog = openfile(tmpdir+"/adaguclog.log");
raise ValueError( "Unable to retrieve "+url+"\n"+adaguclog+"\n");
if(os.path.isfile(filetogenerate) != True):
adaguclog = openfile(tmpdir+"/adaguclog.log");
raise ValueError ("Succesfully completed WCS DescribeCoverage, but no data found. Log is: "+url+"\n"+adaguclog+"\n");
try:
xmldoc = minidom.parse(filetogenerate)
except:
adaguclog = openfile(tmpdir+"/adaguclog.log");
raise ValueError ("Succesfully completed WCS DescribeCoverage, but no data found for "+url+"\n"+adaguclog+"\n");
try:
itemlist = xmldoc.getElementsByTagName('gml:timePosition')
if(len(itemlist)!=0):
listtoreturn = [];
for s in itemlist:
listtoreturn.append(isodate.parse_datetime(s.childNodes[0].nodeValue))
return listtoreturn
else:
start_date = xmldoc.getElementsByTagName('gml:begin')[0].childNodes[0].nodeValue
end_date = xmldoc.getElementsByTagName('gml:end')[0].childNodes[0].nodeValue
res_date = xmldoc.getElementsByTagName('gml:duration')[0].childNodes[0].nodeValue
logging.debug(start_date);
logging.debug(end_date);
logging.debug(res_date);
return list(daterange(isodate.parse_datetime(start_date),isodate.parse_datetime(end_date),isodate.parse_duration(res_date)));
except:
pass
return []
def defaultCallback(message,percentage):
return
"""
This requires a working ADAGUC server in the PATH environment, ADAGUC_CONFIG environment variable must point to ADAGUC's config file.
"""
def iteratewcs(TIME = "",BBOX = "-180,-90,180,90",CRS = "EPSG:4326",RESX=None,RESY=None,WIDTH=None, HEIGHT= None,WCSURL="",TMP=".",COVERAGE="pr",LOGFILE=None,OUTFILE="out.nc",FORMAT="netcdf",CALLBACK=defaultCallback):
adagucexecutable='adagucserver'
""" Check if adagucserver is in the path """
if(which(adagucexecutable) == None):
raise ValueError("ADAGUC Executable '"+adagucexecutable+"' not found in PATH");
CALLBACK("Starting iterateWCS",1)
tmpdir = TMP+"/iteratewcstmp";
shutil.rmtree(tmpdir, ignore_errors=True)
mkdir_p(tmpdir);
""" Determine which dates to do based on describe coverage call"""
CALLBACK("Starting WCS DescribeCoverage request",1)
founddates = describeCoverage(adagucexecutable,tmpdir,LOGFILE,WCSURL,COVERAGE);
start_date=""
end_date=""
if len(TIME) > 0 :
if len(TIME.split("/")) >= 2:
start_date = isodate.parse_datetime(TIME.split("/")[0]);
end_date = isodate.parse_datetime(TIME.split("/")[1]);
else:
if TIME == None or TIME == "*" or TIME == "None":
start_date = isodate.parse_datetime("0001-01-01T00:00:00Z");
end_date = isodate.parse_datetime("9999-01-01T00:00:00Z");
else:
start_date = isodate.parse_datetime(TIME);
end_date = isodate.parse_datetime(TIME);
CALLBACK("File has "+str(len(founddates))+" dates",1)
datestodo = []
if len(founddates) > 0:
for date in founddates:
if(date>=start_date and date<=end_date):
datestodo.append(date)
else:
datestodo.append("*");
CALLBACK("Found "+str(len(datestodo))+" dates",1)
if(len(datestodo) == 0):
raise ValueError("No data found in resource for given dates. Possible date range should be within "+str(founddates[0])+" and "+str(founddates[-1]))
numdatestodo=len(datestodo);
datesdone = 0;
filetogenerate = ""
CALLBACK("Starting Iterating WCS GetCoverage",1)
def makeGetCoverage(single_date):
filetime=""
wcstime=""
messagetime = ""
url = WCSURL + "&SERVICE=WCS&REQUEST=GetCoverage&";
url = url + "FORMAT="+urllib.quote_plus(FORMAT)+"&";
url = url + "COVERAGE="+urllib.quote_plus(COVERAGE)+"&";
logging.debug("WCS GetCoverage URL: "+str(url));
for j in range(0,len(single_date)):
wcsdate = single_date[j]
if wcsdate != "*":
if(j>0):
wcstime=wcstime + ","
wcstime=wcstime + time.strftime("%Y-%m-%dT%H:%M:%SZ", wcsdate.timetuple())
filetime=time.strftime("%Y%m%dT%H%M%SZ", single_date[0].timetuple()) + '-' + time.strftime("%Y%m%dT%H%M%SZ", single_date[-1].timetuple())
messagetime=time.strftime("%Y%m%dT%H%M%SZ", single_date[0].timetuple())
url = url + "TIME="+urllib.quote_plus(wcstime)+"&";
url = url + "BBOX="+BBOX+"&";
if RESX != None:
url = url + "RESX="+str(RESX)+"&";
if RESY != None:
url = url + "RESY="+str(RESY)+"&";
if WIDTH != None:
url = url + "WIDTH="+str(WIDTH)+"&";
if HEIGHT != None:
url = url + "HEIGHT="+str(HEIGHT)+"&";
url = url + "CRS="+urllib.quote_plus(CRS)+"&";
logging.debug(url);
filetogenerate = tmpdir+"/file"+filetime
if(FORMAT == "netcdf"):
filetogenerate = filetogenerate + ".nc"
if(FORMAT == "geotiff"):
filetogenerate = filetogenerate + ".tiff"
if(FORMAT == "aaigrid"):
filetogenerate = filetogenerate + ".grd"
status = callADAGUC(adagucexecutable,tmpdir,LOGFILE,url,filetogenerate);
if(status != 0):
adaguclog = openfile(tmpdir+"/adaguclog.log");
raise ValueError( "Unable to retrieve "+url+"\n"+adaguclog+"\n");
if(os.path.isfile(filetogenerate) != True):
adaguclog = openfile(tmpdir+"/adaguclog.log");
raise ValueError ("Succesfully completed WCS GetCoverage, but no data found for "+url+"\n"+adaguclog+"\n");
if(CALLBACK==None):
print str(int((float(datesdone)/numdatestodo)*90.))
else:
CALLBACK("Processing %s " % messagetime,((float(datesdone)/float(numdatestodo))*90.))
return filetogenerate
""" Make the WCS GetCoverage calls """
grouped_dates = []
numberOfDatesInGroup = 0;
maxRequestsAtOnce = 1
if(FORMAT == "netcdf"):
maxRequestsAtOnce = 8
for single_date in datestodo:
grouped_dates.append(single_date)
datesdone=datesdone+1;
if (len(grouped_dates) >= maxRequestsAtOnce):
filetogenerate = makeGetCoverage(grouped_dates)
grouped_dates = []
if len(grouped_dates) > 0:
filetogenerate = makeGetCoverage(grouped_dates)
def monitor2(line):
dolog(tmpdir,line);
try:
data = json.loads(line)
if(CALLBACK == None):
print float(data["percentage"])*(1./10)+90
else:
CALLBACK("Processing % " % data["message"],float(data["percentage"])*(1./10)+90)
except:
CALLBACK(line,50)
""" If it is netcdf, make a new big netcdf file """
if(FORMAT == "netcdf"):
if datesdone == 1:
shutil.copyfile(filetogenerate ,OUTFILE)
if datesdone > 1:
cleanlog(tmpdir);
dolog(tmpdir,tmpdir)
dolog(tmpdir,OUTFILE)
cmds=['aggregate_time',tmpdir,OUTFILE]
dolog(tmpdir,cmds)
status = CGIRunner.CGIRunner().startProcess(cmds,monitor2)
if(status != 0):
dolog(tmpdir,"statuscode: "+str(status))
data = getlog(tmpdir)
raise ValueError('Unable to aggregate: statuscode='+str(status)+"\n"+data)
else:
CALLBACK("zipping to %s" % (OUTFILE), 95);
makezip(tmpdir, os.path.abspath(OUTFILE))
logging.debug("Writing to "+str(OUTFILE));
shutil.rmtree(tmpdir, ignore_errors=True)
return 0