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

atlxi_dhdt.py 15 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
  1. # -*- coding: utf-8 -*-
  2. # ---
  3. # jupyter:
  4. # jupytext:
  5. # formats: ipynb,py:hydrogen
  6. # text_representation:
  7. # extension: .py
  8. # format_name: hydrogen
  9. # format_version: '1.3'
  10. # jupytext_version: 1.11.3
  11. # kernelspec:
  12. # display_name: deepicedrain
  13. # language: python
  14. # name: deepicedrain
  15. # ---
  16. # %% [markdown]
  17. # # **ICESat-2 ATL11 Rate of Height change over Time (dhdt)**
  18. #
  19. # This Jupyter notebook will cover the calculation of
  20. # Ice Height Changes (dh) over Time (dt) using Linear Regression.
  21. # Focusing on the Antarctic continent, for the ICESat-2 time period.
  22. # To save on computational resources, we'll run through a few preprocessing steps:
  23. #
  24. # 1. Select essential points
  25. # - Subset to geographic region of interest (optional)
  26. # - Drop points without at least 2 valid heights across all ICESat-2 cycles
  27. # 2. Calculate height range (h_range)
  28. # - Done for points which are valid and in geographic region of interest
  29. # - Uses the `deepicedrain.nanptp` function
  30. # 3. Calculate rate of height change over time (dhdt)
  31. # - Done for points with `h_range > 0.25 metres`
  32. # - Uses the `deepicedrain.nan_linregress` function
  33. #
  34. # Adapted from https://github.com/suzanne64/ATL11/blob/master/plotting_scripts/AA_dhdt_map.ipynb
  35. # %%
  36. import os
  37. import cudf # comment out if no GPU
  38. import dask
  39. import geopandas as gpd
  40. import holoviews as hv
  41. import hvplot.cudf # comment out if no GPU
  42. import hvplot.pandas
  43. import intake
  44. import numpy as np
  45. import pandas as pd
  46. import panel as pn
  47. import pygmt
  48. import tqdm
  49. import xarray as xr
  50. import deepicedrain
  51. # %%
  52. client = dask.distributed.Client(n_workers=16, threads_per_worker=1)
  53. client
  54. # %% [markdown]
  55. # # Select essential points
  56. # %%
  57. # Xarray open_dataset preprocessor to add fields based on input filename.
  58. add_path_to_ds = lambda ds: ds.assign_coords(
  59. coords=intake.source.utils.reverse_format(
  60. format_string="ATL11.003z123/ATL11_{referencegroundtrack:04d}1x_{}_{}_{}.zarr",
  61. resolved_string=ds.encoding["source"],
  62. )
  63. )
  64. # Load ATL11 data from Zarr
  65. ds: xr.Dataset = xr.open_mfdataset(
  66. paths="ATL11.003z123/ATL11_*_003_01.zarr",
  67. chunks="auto",
  68. engine="zarr",
  69. combine="nested",
  70. concat_dim="ref_pt",
  71. parallel="True",
  72. preprocess=add_path_to_ds,
  73. backend_kwargs={"consolidated": True},
  74. )
  75. # %% [markdown]
  76. # ## Trim out unnecessary values (optional)
  77. #
  78. # There's ~220 million ATL11 points for the whole of Antarctica,
  79. # and not all of them will be needed depending on what you want to do.
  80. # To cut down on the number of data points the computer needs to work on,
  81. # we can:
  82. #
  83. # - Subset to geographic region of interest
  84. # - Ensure there are at least 2 height values to calculate trend over time
  85. # %%
  86. # Antarctic bounding box locations with EPSG:3031 coordinates
  87. regions = gpd.read_file(filename="deepicedrain/deepicedrain_regions.geojson")
  88. regions: gpd.GeoDataFrame = regions.set_index(keys="placename")
  89. # %%
  90. # Subset dataset to geographic region of interest
  91. placename: str = "antarctica"
  92. region: deepicedrain.Region = deepicedrain.Region.from_gdf(gdf=regions.loc[placename])
  93. # ds = region.subset(data=ds)
  94. # %%
  95. # We need at least 2 points to draw a trend line or compute differences
  96. # So let's drop points with less than 2 valid values across all cycles
  97. # Will take maybe 10-15 min to trim down ~220 million points to ~190 million
  98. print(f"Originally {len(ds.ref_pt)} points")
  99. # ds: xr.Dataset = ds.dropna(dim="ref_pt", thresh=2, subset=["h_corr"])
  100. print(f"Trimmed to {len(ds.ref_pt)} points")
  101. # %% [markdown]
  102. # ### Optimize dataset for big calculations later
  103. #
  104. # We'll rechunk the dataset to a reasonable chunk size,
  105. # and persist key dataset variables in memory so that the parallel
  106. # computations will be more efficient in later sections.
  107. # %%
  108. # ds["h_corr"] = ds.h_corr.unify_chunks()
  109. # %%
  110. # Persist the height and time data in distributed memory
  111. # ds["h_corr"] = ds.h_corr.persist()
  112. # ds["delta_time"] = ds.delta_time.persist()
  113. # %% [markdown]
  114. # ### Retrieve some basic information for plots later
  115. #
  116. # Simply getting the number of cycles and date range
  117. # to put into our plots later on
  118. # %%
  119. # Get number of ICESat-2 cycles used
  120. num_cycles: int = len(ds.cycle_number)
  121. # %%
  122. # Get first and last dates to put into our plots
  123. min_date, max_date = ("2019-03-29", "2020-12-24")
  124. if min_date is None:
  125. min_delta_time = np.nanmin(ds.delta_time.isel(cycle_number=0).data).compute()
  126. min_utc_time = deepicedrain.deltatime_to_utctime(min_delta_time)
  127. min_date: str = np.datetime_as_string(arr=min_utc_time, unit="D")
  128. if max_date is None:
  129. max_delta_time = np.nanmax(ds.delta_time.isel(cycle_number=-1).data).compute()
  130. max_utc_time = deepicedrain.deltatime_to_utctime(max_delta_time)
  131. max_date: str = np.datetime_as_string(arr=max_utc_time, unit="D")
  132. print(f"Handling {num_cycles} ICESat-2 cycles from {min_date} to {max_date}")
  133. # %%
  134. # %% [markdown]
  135. # # Calculate height range (h_range)
  136. #
  137. # A simple way of finding active subglacial lakes is to see where
  138. # there has been a noticeably rapid change in elevation over
  139. # a short period of time such as 2-5 metres a year (or ~4x91-day ICESat-2 cycles).
  140. # 'Range of height' is quick way to do this,
  141. # basically just doing maximum height minus minimum height.
  142. # %%
  143. # Calculate height range across cycles, parallelized using dask
  144. ds["h_range"]: xr.DataArray = xr.apply_ufunc(
  145. deepicedrain.nanptp, # min point to max point (range) that handles NaN values
  146. ds.h_corr,
  147. input_core_dims=[["cycle_number"]],
  148. dask="allowed",
  149. output_dtypes=[ds.h_corr.dtype],
  150. kwargs={"axis": 1},
  151. )
  152. # %%
  153. # %%time
  154. # Compute height range. Also include all height and time info
  155. ds_ht: xr.Dataset = ds[["h_range", "h_corr", "delta_time"]].compute()
  156. # %%
  157. # Non-parallelized
  158. # h_range = deepicedrain.nanptp(a=ds.h_corr[0:1], axis=1)
  159. # Ensure no height range values which are zero (usually due to only 1 data point)
  160. # assert len(dask.array.argwhere(dsh.h_range <= 0.0).compute()) == 0
  161. # %%
  162. # Save or Load height range data
  163. # ds_ht.to_zarr(store=f"ATLXI/ds_hrange_time_{placename}.zarr", mode="w", consolidated=True)
  164. ds_ht: xr.Dataset = xr.open_dataset(
  165. filename_or_obj=f"ATLXI/ds_hrange_time_{placename}.zarr",
  166. chunks={"cycle_number": 7},
  167. engine="zarr",
  168. backend_kwargs={"consolidated": True},
  169. )
  170. # ds: xr.Dataset = ds_ht # shortcut for dhdt calculation later
  171. # %%
  172. df_hr: pd.DataFrame = ds_ht.h_range.to_dataframe()
  173. # %%
  174. print(df_hr.describe())
  175. # %%
  176. # Datashade our height values (vector points) onto a grid (raster image)
  177. agg_grid: xr.DataArray = region.datashade(df=df_hr, z_dim="h_range")
  178. print(agg_grid)
  179. # %%
  180. # Plot our map!
  181. scale: int = region.scale
  182. fig = pygmt.Figure()
  183. pygmt.makecpt(cmap="tokyo", series=[0.5, 5, 0.5], reverse=True)
  184. fig.grdimage(
  185. grid=agg_grid,
  186. region=region.bounds(),
  187. projection=f"x1:{scale}",
  188. frame=["afg", f'WSne+t"ICESat-2 Ice Surface Height Range over {region.name}"'],
  189. nan_transparent=True,
  190. )
  191. fig.colorbar(
  192. position="JCR+e",
  193. frame=["af", f'x+l"height range from {min_date} to {max_date}"', "y+lm"],
  194. )
  195. # for subglacial_lake in subglacial_lakes:
  196. # fig.plot(data=subglacial_lake, L=True, pen="thin")
  197. fig.coast(
  198. region=region.bounds(),
  199. projection=f"s0/-90/-71/1:{scale}",
  200. area_thresh="+ag",
  201. resolution="i",
  202. shorelines="0.5p",
  203. verbose="q",
  204. )
  205. fig.savefig(f"figures/plot_atl11_hrange_{placename}_{min_date}_{max_date}.png")
  206. fig.show(width=600)
  207. # %%
  208. # %% [markdown]
  209. # # Calculate rate of height change over time (dhdt)
  210. #
  211. # Performing linear regression in parallel.
  212. # Uses the [`scipy.stats.linregress`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.linregress.html) function,
  213. # parallelized with xarray's [`apply_ufunc`](http://xarray.pydata.org/en/v0.15.1/examples/apply_ufunc_vectorize_1d.html) method
  214. # on a Dask cluster.
  215. # %%
  216. # Take only the points where there is more than 0.25 metres of elevation change
  217. # Trim down ~220 million points to ~36 million
  218. # ds = ds.where(cond=ds.h_range > 0.25, drop=True)
  219. print(f"Trimmed to {len(ds.ref_pt)} points")
  220. # %%
  221. # Do linear regression on many datapoints, parallelized using dask
  222. dhdt_params: xr.DataArray = xr.apply_ufunc(
  223. deepicedrain.nan_linregress,
  224. ds.delta_time.astype(np.uint64), # x is time in nanoseconds
  225. ds.h_corr, # y is height in metres
  226. input_core_dims=[["cycle_number"], ["cycle_number"]],
  227. output_core_dims=[["dhdt_parameters"]],
  228. # output_core_dims=[["slope_ns"], ["intercept"], ["r_value"], ["p_value"], ["std_err"]],
  229. dask="parallelized",
  230. vectorize=True,
  231. output_dtypes=[np.float32],
  232. output_sizes={"dhdt_parameters": 5},
  233. # output_sizes={"slope_ns":1, "intercept":1, "r_value":1, "p_value":1, "std_err":1}
  234. )
  235. # %%
  236. # Construct an xarray.Dataset containing time, height, and dhdt variables
  237. ds_dhdt: xr.Dataset = ds[["delta_time", "h_corr"]]
  238. for var_name, dataarray in zip(
  239. ["slope", "intercept", "r_value", "p_value", "std_err"], dhdt_params.transpose()
  240. ):
  241. ds_dhdt[f"dhdt_{var_name}"]: xr.DataArray = dataarray
  242. # %%
  243. # Convert dhdt_slope units from metres per nanosecond to metres per year
  244. # 1 year = 365.25 days x 24 hours x 60 min x 60 seconds x 1_000_000_000 nanoseconds
  245. ds_dhdt["dhdt_slope"] = ds_dhdt["dhdt_slope"] * (365.25 * 24 * 60 * 60 * 1_000_000_000)
  246. # %%
  247. # %%time
  248. # Compute rate of height change over time (dhdt). Also include all height and time info
  249. ds_dhdt: xr.Dataset = ds_dhdt.compute()
  250. # %%
  251. # Do linear regression on single datapoint
  252. # slope_ns, intercept, r_value, p_value, std_err = nan_linregress(
  253. # x=ds.delta_time[:1].data.astype(np.uint64), y=ds.h_corr[:1].data
  254. # )
  255. # print(slope_ns, intercept, r_value, p_value, std_err)
  256. # %%
  257. # Load or Save rate of height change over time (dhdt) data
  258. # ds_dhdt.to_zarr(store=f"ATLXI/ds_dhdt_{placename}.zarr", mode="w", consolidated=True)
  259. ds_dhdt: xr.Dataset = xr.open_dataset(
  260. filename_or_obj=f"ATLXI/ds_dhdt_{placename}.zarr",
  261. chunks="auto",
  262. engine="zarr",
  263. backend_kwargs={"consolidated": True},
  264. )
  265. # %%
  266. df_slope: pd.DataFrame = ds_dhdt.dhdt_slope.to_dataframe()
  267. # %%
  268. # Datashade our height values (vector points) onto a grid (raster image)
  269. agg_grid: xr.DataArray = region.datashade(df=df_slope, z_dim="dhdt_slope")
  270. print(agg_grid)
  271. # %%
  272. # Plot our map!
  273. scale: int = region.scale
  274. fig = pygmt.Figure()
  275. pygmt.makecpt(cmap="roma", series=[-5, 5, 0.5], continuous=True)
  276. fig.grdimage(
  277. grid=agg_grid,
  278. region=region.bounds(),
  279. projection=f"x1:{scale}",
  280. frame=[
  281. "afg",
  282. f'WSne+t"ICESat-2 Change in Ice Surface Height over Time at {region.name}"',
  283. ],
  284. nan_transparent=True,
  285. )
  286. fig.colorbar(
  287. position="JCR+e",
  288. frame=["af", f'x+l"dH/dt from {min_date} to {max_date}"', "y+lm/yr"],
  289. )
  290. # for subglacial_lake in subglacial_lakes:
  291. # fig.plot(data=subglacial_lake, L=True, pen="thinnest")
  292. fig.coast(
  293. region=region.bounds(),
  294. projection=f"s0/-90/-71/1:{scale}",
  295. area_thresh="+ag",
  296. resolution="i",
  297. shorelines="0.5p",
  298. verbose="q",
  299. )
  300. fig.savefig(f"figures/plot_atl11_dhdt_{placename.lower()}_{min_date}_{max_date}.png")
  301. fig.show(width=600)
  302. # %%
  303. # %% [markdown]
  304. # # Along track plots of subglacial lake drainage/filling events
  305. #
  306. # Let's take a closer look at one potential
  307. # subglacial lake filling event at Whillans Ice Stream.
  308. # We'll plot a cross-section view of
  309. # ice surface height changes over time,
  310. # along an ICESat-2 reference ground track.
  311. # %%
  312. # Save or load dhdt data from Parquet file
  313. for placename in tqdm.tqdm(
  314. iterable=[
  315. "whillans_downstream",
  316. "whillans_upstream",
  317. "siple_coast",
  318. "slessor_downstream",
  319. "amundsen_sea_embayment",
  320. ]
  321. ):
  322. # TODO make the region detection code below better
  323. try:
  324. ice_boundaries: gpd.GeoDataFrame = (
  325. deepicedrain.catalog.measures_antarctic_boundaries.read()
  326. )
  327. drainage_basins: gpd.GeoDataFrame = ice_boundaries.query(expr="TYPE == 'GR'")
  328. drainage_basins: gpd.GeoDataFrame = drainage_basins.set_index(keys="NAME")
  329. region: deepicedrain.Region = deepicedrain.Region.from_gdf(
  330. gdf=drainage_basins.loc[placename], name="Recovery Basin"
  331. )
  332. except KeyError:
  333. region: deepicedrain.Region = deepicedrain.Region.from_gdf(
  334. gdf=regions.loc[placename]
  335. )
  336. if not os.path.exists(f"ATLXI/df_dhdt_{placename.lower()}.parquet"):
  337. # Subset dataset to geographic region of interest
  338. ds_subset: xr.Dataset = region.subset(data=ds_dhdt)
  339. # Rename delta_time (timedelta64) to utc_time (datetime64), because that's what it is
  340. ds_subset = ds_subset.rename(name_dict={"delta_time": "utc_time"})
  341. # Save to parquet format. If the dask workers get killed, reduce the number
  342. # of workers (e.g. 72 to 32) so that each worker will have more memory
  343. deepicedrain.ndarray_to_parquet(
  344. ndarray=ds_subset,
  345. parquetpath=f"ATLXI/df_dhdt_{placename.lower()}.parquet",
  346. variables=[
  347. "x",
  348. "x_atc",
  349. "y",
  350. "y_atc",
  351. "dhdt_slope",
  352. "referencegroundtrack",
  353. "h_corr",
  354. "utc_time",
  355. ],
  356. dropnacols=["dhdt_slope"],
  357. startcol=3,
  358. use_deprecated_int96_timestamps=True,
  359. )
  360. # df_dhdt = pd.read_parquet(f"ATLXI/df_dhdt_{placename}.parquet")
  361. df_dhdt: cudf.DataFrame = cudf.read_parquet(f"ATLXI/df_dhdt_{placename}.parquet")
  362. # %%
  363. # Interactive holoviews scatter plot to find referencegroundtrack needed
  364. # Tip: Hover over the points, and find those with high 'dhdt_slope' values
  365. viewer = deepicedrain.IceSat2Explorer(name="ICESat-2 Explorer", placename=placename)
  366. dashboard: pn.layout.Column = pn.Column(viewer.widgets, viewer.view)
  367. # dashboard
  368. # %%
  369. # Show dashboard in another browser tab
  370. dashboard.show()
  371. # %%
  372. # Select a few Reference Ground tracks to look at
  373. rgts: list = [135, 327, 388, 577, 1080, 1272] # Whillans upstream
  374. # rgts: list = [236, 501 , 562, 1181] # whillans_downstream
  375. for rgt in rgts:
  376. df_rgt: pd.DataFrame = df_dhdt.query(expr="referencegroundtrack == @rgt")
  377. df_rgt = deepicedrain.wide_to_long(
  378. df=df_rgt.to_pandas(), stubnames=["h_corr", "utc_time"], j="cycle_number"
  379. )
  380. print(f"Looking at Reference Ground Tracks: {rgts}")
  381. # %%
  382. # Select one laser pair (out of three) based on y_atc field
  383. # df = df_rgt.query(expr="y_atc < -100") # left
  384. df = df_rgt.query(expr="abs(y_atc) < 100") # centre
  385. # df = df_rgt.query(expr="y_atc > 100") # right
  386. # %%
  387. # Interactive scatter plot of height along one laser pair track, over time
  388. df.hvplot.scatter(
  389. x="x_atc",
  390. y="h_corr",
  391. by="cycle_number",
  392. hover=True,
  393. hover_cols=["x", "y", "dhdt_slope"],
  394. )
  395. # %%
  396. # Filter points to those with significant dhdt values > +/- 0.2 m/yr
  397. # TODO Use Hausdorff Distance to get location of maximum change!!!
  398. df = df.query(expr="abs(dhdt_slope) > 0.2 & h_corr < 300")
  399. # %%
  400. # Plot 2D along track view of Ice Surface Height Changes over Time
  401. fig = deepicedrain.plot_alongtrack(df=df, rgtpair=f"{rgt:04d}", regionname=region.name)
  402. fig.savefig(fname=f"figures/alongtrack_{placename}_{rgt}.png")
  403. fig.show()
  404. # %%
Tip!

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

Comments

Loading...