Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

nsidc-download-ATL11.py 11 KB

You have to be logged in to leave a comment. Sign In
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
  1. #!/usr/bin/env python
  2. # ----------------------------------------------------------------------------
  3. # NSIDC Data Download Script
  4. #
  5. # Copyright (c) 2021 Regents of the University of Colorado
  6. # Permission is hereby granted, free of charge, to any person obtaining
  7. # a copy of this software and associated documentation files (the "Software"),
  8. # to deal in the Software without restriction, including without limitation
  9. # the rights to use, copy, modify, merge, publish, distribute, sublicense,
  10. # and/or sell copies of the Software, and to permit persons to whom the
  11. # Software is furnished to do so, subject to the following conditions:
  12. # The above copyright notice and this permission notice shall be included
  13. # in all copies or substantial portions of the Software.
  14. #
  15. # Tested in Python 2.7 and Python 3.4, 3.6, 3.7
  16. #
  17. # To run the script at a Linux, macOS, or Cygwin command-line terminal:
  18. # $ python nsidc-download-ATL11.py
  19. #
  20. # On Windows, open Start menu -> Run and type cmd. Then type:
  21. # python nsidc-download-ATL11.py
  22. #
  23. # The script will first search Earthdata for all matching files.
  24. # You will then be prompted for your Earthdata username/password
  25. # and the script will download the matching files.
  26. #
  27. # If you wish, you may store your Earthdata username/password in a .netrc
  28. # file in your $HOME directory and the script will automatically attempt to
  29. # read this file. The .netrc file should have the following format:
  30. # machine urs.earthdata.nasa.gov login myusername password mypassword
  31. # where 'myusername' and 'mypassword' are your Earthdata credentials.
  32. #
  33. from __future__ import print_function
  34. import base64
  35. import itertools
  36. import json
  37. import netrc
  38. import ssl
  39. import sys
  40. from getpass import getpass
  41. try:
  42. from urllib.parse import urlparse
  43. from urllib.request import urlopen, Request, build_opener, HTTPCookieProcessor
  44. from urllib.error import HTTPError, URLError
  45. except ImportError:
  46. from urlparse import urlparse
  47. from urllib2 import (
  48. urlopen,
  49. Request,
  50. HTTPError,
  51. URLError,
  52. build_opener,
  53. HTTPCookieProcessor,
  54. )
  55. short_name = "ATL11"
  56. version = "003"
  57. time_start = "2019-03-29T00:00:00Z"
  58. time_end = "2021-04-21T20:50:43Z"
  59. bounding_box = ""
  60. polygon = ""
  61. filename_filter = "*1?_0?0?_003_0?.h5"
  62. url_list = []
  63. CMR_URL = "https://cmr.earthdata.nasa.gov"
  64. URS_URL = "https://urs.earthdata.nasa.gov"
  65. CMR_PAGE_SIZE = 2000
  66. CMR_FILE_URL = (
  67. "{0}/search/granules.json?provider=NSIDC_ECS"
  68. "&sort_key[]=start_date&sort_key[]=producer_granule_id"
  69. "&scroll=true&page_size={1}".format(CMR_URL, CMR_PAGE_SIZE)
  70. )
  71. def get_username():
  72. username = ""
  73. # For Python 2/3 compatibility:
  74. try:
  75. do_input = raw_input # noqa
  76. except NameError:
  77. do_input = input
  78. while not username:
  79. try:
  80. username = do_input("Earthdata username: ")
  81. except KeyboardInterrupt:
  82. quit()
  83. return username
  84. def get_password():
  85. password = ""
  86. while not password:
  87. try:
  88. password = getpass("password: ")
  89. except KeyboardInterrupt:
  90. quit()
  91. return password
  92. def get_credentials(url):
  93. """Get user credentials from .netrc or prompt for input."""
  94. credentials = None
  95. errprefix = ""
  96. try:
  97. info = netrc.netrc()
  98. username, account, password = info.authenticators(urlparse(URS_URL).hostname)
  99. errprefix = "netrc error: "
  100. except Exception as e:
  101. if not ("No such file" in str(e)):
  102. print("netrc error: {0}".format(str(e)))
  103. username = None
  104. password = None
  105. while not credentials:
  106. if not username:
  107. username = get_username()
  108. password = get_password()
  109. credentials = "{0}:{1}".format(username, password)
  110. credentials = base64.b64encode(credentials.encode("ascii")).decode("ascii")
  111. if url:
  112. try:
  113. req = Request(url)
  114. req.add_header("Authorization", "Basic {0}".format(credentials))
  115. opener = build_opener(HTTPCookieProcessor())
  116. opener.open(req)
  117. except HTTPError:
  118. print(errprefix + "Incorrect username or password")
  119. errprefix = ""
  120. credentials = None
  121. username = None
  122. password = None
  123. return credentials
  124. def build_version_query_params(version):
  125. desired_pad_length = 3
  126. if len(version) > desired_pad_length:
  127. print('Version string too long: "{0}"'.format(version))
  128. quit()
  129. version = str(int(version)) # Strip off any leading zeros
  130. query_params = ""
  131. while len(version) <= desired_pad_length:
  132. padded_version = version.zfill(desired_pad_length)
  133. query_params += "&version={0}".format(padded_version)
  134. desired_pad_length -= 1
  135. return query_params
  136. def filter_add_wildcards(filter):
  137. if not filter.startswith("*"):
  138. filter = "*" + filter
  139. if not filter.endswith("*"):
  140. filter = filter + "*"
  141. return filter
  142. def build_filename_filter(filename_filter):
  143. filters = filename_filter.split(",")
  144. result = "&options[producer_granule_id][pattern]=true"
  145. for filter in filters:
  146. result += "&producer_granule_id[]=" + filter_add_wildcards(filter)
  147. return result
  148. def build_cmr_query_url(
  149. short_name,
  150. version,
  151. time_start,
  152. time_end,
  153. bounding_box=None,
  154. polygon=None,
  155. filename_filter=None,
  156. ):
  157. params = "&short_name={0}".format(short_name)
  158. params += build_version_query_params(version)
  159. params += "&temporal[]={0},{1}".format(time_start, time_end)
  160. if polygon:
  161. params += "&polygon={0}".format(polygon)
  162. elif bounding_box:
  163. params += "&bounding_box={0}".format(bounding_box)
  164. if filename_filter:
  165. params += build_filename_filter(filename_filter)
  166. return CMR_FILE_URL + params
  167. def cmr_download(urls):
  168. """Download files from list of urls."""
  169. if not urls:
  170. return
  171. url_count = len(urls)
  172. print("Downloading {0} files...".format(url_count))
  173. credentials = None
  174. for index, url in enumerate(urls, start=1):
  175. if not credentials and urlparse(url).scheme == "https":
  176. credentials = get_credentials(url)
  177. filename = url.split("/")[-1]
  178. print(
  179. "{0}/{1}: {2}".format(
  180. str(index).zfill(len(str(url_count))), url_count, filename
  181. )
  182. )
  183. try:
  184. # In Python 3 we could eliminate the opener and just do 2 lines:
  185. # resp = requests.get(url, auth=(username, password))
  186. # open(filename, 'wb').write(resp.content)
  187. req = Request(url)
  188. if credentials:
  189. req.add_header("Authorization", "Basic {0}".format(credentials))
  190. opener = build_opener(HTTPCookieProcessor())
  191. data = opener.open(req).read()
  192. open(filename, "wb").write(data)
  193. except HTTPError as e:
  194. print("HTTP error {0}, {1}".format(e.code, e.reason))
  195. except URLError as e:
  196. print("URL error: {0}".format(e.reason))
  197. except IOError:
  198. raise
  199. except KeyboardInterrupt:
  200. quit()
  201. def cmr_filter_urls(search_results):
  202. """Select only the desired data files from CMR response."""
  203. if "feed" not in search_results or "entry" not in search_results["feed"]:
  204. return []
  205. entries = [e["links"] for e in search_results["feed"]["entry"] if "links" in e]
  206. # Flatten "entries" to a simple list of links
  207. links = list(itertools.chain(*entries))
  208. urls = []
  209. unique_filenames = set()
  210. for link in links:
  211. if "href" not in link:
  212. # Exclude links with nothing to download
  213. continue
  214. if "inherited" in link and link["inherited"] is True:
  215. # Why are we excluding these links?
  216. continue
  217. if "rel" in link and "data#" not in link["rel"]:
  218. # Exclude links which are not classified by CMR as "data" or "metadata"
  219. continue
  220. if "title" in link and "opendap" in link["title"].lower():
  221. # Exclude OPeNDAP links--they are responsible for many duplicates
  222. # This is a hack; when the metadata is updated to properly identify
  223. # non-datapool links, we should be able to do this in a non-hack way
  224. continue
  225. filename = link["href"].split("/")[-1]
  226. if filename in unique_filenames:
  227. # Exclude links with duplicate filenames (they would overwrite)
  228. continue
  229. unique_filenames.add(filename)
  230. urls.append(link["href"])
  231. return urls
  232. def cmr_search(
  233. short_name,
  234. version,
  235. time_start,
  236. time_end,
  237. bounding_box="",
  238. polygon="",
  239. filename_filter="",
  240. ):
  241. """Perform a scrolling CMR query for files matching input criteria."""
  242. cmr_query_url = build_cmr_query_url(
  243. short_name=short_name,
  244. version=version,
  245. time_start=time_start,
  246. time_end=time_end,
  247. bounding_box=bounding_box,
  248. polygon=polygon,
  249. filename_filter=filename_filter,
  250. )
  251. print("Querying for data:\n\t{0}\n".format(cmr_query_url))
  252. cmr_scroll_id = None
  253. ctx = ssl.create_default_context()
  254. ctx.check_hostname = False
  255. ctx.verify_mode = ssl.CERT_NONE
  256. try:
  257. urls = []
  258. while True:
  259. req = Request(cmr_query_url)
  260. if cmr_scroll_id:
  261. req.add_header("cmr-scroll-id", cmr_scroll_id)
  262. response = urlopen(req, context=ctx)
  263. if not cmr_scroll_id:
  264. # Python 2 and 3 have different case for the http headers
  265. headers = {k.lower(): v for k, v in dict(response.info()).items()}
  266. cmr_scroll_id = headers["cmr-scroll-id"]
  267. hits = int(headers["cmr-hits"])
  268. if hits > 0:
  269. print("Found {0} matches.".format(hits))
  270. else:
  271. print("Found no matches.")
  272. search_page = response.read()
  273. search_page = json.loads(search_page.decode("utf-8"))
  274. url_scroll_results = cmr_filter_urls(search_page)
  275. if not url_scroll_results:
  276. break
  277. if hits > CMR_PAGE_SIZE:
  278. print(".", end="")
  279. sys.stdout.flush()
  280. urls += url_scroll_results
  281. if hits > CMR_PAGE_SIZE:
  282. print()
  283. return urls
  284. except KeyboardInterrupt:
  285. quit()
  286. def main():
  287. global short_name, version, time_start, time_end, bounding_box, polygon, filename_filter, url_list
  288. # Supply some default search parameters, just for testing purposes.
  289. # These are only used if the parameters aren't filled in up above.
  290. if "short_name" in short_name:
  291. short_name = "MOD10A2"
  292. version = "6"
  293. time_start = "2001-01-01T00:00:00Z"
  294. time_end = "2019-03-07T22:09:38Z"
  295. bounding_box = ""
  296. polygon = "-109,37,-102,37,-102,41,-109,41,-109,37"
  297. filename_filter = "A2019"
  298. url_list = []
  299. if not url_list:
  300. url_list = cmr_search(
  301. short_name,
  302. version,
  303. time_start,
  304. time_end,
  305. bounding_box=bounding_box,
  306. polygon=polygon,
  307. filename_filter=filename_filter,
  308. )
  309. # cmr_download(url_list)
  310. return url_list
  311. if __name__ == "__main__":
  312. url_list = main()
  313. url_list = [
  314. f'{url.replace("DP9/", "")}\n' for url in url_list if not url.endswith("xml")
  315. ]
  316. with open(file="ATL11_to_download.txt", mode="w") as f:
  317. f.writelines(url_list)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...