This repository has been archived by the owner on Jan 3, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 45
/
podaac.py
604 lines (491 loc) · 24.2 KB
/
podaac.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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
# Copyright 2016 California Institute of Technology.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import requests
from future.moves.urllib.parse import urlencode
from future.moves.urllib.request import urlopen, urlretrieve
from future.moves.http.client import HTTPSConnection
import os
import zipfile
import json
import time
import xml.etree.ElementTree as ET
URL = 'https://podaac.jpl.nasa.gov/ws/'
IMAGE_URL = 'https://podaac-tools.jpl.nasa.gov/l2ss-services/l2ss/preview/'
class Podaac:
def __init__(self):
self.URL = 'http://podaac.jpl.nasa.gov/ws/'
def dataset_metadata(self, dataset_id='', short_name='', format='iso'):
'''Dataset metadata service retrieves the metadata of a \
dataset on PO.DAACs dataset catalog using the following \
parameters: dataset_id, short_name, and format.
:param dataset_id: dataset persistent ID. dataset_id or short_name \
is required for this metadata service.
:type dataset_id: :mod:`string`
:param short_name: dataset short_name. dataset_id or short_name \
is required for this metadata service.
:type short_name: :mod:`string`
:param format: metadata format. Default format is iso.
:type format: :mod:`string`
:returns: an xml response based on the requested 'format'. Options \
are 'iso' and 'gcmd'.
'''
try:
url = self.URL + 'metadata/dataset/?'
if(dataset_id):
url = url + 'datasetId=' + dataset_id
else:
raise Exception("Dataset Id is required")
if(short_name):
url = url + '&shortName=' + short_name
url = url + '&format=' + format
metadata = requests.get(url)
status_codes = [404, 400, 503, 408]
if metadata.status_code in status_codes:
metadata.raise_for_status()
except requests.exceptions.HTTPError as error:
print(error)
raise
return metadata.text
def dataset_search(self, keyword='', start_time='', end_time='', start_index='', dataset_id='', short_name='',
instrument='', satellite='', file_format='', status='', process_level='', sort_by='',
bbox='', items_per_page='7', pretty='True', format='atom', full='False'):
'''Dataset Search service searches PO.DAAC's dataset catalog, over \
Level 2, Level 3, and Level 4 datasets, using the following parameters: \
dataset_id, short_name, start_time, end_time, bbox, and others.
:param keyword: keyword specifies search text to search for datasets. \
Example: 'modis'
:type keyword: :mod:`string`
:param start_time: start time in the format of YYYY-MM-DDTHH:mm:ssZ. \
'Z' is the time-offset, where 'Z' signifies UTC or an actual \
offset can be used. Example: 2012-01-22T01:21:21Z
:type start_time: :mod:`time`
:param end_time: stop time in the format of YYYY-MM-DDTHH:mm:ssZ. \
'Z' is the time-offset, where 'Z' signifies UTC or an actual \
offset can be used. Example: 2012-01-22T01:21:21Z
:type end_time: :mod:`time`
:param start_index: start index of entries found for search. Example: 1
:type start_index: :mod:`int`
:param items_per_page: number of results per page for \
opensearch result. If format is not specified, format is set \
to 7. The value range is from 0 to 400
:type items_per_page: :mod:`int`
:param dataset_id: dataset persistent ID. \
Example: PODAAC-MODSA-T8D9N
:type dataset_id: :mod:`string`
:param short_name: dataset short_name. \
Example: MODIS_AQUA_L3_SST_THERMAL_8DAY_9KM_NIGHTTIME
:type short_name: :mod:`string`
:param instrument: dataset instrument. Example: MODIS
:type instrument: :mod:`string`
:param satellite: dataset satellite. Example: AQUA
:type satellite: :mod:`string`
:param file_format: dataset data format. \
Possible values: HDF, NetCDF
:type file_format: :mod:`string`
:param status: dataset status. \
Possible values: OPEN, PREVIEW, SIMULATED, RETIRED
:type status: :mod:`string`
:param processLevel: dataset processing level. \
Possible values: 1B, 2, 2P, 3, 4
:type processLevel: :mod:`string`
:param pretty: "true" to enable pretty output for xml. \
If pretty is not specified, pretty is set to true.
:type pretty: :mod:`boolean`
:param format: response format. If format is not specified, \
format is set to atom. Possible values: atom, html.
:type format: :mod:`string`
:param sort_by: determines ordering of response. If sort_by \
is not specified, sort order is by score (most relevant \
dataset first). Possible values: timeAsc, timeDesc, \
popularityAsc, popularityDesc.
:type sort_by: :mod:`string`
:param bbox: bounding box for spatial search. format \
should look like "bbox=0.0,-45.0,180.0,40.0" which is \
in order of west, south, east, north. Longitude values needs \
to be in range of [-180.0,180.0]. Example: 0.0,-45.0,180.0,40.0
:type bbox: :mod:`string`
:param full: "true" to return response with complete PO.DAAC \
metadata per entry. If full is not specified, full is set to false. \
Possible values: true, false
:type full: :mod:`string`
:returns: the specified response format. If format is not specified, \
format is set to atom. Possible values: atom, html
'''
try:
url = self.URL + 'search/dataset/?'
url = url + 'itemsPerPage=' + items_per_page + '&pretty=' + \
pretty + '&format=' + format + '&full=' + full
if(dataset_id):
url = url + '&keyword=' + keyword
if(start_time):
url = url + '&startTime=' + start_time
if(end_time):
url = url + '&endTime=' + end_time
if(bbox):
url = url + '&bbox=' + bbox
if(start_index):
url = url + '&startIndex=' + start_index
if(dataset_id):
url = url + '&datasetId=' + dataset_id
if(short_name):
url = url + '&shortName=' + short_name
if(instrument):
url = url + '&instrument=' + instrument
if(satellite):
url = url + '&satellite=' + satellite
if(file_format):
url = url + '&fileFormat=' + file_format
if(status):
url = url + '&status=' + status
if(process_level):
url = url + '&processLevel=' + process_level
if(sort_by):
url = url + '&sortBy=' + sort_by
if(bbox):
url = url + '&bbox=' + bbox
datasets = requests.get(url)
status_codes = [404, 400, 503, 408]
if datasets.status_code in status_codes:
datasets.raise_for_status()
except requests.exceptions.HTTPError as error:
print(error)
raise
return datasets.text
def dataset_variables(self, dataset_id):
'''Provides list of dataset variables.
:param dataset_id: dataset persistent ID. dataset_id or short_name \
is required for this metadata service.
:type dataset_id: :mod:`string`
:returns: a list of dataset variables for the dataset.
'''
try:
url = self.URL + 'dataset/variables/?datasetId=' + dataset_id
variables = requests.get(url)
status_codes = [404, 400, 503, 408]
if variables.status_code in status_codes:
variables.raise_for_status()
except requests.exceptions.HTTPError as error:
print(error)
raise
dataset_variables = json.loads(variables.text)['variables']
return dataset_variables
def granule_metadata(self, dataset_id='', short_name='', granule_name='', format='iso'):
'''Granule metadata service retrieves the metadata of a granule \
on PO.DAACs catalog in ISO-19115.
:param dataset_id: dataset persistent ID. dataset_id or short_name \
is required for this metadata service.
:type dataset_id: :mod:`string`
:param short_name: dataset short_name. dataset_id or short_name \
is required for this metadata service.
:type short_name: :mod:`string`
:param granule_name: granule name. granule name is required \
for this metadata service.
:type granule_name: :mod:`string`
:param format: metadata format. Default format is iso.
:type format: :mod:`string`
:returns: an xml response based on the requested 'format'.
'''
try:
url = self.URL + 'metadata/granule/?'
if(dataset_id):
url = url + 'datasetId=' + dataset_id
else:
raise Exception("Dataset Id is required")
if(short_name):
url = url + '&shortName=' + short_name
if(granule_name):
url = url + '&granuleName=' + granule_name
url = url + '&format=' + format
granule_md = requests.get(url)
status_codes = [404, 400, 503, 408]
if granule_md.status_code in status_codes:
granule_md.raise_for_status()
except requests.exceptions.HTTPError as error:
print(error)
raise
return granule_md.text
def load_last24hours_datacasting_granule_md(self, dataset_id='', short_name='', format='datacasting', items_per_page=7):
'''Granule metadata service retrieves metadata for a list \
of granules archived within the last 24 hours in Datacasting \
format.
:param dataset_id: dataset persistent ID. dataset_id or short_name \
is required for this metadata service.
:type dataset_id: :mod:`string`
:param short_name: dataset short_name. dataset_id or short_name \
is required for this metadata service.
:type short_name: :mod:`string`
:param format: metadata format. Must set to 'datacasting'.
:type format: :mod:`string`
:param items_per_page: number of results per page. Default value is 7. \
The value range is from 0 to 5000.
:type items_per_page: :mod:`int`
:returns: an xml response based on the requested 'format'. Options \
are 'iso' and 'gcmd'.
'''
try:
url = self.URL + 'metadata/granule/?'
if(dataset_id):
url = url + 'datasetId=' + dataset_id
else:
raise Exception("Dataset Id is required")
if(short_name):
url = url + '&shortName=' + short_name
url = url + '&itemsPerPage=' + \
str(items_per_page) + '&format=' + format
granule_md = requests.get(url)
status_codes = [404, 400, 503, 408]
if granule_md.status_code in status_codes:
granule_md.raise_for_status()
except requests.exceptions.HTTPError as error:
print(error)
raise
return granule_md.text
def granule_search(self, dataset_id='', start_time='', end_time='', bbox='', start_index='', sort_by='timeAsc',
items_per_page='7', format='atom', pretty='True'):
'''Search Granule does granule searching on PO.DAAC level 2 swath \
datasets (individual orbits of a satellite), and level 3 & 4 \
gridded datasets (time averaged to span the globe). Coverage \
footpritnt polygons are used to enable spatial search on level 2 \
swath dataset. Currently, our footprints can contain no data and \
also gaps in the swath data. Spatial search on level 2 data can \
return granules where actual data does not intersect the selected \
bounding box but its footprint intersects the selected bounding \
box. The following parameters are supported: dataset_id, \
short_name, start_time, end_time, bbox, and others.
:param dataset_id: dataset persistent ID. dataset_id or short_name \
is required for a granule search. Example: PODAAC-ASOP2-25X01
:type dataset_id: :mod:`string`
:param start_time: start time in the format of YYYY-MM-DDTHH:mm:ssZ. \
'Z' is the time-offset, where 'Z' signifies UTC or an actual offset \
can be used. Example: 2013-01-01T01:30:00Z
:type start_time: :mod:`time`
:param end_time: stop time in the format of YYYY-MM-DDTHH:mm:ssZ. \
'Z' is the time-offset, where 'Z' signifies UTC or an actual \
offset can be used. Example: 2014-01-01T00:00:00Z
:type end_time: :mod:`time`
:param bbox: bounding box for spatial search. format should look \
like "bbox=0,0,180,90" which is in order of west, south, east, \
north. Longitude values needs to be in range of [-180, 180]. \
Latitude values needs to be in range of [-90, 90]. For level \
2 datasets, spatial search is available for a subset. Call the \
list_available_Level2_dataset_ids and \
list_available_level2_datasetShortNames functions to see the \
subset. BBox example: 0,0,180,90
:type bbox: :mod:`string`
:param start_index: start index of entries found for search. \
Example: 1
:type start_index: :mod:`int`
:param items_per_page: number of results per page for opensearch \
result. If format is not specified, format is set to 7. The \
value range is from 0 to 400
:type items_per_page: :mod:`int`
:param sort_by: determines ordering of response. Possible \
values: timeAsc, timeDesc.
:type sort_by: :mod:`string`
:param format: response format. If format is not specified, \
format is set to atom. Possible values: atom, html.
:type format: :mod:`string`
:param pretty: "true" to enable pretty output for xml. \
If pretty is not specified, pretty is set to true. Possible \
values: true, false.
:type pretty: :mod:`boolean`
:returns: an xml response based on the requested 'format'. Options \
are 'atom' and 'html'.
'''
try:
url = self.URL + 'search/granule/?'
if(dataset_id):
url = url + 'datasetId=' + dataset_id
else:
raise Exception("Dataset Id is required")
if(start_time):
url = url + '&startTime=' + start_time
if(end_time):
url = url + '&endTime=' + end_time
if(bbox):
url = url + '&bbox=' + bbox
if(start_index):
url = url + '&startIndex=' + start_index
url = url + '&sortBy=' + sort_by + \
'&itemsPerPage=' + items_per_page + '&format=' + format + '&pretty=' + pretty
granules = requests.get(url)
status_codes = [404, 400, 503, 408]
if granules.status_code in status_codes:
granules.raise_for_status()
except requests.exceptions.HTTPError as error:
print(error)
raise
return granules.text
def granule_preview(self, dataset_id='', image_variable='', path=''):
'''The PODAAC Image service renders granules in the \
PO.DAACs catalog to images such as jpeg and/or png. \
This image service also utilizes OGC WMS protocol. \
(http://www.opengeospatial.org/standards/wms). If the \
granule does not have any data in the given selected \
bounding box, HTTP 500 will be thrown since there is \
no data to be imaged. Granule Search service can be used \
to find level 2 swath data. However, the level 2 \
spatial search uses coverage footprint polygons \
generated for each granule, and this footprint can \
contain no data or gaps. If the selected bounding box \
resides on no data or gaps, HTTP 500 will be thrown. \
There are three request methods in this service. They \
are GetCapabilities, GetLegendGraphic, and GetMap.
:param dataset_id: dataset persistent ID. dataset_id or \
short_name is required for a granule search. Example: \
PODAAC-ASOP2-25X01 :mod:`string`
:type dataset_id: :mod:`string`
:param image_variable: variables of the granule which have \
'Preview Images'. Image variables can be found \
from Dataset Variable service. Use "id" from "imgVariable" \
element.\
:type image_variable: :mod:`string`
:param path: Destination directory into which the granule \
needs to be downloaded.
:type format: :mod:`string`
:returns: a png image file.
'''
try:
bbox = '-180,-90,180,90'
if(dataset_id == ''):
raise Exception("Required dataset_id")
image_data = self.granule_search(dataset_id=dataset_id, bbox=bbox)
root = ET.fromstring(image_data.encode('utf-8'))
# fetching the [URL Template]
url_template = ''
for entry in root.iter('{http://www.w3.org/2005/Atom}entry'):
for element in entry:
if element.tag == '{http://www.w3.org/2005/Atom}link':
if element.attrib['title'] == "Preview Image":
url_template = element.attrib['href']
break
if url_template == '':
raise Exception(
"Preview Image not available for this dataset.")
url = url_template + '/' + image_variable + '.png'
if path == '':
path = os.path.join(os.path.dirname(
__file__), dataset_id + '.png')
else:
path = path + '/' + dataset_id + '.png'
image = open(path, 'wb')
image.write(urlopen(url).read())
except Exception:
raise
return image
def granule_subset(self, input_file_path, path=''):
'''Subset Granule service allows users to Submit subset jobs. \
Use of this service should be preceded by a Granule Search in \
order to identify and generate a list of granules to be subsetted.
:param input_file_path: path to a json file which contains the \
the request that you want to send to PO.DAAC
:type input_file_path: :mod:`string`
:param path: path to a directory where you want the subsetted \
dataset to be stored.
:type path: :mod:`string`
:returns: a zip file downloaded and extracted in the destination\
directory path provided.
'''
data = open(input_file_path, 'r+')
input_data = json.load(data)
input_string = json.dumps(input_data)
# submit subset request
params = urlencode({'query': input_string})
headers = {
"Content-type": "application/x-www-form-urlencoded", "Accept": "*"}
conn = HTTPSConnection("podaac.jpl.nasa.gov")
conn.request("POST", "/ws/subset/granule?request=submit",
params, headers)
response = conn.getresponse()
data = response.read().decode('utf-8')
result = json.loads(data)
token = result['token']
conn.close()
flag = 0
while(flag == 0):
url = url = self.URL + "subset/status?token=" + token
subset_response = requests.get(url).text
subset_response_json = json.loads(subset_response)
status = subset_response_json['status']
if (status == "done"):
flag = 1
if (status == "error"):
raise Exception(
"Unexpected error occured for the subset job you have requested")
time.sleep(1)
print("Done! downloading the dataset zip .....")
download_url = subset_response_json['resultURLs'][0]
split = download_url.split('/')
length = len(split)
zip_file_name = split[length - 1]
if path == '':
path = os.path.join(os.path.dirname(__file__), zip_file_name)
else:
path = path + zip_file_name
response = urlretrieve(download_url, path)
zip_content = zipfile.ZipFile(path)
zip_content.extractall()
os.remove(path)
def subset_status(self, token=''):
'''Subset Granule Status service allows users to check the status \
of submitted subset job.
The possible status that it returns include the following.. ::
* "submitted" : returned on successful submission of the request.
* "error" : returned when there is error in the JSON POST request.
* "unknown" : returned when the datasetId you sent is not valid.
* "done" : returned when subsetting job you submitted is done.
:param token: string token that is returned by PO.DAAC whilst \
submitting a subset request.
:type token: :mod:`string`
:returns: the status of the subset request.
'''
url = self.URL + "subset/status?token=" + token
subset_data = requests.get(url).text
subset_data_json = json.loads(subset_data)
status = subset_data_json['status']
return status
def extract_l4_granule(self, dataset_id='', path=''):
'''This is an additional function that we have provided apart \
from the availalble webservices. The extract_l4_granule helps \
retrieve the level 4 datasets from openDap server directly, \
accompanied by the search granule for retrieving granule name \
related to the specific dataset_id and short_name
:param dataset_id: dataset persistent ID. dataset_id or \
short_name is required for a granule search. Example: \
PODAAC-ASOP2-25X01
:type dataset_id: :mod:`string`
:param short_name: the shorter name for a dataset. \
Either short_name or dataset_id is required for a \
granule search. Example: ASCATA-L2-25km
:type short_name: :mod:`string`
:param path: Destination directory into which the granule \
needs to be downloaded.
:type format: :mod:`string`
'''
try:
start_index = '1'
search_data = self.granule_search(
dataset_id=dataset_id, start_index=start_index)
root = ET.fromstring(search_data.encode('utf-8'))
url = root[12][7].attrib['href']
granule_name = root[12][0].text
granule_name = granule_name.rsplit(".", 1)[0]
if path == '':
path = os.path.join(os.path.dirname(__file__), granule_name)
else:
path = path + '/' + granule_name
urlretrieve(url, path)
except Exception:
raise
return granule_name