-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
nsidc-download-ATL11.py
368 lines (317 loc) · 11.4 KB
/
nsidc-download-ATL11.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
#!/usr/bin/env python
# ----------------------------------------------------------------------------
# NSIDC Data Download Script
#
# Copyright (c) 2021 Regents of the University of Colorado
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# Tested in Python 2.7 and Python 3.4, 3.6, 3.7
#
# To run the script at a Linux, macOS, or Cygwin command-line terminal:
# $ python nsidc-download-ATL11.py
#
# On Windows, open Start menu -> Run and type cmd. Then type:
# python nsidc-download-ATL11.py
#
# The script will first search Earthdata for all matching files.
# You will then be prompted for your Earthdata username/password
# and the script will download the matching files.
#
# If you wish, you may store your Earthdata username/password in a .netrc
# file in your $HOME directory and the script will automatically attempt to
# read this file. The .netrc file should have the following format:
# machine urs.earthdata.nasa.gov login myusername password mypassword
# where 'myusername' and 'mypassword' are your Earthdata credentials.
#
from __future__ import print_function
import base64
import itertools
import json
import netrc
import ssl
import sys
from getpass import getpass
try:
from urllib.parse import urlparse
from urllib.request import urlopen, Request, build_opener, HTTPCookieProcessor
from urllib.error import HTTPError, URLError
except ImportError:
from urlparse import urlparse
from urllib2 import (
urlopen,
Request,
HTTPError,
URLError,
build_opener,
HTTPCookieProcessor,
)
short_name = "ATL11"
version = "003"
time_start = "2019-03-29T00:00:00Z"
time_end = "2021-04-21T20:50:43Z"
bounding_box = ""
polygon = ""
filename_filter = "*1?_0?0?_003_0?.h5"
url_list = []
CMR_URL = "https://cmr.earthdata.nasa.gov"
URS_URL = "https://urs.earthdata.nasa.gov"
CMR_PAGE_SIZE = 2000
CMR_FILE_URL = (
"{0}/search/granules.json?provider=NSIDC_ECS"
"&sort_key[]=start_date&sort_key[]=producer_granule_id"
"&scroll=true&page_size={1}".format(CMR_URL, CMR_PAGE_SIZE)
)
def get_username():
username = ""
# For Python 2/3 compatibility:
try:
do_input = raw_input # noqa
except NameError:
do_input = input
while not username:
try:
username = do_input("Earthdata username: ")
except KeyboardInterrupt:
quit()
return username
def get_password():
password = ""
while not password:
try:
password = getpass("password: ")
except KeyboardInterrupt:
quit()
return password
def get_credentials(url):
"""Get user credentials from .netrc or prompt for input."""
credentials = None
errprefix = ""
try:
info = netrc.netrc()
username, account, password = info.authenticators(urlparse(URS_URL).hostname)
errprefix = "netrc error: "
except Exception as e:
if not ("No such file" in str(e)):
print("netrc error: {0}".format(str(e)))
username = None
password = None
while not credentials:
if not username:
username = get_username()
password = get_password()
credentials = "{0}:{1}".format(username, password)
credentials = base64.b64encode(credentials.encode("ascii")).decode("ascii")
if url:
try:
req = Request(url)
req.add_header("Authorization", "Basic {0}".format(credentials))
opener = build_opener(HTTPCookieProcessor())
opener.open(req)
except HTTPError:
print(errprefix + "Incorrect username or password")
errprefix = ""
credentials = None
username = None
password = None
return credentials
def build_version_query_params(version):
desired_pad_length = 3
if len(version) > desired_pad_length:
print('Version string too long: "{0}"'.format(version))
quit()
version = str(int(version)) # Strip off any leading zeros
query_params = ""
while len(version) <= desired_pad_length:
padded_version = version.zfill(desired_pad_length)
query_params += "&version={0}".format(padded_version)
desired_pad_length -= 1
return query_params
def filter_add_wildcards(filter):
if not filter.startswith("*"):
filter = "*" + filter
if not filter.endswith("*"):
filter = filter + "*"
return filter
def build_filename_filter(filename_filter):
filters = filename_filter.split(",")
result = "&options[producer_granule_id][pattern]=true"
for filter in filters:
result += "&producer_granule_id[]=" + filter_add_wildcards(filter)
return result
def build_cmr_query_url(
short_name,
version,
time_start,
time_end,
bounding_box=None,
polygon=None,
filename_filter=None,
):
params = "&short_name={0}".format(short_name)
params += build_version_query_params(version)
params += "&temporal[]={0},{1}".format(time_start, time_end)
if polygon:
params += "&polygon={0}".format(polygon)
elif bounding_box:
params += "&bounding_box={0}".format(bounding_box)
if filename_filter:
params += build_filename_filter(filename_filter)
return CMR_FILE_URL + params
def cmr_download(urls):
"""Download files from list of urls."""
if not urls:
return
url_count = len(urls)
print("Downloading {0} files...".format(url_count))
credentials = None
for index, url in enumerate(urls, start=1):
if not credentials and urlparse(url).scheme == "https":
credentials = get_credentials(url)
filename = url.split("/")[-1]
print(
"{0}/{1}: {2}".format(
str(index).zfill(len(str(url_count))), url_count, filename
)
)
try:
# In Python 3 we could eliminate the opener and just do 2 lines:
# resp = requests.get(url, auth=(username, password))
# open(filename, 'wb').write(resp.content)
req = Request(url)
if credentials:
req.add_header("Authorization", "Basic {0}".format(credentials))
opener = build_opener(HTTPCookieProcessor())
data = opener.open(req).read()
open(filename, "wb").write(data)
except HTTPError as e:
print("HTTP error {0}, {1}".format(e.code, e.reason))
except URLError as e:
print("URL error: {0}".format(e.reason))
except IOError:
raise
except KeyboardInterrupt:
quit()
def cmr_filter_urls(search_results):
"""Select only the desired data files from CMR response."""
if "feed" not in search_results or "entry" not in search_results["feed"]:
return []
entries = [e["links"] for e in search_results["feed"]["entry"] if "links" in e]
# Flatten "entries" to a simple list of links
links = list(itertools.chain(*entries))
urls = []
unique_filenames = set()
for link in links:
if "href" not in link:
# Exclude links with nothing to download
continue
if "inherited" in link and link["inherited"] is True:
# Why are we excluding these links?
continue
if "rel" in link and "data#" not in link["rel"]:
# Exclude links which are not classified by CMR as "data" or "metadata"
continue
if "title" in link and "opendap" in link["title"].lower():
# Exclude OPeNDAP links--they are responsible for many duplicates
# This is a hack; when the metadata is updated to properly identify
# non-datapool links, we should be able to do this in a non-hack way
continue
filename = link["href"].split("/")[-1]
if filename in unique_filenames:
# Exclude links with duplicate filenames (they would overwrite)
continue
unique_filenames.add(filename)
urls.append(link["href"])
return urls
def cmr_search(
short_name,
version,
time_start,
time_end,
bounding_box="",
polygon="",
filename_filter="",
):
"""Perform a scrolling CMR query for files matching input criteria."""
cmr_query_url = build_cmr_query_url(
short_name=short_name,
version=version,
time_start=time_start,
time_end=time_end,
bounding_box=bounding_box,
polygon=polygon,
filename_filter=filename_filter,
)
print("Querying for data:\n\t{0}\n".format(cmr_query_url))
cmr_scroll_id = None
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
try:
urls = []
while True:
req = Request(cmr_query_url)
if cmr_scroll_id:
req.add_header("cmr-scroll-id", cmr_scroll_id)
response = urlopen(req, context=ctx)
if not cmr_scroll_id:
# Python 2 and 3 have different case for the http headers
headers = {k.lower(): v for k, v in dict(response.info()).items()}
cmr_scroll_id = headers["cmr-scroll-id"]
hits = int(headers["cmr-hits"])
if hits > 0:
print("Found {0} matches.".format(hits))
else:
print("Found no matches.")
search_page = response.read()
search_page = json.loads(search_page.decode("utf-8"))
url_scroll_results = cmr_filter_urls(search_page)
if not url_scroll_results:
break
if hits > CMR_PAGE_SIZE:
print(".", end="")
sys.stdout.flush()
urls += url_scroll_results
if hits > CMR_PAGE_SIZE:
print()
return urls
except KeyboardInterrupt:
quit()
def main():
global short_name, version, time_start, time_end, bounding_box, polygon, filename_filter, url_list
# Supply some default search parameters, just for testing purposes.
# These are only used if the parameters aren't filled in up above.
if "short_name" in short_name:
short_name = "MOD10A2"
version = "6"
time_start = "2001-01-01T00:00:00Z"
time_end = "2019-03-07T22:09:38Z"
bounding_box = ""
polygon = "-109,37,-102,37,-102,41,-109,41,-109,37"
filename_filter = "A2019"
url_list = []
if not url_list:
url_list = cmr_search(
short_name,
version,
time_start,
time_end,
bounding_box=bounding_box,
polygon=polygon,
filename_filter=filename_filter,
)
# cmr_download(url_list)
return url_list
if __name__ == "__main__":
url_list = main()
url_list = [
f'{url.replace("DP9/", "")}\n' for url in url_list if not url.endswith("xml")
]
with open(file="ATL11_to_download.txt", mode="w") as f:
f.writelines(url_list)