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

atl06_play.py 16 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
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
  1. # ---
  2. # jupyter:
  3. # jupytext:
  4. # formats: ipynb,py:hydrogen
  5. # text_representation:
  6. # extension: .py
  7. # format_name: hydrogen
  8. # format_version: '1.3'
  9. # jupytext_version: 1.11.4
  10. # kernelspec:
  11. # display_name: deepicedrain
  12. # language: python
  13. # name: deepicedrain
  14. # ---
  15. # %% [markdown]
  16. # # **ATLAS/ICESat-2 Land Ice Height [ATL06](https://nsidc.org/data/atl06/) Exploratory Data Analysis**
  17. #
  18. # [Yet another](https://xkcd.com/927) take on playing with ICESat-2's Land Ice Height ATL06 data,
  19. # specfically with a focus on analyzing ice elevation changes over Antarctica.
  20. # Specifically, this jupyter notebook will cover:
  21. #
  22. # - Downloading datasets from the web via [intake](https://intake.readthedocs.io)
  23. # - Performing [Exploratory Data Analysis](https://en.wikipedia.org/wiki/Exploratory_data_analysis)
  24. # using the [PyData](https://pydata.org) stack (e.g. [xarray](http://xarray.pydata.org), [dask](https://dask.org))
  25. # - Plotting figures using [Hvplot](https://hvplot.holoviz.org) and [PyGMT](https://www.pygmt.org)
  26. #
  27. # This is in contrast with the [icepyx](https://github.com/icesat2py/icepyx) package
  28. # and 'official' 2019/2020 [ICESat-2 Hackweek tutorials](https://github.com/ICESAT-2HackWeek/ICESat2_hackweek_tutorials) (which are also awesome!)
  29. # that tends to use a slightly different approach (e.g. handcoded download scripts, [h5py](http://www.h5py.org) for data reading, etc).
  30. # The core concept here is to run things in a more intuitive and scalable (parallelizable) manner on a continent scale (rather than just a specific region).
  31. # %%
  32. import glob
  33. import json
  34. import logging
  35. import netrc
  36. import os
  37. import cartopy
  38. import dask
  39. import dask.distributed
  40. import dvc.repo
  41. import hvplot.dask
  42. import hvplot.pandas
  43. import hvplot.xarray
  44. import icepyx as ipx
  45. import intake
  46. import matplotlib.pyplot as plt
  47. import numpy as np
  48. import pandas as pd
  49. import pyproj
  50. import requests
  51. import tqdm
  52. import xarray as xr
  53. import deepicedrain
  54. # %%
  55. # Limit compute to 8 cores for download part
  56. client = dask.distributed.Client(n_workers=8, threads_per_worker=1)
  57. client
  58. # %% [markdown]
  59. # ## Quick view
  60. #
  61. # Use our [intake catalog](https://intake.readthedocs.io/en/latest/catalog.html) to get some sample ATL06 data
  62. # (while making sure we have our Earthdata credentials set up properly),
  63. # and view it using [xarray](https://xarray.pydata.org) and [hvplot](https://hvplot.pyviz.org).
  64. # %%
  65. # Open the local intake data catalog file containing ICESat-2 stuff
  66. catalog = intake.open_catalog("deepicedrain/atlas_catalog.yaml")
  67. # or if the deepicedrain python package is installed, you can use either of the below:
  68. # catalog = deepicedrain.catalog
  69. # catalog = intake.cat.atlas_cat
  70. # %%
  71. try:
  72. netrc.netrc()
  73. except FileNotFoundError as error_msg:
  74. print(
  75. f"{error_msg}, please follow instructions to create one at "
  76. "https://nsidc.org/support/faq/what-options-are-available-bulk-downloading-data-https-earthdata-login-enabled "
  77. 'basically using `echo "machine urs.earthdata.nasa.gov login <uid> password <password>" >> ~/.netrc`'
  78. )
  79. raise
  80. # data download will depend on having a .netrc file in home folder
  81. dataset: xr.Dataset = catalog.icesat2atl06.to_dask().unify_chunks()
  82. print(dataset)
  83. # %%
  84. # dataset.hvplot.points(
  85. # x="longitude",
  86. # y="latitude",
  87. # c="h_li",
  88. # cmap="Blues",
  89. # rasterize=True,
  90. # hover=True,
  91. # width=800,
  92. # height=500,
  93. # geo=True,
  94. # coastline=True,
  95. # crs=cartopy.crs.PlateCarree(),
  96. # projection=cartopy.crs.Stereographic(central_latitude=-71),
  97. # )
  98. catalog.icesat2atl06.hvplot.quickview()
  99. # %% [markdown]
  100. # ## Download ATL06 data using intake
  101. #
  102. # Pulling in all of the raw ATL06 data (HDF5 format) from the NSIDC servers via an intake catalog file.
  103. # Note that this will involve 100s if not 1000s of GBs of data, so make sure there's enough storage!!
  104. # %%
  105. # Download all ICESAT2 ATLAS hdf files from start to end date
  106. # dates0 = pd.date_range(start="2018.10.14", end="2018.12.08") # 0th batch
  107. # dates1 = pd.date_range(start="2018.12.10", end="2019.06.26") # 1st batch
  108. # Skip ICESat-2 cycles 1 to 2 from 2018.10.14 to 2019.03.28 above
  109. dates1 = pd.date_range(start="2019.03.29", end="2019.06.26") # 1st batch
  110. dates2 = pd.date_range(start="2019.07.26", end="2021.07.15") # 3rd batch
  111. dates = dates1.append(other=dates2)
  112. # dates = pd.date_range(start="2020.11.11", end="2021.07.15") # custom batch
  113. # %%
  114. # Submit download jobs to Client
  115. futures = []
  116. for date in dates:
  117. # revision = 2 if date in pd.date_range(start="2020.04.22", end="2020.05.04") else 1
  118. source = catalog.icesat2atlasdownloader(date=date, revision=1)
  119. future = client.submit(
  120. func=source.discover, key=f"download-{date}"
  121. ) # triggers download of the file(s), or loads from cache
  122. futures.append(future)
  123. # %% [markdown]
  124. # ## Download ATL06 data using icepyx and dvc's get-url function
  125. #
  126. # Alternative way to obtain raw ATL06 data (HDF5 format) from NSIDC servers
  127. # %%
  128. @dask.delayed
  129. def get_ATL06_links(referencegroundtrack: str = "0001") -> pd.Series:
  130. """Use icepyx to get ATL06 download URL links."""
  131. antarctic_region = ipx.Query(
  132. dataset="ATL06",
  133. date_range=["2019-03-29", "2021-07-15"],
  134. spatial_extent=[180, -89, -180, -60],
  135. version="4",
  136. tracks=[referencegroundtrack],
  137. )
  138. antarctic_region.avail_granules()
  139. df: pd.DataFrame = pd.json_normalize(
  140. antarctic_region.granules.avail, record_path="links"
  141. )
  142. links: pd.Series = df.query("type == 'application/x-hdfeos'").href
  143. os.makedirs(name=f"ATL06.00X/{referencegroundtrack}", exist_ok=True)
  144. links.to_csv(
  145. f"ATL06.00X/{referencegroundtrack}/ATL06_file_list.txt",
  146. index=False,
  147. header=None,
  148. )
  149. return links
  150. # %%
  151. # Submit download jobs to Client
  152. links: list = []
  153. for rgt in range(1, 1388):
  154. referencegroundtrack: str = str(rgt).zfill(4)
  155. _links = get_ATL06_links(referencegroundtrack=referencegroundtrack)
  156. links.append(_links)
  157. # %%
  158. _ = client.compute(links)
  159. # %%
  160. futures = []
  161. repo = dvc.repo.Repo(root_dir=".")
  162. for rgt in range(1, 1388):
  163. referencegroundtrack: str = str(rgt).zfill(4)
  164. with open(f"ATL06.00X/{referencegroundtrack}/ATL06_file_list.txt") as f:
  165. links = f.readlines()
  166. for url in links:
  167. filename = os.path.basename(url.strip())
  168. if not os.path.exists(f"ATL06.00X/{referencegroundtrack}/{filename}"):
  169. future = client.submit(
  170. func=repo.get_url,
  171. url=url.strip(),
  172. out=f"ATL06.00X/{referencegroundtrack}",
  173. jobs=1,
  174. key=f"download-{referencegroundtrack}-{filename}",
  175. )
  176. futures.append(future)
  177. # %%
  178. # Check download progress here, https://stackoverflow.com/a/37901797/6611055
  179. responses = []
  180. for f in tqdm.tqdm(
  181. iterable=dask.distributed.as_completed(futures=futures), total=len(futures)
  182. ):
  183. responses.append(f.result())
  184. # %%
  185. # In case of error, check which downloads are unfinished
  186. # Manually delete those folders and retry
  187. unfinished = []
  188. for foo in futures:
  189. if foo.status != "finished":
  190. print(foo)
  191. unfinished.append(foo)
  192. if foo.status == "error":
  193. foo.retry()
  194. # pass
  195. # %%
  196. try:
  197. assert len(unfinished) == 0
  198. except AssertionError:
  199. for task in unfinished:
  200. print(task)
  201. raise ValueError(
  202. f"{len(unfinished)} download tasks are unfinished,"
  203. " please delete those folders and retry again!"
  204. )
  205. # %%
  206. # %% [markdown]
  207. # ## Exploratory data analysis on local files
  208. #
  209. # Now that we've downloaded a good chunk of data and cached them locally,
  210. # we can have some fun with visualizing the point clouds!
  211. # %%
  212. root_directory = os.path.dirname(
  213. catalog.icesat2atl06.storage_options["simplecache"]["cache_storage"]
  214. )
  215. # %%
  216. def get_crossing_dates(
  217. catalog_entry: intake.catalog.local.LocalCatalogEntry,
  218. root_directory: str,
  219. referencegroundtrack: str = "????",
  220. datetimestr: str = "*",
  221. cyclenumber: str = "??",
  222. orbitalsegment: str = "??",
  223. version: str = "003",
  224. revision: str = "01",
  225. ) -> dict:
  226. """
  227. Given a 4-digit reference groundtrack (e.g. 1234),
  228. we output a dictionary where the
  229. key is the date in "YYYY.MM.DD" format when an ICESAT2 crossing was made and the
  230. value is the filepath to the HDF5 data file.
  231. """
  232. # Get a glob string that looks like "ATL06_??????????????_XXXX????_002_01.h5"
  233. globpath: str = catalog_entry.path_as_pattern
  234. if datetimestr == "*":
  235. globpath: str = globpath.replace("{datetime:%Y%m%d%H%M%S}", "??????????????")
  236. globpath: str = globpath.format(
  237. referencegroundtrack=referencegroundtrack,
  238. cyclenumber=cyclenumber,
  239. orbitalsegment=orbitalsegment,
  240. version=version,
  241. revision=revision,
  242. )
  243. # Get list of filepaths (dates are contained in the filepath)
  244. globedpaths: list = glob.glob(os.path.join(root_directory, "??????????", globpath))
  245. # Pick out just the dates in "YYYY.MM.DD" format from the globedpaths
  246. # crossingdates = [os.path.basename(os.path.dirname(p=p)) for p in globedpaths]
  247. crossingdates: dict = {
  248. os.path.basename(os.path.dirname(p=p)): p for p in sorted(globedpaths)
  249. }
  250. return crossingdates
  251. # %%
  252. crossing_dates_dict = {}
  253. for rgt in range(1, 1388): # ReferenceGroundTrack goes from 0001 to 1387
  254. referencegroundtrack: str = f"{rgt}".zfill(4)
  255. crossing_dates: dict = dask.delayed(get_crossing_dates)(
  256. catalog_entry=catalog.icesat2atl06,
  257. root_directory=root_directory,
  258. referencegroundtrack=referencegroundtrack,
  259. )
  260. crossing_dates_dict[referencegroundtrack] = crossing_dates
  261. crossing_dates_dict = dask.compute(crossing_dates_dict)[0]
  262. # %%
  263. crossing_dates_dict["0349"].keys()
  264. # %% [markdown]
  265. # ![ICESat-2 Laser Beam Pattern](https://ars.els-cdn.com/content/image/1-s2.0-S0034425719303712-gr1.jpg)
  266. # %%
  267. def six_laser_beams(filepaths: list) -> dask.dataframe.DataFrame:
  268. """
  269. For all 6 lasers along one reference ground track,
  270. concatenate all points from all crossing dates into one Dask DataFrame
  271. E.g. if there are 5 crossing dates and 6 lasers,
  272. there would be data from 5 x 6 = 30 files being concatenated together.
  273. """
  274. lasers: list = ["gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r"]
  275. objs: list = [
  276. xr.open_mfdataset(
  277. paths=filepaths,
  278. combine="by_coords",
  279. engine="h5netcdf",
  280. group=f"{laser}/land_ice_segments",
  281. parallel=True,
  282. ).assign_coords(coords={"laser": laser})
  283. for laser in lasers
  284. ]
  285. try:
  286. da: xr.Dataset = xr.concat(objs=objs, dim="laser")
  287. df: dask.dataframe.DataFrame = da.unify_chunks().to_dask_dataframe()
  288. except ValueError:
  289. # ValueError: cannot reindex or align along dimension 'delta_time'
  290. # because the index has duplicate values
  291. df: dask.dataframe.DataFrame = dask.dataframe.concat(
  292. [obj.unify_chunks().to_dask_dataframe() for obj in objs]
  293. )
  294. return df
  295. # %%
  296. dataset_dict = {}
  297. # ReferenceGroundTrack goes from 0001 to 1387
  298. for referencegroundtrack in list(crossing_dates_dict)[348:349]:
  299. # print(referencegroundtrack)
  300. filepaths = list(crossing_dates_dict[referencegroundtrack].values())
  301. if len(filepaths) > 0:
  302. dataset_dict[referencegroundtrack] = dask.delayed(obj=six_laser_beams)(
  303. filepaths=filepaths
  304. )
  305. # df = six_laser_beams(filepaths=filepaths)
  306. # %%
  307. df = dataset_dict["0349"].compute() # loads into a dask dataframe (lazy)
  308. # %%
  309. df
  310. # %%
  311. # %%
  312. # compute every referencegroundtrack, slow... though somewhat parallelized
  313. # dataset_dict = dask.compute(dataset_dict)[0]
  314. # %%
  315. # big dataframe containing data across all 1387 reference ground tracks!
  316. # bdf = dask.dataframe.concat(dfs=list(dataset_dict.values()))
  317. # %%
  318. # %% [raw]
  319. # # https://xarray.pydata.org/en/stable/combining.html#concatenate
  320. # # For all 6 lasers one one date ~~along one reference ground track~~,
  321. # # concatenate all points ~~from one dates~~ into one xr.Dataset
  322. # lasers = ["gt1l", "gt1r", "gt2l", "gt2r", "gt3l", "gt3r"]
  323. # da = xr.concat(
  324. # objs=(
  325. # catalog.icesat2atl06(laser=laser, referencegroundtrack=referencegroundtrack)
  326. # .to_dask()
  327. # for laser in lasers
  328. # ),
  329. # dim=pd.Index(data=lasers, name="laser")
  330. # )
  331. # %%
  332. # %% [markdown]
  333. # ## Plot ATL06 points!
  334. # %%
  335. # Convert dask.DataFrame to pd.DataFrame
  336. df: pd.DataFrame = df.compute()
  337. # %%
  338. # Drop points with poor quality
  339. df = df.dropna(subset=["h_li"]).query(expr="atl06_quality_summary == 0").reset_index()
  340. # %%
  341. # Get a small random sample of our data
  342. dfs = df.sample(n=1_000, random_state=42)
  343. dfs.head()
  344. # %%
  345. dfs.hvplot.scatter(
  346. x="longitude",
  347. y="latitude",
  348. by="laser",
  349. hover_cols=["delta_time", "segment_id"],
  350. # datashade=True, dynspread=True,
  351. # width=800, height=500, colorbar=True
  352. )
  353. # %% [markdown]
  354. # ### Transform from EPSG:4326 (lat/lon) to EPSG:3031 (Antarctic Polar Stereographic)
  355. # %%
  356. dfs["x"], dfs["y"] = deepicedrain.lonlat_to_xy(
  357. longitude=dfs.longitude, latitude=dfs.latitude
  358. )
  359. # %%
  360. dfs.head()
  361. # %%
  362. dfs.hvplot.scatter(
  363. x="x",
  364. y="y",
  365. by="laser",
  366. hover_cols=["delta_time", "segment_id", "h_li"],
  367. # datashade=True, dynspread=True,
  368. # width=800, height=500, colorbar=True
  369. )
  370. # %%
  371. # Plot cross section view
  372. dfs.hvplot.scatter(x="x", y="h_li", by="laser")
  373. # %%
  374. # %% [markdown]
  375. # ## Experimental Work-in-Progress stuff below
  376. # %% [markdown]
  377. # ### Play using XrViz
  378. # %%
  379. import xrviz
  380. # %%
  381. xrviz.example()
  382. # %%
  383. # https://xrviz.readthedocs.io/en/latest/set_initial_parameters.html
  384. initial_params = {
  385. # Select variable to plot
  386. "Variables": "h_li",
  387. # Set coordinates
  388. "Set Coords": ["longitude", "latitude"],
  389. # Axes
  390. "x": "longitude",
  391. "y": "latitude",
  392. # "sigma": "animate",
  393. # Projection
  394. # "is_geo": True,
  395. # "basemap": True,
  396. # "crs": "PlateCarree"
  397. }
  398. dashboard = xrviz.dashboard.Dashboard(data=dataset) # , initial_params=initial_params)
  399. # %%
  400. dashboard.panel
  401. # %%
  402. dashboard.show()
  403. # %%
  404. # %% [markdown]
  405. # ## OpenAltimetry
  406. # %%
  407. "minx=-154.56678505984297&miny=-88.82881451427136&maxx=-125.17872921546498&maxy=-81.34051361301398&date=2019-05-02&trackId=516"
  408. # %%
  409. # Paste the OpenAltimetry selection parameters here
  410. OA_REFERENCE_URL = "minx=-177.64275595145213&miny=-88.12014866942751&maxx=-128.25920892322736&maxy=-85.52394234080862&date=2019-05-02&trackId=515"
  411. # We populate a list with the photon data using the OpenAltimetry API, no HDF!
  412. OA_URL = (
  413. "https://openaltimetry.org/data/icesat2/getPhotonData?client=jupyter&"
  414. + OA_REFERENCE_URL
  415. )
  416. OA_PHOTONS = ["Noise", "Low", "Medium", "High"]
  417. # OA_PLOTTED_BEAMS = [1,2,3,4,5,6] you can select up to 6 beams for each ground track.
  418. # Some beams may not be usable due cloud covering or QC issues.
  419. OA_BEAMS = [3, 4]
  420. # %%
  421. minx, miny, maxx, maxy = [-156, -88, -127, -84]
  422. date = "2019-05-02" # UTC date?
  423. track = 515 #
  424. beam = 1 # 1 to 6
  425. params = {
  426. "client": "jupyter",
  427. "minx": minx,
  428. "miny": miny,
  429. "maxx": maxx,
  430. "maxy": maxy,
  431. "date": date,
  432. "trackId": str(track),
  433. "beam": str(beam),
  434. }
  435. # %%
  436. r = requests.get(
  437. url="https://openaltimetry.org/data/icesat2/getPhotonData", params=params
  438. )
  439. # %%
  440. # OpenAltimetry Data cleansing
  441. df = pd.io.json.json_normalize(data=r.json()["series"], meta="name", record_path="data")
  442. df.name = df.name.str.split().str.get(0) # Get e.g. just "Low" instead of "Low [12345]"
  443. df.query(
  444. expr="name in ('Low', 'Medium', 'High')", inplace=True
  445. ) # filter out Noise and Buffer points
  446. df.rename(columns={0: "latitude", 1: "elevation", 2: "longitude"}, inplace=True)
  447. df = df.reindex(
  448. columns=["longitude", "latitude", "elevation", "name"]
  449. ) # reorder columns
  450. df.reset_index(inplace=True)
  451. df
  452. # %%
  453. df.hvplot.scatter(x="latitude", y="elevation")
  454. # %%
Tip!

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

Comments

Loading...