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

spatiotemporal.py 17 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
  1. """
  2. Geospatial and Temporal class that implements some handy tools.
  3. Does bounding box region subsets, coordinate/time conversions, and more!
  4. """
  5. import dataclasses
  6. import datetime
  7. import os
  8. import shutil
  9. import tempfile
  10. import datashader
  11. import geopandas as gpd
  12. import numpy as np
  13. import pandas as pd
  14. import pyproj
  15. import scipy.stats
  16. import xarray as xr
  17. @dataclasses.dataclass(frozen=True)
  18. class Region:
  19. """
  20. A nice bounding box data class structure that holds the coordinates of its
  21. left, right, bottom and top extent, and features convenience functions for
  22. performing spatial subsetting and visualization based on those boundaries.
  23. """
  24. name: str # name of region
  25. xmin: float # left coordinate
  26. xmax: float # right coordinate
  27. ymin: float # bottom coordinate
  28. ymax: float # top coordinate
  29. @classmethod
  30. def from_gdf(
  31. cls,
  32. gdf: gpd.GeoDataFrame,
  33. name_col: str = None,
  34. spacing: float = 1000.0,
  35. **kwargs,
  36. ):
  37. """
  38. Create a deepicedrain.Region instance from a geopandas GeoDataFrame
  39. (single row only). The bounding box will be automatically calculated
  40. from the geometry, rounded up and down as necessary if `spacing` is set.
  41. Parameters
  42. ----------
  43. gdf : geopandas.GeoDataFrame
  44. A single row geodataframe with a Polygon or Polyline type geometry.
  45. name_col : str
  46. Name of the column in the geodataframe to use for setting the name
  47. of the Region. If unset, the name of the region will be
  48. automatically based on the first column of the geodataframe.
  49. Alternatively, pass in `name="Some Name"` to directly set the name.
  50. spacing : float
  51. Number to round coordinates up and down such that the bounding box
  52. are in nice intervals (requires PyGMT). Set to None to use exact
  53. bounds of input shape instead (uses Shapely only). Default is 1000m
  54. for rounding bounding box coordinates to nearest kilometre.
  55. Returns
  56. -------
  57. region : deepicedrain.Region
  58. """
  59. if "name" not in kwargs:
  60. try:
  61. kwargs["name"] = gdf[name_col]
  62. except KeyError:
  63. kwargs["name"] = gdf.iloc[0]
  64. try:
  65. import pygmt
  66. xmin, xmax, ymin, ymax = pygmt.info(
  67. table=np.vstack(gdf.geometry.convex_hull.exterior.coords.xy).T,
  68. spacing=float(spacing),
  69. )
  70. except (ImportError, TypeError):
  71. xmin, ymin, xmax, ymax = gdf.geometry.bounds
  72. kwargs.update({"xmin": xmin, "xmax": xmax, "ymin": ymin, "ymax": ymax})
  73. return cls(**kwargs)
  74. @property
  75. def scale(self) -> int:
  76. """
  77. Automatically set a map scale (1:scale)
  78. based on x-coordinate range divided by 0.2
  79. """
  80. return int((self.xmax - self.xmin) / 0.2)
  81. def bounds(self, style="lrbt") -> tuple:
  82. """
  83. Convenience function to get the bounding box coordinates
  84. of the region in two different styles, lrbt or lbrt.
  85. Defaults to 'lrbt', i.e. left, right, bottom, top.
  86. """
  87. if style == "lrbt": # left, right, bottom, top (for PyGMT)
  88. return (self.xmin, self.xmax, self.ymin, self.ymax)
  89. elif style == "lbrt": # left, bottom, right, top (for Shapely, etc)
  90. return (self.xmin, self.ymin, self.xmax, self.ymax)
  91. else:
  92. raise NotImplementedError(f"Unknown style type {style}")
  93. def datashade(
  94. self,
  95. df: pd.DataFrame,
  96. x_dim: str = "x",
  97. y_dim: str = "y",
  98. z_dim: str = "h_range",
  99. plot_width: int = 1400,
  100. ) -> xr.DataArray:
  101. """
  102. Convenience function to quickly datashade a table of x, y, z points
  103. into a grid for visualization purposes, using a mean aggregate function
  104. """
  105. # Datashade our height values (vector points) onto a grid (raster image)
  106. # Will maintain the correct aspect ratio according to the region bounds
  107. canvas: datashader.core.Canvas = datashader.Canvas(
  108. plot_width=plot_width,
  109. plot_height=int(
  110. plot_width * ((self.ymax - self.ymin) / (self.xmax - self.xmin))
  111. ),
  112. x_range=(self.xmin, self.xmax),
  113. y_range=(self.ymin, self.ymax),
  114. )
  115. return canvas.points(
  116. source=df, x=x_dim, y=y_dim, agg=datashader.mean(column=z_dim)
  117. )
  118. def subset(
  119. self, data: xr.Dataset, x_dim: str = "x", y_dim: str = "y", drop: bool = True
  120. ) -> xr.Dataset:
  121. """
  122. Convenience function to find datapoints in an xarray.Dataset or
  123. pandas.DataFrame that fit within the bounding boxes of this region.
  124. Note that the 'drop' boolean flag is only valid for xarray.Dataset.
  125. """
  126. cond = np.logical_and(
  127. np.logical_and(data[x_dim] > self.xmin, data[x_dim] < self.xmax),
  128. np.logical_and(data[y_dim] > self.ymin, data[y_dim] < self.ymax),
  129. )
  130. try:
  131. # xarray.DataArray subset method
  132. data_subset = data.where(cond=cond, drop=drop)
  133. except TypeError:
  134. # pandas.DataFrame subset method
  135. data_subset = data.loc[cond]
  136. return data_subset
  137. def deltatime_to_utctime(
  138. dataarray: xr.DataArray,
  139. start_epoch: np.datetime64 = np.datetime64("2018-01-01T00:00:00.000000"),
  140. ) -> xr.DataArray:
  141. """
  142. Converts GPS time in nanoseconds from an epoch (default is 2018 Jan 1st)
  143. to Coordinated Universal Time (UTC).
  144. Note, does not account for leap seconds! There are none declared since the
  145. last one announced on 31/12/2016, so it should be fine for now as of 2020.
  146. """
  147. try:
  148. start_epoch = dataarray.__class__(start_epoch).squeeze()
  149. except ValueError: # Could not convert object to NumPy timedelta
  150. pass
  151. utc_time: xr.DataArray = start_epoch + dataarray
  152. return utc_time
  153. def lonlat_to_xy(
  154. longitude: xr.DataArray, latitude: xr.DataArray, epsg: int = 3031
  155. ) -> (xr.DataArray, xr.DataArray):
  156. """
  157. Reprojects longitude/latitude EPSG:4326 coordinates to x/y coordinates.
  158. Default conversion is to Antarctic Stereographic Projection EPSG:3031.
  159. See also https://pyproj4.github.io/pyproj/latest/api/proj.html#pyproj-proj
  160. Parameters
  161. ----------
  162. longitude : xr.DataArray or dask.dataframe.core.Series
  163. Input longitude coordinate(s).
  164. latitude : xr.DataArray or dask.dataframe.core.Series
  165. Input latitude coordinate(s).
  166. epsg : int
  167. EPSG integer code for the desired output coordinate system. Default is
  168. 3031 for Antarctic Polar Stereographic Projection.
  169. Returns
  170. -------
  171. x : xr.DataArray or dask.dataframe.core.Series
  172. The transformed x coordinate(s).
  173. y : xr.DataArray or dask.dataframe.core.Series
  174. The transformed y coordinate(s).
  175. """
  176. x, y = pyproj.Proj(projparams=epsg)(longitude, latitude)
  177. if hasattr(longitude, "coords"):
  178. return (
  179. xr.DataArray(data=x, coords=longitude.coords),
  180. xr.DataArray(data=y, coords=latitude.coords),
  181. )
  182. else:
  183. return x, y
  184. def point_in_polygon_gpu(
  185. points_df, # cudf.DataFrame with x and y columns of point coordinates
  186. poly_df: gpd.GeoDataFrame, # geopandas.GeoDataFrame with polygon shapes
  187. points_x_col: str = "x",
  188. points_y_col: str = "y",
  189. poly_label_col: str = None,
  190. poly_limit: int = 32,
  191. ):
  192. """
  193. Find polygon labels for each of the input points.
  194. This is a GPU accelerated version that requires cuspatial!
  195. Parameters
  196. ----------
  197. points_df : cudf.DataFrame
  198. A dataframe in GPU memory containing the x and y coordinates.
  199. points_x_col : str
  200. Name of the x coordinate column in points_df. Default is "x".
  201. points_y_col : str
  202. Name of the y coordinate column in points_df. Default is "y".
  203. poly_df : geopandas.GeoDataFrame
  204. A geodataframe in CPU memory containing polygons geometries in each
  205. row.
  206. poly_label_col : str
  207. Name of the column in poly_df that will be used to label the points,
  208. e.g. "placename". Default is to automatically use the first column
  209. unless otherwise specified.
  210. poly_limit : int
  211. Number of polygons to check in each loop of the point in polygon
  212. algorithm, workaround for a limitation in cuspatial. Default is 32
  213. (maximum), adjust to lower value (e.g. 16) if hitting MemoryError.
  214. Returns
  215. -------
  216. point_labels : cudf.Series
  217. A column of labels that indicates which polygon the points fall into.
  218. """
  219. import cudf
  220. import cuspatial
  221. poly_df_: gpd.GeoDataFrame = poly_df.reset_index()
  222. # Simply use first column of geodataframe as label if not provided (None)
  223. # See https://stackoverflow.com/a/22736342/6611055
  224. poly_label_col: str = poly_label_col or poly_df.columns[0]
  225. point_labels: cudf.Series = cudf.Series(index=points_df.index).astype(
  226. poly_df[poly_label_col].dtype
  227. )
  228. # Load CPU-based GeoDataFrame into a GPU-based cuspatial friendly format
  229. # This is a workaround until the related feature request at
  230. # https://github.com/rapidsai/cuspatial/issues/165 is implemented
  231. with tempfile.TemporaryDirectory() as tmpdir:
  232. # Save geodataframe to a temporary shapefile,
  233. # so that we can load it into GPU memory using cuspatial
  234. tmpshpfile = os.path.join(tmpdir, "poly_df.shp")
  235. poly_df_.to_file(filename=tmpshpfile, driver="ESRI Shapefile")
  236. # Load polygon_offsets, ring_offsets and polygon xy points
  237. # from temporary shapefile into GPU memory
  238. poly_offsets, poly_ring_offsets, poly_points = cuspatial.read_polygon_shapefile(
  239. filename=tmpshpfile
  240. )
  241. # Run the actual point in polygon algorithm!
  242. # Note that cuspatial's point_in_polygon function has a 32 polygon limit,
  243. # hence the for-loop code below. See also
  244. # https://github.com/rapidsai/cuspatial/blob/branch-0.15/notebooks/nyc_taxi_years_correlation.ipynb
  245. num_poly: int = len(poly_df_)
  246. point_in_poly_iter: list = list(np.arange(0, num_poly, poly_limit - 1)) + [num_poly]
  247. for i in range(len(point_in_poly_iter) - 1):
  248. start, end = point_in_poly_iter[i], point_in_poly_iter[i + 1]
  249. poly_labels: cudf.DataFrame = cuspatial.point_in_polygon(
  250. test_points_x=points_df[points_x_col],
  251. test_points_y=points_df[points_y_col],
  252. poly_offsets=poly_offsets[start:end],
  253. poly_ring_offsets=poly_ring_offsets,
  254. poly_points_x=poly_points.x,
  255. poly_points_y=poly_points.y,
  256. )
  257. # Label each point with polygon they fall in
  258. for label in poly_labels.columns:
  259. point_labels.loc[poly_labels[label]] = poly_df_.loc[label][poly_label_col]
  260. return point_labels
  261. def spatiotemporal_cube(
  262. table: pd.DataFrame,
  263. placename: str = "",
  264. x_var: str = "x",
  265. y_var: str = "y",
  266. z_var: str = "h_corr",
  267. dhdt_var: str = "dhdt_slope",
  268. spacing: int = 250,
  269. clip_limits: bool = True,
  270. cycles: list = None,
  271. projection: str = "+proj=stere +lat_0=-90 +lat_ts=-71 +lon_0=0 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs",
  272. folder: str = "",
  273. ) -> xr.Dataset:
  274. """
  275. Interpolates a time-series point cloud into an xarray.Dataset data cube.
  276. Uses `pygmt`'s blockmedian and surface algorithms to produce individual
  277. NetCDF grids, and `xarray` to stack each NetCDF grid into one dataset.
  278. Steps are as follows:
  279. 1. Create several xarray.DataArray grid surfaces from a table of points,
  280. one for each time cycle.
  281. 2. Stacked the grids along a time cycle axis into a xarray.Dataset which is
  282. a spatiotemporal data cube with 'x', 'y' and 'cycle_number' dimensions.
  283. _1__2__3_
  284. * * / / / /|
  285. * * / / / / |
  286. * * * /__/__/__/ | y
  287. * * * --> | | | | |
  288. * * * | | | | /
  289. * * |__|__|__|/ x
  290. cycle
  291. Parameters
  292. ----------
  293. table : pandas.DataFrame
  294. A table containing the ICESat-2 track data from multiple cycles. It
  295. should ideally have geographical columns called 'x', 'y', and attribute
  296. columns like 'h_corr_1', 'h_corr_2', etc for each cycle time.
  297. placename : str
  298. Optional. A descriptive placename for the data (e.g. some_ice_stream),
  299. to be used in the temporary NetCDF filename.
  300. x_var : str
  301. The x coordinate column name to use from the table data. Default is
  302. 'x'.
  303. y_var : str
  304. The y coordinate column name to use from the table data. Default is
  305. 'y'.
  306. z_var : str
  307. The z column name to use from the table data. This will be the
  308. attribute that the surface algorithm will run on. Default is 'h_corr'.
  309. spacing : float or str
  310. The spatial resolution of the resulting grid, provided as a number or
  311. as 'dx/dy' increments. This is passed on to `pygmt.blockmedian` and
  312. `pygmt.surface`. Default is 250 (metres).
  313. clip_limits : bool
  314. Whether or not to clip the output grid surface to ± 3 times the median
  315. absolute deviation of the data table's z-values. Useful for handling
  316. outlier values in the data table. Default is True (will clip).
  317. cycles : list
  318. The cycle numbers to run the gridding algorithm on, e.g. [3, 4] will
  319. use columns 'h_corr_3' and 'h_corr_4'. Default is None which will
  320. automatically determine the cycles for a given z_var.
  321. projection : str
  322. The proj4 string to store in the NetCDF output, will be passed directly
  323. to `pygmt.surface`'s J (projection) argument. Default is '+proj=stere
  324. +lat_0=-90 +lat_ts=-71 +lon_0=0 +k=1 +x_0=0 +y_0=0 +datum=WGS84
  325. +units=m +no_defs', i.e. Antarctic Polar Stereographic EPSG:3031.
  326. folder : str
  327. The folder to keep the intermediate NetCDF files in. Default is to
  328. place the files in the current working directory.
  329. Returns
  330. -------
  331. cube : xarray.Dataset
  332. A 3-dimensional data cube made of digital surfaces stacked along a time
  333. cycle axis.
  334. """
  335. import pygmt
  336. import tqdm
  337. # Determine grid's bounding box region (xmin, xmax, ymin, ymax)
  338. grid_region: np.ndarray = pygmt.info(
  339. table=table[[x_var, y_var]], spacing=f"s{spacing}"
  340. )
  341. # Automatically determine list of cycles if None is given
  342. if cycles is None:
  343. cycles: list = [
  344. int(col[len(z_var) + 1 :]) for col in table.columns if col.startswith(z_var)
  345. ]
  346. # Limit surface output to within 3 median absolute deviations of median value
  347. if clip_limits:
  348. z_values = table[[f"{z_var}_{cycle}" for cycle in cycles]]
  349. median: float = np.nanmedian(z_values)
  350. meddev: float = scipy.stats.median_abs_deviation(
  351. x=z_values, axis=None, nan_policy="omit"
  352. )
  353. limits: list = [f"l{median - 3 * meddev}", f"u{median + 3 * meddev}"]
  354. else:
  355. limits = None
  356. # Create one grid surface for each time cycle
  357. _placename = f"_{placename}" if placename else ""
  358. surface_kwargs = dict(
  359. region=grid_region,
  360. spacing=spacing,
  361. J=f'"{projection}"', # projection
  362. M="3c", # mask values 3 pixel cells outside/away from valid data
  363. T=0.35, # tension factor
  364. verbose="e", # error messages only
  365. )
  366. for cycle in tqdm.tqdm(iterable=cycles):
  367. df_trimmed = pygmt.blockmedian(
  368. table=table[[x_var, y_var, f"{z_var}_{cycle}"]].dropna(),
  369. region=grid_region,
  370. spacing=f"{spacing}+e",
  371. )
  372. outfile = f"{z_var}{_placename}_cycle_{cycle}.nc"
  373. pygmt.surface(
  374. data=df_trimmed.values, outfile=outfile, L=limits, **surface_kwargs
  375. )
  376. # Move files into new folder if requested
  377. paths: list = [f"{z_var}{_placename}_cycle_{cycle}.nc" for cycle in cycles]
  378. if folder:
  379. paths: list = [
  380. shutil.move(src=path, dst=os.path.join(folder, path)) for path in paths
  381. ]
  382. # Stack several NetCDF grids into one NetCDF along the time cycle axis
  383. dataset: xr.Dataset = xr.open_mfdataset(
  384. paths=paths,
  385. combine="nested",
  386. concat_dim=[pd.Index(data=cycles, name="cycle_number")],
  387. attrs_file=paths[-1],
  388. )
  389. # Extra data variables, calculated using point data and then interpolated to grid
  390. if dhdt_var in table.columns:
  391. # Mean elevation (<z>)
  392. df_zmean: pd.DataFrame = pygmt.blockmedian(
  393. table=pd.concat(
  394. objs=[table[[x_var, y_var]], z_values.mean(axis="columns")], axis=1
  395. ),
  396. region=grid_region,
  397. spacing=f"{spacing}+e",
  398. )
  399. dataset["z_mean"]: xr.DataArray = pygmt.surface(
  400. data=df_zmean.values, **surface_kwargs
  401. )
  402. dataset["z_mean"].attrs["long_name"] = f"Mean {z_var}"
  403. # Rate of elevation change (dhdt)
  404. df_dhdt: pd.DataFrame = pygmt.blockmedian(
  405. table=table[[x_var, y_var, "dhdt_slope"]],
  406. region=grid_region,
  407. spacing=f"{spacing}+e",
  408. )
  409. dataset["dhdt"]: xr.DataArray = pygmt.surface(
  410. data=df_dhdt.values, **surface_kwargs
  411. )
  412. dataset["dhdt"].attrs["long_name"] = f"Rate of elevation change over time"
  413. return dataset
Tip!

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

Comments

Loading...