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_lake.py 20 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
537
538
539
540
541
542
  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 Active Subglacial Lakes in Antarctica**
  18. #
  19. # Finding subglacial lakes that are draining or filling under the ice!
  20. # They can be detected with ICESat-2 data, as significant changes in height
  21. # (> 1 metre) over a relatively short duration (< 1 year), i.e. a high rate of
  22. # elevation change over time (dhdt).
  23. #
  24. # In this notebook, we'll use some neat tools to help us examine the lakes:
  25. # - To find active subglacial lake boundaries,
  26. # use an *unsupervised clustering* technique
  27. # - To see ice surface elevation trends at a higher temporal resolution (< 3 months),
  28. # perform *crossover track error analysis* on intersecting ICESat-2 tracks
  29. #
  30. # To speed up analysis on millions of points,
  31. # we will use state of the art GPU algorithms enabled by RAPIDS AI libraries,
  32. # or parallelize the processing across our HPC's many CPU cores using Dask.
  33. # %%
  34. import os
  35. import subprocess
  36. # os.environ["CUDA_VISIBLE_DEVICES"] = "1"
  37. import cudf
  38. import cuml
  39. import dask
  40. import dask.array
  41. import geopandas as gpd
  42. import hvplot.xarray
  43. import numpy as np
  44. import pandas as pd
  45. import panel as pn
  46. import pygmt
  47. import scipy.spatial
  48. import shapely.geometry
  49. import tqdm
  50. import xarray as xr
  51. import zarr
  52. import deepicedrain
  53. # %%
  54. use_cupy: bool = True
  55. if use_cupy:
  56. import cupy
  57. import dask_cuda
  58. import dask_cudf
  59. cluster = dask_cuda.LocalCUDACluster(n_workers=2, threads_per_worker=1)
  60. else:
  61. cluster = dask.distributed.LocalCluster(n_workers=8, threads_per_worker=1)
  62. client = dask.distributed.Client(address=cluster)
  63. client
  64. # %% [markdown]
  65. # # Data Preparation
  66. # %%
  67. if not os.path.exists("ATLXI/df_dhdt_antarctica.parquet"):
  68. zarrarray = zarr.open_consolidated(store=f"ATLXI/ds_dhdt_antarctica.zarr", mode="r")
  69. _ = deepicedrain.ndarray_to_parquet(
  70. ndarray=zarrarray,
  71. parquetpath="ATLXI/df_dhdt_antarctica.parquet",
  72. variables=["x", "y", "dhdt_slope", "referencegroundtrack"], # "h_corr"],
  73. dropnacols=["dhdt_slope"],
  74. )
  75. # %%
  76. # Read in Antarctic Drainage Basin Boundaries shapefile into a GeoDataFrame
  77. ice_boundaries: gpd.GeoDataFrame = (
  78. deepicedrain.catalog.measures_antarctic_boundaries.read()
  79. )
  80. drainage_basins: gpd.GeoDataFrame = ice_boundaries.query(expr="TYPE == 'GR'")
  81. # %% [markdown]
  82. # ## Load in ICESat-2 data (x, y, dhdt) and do initial trimming
  83. # %%
  84. # Read in raw x, y, dhdt_slope and referencegroundtrack data into the GPU
  85. cudf_raw: cudf.DataFrame = dask_cudf.read_parquet(
  86. path="ATLXI/df_dhdt_antarctica.parquet",
  87. columns=["x", "y", "dhdt_slope", "referencegroundtrack"],
  88. # filters=[[('dhdt_slope', '<', -0.105)], [('dhdt_slope', '>', 0.105)]],
  89. )
  90. # Filter to points with dhdt that is less than -0.105 m/yr or more than +0.105 m/yr
  91. # Based on ICESat-2 ATL06's accuracy and precision of 3.3 ± 7.2cm from Brunt et al 2020
  92. # See https://doi.org/10.1029/2020GL090572
  93. cudf_many = cudf_raw.loc[abs(cudf_raw.dhdt_slope) > 0.105].compute()
  94. print(f"Trimmed {len(cudf_raw)} -> {len(cudf_many)}")
  95. if "cudf_raw" in globals():
  96. del cudf_raw
  97. # %%
  98. # Clip outlier values to 3 sigma (standard deviations) from mean
  99. _mean = cudf_many.dhdt_slope.mean()
  100. _std = cudf_many.dhdt_slope.std()
  101. cudf_many.dhdt_slope.clip(
  102. lower=np.float32(_mean - 3 * _std), upper=np.float32(_mean + 3 * _std), inplace=True
  103. )
  104. # %% [markdown]
  105. # ## Label ICESat-2 points according to their drainage basin
  106. #
  107. # Uses Point in Polygon.
  108. # For each point, find out which Antarctic Drainage Basin they are in.
  109. # This will also remove the points on floating (FR) ice shelves and islands (IS),
  110. # so that we keep only points on the grounded (GR) ice regions.
  111. # %%
  112. # Use point in polygon to label points according to the drainage basins they fall in
  113. cudf_many["drainage_basin"]: cudf.Series = deepicedrain.point_in_polygon_gpu(
  114. points_df=cudf_many, poly_df=drainage_basins, poly_limit=16
  115. )
  116. X_many = cudf_many.dropna() # drop points that are not in a drainage basin
  117. print(f"Trimmed {len(cudf_many)} -> {len(X_many)}")
  118. # %% [markdown]
  119. # # Find Active Subglacial Lake clusters
  120. #
  121. # Uses Density-based spatial clustering of applications with noise (DBSCAN).
  122. # %% [markdown]
  123. # ### Subglacial Lake Finder algorithm
  124. #
  125. # For each Antarctic drainage basin:
  126. #
  127. # 1. Select all points with significant elevation change over time (dhdt)
  128. # - Specifically, the (absolute) dhdt value should be
  129. # 2x the median (absolute) dhdt for that drainage basin
  130. # - E.g. if median dhdt for basin is 0.35 m/yr,
  131. # we choose points that have dhdt > 0.70 m/yr
  132. # 2. Run unsupervised clustering to pick out active subglacial lakes
  133. # - Split into draining (-dhdt) and filling (+dhdt) points first
  134. # - Use DBSCAN algorithm to cluster points into groups,
  135. # with an eps (distance) of 3 km and minimum sample size of 250 points
  136. # 3. Check each potential point cluster to see if it meets active lake criteria
  137. # 1. Build a convex hull 'lake' polygon around clustered points
  138. # 2. Check that the 'lake' has significant elevation change relative to outside
  139. # - For the area in the 5 km buffer region **outside** the 'lake' polygon:
  140. # - Find median dhdt (outer_dhdt)
  141. # - Find median absolute deviation of dhdt values (outer_mad)
  142. # - For the area **inside** the 'lake' polygon:
  143. # - Find median dhdt (inner_dhdt)
  144. # - If the potential lake shows an elevation change that is more than
  145. # 3x the surrounding deviation of background elevation change,
  146. # we infer that this is likely an active subglacial 'lake'
  147. # %%
  148. # Subglacial lake finder
  149. activelakes: dict = {
  150. "basin_name": [], # Antarctic drainage basin name
  151. "refgtracks": [], # Pipe-delimited list of ICESat-2 reference ground tracks
  152. "num_points": [], # Number of clustered data points
  153. "maxabsdhdt": [], # Maximum absolute dhdt value inside of lake boundary
  154. "inner_dhdt": [], # Median elev change over time (dhdt) inside of lake bounds
  155. "mean_dhdt": [], # Mean elev change over time (dhdt) inside of lake bounds
  156. "outer_dhdt": [], # Median elevation change over time (dhdt) outside of lake
  157. "outer_std": [], # Standard deviation of dhdt outside of lake
  158. "outer_mad": [], # Median absolute deviation of dhdt outside of lake
  159. "geometry": [], # Shapely Polygon geometry holding lake boundary coordinates
  160. }
  161. basin_name: str = "Cook" # Set a basin name here
  162. basins = drainage_basins[drainage_basins.NAME == basin_name].index # one specific basin
  163. # basins = drainage_basins[
  164. # drainage_basins.NAME.isin(("Cook", "Whillans"))
  165. # ].index # some specific basins
  166. basins: pd.core.indexes.numeric.Int64Index = drainage_basins.index # run on all basins
  167. eps: int = 3000 # ICESat-2 tracks are separated by ~3 km across track, with each laser pair ~90 m apart
  168. min_samples: int = 300
  169. for basin_index in tqdm.tqdm(iterable=basins):
  170. # Initial data cleaning, filter to rows that are in the drainage basin
  171. basin = drainage_basins.loc[basin_index]
  172. X_local = X_many.loc[X_many.drainage_basin == basin.NAME] # .reset_index(drop=True)
  173. # Get points with dhdt_slope higher than 3x the median dhdt_slope for the basin
  174. # E.g. if median dhdt_slope is 0.30 m/yr, then we cluster points over 0.90 m/yr
  175. abs_dhdt = X_local.dhdt_slope.abs()
  176. tolerance: float = 3 * abs_dhdt.median()
  177. X = X_local.loc[abs_dhdt > tolerance]
  178. if len(X) <= 1000: # don't run on too few points
  179. continue
  180. # Run unsupervised clustering separately on draining and filling lakes
  181. # Draining lake points have negative labels (e.g. -1, -2, 3),
  182. # Filling lake points have positive labels (e.g. 1, 2, 3),
  183. # Noise points have NaN labels (i.e. NaN)
  184. cluster_vars = ["x", "y", "dhdt_slope"]
  185. draining_lake_labels = -deepicedrain.find_clusters(
  186. X=X.loc[X.dhdt_slope < 0][cluster_vars],
  187. eps=eps,
  188. min_samples=min_samples,
  189. verbose=cuml.common.logger.level_error,
  190. )
  191. filling_lake_labels = deepicedrain.find_clusters(
  192. X=X.loc[X.dhdt_slope > 0][cluster_vars],
  193. eps=eps,
  194. min_samples=min_samples,
  195. verbose=cuml.common.logger.level_error,
  196. )
  197. lake_labels = cudf.concat(objs=[draining_lake_labels, filling_lake_labels])
  198. lake_labels: cudf.Series = lake_labels.sort_index()
  199. assert lake_labels.name == "cluster_id"
  200. # Checking all potential subglacial lakes in a basin
  201. clusters: cudf.Series = lake_labels.unique()
  202. for cluster_label in clusters.to_array():
  203. # Store attribute and geometry information of each active lake
  204. lake_points: cudf.DataFrame = X.loc[lake_labels == cluster_label]
  205. # More data cleaning, dropping clusters with too few points
  206. try:
  207. assert len(lake_points) > 100
  208. except AssertionError:
  209. lake_labels = lake_labels.replace(to_replace=cluster_label, value=None)
  210. continue
  211. multipoint: shapely.geometry.MultiPoint = shapely.geometry.MultiPoint(
  212. points=lake_points[["x", "y"]].as_matrix()
  213. )
  214. convexhull: shapely.geometry.Polygon = multipoint.convex_hull
  215. # Filter out (most) false positive subglacial lakes
  216. # Check that elevation change over time in lake is anomalous to outside
  217. # The 5000 m distance from lake boundary setting is empirically based on
  218. # Smith et al. 2009's methodology at https://doi.org/10.3189/002214309789470879
  219. outer_ring_buffer = convexhull.buffer(distance=5000) - convexhull
  220. X_local["in_donut_ring"] = deepicedrain.point_in_polygon_gpu(
  221. points_df=X_local,
  222. poly_df=gpd.GeoDataFrame({"name": True, "geometry": [outer_ring_buffer]}),
  223. )
  224. outer_points = X_local.dropna(subset="in_donut_ring")
  225. outer_dhdt: float = outer_points.dhdt_slope.median()
  226. outer_std: float = outer_points.dhdt_slope.std()
  227. outer_mad: float = scipy.stats.median_abs_deviation(
  228. x=outer_points.dhdt_slope.to_pandas()
  229. )
  230. mean_dhdt: float = lake_points.dhdt_slope.mean()
  231. inner_dhdt: float = lake_points.dhdt_slope.median()
  232. X_local = X_local.drop(labels="in_donut_ring", axis="columns")
  233. # If lake interior's median dhdt value is within 3 median absolute deviations
  234. # of the lake exterior's dhdt value, we remove the lake label
  235. # I.e. skip if above background change not significant enough
  236. # Inspired by Kim et al. 2016's methodology at https://doi.org/10.5194/tc-10-2971-2016
  237. if abs(inner_dhdt - outer_dhdt) < 3 * outer_mad:
  238. lake_labels = lake_labels.replace(to_replace=cluster_label, value=None)
  239. continue
  240. maxabsdhdt: float = (
  241. lake_points.dhdt_slope.max()
  242. if cluster_label > 0 # positive label = filling
  243. else lake_points.dhdt_slope.min() # negative label = draining
  244. )
  245. refgtracks: str = "|".join(
  246. map(str, lake_points.referencegroundtrack.unique().to_pandas())
  247. )
  248. # Save key variables to dictionary that will later go into geodataframe
  249. activelakes["basin_name"].append(basin.NAME)
  250. activelakes["refgtracks"].append(refgtracks)
  251. activelakes["num_points"].append(len(lake_points))
  252. activelakes["maxabsdhdt"].append(maxabsdhdt)
  253. activelakes["inner_dhdt"].append(inner_dhdt)
  254. activelakes["mean_dhdt"].append(mean_dhdt)
  255. activelakes["outer_dhdt"].append(outer_dhdt)
  256. activelakes["outer_std"].append(outer_std)
  257. activelakes["outer_mad"].append(outer_mad)
  258. activelakes["geometry"].append(convexhull)
  259. # Calculate total number of lakes found for one drainage basin
  260. clusters: cudf.Series = lake_labels.unique()
  261. n_draining, n_filling = (clusters < 0).sum(), (clusters > 0).sum()
  262. if n_draining + n_filling > 0:
  263. print(f"{len(X)} rows at {basin.NAME} above ± {tolerance:.2f} m/yr")
  264. print(f"{n_draining} draining and {n_filling} filling lakes found")
  265. if len(activelakes["geometry"]) >= 1:
  266. gdf = gpd.GeoDataFrame(activelakes, crs="EPSG:3031")
  267. basename = "antarctic_subglacial_lakes" # f"temp_{basin_name.lower()}_lakes" #
  268. gdf.to_file(filename=f"{basename}_3031.geojson", driver="GeoJSON")
  269. gdf.to_crs(crs={"init": "epsg:4326"}).to_file(
  270. filename=f"{basename}_4326.geojson", driver="GeoJSON"
  271. )
  272. print(f"Total of {len(gdf)} subglacial lakes found")
  273. # %% [markdown]
  274. # ## Visualize lakes
  275. # %%
  276. # Concatenate XY points with labels, and move data from GPU to CPU
  277. X: cudf.DataFrame = cudf.concat(objs=[X, lake_labels], axis="columns")
  278. X_ = X.to_pandas()
  279. # %%
  280. # Plot clusters on a map in colour, noise points/outliers as small dots
  281. fig = pygmt.Figure()
  282. n_clusters_ = len(X_.cluster_id.unique()) - 1 # No. of clusters minus noise (NaN)
  283. sizes = (X_.cluster_id.isna()).map(arg={True: 0.01, False: 0.1})
  284. pygmt.makecpt(cmap="polar", series=(-1, 1, 2), color_model="+cDrain,Fill", reverse=True)
  285. fig.plot(
  286. x=X_.x,
  287. y=X_.y,
  288. sizes=sizes,
  289. style="cc",
  290. color=pd.cut(x=X_.cluster_id, bins=(-np.inf, 0, np.inf), labels=[-1, 1]),
  291. cmap=True,
  292. frame=[
  293. f'WSne+t"Estimated number of lake clusters at {basin.NAME}: {n_clusters_}"',
  294. 'xafg+l"Polar Stereographic X (m)"',
  295. 'yafg+l"Polar Stereographic Y (m)"',
  296. ],
  297. )
  298. basinx, basiny = basin.geometry.exterior.coords.xy
  299. fig.plot(x=basinx, y=basiny, pen="thinnest,-")
  300. fig.colorbar(position='JMR+w2c/0.5c+m+n"Unclassified"', L="i0.5c")
  301. fig.savefig(fname=f"figures/subglacial_lake_clusters_at_{basin.NAME}.png")
  302. fig.show()
  303. # %% [markdown]
  304. # # Select a subglacial lake to examine
  305. # %%
  306. # Load dhdt data from Parquet file
  307. placename: str = "siple_coast" # "slessor_downstream" # "Recovery" # "Whillans"
  308. df_dhdt: cudf.DataFrame = cudf.read_parquet(
  309. f"ATLXI/df_dhdt_{placename.lower()}.parquet"
  310. )
  311. # %%
  312. # Choose one Antarctic active subglacial lake polygon with EPSG:3031 coordinates
  313. lake_name: str = "Whillans IX"
  314. lake_catalog = deepicedrain.catalog.subglacial_lakes()
  315. lake_ids, transect_id = (
  316. pd.json_normalize(lake_catalog.metadata["lakedict"])
  317. .query("lakename == @lake_name")[["ids", "transect"]]
  318. .iloc[0]
  319. )
  320. lake = (
  321. lake_catalog.read()
  322. .loc[lake_ids]
  323. .dissolve(by=np.zeros(shape=len(lake_ids), dtype="int64"), as_index=False)
  324. .squeeze()
  325. )
  326. region = deepicedrain.Region.from_gdf(gdf=lake, name=lake_name)
  327. draining: bool = lake.inner_dhdt < 0
  328. print(lake)
  329. lake.geometry
  330. # %%
  331. # Subset data to lake of interest
  332. placename: str = region.name.lower().replace(" ", "_")
  333. df_lake: cudf.DataFrame = region.subset(data=df_dhdt)
  334. # Get all raw xyz points and one transect line dataframe
  335. track_dict: dict = deepicedrain.split_tracks(df=df_lake.to_pandas())
  336. track_points: pd.DataFrame = (
  337. pd.concat(track_dict.values())
  338. .groupby(by=["x", "y"])
  339. .mean() # z value is mean h_corr over all cycles
  340. .reset_index()[["x", "y", "h_corr"]]
  341. )
  342. try:
  343. _rgt, _pt = transect_id.split("_")
  344. df_transect: pd.DataFrame = (
  345. track_dict[transect_id][["x", "y", "h_corr", "cycle_number"]]
  346. .groupby(by=["x", "y"])
  347. .max() # z value is maximum h_corr over all cycles
  348. .reset_index()
  349. )
  350. except AttributeError:
  351. pass
  352. # Save lake outline to OGR GMT file format
  353. outline_points: str = f"figures/{placename}/{placename}.gmt"
  354. if not os.path.exists(path=outline_points):
  355. os.makedirs(name=f"figures/{placename}", exist_ok=True)
  356. lake_catalog.read().loc[list(lake_ids)].to_file(
  357. filename=outline_points, driver="OGR_GMT"
  358. )
  359. # %% [markdown]
  360. # ## Create an interpolated ice surface elevation grid for each ICESat-2 cycle
  361. # %%
  362. # Generate gridded time-series of ice elevation over lake
  363. cycles: tuple = (3, 4, 5, 6, 7, 8, 9)
  364. os.makedirs(name=f"figures/{placename}", exist_ok=True)
  365. ds_lake: xr.Dataset = deepicedrain.spatiotemporal_cube(
  366. table=df_lake.to_pandas(),
  367. placename=placename,
  368. cycles=cycles,
  369. folder=f"figures/{placename}",
  370. )
  371. ds_lake.to_netcdf(path=f"figures/{placename}/xyht_{placename}.nc", mode="w")
  372. # %%
  373. # Get 3D grid_region (xmin/xmax/ymin/ymax/zmin/zmax),
  374. # and calculate normalized z-values as Elevation delta relative to Cycle 3
  375. z_limits: tuple = (float(ds_lake.z.min()), float(ds_lake.z.max())) # original z limits
  376. grid_region: tuple = region.bounds() + z_limits
  377. ds_lake_diff: xr.Dataset = ds_lake - ds_lake.sel(cycle_number=3).z
  378. z_diff_limits: tuple = (float(ds_lake_diff.z.min()), float(ds_lake_diff.z.max()))
  379. diff_grid_region: np.ndarray = np.append(arr=grid_region[:4], values=z_diff_limits)
  380. print(f"Elevation limits are: {z_limits}")
  381. # %%
  382. # 3D plot of mean ice surface elevation (<z>) and rate of ice elevation change (dhdt)
  383. fig = deepicedrain.plot_icesurface(
  384. grid=f"figures/{placename}/xyht_{placename}.nc?z_mean",
  385. grid_region=grid_region,
  386. diff_grid=f"figures/{placename}/xyht_{placename}.nc?dhdt",
  387. track_points=track_points.to_numpy(),
  388. outline_points=outline_points,
  389. azimuth=157.5, # 202.5 # 270
  390. elevation=45, # 60
  391. title=f"{region.name} Ice Surface",
  392. )
  393. # Plot crossing transect line
  394. fig.plot3d(
  395. data=df_transect[["x", "y", "h_corr"]].to_numpy(),
  396. color="yellow2",
  397. style="c0.1c",
  398. zscale=True,
  399. perspective=True,
  400. )
  401. fig.savefig(f"figures/{placename}/dsm_{placename}_cycles_{cycles[0]}-{cycles[-1]}.png")
  402. fig.show()
  403. # %%
  404. # 3D plots of gridded ice surface elevation over time (one per cycle)
  405. for cycle in tqdm.tqdm(iterable=cycles):
  406. time_nsec: pd.Timestamp = df_lake[f"utc_time_{cycle}"].to_pandas().mean()
  407. time_sec: str = np.datetime_as_string(arr=time_nsec.to_datetime64(), unit="s")
  408. # grid = ds_lake.sel(cycle_number=cycle).z
  409. fig = deepicedrain.plot_icesurface(
  410. grid=f"figures/{placename}/h_corr_{placename}_cycle_{cycle}.nc",
  411. grid_region=grid_region,
  412. diff_grid=ds_lake_diff.sel(cycle_number=cycle).z,
  413. diff_grid_region=diff_grid_region,
  414. track_points=df_lake[["x", "y", f"h_corr_{cycle}"]].dropna().as_matrix(),
  415. outline_points=outline_points,
  416. azimuth=157.5, # 202.5 # 270
  417. elevation=45, # 60
  418. title=f"{region.name} at Cycle {cycle} ({time_sec})",
  419. )
  420. fig.savefig(f"figures/{placename}/dsm_{placename}_cycle_{cycle}.png")
  421. fig.show()
  422. # %%
  423. # Make an animated GIF of changing ice surface from the PNG files
  424. # !convert -delay 120 -loop 0 figures/{placename}/dsm_*.png {gif_fname}
  425. gif_fname: str = (
  426. f"figures/{placename}/dsm_{placename}_cycles_{cycles[0]}-{cycles[-1]}.gif"
  427. )
  428. subprocess.check_call(
  429. [
  430. "convert",
  431. "-delay",
  432. "120",
  433. "-loop",
  434. "0",
  435. f"figures/{placename}/dsm_*cycle_*.png",
  436. gif_fname,
  437. ]
  438. )
  439. # %%
  440. # HvPlot 2D interactive view of ice surface elevation grids over each ICESat-2 cycle
  441. dashboard: pn.layout.Column = pn.Column(
  442. ds_lake.hvplot.image(x="x", y="y", clim=z_limits, cmap="gist_earth", data_aspect=1)
  443. # * ds_lake.hvplot.contour(x="x", y="y", clim=z_limits, data_aspect=1)
  444. )
  445. dashboard.show(port=30227)
  446. # %% [markdown]
  447. # ## Along track plots of ice surface elevation change over time
  448. # %%
  449. # Select a few Reference Ground tracks to look at
  450. savefig_tasks: list = [] # empty list of save figure tasks
  451. rgts: list = [int(rgt) for rgt in lake.refgtracks.split("|")]
  452. print(f"Looking at Reference Ground Tracks: {rgts}")
  453. track_dict: dict = deepicedrain.split_tracks(df=df_lake.to_pandas())
  454. for rgtpair, df_ in track_dict.items():
  455. # Transect plot along a reference ground track
  456. fig = dask.delayed(obj=deepicedrain.plot_alongtrack)(
  457. df=df_, rgtpair=rgtpair, regionname=region.name, oldtonew=draining
  458. )
  459. savefig_task = fig.savefig(
  460. fname=f"figures/{placename}/alongtrack_{placename}_{rgtpair}.png"
  461. )
  462. savefig_tasks.append(savefig_task)
  463. # %%
  464. futures = [client.compute(savefig_task) for savefig_task in savefig_tasks]
  465. for _ in tqdm.tqdm(
  466. iterable=dask.distributed.as_completed(futures=futures), total=len(savefig_tasks)
  467. ):
  468. pass
  469. # %%
Tip!

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

Comments

Loading...