-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcreate_metadata.py
2895 lines (2360 loc) · 175 KB
/
create_metadata.py
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import time
import pandas as pd
from glob import glob
import random
import xarray, rioxarray, rasterio
import xrspatial.curvature
import xrspatial.aspect
import argparse
from rioxarray import merge
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import oggm
from oggm import utils
import geopandas as gpd
from tqdm import tqdm
from scipy import spatial
from astropy.convolution import Gaussian2DKernel, convolve, convolve_fft
from sklearn.neighbors import KDTree
import shapely
from shapely.geometry import Point, Polygon
from shapely.ops import unary_union, nearest_points
from pyproj import Transformer, Geod
from joblib import Parallel, delayed
from create_rgi_mosaic_tanxedem import create_glacier_tile_dem_mosaic
from utils_metadata import from_lat_lon_to_utm_and_epsg, gaussian_filter_with_nans, haversine, lmax_imputer
from imputation_policies import smb_elev_functs, smb_elev_functs_hugo
pd.set_option('display.max_colwidth', None)
pd.set_option('display.width', None)
pd.set_option('display.max_rows', None)
"""
This program creates a dataframe of metadata for the points in glathida.
Time all rgis: 293m
1. add_rgi. Time: 1min. TESTED.
2. add_RGIId_and_OGGM_stats. TESTED. All rgis: 15 min
3. add_slopes_elevation. TESTED. All rgis: 70 min
- No nan can be produced here.
4. add_millan_vx_vy_ith. TESTED. All rgis: 8 min
- Points inside the glacier but close to the borders can be interpolated as nan.
- Note: method to interpolate is chosen as "nearest" to reduce as much as possible these nans.
5. add_dist_from_boder_using_geometries. TESTED. All rgis: 1h40m
- Note: if a point is inside a nunatak the distance will be set to nan.
6. add_farinotti_ith. TESTED. All rgis: 1h15m
- Points inside the glacier but close to the borders can be interpolated as nan.
- Note: method to interpolate is chosen as "nearest" to reduce as much as possible these nans.
7. add_dist_from_water. 5 mins
"""
parser = argparse.ArgumentParser()
parser.add_argument('--path_ttt_csv', type=str,default="/media/maffe/nvme/glathida/glathida-3.1.0/glathida-3.1.0/data/TTT.csv",
help="Path to TTT.csv file")
parser.add_argument('--path_ttt_rgi_csv', type=str,default="/media/maffe/nvme/glathida/glathida-3.1.0/glathida-3.1.0/data/TTT_rgi.csv",
help="Path to TTT_rgi.csv file")
parser.add_argument('--path_O1Regions_shp', type=str,default="/home/maffe/OGGM/rgi/RGIV62/00_rgi62_regions/00_rgi62_O1Regions.shp",
help="Path to OGGM's 00_rgi62_O1Regions.shp shapefiles of all 19 RGI regions")
parser.add_argument('--mosaic', type=str,default="/media/maffe/nvme/Tandem-X-EDEM/",
help="Path to DEM mosaics")
parser.add_argument('--oggm', type=str,default="/home/maffe/OGGM/", help="Path to OGGM folder")
parser.add_argument('--millan_velocity_folder', type=str,default="/media/maffe/nvme/Millan/velocity/",
help="Path to Millan velocity data")
parser.add_argument('--millan_icethickness_folder', type=str,default="/media/maffe/nvme/Millan/thickness/",
help="Path to Millan ice thickness data")
parser.add_argument('--NSIDC_icethickness_folder_Greenland', type=str,default="/media/maffe/nvme/BedMachine_v5/",
help="Path to BedMachine v5 Greenland")
parser.add_argument('--NSIDC_velocity_folder_Antarctica', type=str,default="/media/maffe/nvme/Antarctica_NSIDC/velocity/NSIDC-0754/",
help="Path to AnIS velocity data")
parser.add_argument('--NSIDC_icethickness_folder_Antarctica', type=str,default="/media/maffe/nvme/Antarctica_NSIDC/thickness/NSIDC-0756/",
help="Path to AnIS velocity data")
parser.add_argument('--farinotti_icethickness_folder', type=str,default="/media/maffe/nvme/Farinotti/composite_thickness_RGI60-all_regions/",
help="Path to Farinotti ice thickness data")
parser.add_argument('--OGGM_folder', type=str,default="/home/maffe/OGGM", help="Path to OGGM main folder")
parser.add_argument('--RACMO_folder', type=str,default="/media/maffe/nvme/racmo", help="Path to RACMO main folder")
parser.add_argument('--path_ERA5_t2m_folder', type=str,default="/media/maffe/nvme/ERA5/", help="Path to ERA5 folder")
parser.add_argument('--GSHHG_folder', type=str,default="/media/maffe/nvme/gshhg/", help="Path to GSHHG folder")
parser.add_argument('--save', type=int, default=0, help="Save final dataset or not.")
parser.add_argument('--save_outname', type=str,
default="/media/maffe/nvme/glathida/glathida-3.1.0/glathida-3.1.0/data/metadata35",
help="Saved dataframe name.")
# Setup oggm
utils.get_rgi_dir(version='62')
utils.get_rgi_intersects_dir(version='62')
args = parser.parse_args()
""" Add rgi values """
def add_rgi(glathida, path_O1_shp):
print(f'Adding RGI method...')
if ('RGI' in list(glathida)):
print('Variable RGI already in dataframe.')
return glathida
world = gpd.read_file(path_O1_shp)
glathida['RGI'] = [np.nan]*len(glathida)
lats = glathida['POINT_LAT']
lons = glathida['POINT_LON']
points = [Point(ilon, ilat) for (ilon, ilat) in zip(lons, lats)]
# Define the regions
region1a = world.loc[0]['geometry']
region1b = world.loc[1]['geometry']
region1 = shapely.ops.unary_union([region1a, region1b]) #class 'shapely.geometry.polygon.Polygon
region2 = world.loc[2]['geometry']
region3 = world.loc[3]['geometry']
region4 = world.loc[4]['geometry']
region5 = world.loc[5]['geometry']
region6 = world.loc[6]['geometry']
region7 = world.loc[7]['geometry']
region8 = world.loc[8]['geometry']
region9 = world.loc[9]['geometry']
region10a = world.loc[10]['geometry']
region10b = world.loc[11]['geometry']
region10 = shapely.ops.unary_union([region10a, region10b]) # shapely.geometry.multipolygon.MultiPolygon
region11 = world.loc[12]['geometry']
region12 = world.loc[13]['geometry']
region13 = world.loc[14]['geometry']
region14 = world.loc[15]['geometry']
region15 = world.loc[16]['geometry']
region16 = world.loc[17]['geometry']
region17 = world.loc[18]['geometry']
region18 = world.loc[19]['geometry']
region19 = world.loc[20]['geometry']
all_regions = [region1, region2, region3, region4, region5, region6, region7, region8, region9, region10,
region11, region12, region13, region14, region15, region16, region17, region18, region19]
# loop over the region geometries
for n, region in tqdm(enumerate(all_regions), total=len(all_regions), leave=True):
# mask True/False to decide whether the points are inside the region geometry
mask_points_in_region = region.contains(points)
# select only those points inside the glacier
df_poins_in_region = glathida[mask_points_in_region]
# add to dataframe
glathida.loc[df_poins_in_region.index, 'RGI'] = n+1
print(glathida['RGI'].value_counts())
print(glathida['RGI'].count()) # does not count nans
ifplot = False
if ifplot:
cmap = plt.cm.jet
# extract all colors from the .jet map
cmaplist = [cmap(i) for i in range(cmap.N)]
# create the new map
cmap = matplotlib.colors.LinearSegmentedColormap.from_list('Custom cmap', cmaplist, cmap.N)
# define the bins and normalize
num_colors = len(all_regions)
bounds = np.linspace(1, num_colors, num_colors)
norm = matplotlib.colors.BoundaryNorm(bounds, cmap.N)
# rgi boundaries colors
colors = cmap(norm(bounds))
fig, ax1 = plt.subplots()
ax1.scatter(lons, lats, s=1, c=glathida['RGI'], cmap=cmap, norm=norm)
for n, rgi_geom in enumerate(all_regions):
if (rgi_geom.geom_type == 'Polygon'):
ax1.plot(*rgi_geom.exterior.xy, c=colors[n])
elif (rgi_geom.geom_type == 'MultiPolygon'):
for geom in rgi_geom.geoms:
ax1.plot(*geom.exterior.xy, c=colors[n])
else: raise ValueError("Geom type not recognized. Check.")
plt.show()
return glathida
""" Add Slopes and Elevation """
def add_slopes_elevation(glathida, path_mosaic):
print('Running slope and elevation method...')
ts = time.time()
if (any(ele in list(glathida) for ele in ['elevation', 'slope50'])):
print('Variables slope_lat, slope_lon or elevation already in dataframe.')
return glathida
glathida['elevation'] = [np.nan] * len(glathida)
glathida['slope50'] = [np.nan] * len(glathida)
glathida['slope75'] = [np.nan] * len(glathida)
glathida['slope100'] = [np.nan] * len(glathida)
glathida['slope125'] = [np.nan] * len(glathida)
glathida['slope150'] = [np.nan] * len(glathida)
glathida['slope300'] = [np.nan] * len(glathida)
glathida['slope450'] = [np.nan] * len(glathida)
glathida['slopegfa'] = [np.nan] * len(glathida)
#glathida['slope_lat'] = [np.nan] * len(glathida)
#glathida['slope_lon'] = [np.nan] * len(glathida)
#glathida['slope_lat_gf50'] = [np.nan] * len(glathida)
#glathida['slope_lon_gf50'] = [np.nan] * len(glathida)
#glathida['slope_lat_gf75'] = [np.nan] * len(glathida)
#glathida['slope_lon_gf75'] = [np.nan] * len(glathida)
#glathida['slope_lat_gf100'] = [np.nan] * len(glathida)
#glathida['slope_lon_gf100'] = [np.nan] * len(glathida)
#glathida['slope_lat_gf125'] = [np.nan] * len(glathida)
#glathida['slope_lon_gf125'] = [np.nan] * len(glathida)
#glathida['slope_lat_gf150'] = [np.nan] * len(glathida)
#glathida['slope_lon_gf150'] = [np.nan] * len(glathida)
#glathida['slope_lat_gf300'] = [np.nan] * len(glathida)
#glathida['slope_lon_gf300'] = [np.nan] * len(glathida)
#glathida['slope_lat_gf450'] = [np.nan] * len(glathida)
#glathida['slope_lon_gf450'] = [np.nan] * len(glathida)
#glathida['slope_lat_gfa'] = [np.nan] * len(glathida)
#glathida['slope_lon_gfa'] = [np.nan] * len(glathida)
glathida['curv_50'] = [np.nan] * len(glathida)
glathida['curv_300'] = [np.nan] * len(glathida)
glathida['curv_gfa'] = [np.nan] * len(glathida)
glathida['aspect_50'] = [np.nan] * len(glathida)
glathida['aspect_300'] = [np.nan] * len(glathida)
glathida['aspect_gfa'] = [np.nan] * len(glathida)
datax = [] # just to analyse the results
datay = [] # just to analyse the results
regions = list(range(1, 20))
for rgi in regions:
glathida_rgi = glathida.loc[glathida['RGI'] == rgi]
if len(glathida_rgi)==0:
continue
ids_rgi = glathida_rgi['GlaThiDa_ID'].unique().tolist()
for id_rgi in tqdm(ids_rgi, total=len(ids_rgi), desc=f"rgi {rgi} Glathida ID", leave=True):
glathida_id = glathida_rgi.loc[glathida_rgi['GlaThiDa_ID'] == id_rgi] # collapse glathida_rgi to specific id
glathida_id = glathida_id.copy()
glathida_id['northings'] = np.nan
glathida_id['eastings'] = np.nan
glathida_id['epsg'] = np.nan
for idx in glathida_id.index:
lat = glathida_id.at[idx, 'POINT_LAT']
lon = glathida_id.at[idx, 'POINT_LON']
e, n, _, _, epsg = from_lat_lon_to_utm_and_epsg(lat, lon)
glathida_id.at[idx, 'northings'] = n
glathida_id.at[idx, 'eastings'] = e
glathida_id.at[idx, 'epsg'] = int(epsg)
# get unique epsgs
unique_epsgs = glathida_id['epsg'].unique().astype(int).tolist()
for epsg_unique in unique_epsgs:
glathida_id_epsg = glathida_id.loc[glathida_id['epsg'] == epsg_unique]
indexes_all_epsg = glathida_id_epsg.index.tolist()
lats = np.array(glathida_id_epsg['POINT_LAT'])
lons = np.array(glathida_id_epsg['POINT_LON'])
northings = np.array(glathida_id_epsg['northings'])
eastings = np.array(glathida_id_epsg['eastings'])
swlat = np.amin(lats)
swlon = np.amin(lons)
nelat = np.amax(lats)
nelon = np.amax(lons)
deltalat = np.abs(swlat - nelat)
deltalon = np.abs(swlon - nelon)
delta = max(deltalat, deltalon, 0.1)
northings_xar = xarray.DataArray(northings)
eastings_xar = xarray.DataArray(eastings)
# clip
try:
focus = create_glacier_tile_dem_mosaic(minx=swlon - delta,
miny=swlat - delta,
maxx=nelon + delta,
maxy=nelat + delta,
rgi=rgi, path_tandemx=path_mosaic)
except:
raise ValueError(f"Problems in method add_slopes_elevation for rgi {rgi} glacier_id: {id_rgi}, "
f"glacier box {swlon - delta} {swlat - delta} {nelon + delta} {nelat + delta}")
focus = focus.squeeze()
# Reproject to utm (projection distortions along boundaries converted to nans)
focus_utm = focus.rio.reproject(epsg_unique, resampling=rasterio.enums.Resampling.bilinear, nodata=-9999)
focus_utm = focus_utm.where(focus_utm != -9999, np.nan)
# clip the utm with a buffer of 2 km in both dimentions
focus_utm_clipped = focus_utm.rio.clip_box(
minx=min(eastings)-2000,
miny=min(northings)-2000,
maxx=max(eastings)+2000,
maxy=max(northings)+2000)
# Get the resolution in meters of the utm focus (resolutions in x and y should be the same!?)
res_utm_metres = focus_utm_clipped.rio.resolution()[0]
# Calculate sigma in meters for adaptive gaussian fiter
sigma_af_min, sigma_af_max = 100.0, 2000.0
try:
# Each id_rgi may come with multiple area values and also nans (probably if all points outside glacier geometries)
area_id = glathida_id_epsg['Area'].min() # km2
lmax_id = glathida_id_epsg['Lmax'].max() # m
a = 1e6*area_id/(np.pi*0.5*lmax_id)
sigma_af = int(min(max(a, sigma_af_min), sigma_af_max))
#print(area_id, lmax_id, a, value)
except Exception as e:
sigma_af = sigma_af_min
# Ensure that our value correctly in range [50.0, 2000.0]
assert sigma_af_min <= sigma_af <= sigma_af_max, f"Value {sigma_af} is not within the range [{sigma_af_min}, {sigma_af_max}]"
#print(f"Adaptive gaussian filter with sigma = {value} meters.")
# Calculate how many pixels I need for a resolution of 50, 100, 150, 300 meters
num_px_sigma_50 = max(1, round(50/res_utm_metres))
num_px_sigma_75 = max(1, round(75/res_utm_metres))
num_px_sigma_100 = max(1, round(100/res_utm_metres))
num_px_sigma_125 = max(1, round(125 / res_utm_metres))
num_px_sigma_150 = max(1, round(150/res_utm_metres))
num_px_sigma_300 = max(1, round(300/res_utm_metres))
num_px_sigma_450 = max(1, round(450/res_utm_metres))
num_px_sigma_af = max(1, round(sigma_af / res_utm_metres))
kernel50 = Gaussian2DKernel(num_px_sigma_50, x_size=4 * num_px_sigma_50 + 1, y_size=4 * num_px_sigma_50 + 1)
kernel75 = Gaussian2DKernel(num_px_sigma_75, x_size=4 * num_px_sigma_75 + 1, y_size=4 * num_px_sigma_75 + 1)
kernel100 = Gaussian2DKernel(num_px_sigma_100, x_size=4 * num_px_sigma_100 + 1, y_size=4 * num_px_sigma_100 + 1)
kernel125 = Gaussian2DKernel(num_px_sigma_125, x_size=4 * num_px_sigma_125 + 1, y_size=4 * num_px_sigma_125 + 1)
kernel150 = Gaussian2DKernel(num_px_sigma_150, x_size=4 * num_px_sigma_150 + 1, y_size=4 * num_px_sigma_150 + 1)
kernel300 = Gaussian2DKernel(num_px_sigma_300, x_size=4 * num_px_sigma_300 + 1, y_size=4 * num_px_sigma_300 + 1)
kernel450 = Gaussian2DKernel(num_px_sigma_450, x_size=4 * num_px_sigma_450 + 1, y_size=4 * num_px_sigma_450 + 1)
kernelaf = Gaussian2DKernel(num_px_sigma_af, x_size=4 * num_px_sigma_af + 1, y_size=4 * num_px_sigma_af + 1)
# New way, first slope, and then smooth it
#dz_dlat_xar, dz_dlon_xar = focus_utm_clipped.differentiate(coord='y'), focus_utm_clipped.differentiate(coord='x')
#slope = focus_utm_clipped.copy(deep=True, data=(dz_dlat_xar ** 2 + dz_dlon_xar ** 2) ** 0.5)
#slope_50 = convolve_fft(slope.values, kernel50, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
#slope_75 = convolve_fft(slope.values, kernel75, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
#slope_100 = convolve_fft(slope.values, kernel100, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
#slope_125 = convolve_fft(slope.values, kernel125, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
#slope_150 = convolve_fft(slope.values, kernel150, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
#slope_300 = convolve_fft(slope.values, kernel300, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
#slope_450 = convolve_fft(slope.values, kernel450, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
#slope_af = convolve_fft(slope.values, kernelaf, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
"""astropy"""
preserve_nans = True
focus_filter_50_utm = convolve_fft(focus_utm_clipped.values, kernel50, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
focus_filter_75_utm = convolve_fft(focus_utm_clipped.values, kernel75, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
focus_filter_100_utm = convolve_fft(focus_utm_clipped.values, kernel100, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
focus_filter_125_utm = convolve_fft(focus_utm_clipped.values, kernel125, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
focus_filter_150_utm = convolve_fft(focus_utm_clipped.values, kernel150, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
focus_filter_300_utm = convolve_fft(focus_utm_clipped.values, kernel300, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
focus_filter_450_utm = convolve_fft(focus_utm_clipped.values, kernel450, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
focus_filter_af_utm = convolve_fft(focus_utm_clipped.values, kernelaf, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
# create xarray object of filtered dem
focus_filter_xarray_50_utm = focus_utm_clipped.copy(data=focus_filter_50_utm)
focus_filter_xarray_75_utm = focus_utm_clipped.copy(data=focus_filter_75_utm)
focus_filter_xarray_100_utm = focus_utm_clipped.copy(data=focus_filter_100_utm)
focus_filter_xarray_125_utm = focus_utm_clipped.copy(data=focus_filter_125_utm)
focus_filter_xarray_150_utm = focus_utm_clipped.copy(data=focus_filter_150_utm)
focus_filter_xarray_300_utm = focus_utm_clipped.copy(data=focus_filter_300_utm)
focus_filter_xarray_450_utm = focus_utm_clipped.copy(data=focus_filter_450_utm)
focus_filter_xarray_af_utm = focus_utm_clipped.copy(data=focus_filter_af_utm)
# calculate slopes for restricted dem
# using numpy.gradient dz_dlat, dz_dlon = np.gradient(focus_utm_clipped.values, -res_utm_metres, res_utm_metres) # [m/m]
dz_dlat_xar, dz_dlon_xar = focus_utm_clipped.differentiate(coord='y'), focus_utm_clipped.differentiate(coord='x')
dz_dlat_filter_xar_50, dz_dlon_filter_xar_50 = focus_filter_xarray_50_utm.differentiate(coord='y'), focus_filter_xarray_50_utm.differentiate(coord='x')
dz_dlat_filter_xar_75, dz_dlon_filter_xar_75 = focus_filter_xarray_75_utm.differentiate(coord='y'), focus_filter_xarray_75_utm.differentiate(coord='x')
dz_dlat_filter_xar_100, dz_dlon_filter_xar_100 = focus_filter_xarray_100_utm.differentiate(coord='y'), focus_filter_xarray_100_utm.differentiate(coord='x')
dz_dlat_filter_xar_125, dz_dlon_filter_xar_125 = focus_filter_xarray_125_utm.differentiate(coord='y'), focus_filter_xarray_125_utm.differentiate(coord='x')
dz_dlat_filter_xar_150, dz_dlon_filter_xar_150 = focus_filter_xarray_150_utm.differentiate(coord='y'), focus_filter_xarray_150_utm.differentiate(coord='x')
dz_dlat_filter_xar_300, dz_dlon_filter_xar_300 = focus_filter_xarray_300_utm.differentiate(coord='y'), focus_filter_xarray_300_utm.differentiate(coord='x')
dz_dlat_filter_xar_450, dz_dlon_filter_xar_450 = focus_filter_xarray_450_utm.differentiate(coord='y'), focus_filter_xarray_450_utm.differentiate(coord='x')
dz_dlat_filter_xar_af, dz_dlon_filter_xar_af = focus_filter_xarray_af_utm.differentiate(coord='y'), focus_filter_xarray_af_utm.differentiate(coord='x')
slope_50_xar = focus_utm_clipped.copy(data=(dz_dlat_filter_xar_50 ** 2 + dz_dlon_filter_xar_50 ** 2) ** 0.5)
slope_75_xar = focus_utm_clipped.copy(data=(dz_dlat_filter_xar_75 ** 2 + dz_dlon_filter_xar_75 ** 2) ** 0.5)
slope_100_xar = focus_utm_clipped.copy(data=(dz_dlat_filter_xar_100 ** 2 + dz_dlon_filter_xar_100 ** 2) ** 0.5)
slope_125_xar = focus_utm_clipped.copy(data=(dz_dlat_filter_xar_125 ** 2 + dz_dlon_filter_xar_125 ** 2) ** 0.5)
slope_150_xar = focus_utm_clipped.copy(data=(dz_dlat_filter_xar_150 ** 2 + dz_dlon_filter_xar_150 ** 2) ** 0.5)
slope_300_xar = focus_utm_clipped.copy(data=(dz_dlat_filter_xar_300 ** 2 + dz_dlon_filter_xar_300 ** 2) ** 0.5)
slope_450_xar = focus_utm_clipped.copy(data=(dz_dlat_filter_xar_450 ** 2 + dz_dlon_filter_xar_450 ** 2) ** 0.5)
slope_af_xar = focus_utm_clipped.copy(data=(dz_dlat_filter_xar_af ** 2 + dz_dlon_filter_xar_af ** 2) ** 0.5)
# Calculate curvature and aspect using xrspatial
# Units of the curvature output (1/100) of a z-unit. Units of aspect are between [0, 360]
# Note that xrspatial using a standard 3x3 grid around pixel to calculate stuff
# Note that xrspatial produces nans at boundaries, but that should not be a problem for interpolation.
curv_50 = xrspatial.curvature(focus_filter_xarray_50_utm)
curv_300 = xrspatial.curvature(focus_filter_xarray_300_utm)
curv_af = xrspatial.curvature(focus_filter_xarray_af_utm)
aspect_50 = xrspatial.aspect(focus_filter_xarray_50_utm)
aspect_300 = xrspatial.aspect(focus_filter_xarray_300_utm)
aspect_af = xrspatial.aspect(focus_filter_xarray_af_utm)
# interpolate slope and dem
elevation_data = focus_utm_clipped.interp(y=northings_xar, x=eastings_xar, method='linear').data
slope_50_data = slope_50_xar.interp(y=northings_xar, x=eastings_xar, method='linear').data
slope_75_data = slope_75_xar.interp(y=northings_xar, x=eastings_xar, method='linear').data
slope_100_data = slope_100_xar.interp(y=northings_xar, x=eastings_xar, method='linear').data
slope_125_data = slope_125_xar.interp(y=northings_xar, x=eastings_xar, method='linear').data
slope_150_data = slope_150_xar.interp(y=northings_xar, x=eastings_xar, method='linear').data
slope_300_data = slope_300_xar.interp(y=northings_xar, x=eastings_xar, method='linear').data
slope_450_data = slope_450_xar.interp(y=northings_xar, x=eastings_xar, method='linear').data
slope_af_data = slope_af_xar.interp(y=northings_xar, x=eastings_xar, method='linear').data
#slope_lat_data = dz_dlat_xar.interp(y=northings_xar, x=eastings_xar, method='linear').data
#slope_lon_data = dz_dlon_xar.interp(y=northings_xar, x=eastings_xar, method='linear').data
#slope_lat_data_filter_50 = dz_dlat_filter_xar_50.interp(y=northings_xar, x=eastings_xar, method='linear').data
#slope_lon_data_filter_50 = dz_dlon_filter_xar_50.interp(y=northings_xar, x=eastings_xar, method='linear').data
#slope_lat_data_filter_75 = dz_dlat_filter_xar_75.interp(y=northings_xar, x=eastings_xar, method='linear').data
#slope_lon_data_filter_75 = dz_dlon_filter_xar_75.interp(y=northings_xar, x=eastings_xar, method='linear').data
#slope_lat_data_filter_100 = dz_dlat_filter_xar_100.interp(y=northings_xar, x=eastings_xar, method='linear').data
#slope_lon_data_filter_100 = dz_dlon_filter_xar_100.interp(y=northings_xar, x=eastings_xar, method='linear').data
#slope_lat_data_filter_125 = dz_dlat_filter_xar_125.interp(y=northings_xar, x=eastings_xar, method='linear').data
#slope_lon_data_filter_125 = dz_dlon_filter_xar_125.interp(y=northings_xar, x=eastings_xar, method='linear').data
#slope_lat_data_filter_150 = dz_dlat_filter_xar_150.interp(y=northings_xar, x=eastings_xar, method='linear').data
#slope_lon_data_filter_150 = dz_dlon_filter_xar_150.interp(y=northings_xar, x=eastings_xar, method='linear').data
#slope_lat_data_filter_300 = dz_dlat_filter_xar_300.interp(y=northings_xar, x=eastings_xar, method='linear').data
#slope_lon_data_filter_300 = dz_dlon_filter_xar_300.interp(y=northings_xar, x=eastings_xar, method='linear').data
#slope_lat_data_filter_450 = dz_dlat_filter_xar_450.interp(y=northings_xar, x=eastings_xar, method='linear').data
#slope_lon_data_filter_450 = dz_dlon_filter_xar_450.interp(y=northings_xar, x=eastings_xar, method='linear').data
#slope_lat_data_filter_af = dz_dlat_filter_xar_af.interp(y=northings_xar, x=eastings_xar, method='linear').data
#slope_lon_data_filter_af = dz_dlon_filter_xar_af.interp(y=northings_xar, x=eastings_xar, method='linear').data
curv_data_50 = curv_50.interp(y=northings_xar, x=eastings_xar, method='linear').data
curv_data_300 = curv_300.interp(y=northings_xar, x=eastings_xar, method='linear').data
curv_data_af = curv_af.interp(y=northings_xar, x=eastings_xar, method='linear').data
aspect_data_50 = aspect_50.interp(y=northings_xar, x=eastings_xar, method='linear').data
aspect_data_300 = aspect_300.interp(y=northings_xar, x=eastings_xar, method='linear').data
aspect_data_af = aspect_af.interp(y=northings_xar, x=eastings_xar, method='linear').data
# check if any nan in the interpolate data
contains_nan = any(np.isnan(arr).any() for arr in [slope_50_data, slope_75_data, slope_100_data,
slope_125_data, slope_150_data, slope_300_data,
slope_450_data, slope_af_data,
curv_data_50, curv_data_300, curv_data_af,
aspect_data_50, aspect_data_300, aspect_data_af])
#contains_nan = any(np.isnan(arr).any() for arr in [slope_lon_data, slope_lat_data,
# slope_lon_data_filter_50, slope_lat_data_filter_50,
# slope_lon_data_filter_75, slope_lat_data_filter_75,
# slope_lon_data_filter_100, slope_lat_data_filter_100,
# slope_lon_data_filter_125, slope_lat_data_filter_125,
# slope_lon_data_filter_150, slope_lat_data_filter_150,
# slope_lon_data_filter_300, slope_lat_data_filter_300,
# slope_lon_data_filter_450, slope_lat_data_filter_450,
# slope_lon_data_filter_af, slope_lat_data_filter_af,
# curv_data_50, curv_data_300, curv_data_af,
# aspect_data_50, aspect_data_300, aspect_data_af])
if contains_nan:
raise ValueError(f"Nan detected in elevation/slope calc. Check")
# other checks
assert slope_50_data.shape == slope_150_data.shape == elevation_data.shape, "Different shapes, something wrong!"
assert len(slope_50_data) == len(indexes_all_epsg), "Different shapes, something wrong!"
#assert slope_lat_data.shape == slope_lon_data.shape == elevation_data.shape, "Different shapes, something wrong!"
#assert slope_lat_data_filter_150.shape == slope_lon_data_filter_150.shape == elevation_data.shape, "Different shapes, something wrong!"
#assert len(slope_lat_data) == len(indexes_all_epsg), "Different shapes, something wrong!"
assert curv_data_50.shape == curv_data_300.shape == curv_data_af.shape, "Different shapes, something wrong!"
assert aspect_data_50.shape == aspect_data_300.shape == aspect_data_af.shape, "Different shapes, something wrong!"
# write to dataframe
glathida.loc[indexes_all_epsg, 'elevation'] = elevation_data
glathida.loc[indexes_all_epsg, 'slope50'] = slope_50_data
glathida.loc[indexes_all_epsg, 'slope75'] = slope_75_data
glathida.loc[indexes_all_epsg, 'slope100'] = slope_100_data
glathida.loc[indexes_all_epsg, 'slope125'] = slope_125_data
glathida.loc[indexes_all_epsg, 'slope150'] = slope_150_data
glathida.loc[indexes_all_epsg, 'slope300'] = slope_300_data
glathida.loc[indexes_all_epsg, 'slope450'] = slope_450_data
glathida.loc[indexes_all_epsg, 'slopegfa'] = slope_af_data
#glathida.loc[indexes_all_epsg, 'slope_lat'] = slope_lat_data
#glathida.loc[indexes_all_epsg, 'slope_lon'] = slope_lon_data
#glathida.loc[indexes_all_epsg, 'slope_lat_gf50'] = slope_lat_data_filter_50
#glathida.loc[indexes_all_epsg, 'slope_lon_gf50'] = slope_lon_data_filter_50
#glathida.loc[indexes_all_epsg, 'slope_lat_gf75'] = slope_lat_data_filter_75
#glathida.loc[indexes_all_epsg, 'slope_lon_gf75'] = slope_lon_data_filter_75
#glathida.loc[indexes_all_epsg, 'slope_lat_gf100'] = slope_lat_data_filter_100
#glathida.loc[indexes_all_epsg, 'slope_lon_gf100'] = slope_lon_data_filter_100
#glathida.loc[indexes_all_epsg, 'slope_lat_gf125'] = slope_lat_data_filter_125
#glathida.loc[indexes_all_epsg, 'slope_lon_gf125'] = slope_lon_data_filter_125
#glathida.loc[indexes_all_epsg, 'slope_lat_gf150'] = slope_lat_data_filter_150
#glathida.loc[indexes_all_epsg, 'slope_lon_gf150'] = slope_lon_data_filter_150
#glathida.loc[indexes_all_epsg, 'slope_lat_gf300'] = slope_lat_data_filter_300
#glathida.loc[indexes_all_epsg, 'slope_lon_gf300'] = slope_lon_data_filter_300
#glathida.loc[indexes_all_epsg, 'slope_lat_gf450'] = slope_lat_data_filter_450
#glathida.loc[indexes_all_epsg, 'slope_lon_gf450'] = slope_lon_data_filter_450
#glathida.loc[indexes_all_epsg, 'slope_lat_gfa'] = slope_lat_data_filter_af
#glathida.loc[indexes_all_epsg, 'slope_lon_gfa'] = slope_lon_data_filter_af
glathida.loc[indexes_all_epsg, 'curv_50'] = curv_data_50
glathida.loc[indexes_all_epsg, 'curv_300'] = curv_data_300
glathida.loc[indexes_all_epsg, 'curv_gfa'] = curv_data_af
glathida.loc[indexes_all_epsg, 'aspect_50'] = aspect_data_50
glathida.loc[indexes_all_epsg, 'aspect_300'] = aspect_data_300
glathida.loc[indexes_all_epsg, 'aspect_gfa'] = aspect_data_af
plot_curvature = False
if plot_curvature:
fig, (ax1, ax2, ax3, ax4, ax5, ax6) = plt.subplots(1, 6)
im1 = focus_filter_xarray_50_utm.plot(ax=ax1, cmap='viridis')
im2 = focus_filter_xarray_300_utm.plot(ax=ax2, cmap='viridis')
im3 = curv_50.plot(ax=ax3, cmap='viridis')
im4 = curv_300.plot(ax=ax4, cmap='viridis')
im5 = aspect_50.plot(ax=ax5, cmap='viridis')
im6 = aspect_300.plot(ax=ax6, cmap='viridis')
plt.show()
plot_utm = False
if plot_utm:
fig, ((ax0, ax1, ax2, ax3), (ax01, ax4, ax5, ax6)) = plt.subplots(2, 4, figsize=(8, 5))
im0 =focus.plot(ax=ax0, cmap='viridis', )
im01 =focus_utm.plot(ax=ax01, cmap='viridis', )
s01 = ax01.scatter(x=eastings, y=northings, s=15, c='k')
im1 = focus_utm_clipped.plot(ax=ax1, cmap='viridis', vmin=focus_utm_clipped.min(),vmax=focus_utm_clipped.max())
s1 = ax1.scatter(x=eastings, y=northings, s=15, c=elevation_data, ec=(0, 0, 0, 0.1), cmap='viridis',
vmin=focus_utm_clipped.min(), vmax=focus_utm_clipped.max(), zorder=1)
im2 = dz_dlat_xar.plot(ax=ax2, cmap='viridis', vmin=dz_dlat_xar.min(), vmax=dz_dlat_xar.max())
s2 = ax2.scatter(x=eastings, y=northings, s=15, c=slope_lat_data, ec=(0, 0, 0, 0.1), cmap='viridis',
vmin=dz_dlat_xar.min(), vmax=dz_dlat_xar.max(), zorder=1)
im3 = dz_dlon_xar.plot(ax=ax3, cmap='viridis', vmin=dz_dlon_xar.min(), vmax=dz_dlon_xar.max())
s3 = ax3.scatter(x=eastings, y=northings, s=15, c=slope_lon_data, ec=(0, 0, 0, 0.1), cmap='viridis',
vmin=dz_dlon_xar.min(), vmax=dz_dlon_xar.max(), zorder=1)
im4 = focus_filter_xarray_300_utm.plot(ax=ax4, cmap='viridis', )
s4 = ax4.scatter(x=eastings, y=northings, s=15, c='k')
im5 = dz_dlat_filter_xar_300.plot(ax=ax5, cmap='viridis', vmin=dz_dlat_filter_xar_300.min(), vmax=dz_dlat_filter_xar_300.max())
s5 = ax5.scatter(x=eastings, y=northings, s=15, c=slope_lat_data_filter_300, ec=(0, 0, 0, 0.1),
cmap='viridis', vmin=dz_dlat_filter_xar_300.min(), vmax=dz_dlat_filter_xar_300.max(), zorder=1)
im6 = dz_dlon_filter_xar_300.plot(ax=ax6, cmap='viridis', vmin=dz_dlon_filter_xar_300.min(), vmax=dz_dlon_filter_xar_300.max())
s6 = ax6.scatter(x=eastings, y=northings, s=15, c=slope_lon_data_filter_300, ec=(0, 0, 0, 0.1),
cmap='viridis', vmin=dz_dlon_filter_xar_300.min(), vmax=dz_dlon_filter_xar_300.max(), zorder=1)
plt.show()
print(f"Slopes and elevation done in {(time.time()-ts)/60} min")
return glathida
"""Add surface mass balance"""
def add_smb(glathida, path_RACMO_folder):
if ('smb' in list(glathida)):
print('Variable smb already in dataframe.')
return glathida
glathida['smb'] = [np.nan] * len(glathida)
# Greenland and Antarctica smb using racmo
for rgi in [5, 19,]:
glathida_rgi = glathida.loc[glathida['RGI'] == rgi]
indexes_rgi = glathida_rgi.index.tolist()
if len(glathida_rgi) == 0:
continue
# Import our racmo smoothed (and time averaged)
if rgi==5:
racmo_file = "/greenland_racmo2.3p2/smb_greenland_mean_1961_1990_RACMO23p2_gf.nc"
elif rgi==19:
racmo_file = "/antarctica_racmo2.3p2/2km/smb_antarctica_mean_1979_2021_RACMO23p2_gf.nc"
else: raise ValueError('rgi value for RACMO smb calculation not recognized')
# Units should be in both regions mm w.e./yr = kg/m2yr
racmo = rioxarray.open_rasterio(f'{path_RACMO_folder}{racmo_file}')
# Get rgi measurement coordinates
lats = glathida_rgi['POINT_LAT']
lons = glathida_rgi['POINT_LON']
eastings, northings = (Transformer.from_crs("EPSG:4326", racmo.rio.crs)
.transform(glathida_rgi['POINT_LAT'], glathida_rgi['POINT_LON']))
# Convert coordinates to racmo projection EPSG:3413 (racmo Greenland) or EPSG:3031 (racmo Antarctica)
eastings_ar = xarray.DataArray(eastings)
northings_ar = xarray.DataArray(northings)
# Interpolate racmo onto the points
smb_data = racmo.interp(y=northings_ar, x=eastings_ar, method='linear').data.squeeze()
# Push to dataframe
glathida.loc[indexes_rgi, 'smb'] = smb_data
#print(rgi, np.nanmean(smb_data))
plot_smb = False
if plot_smb:
vmin, vmax = -700, 4000#racmo.min(), racmo.max()
fig, (ax1, ax2) = plt.subplots(1,2)
racmo.plot(ax=ax1, cmap='hsv', vmin=vmin, vmax=vmax)
ax1.scatter(x=eastings, y=northings, c='k', s=20)
racmo.plot(ax=ax2, cmap='hsv', vmin=vmin, vmax=vmax)
ax2.scatter(x=eastings, y=northings, c=smb_data, ec=(0, 0, 0, 0.3), cmap='hsv', vmin=vmin, vmax=vmax, s=20)
plt.show()
# For regions outside Greenland and Antarctica I use another method
regions = [1,2,3,4,6,7,8,9,10,11,12,13,14,15,16,17,18]
for rgi in regions:
glathida_rgi = glathida.loc[glathida['RGI'] == rgi]
if len(glathida_rgi) == 0:
continue
indexes_rgi = glathida_rgi.index.tolist()
lats = glathida_rgi['POINT_LAT']
lons = glathida_rgi['POINT_LON']
elevation_data = glathida_rgi['elevation']
# MERRA-GRACE smb elevation relation (BAD IDEA)
#smb_data = []
#for (lat, lon, elev) in zip(lats, lons, elevation_data):
#smb = smb_elev_functs(rgi, elev, lat, lon) # kg/m2s
#smb *= 31536000 # kg/m2yr
#print(rgi, lat, lon, smb)
#smb_data.append(smb)
#smb_data = np.array(smb_data)
# Surface mass balance loop with Hugonnet-elevation relation
m_hugo = smb_elev_functs_hugo(rgi=rgi).loc[rgi, 'm']
q_hugo = smb_elev_functs_hugo(rgi=rgi).loc[rgi, 'q']
smb_data_hugo = m_hugo * elevation_data + q_hugo # m w.e./yr = (1000kg/m2yr)
smb_data_hugo *= 1.e3 # mm w.e./yr = kg/m2yr
smb_data = np.array(smb_data_hugo)
glathida.loc[indexes_rgi, 'smb'] = smb_data
#print(rgi, m_hugo, q_hugo, np.mean(smb_data))
return glathida
"""Add Millan's velocity vx, vy, ith"""
def add_millan_vx_vy_ith(glathida, path_millan_velocity, path_millan_icethickness):
print('Adding Millan velocity and ice thickness method...')
tm = time.time()
if (any(ele in list(glathida) for ele in ['ith_m', 'v50', 'v100'])):
print('Variable already in dataframe.')
return glathida
glathida['ith_m'] = [np.nan] * len(glathida)
glathida['v50'] = [np.nan] * len(glathida)
glathida['v100'] = [np.nan] * len(glathida)
glathida['v150'] = [np.nan] * len(glathida)
glathida['v300'] = [np.nan] * len(glathida)
glathida['v450'] = [np.nan] * len(glathida)
glathida['vgfa'] = [np.nan] * len(glathida)
#glathida['vx'] = [np.nan] * len(glathida)
#glathida['vy'] = [np.nan] * len(glathida)
#glathida['vx_gf50'] = [np.nan] * len(glathida)
#glathida['vx_gf100'] = [np.nan] * len(glathida)
#glathida['vx_gf150'] = [np.nan] * len(glathida)
#glathida['vx_gf300'] = [np.nan] * len(glathida)
#glathida['vx_gf450'] = [np.nan] * len(glathida)
#glathida['vx_gfa'] = [np.nan] * len(glathida)
#glathida['vy_gf50'] = [np.nan] * len(glathida)
#glathida['vy_gf100'] = [np.nan] * len(glathida)
#glathida['vy_gf150'] = [np.nan] * len(glathida)
#glathida['vy_gf300'] = [np.nan] * len(glathida)
#glathida['vy_gf450'] = [np.nan] * len(glathida)
#glathida['vy_gfa'] = [np.nan] * len(glathida)
#glathida['dvx_dx'] = [np.nan] * len(glathida)
#glathida['dvx_dy'] = [np.nan] * len(glathida)
#glathida['dvy_dx'] = [np.nan] * len(glathida)
#glathida['dvy_dy'] = [np.nan] * len(glathida)
# I believe in rgi 19 I do not contemplate Millan tiles since GlaThiDa GT data are not present outside the ice sheet.
for rgi in [19,]:
glathida_rgi = glathida.loc[glathida['RGI'] == rgi] # glathida to specific rgi
if len(glathida_rgi) == 0:
continue
tqdm.write(f'rgi: {rgi}, Total points: {len(glathida_rgi)}')
# get NSIDC
file_vel_NSIDC = f"{args.NSIDC_velocity_folder_Antarctica}antarctic_ice_vel_phase_map_v01.nc"
mosaic_vel_NSIDC = rioxarray.open_rasterio(file_vel_NSIDC, masked=False)
vx_NSIDC = mosaic_vel_NSIDC.VX
vy_NSIDC = mosaic_vel_NSIDC.VY
assert vx_NSIDC.rio.bounds() == vy_NSIDC.rio.bounds()
assert vx_NSIDC.rio.crs == vy_NSIDC.rio.crs
ids_rgi = glathida_rgi['GlaThiDa_ID'].unique().tolist() # unique IDs
for i, id_rgi in tqdm(enumerate(ids_rgi), total=len(ids_rgi), desc=f"rgi {rgi} Glathida ID", leave=True):
glathida_id = glathida_rgi.loc[glathida_rgi['GlaThiDa_ID'] == id_rgi] # collapse glathida_rgi to specific id
indexes_id = glathida_id.index.tolist()
eastings_id, northings_id = (Transformer.from_crs("EPSG:4326", vx_NSIDC.rio.crs)
.transform(glathida_id['POINT_LAT'], glathida_id['POINT_LON']))
eastings_rgi_id_ar = xarray.DataArray(eastings_id)
northings_rgi_id_ar = xarray.DataArray(northings_id)
minE, maxE = min(eastings_id), max(eastings_id)
minN, maxN = min(northings_id), max(northings_id)
#print(i, len(glathida_id), minE, maxE, minN, maxN, vx_NSIDC.rio.bounds())
ris_metre_nsidc = vx_NSIDC.rio.resolution()[0] #450m
eps = 15000
try:
vx_NSIDC_focus = vx_NSIDC.rio.clip_box(minx=minE - eps, miny=minN - eps, maxx=maxE + eps, maxy=maxN + eps)
vy_NSIDC_focus = vy_NSIDC.rio.clip_box(minx=minE - eps, miny=minN - eps, maxx=maxE + eps, maxy=maxN + eps)
except:
tqdm.write(f'{i} No NSIDC data for rgi {rgi} GlaThiDa_ID {id_rgi}')
continue
# Condition 1. Either v is .rio.nodata or it is zero or it is nan
cond0 = np.all(vx_NSIDC_focus.values == 0)
condnodata = np.all(np.abs(vx_NSIDC_focus.values - vx_NSIDC_focus.rio.nodata) < 1.e-6)
condnan = np.all(np.isnan(vx_NSIDC_focus.values))
all_zero_or_nodata = cond0 or condnodata or condnan
if all_zero_or_nodata:
tqdm.write(f'{i} Cond 1 triggered - No NSIDC vel data for rgi {rgi} GlaThiDa_ID {id_rgi}')
continue
# Condition no. 2. A fast and quick interpolation to see if points intercepts a valid raster region
vals_fast_interp = vx_NSIDC_focus.interp(y=xarray.DataArray(northings_id),
x=xarray.DataArray(eastings_id),
method='nearest').data
cond_valid_fast_interp = (np.isnan(vals_fast_interp).all() or
np.all(np.abs(vals_fast_interp - vx_NSIDC_focus.rio.nodata) < 1.e-6))
if cond_valid_fast_interp:
#fig, ax = plt.subplots()
#vx_NSIDC_focus.values[vx_NSIDC_focus.values == vx_NSIDC_focus.rio.nodata] = np.nan
#im = vx_NSIDC_focus.plot(ax=ax, cmap='binary', zorder=0)
#ax.scatter(x=eastings_id, y=northings_id, s=10, c='r', zorder=1)
#plt.show()
tqdm.write(f'{i} Cond 2 triggered - No NSIDC vel data for rgi {rgi} GlaThiDa_ID {id_rgi} around'
f' {glathida_id['POINT_LAT'].mean():.2f} lat {glathida_id['POINT_LON'].mean():.2f} lon')
continue
# At this stage we should have a good interpolation
#vx_NSIDC_focus.values[vx_NSIDC_focus.values == vx_NSIDC_focus.rio.nodata] = np.nan
#vy_NSIDC_focus.values[vy_NSIDC_focus.values == vy_NSIDC_focus.rio.nodata] = np.nan
vx_NSIDC_focus.values = np.where((vx_NSIDC_focus.values == vx_NSIDC_focus.rio.nodata) | np.isinf(vx_NSIDC_focus.values),
np.nan, vx_NSIDC_focus.values)
vy_NSIDC_focus.values = np.where((vy_NSIDC_focus.values == vy_NSIDC_focus.rio.nodata) | np.isinf(vy_NSIDC_focus.values),
np.nan, vy_NSIDC_focus.values)
vx_NSIDC_focus.rio.write_nodata(np.nan, inplace=True)
vy_NSIDC_focus.rio.write_nodata(np.nan, inplace=True)
assert vx_NSIDC_focus.rio.bounds() == vy_NSIDC_focus.rio.bounds(), "NSIDC vx, vy bounds not the same"
# Note: for rgi 19 we do not interpolate NSIDC to remove nans.
tile_vx = vx_NSIDC_focus.squeeze()
tile_vy = vy_NSIDC_focus.squeeze()
# Calculate sigma in meters for adaptive gaussian fiter
sigma_af_min, sigma_af_max = 100.0, 2000.0
try:
area_id = glathida_rgi.loc[indexes_id, 'Area'].min()
lmax_id = glathida_rgi.loc[indexes_id, 'Lmax'].max()
# print('area', area_id, 'lmax', lmax_id)
# print(lats_rgi_k_id.min(), lats_rgi_k_id.max(), lons_rgi_k_id.min(), lons_rgi_k_id.max(), area_id)
# Each id_rgi may come with multiple area values and also nans (probably if all points outside glacier geometries)
# area_id = glathida_rgi_tile_id['Area'].min() # km2
# lmax_id = glathida_rgi_tile_id['Lmax'].max() # m
a = 1e6 * area_id / (np.pi * 0.5 * lmax_id)
sigma_af = int(min(max(a, sigma_af_min), sigma_af_max))
#print(area_id, lmax_id, a)
except Exception as e:
sigma_af = sigma_af_min
assert sigma_af_min <= sigma_af <= sigma_af_max, f"Value {sigma_af} is not within the range [{sigma_af_min}, {sigma_af_max}]"
# Calculate how many pixels I need for a resolution of xx
# Since NDIDC has res of 450 m, num pixels will can be very small.
num_px_sigma_50 = max(1, round(50 / ris_metre_nsidc))
num_px_sigma_100 = max(1, round(100 / ris_metre_nsidc))
num_px_sigma_150 = max(1, round(150 / ris_metre_nsidc))
num_px_sigma_300 = max(1, round(300 / ris_metre_nsidc))
num_px_sigma_450 = max(1, round(450 / ris_metre_nsidc))
num_px_sigma_af = max(1, round(sigma_af / ris_metre_nsidc))
kernel50 = Gaussian2DKernel(num_px_sigma_50, x_size=4 * num_px_sigma_50 + 1, y_size=4 * num_px_sigma_50 + 1)
kernel100 = Gaussian2DKernel(num_px_sigma_100, x_size=4 * num_px_sigma_100 + 1, y_size=4 * num_px_sigma_100 + 1)
kernel150 = Gaussian2DKernel(num_px_sigma_150, x_size=4 * num_px_sigma_150 + 1, y_size=4 * num_px_sigma_150 + 1)
kernel300 = Gaussian2DKernel(num_px_sigma_300, x_size=4 * num_px_sigma_300 + 1, y_size=4 * num_px_sigma_300 + 1)
kernel450 = Gaussian2DKernel(num_px_sigma_450, x_size=4 * num_px_sigma_450 + 1, y_size=4 * num_px_sigma_450 + 1)
kernelaf = Gaussian2DKernel(num_px_sigma_af, x_size=4 * num_px_sigma_af + 1, y_size=4 * num_px_sigma_af + 1)
tile_v = tile_vx.copy(deep=True, data=(tile_vx ** 2 + tile_vy ** 2) ** 0.5)
# A check to see if velocity modules is as expected
assert float(tile_v.sum()) > 0, "tile v is not as expected."
'''astropy'''
preserve_nans = True
focus_filter_v50 = convolve_fft(tile_v.values, kernel50, nan_treatment='interpolate',
preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
focus_filter_v100 = convolve_fft(tile_v.values, kernel100, nan_treatment='interpolate',
preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
focus_filter_v150 = convolve_fft(tile_v.values, kernel150, nan_treatment='interpolate',
preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
focus_filter_v300 = convolve_fft(tile_v.values, kernel300, nan_treatment='interpolate',
preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
focus_filter_v450 = convolve_fft(tile_v.values, kernel450, nan_treatment='interpolate',
preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
focus_filter_af = convolve_fft(tile_v.values, kernelaf, nan_treatment='interpolate',
preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
#focus_filter_vx_50 = convolve_fft(tile_vx.values.squeeze(), kernel50, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
#focus_filter_vx_100 = convolve_fft(tile_vx.values.squeeze(), kernel100, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
#focus_filter_vx_150 = convolve_fft(tile_vx.values.squeeze(), kernel150, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
#focus_filter_vx_300 = convolve_fft(tile_vx.values.squeeze(), kernel300, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
#focus_filter_vx_450 = convolve_fft(tile_vx.values.squeeze(), kernel450, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
#focus_filter_vx_af = convolve_fft(tile_vx.values.squeeze(), kernelaf, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
#focus_filter_vy_50 = convolve_fft(tile_vy.values.squeeze(), kernel50, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
#focus_filter_vy_100 = convolve_fft(tile_vy.values.squeeze(), kernel100, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
#focus_filter_vy_150 = convolve_fft(tile_vy.values.squeeze(), kernel150, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
#focus_filter_vy_300 = convolve_fft(tile_vy.values.squeeze(), kernel300, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
#focus_filter_vy_450 = convolve_fft(tile_vy.values.squeeze(), kernel450, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
#focus_filter_vy_af = convolve_fft(tile_vy.values.squeeze(), kernelaf, nan_treatment='interpolate', preserve_nan=preserve_nans, boundary='fill', fill_value=np.nan)
'''old method with scipy'''
'''
# Apply filter to velocities
focus_filter_vx_50 = gaussian_filter_with_nans(U=tile_vx.values, sigma=num_px_sigma_50, trunc=3.0)
focus_filter_vx_100 = gaussian_filter_with_nans(U=tile_vx.values, sigma=num_px_sigma_100, trunc=3.0)
focus_filter_vx_150 = gaussian_filter_with_nans(U=tile_vx.values, sigma=num_px_sigma_150, trunc=3.0)
focus_filter_vx_300 = gaussian_filter_with_nans(U=tile_vx.values, sigma=num_px_sigma_300, trunc=3.0)
focus_filter_vx_450 = gaussian_filter_with_nans(U=tile_vx.values, sigma=num_px_sigma_450, trunc=3.0)
focus_filter_vx_af = gaussian_filter_with_nans(U=tile_vx.values, sigma=num_px_sigma_af, trunc=3.0)
focus_filter_vy_50 = gaussian_filter_with_nans(U=tile_vy.values, sigma=num_px_sigma_50, trunc=3.0)
focus_filter_vy_100 = gaussian_filter_with_nans(U=tile_vy.values, sigma=num_px_sigma_100, trunc=3.0)
focus_filter_vy_150 = gaussian_filter_with_nans(U=tile_vy.values, sigma=num_px_sigma_150, trunc=3.0)
focus_filter_vy_300 = gaussian_filter_with_nans(U=tile_vy.values, sigma=num_px_sigma_300, trunc=3.0)
focus_filter_vy_450 = gaussian_filter_with_nans(U=tile_vy.values, sigma=num_px_sigma_450, trunc=3.0)
focus_filter_vy_af = gaussian_filter_with_nans(U=tile_vy.values, sigma=num_px_sigma_af, trunc=3.0)
# Mask back the filtered arrays
focus_filter_vx_50 = np.where(np.isnan(tile_vx.values), np.nan, focus_filter_vx_50)
focus_filter_vx_100 = np.where(np.isnan(tile_vx.values), np.nan, focus_filter_vx_100)
focus_filter_vx_150 = np.where(np.isnan(tile_vx.values), np.nan, focus_filter_vx_150)
focus_filter_vx_300 = np.where(np.isnan(tile_vx.values), np.nan, focus_filter_vx_300)
focus_filter_vx_450 = np.where(np.isnan(tile_vx.values), np.nan, focus_filter_vx_450)
focus_filter_vx_af = np.where(np.isnan(tile_vx.values), np.nan, focus_filter_vx_af)
focus_filter_vy_50 = np.where(np.isnan(tile_vy.values), np.nan, focus_filter_vy_50)
focus_filter_vy_100 = np.where(np.isnan(tile_vy.values), np.nan, focus_filter_vy_100)
focus_filter_vy_150 = np.where(np.isnan(tile_vy.values), np.nan, focus_filter_vy_150)
focus_filter_vy_300 = np.where(np.isnan(tile_vy.values), np.nan, focus_filter_vy_300)
focus_filter_vy_450 = np.where(np.isnan(tile_vy.values), np.nan, focus_filter_vy_450)
focus_filter_vy_af = np.where(np.isnan(tile_vy.values), np.nan, focus_filter_vy_af)
'''
# create xarrays of filtered velocities
focus_filter_v50_ar = tile_v.copy(deep=True, data=focus_filter_v50)
focus_filter_v100_ar = tile_v.copy(deep=True, data=focus_filter_v100)
focus_filter_v150_ar = tile_v.copy(deep=True, data=focus_filter_v150)
focus_filter_v300_ar = tile_v.copy(deep=True, data=focus_filter_v300)
focus_filter_v450_ar = tile_v.copy(deep=True, data=focus_filter_v450)
focus_filter_vfa_ar = tile_v.copy(deep=True, data=focus_filter_af)
#focus_filter_vx_50_ar = tile_vx.copy(deep=True, data=focus_filter_vx_50)
#focus_filter_vx_100_ar = tile_vx.copy(deep=True, data=focus_filter_vx_100)
#focus_filter_vx_150_ar = tile_vx.copy(deep=True, data=focus_filter_vx_150)
#focus_filter_vx_300_ar = tile_vx.copy(deep=True, data=focus_filter_vx_300)
#focus_filter_vx_450_ar = tile_vx.copy(deep=True, data=focus_filter_vx_450)
#focus_filter_vx_af_ar = tile_vx.copy(deep=True, data=focus_filter_vx_af)
#focus_filter_vy_50_ar = tile_vy.copy(deep=True, data=focus_filter_vy_50)
#focus_filter_vy_100_ar = tile_vy.copy(deep=True, data=focus_filter_vy_100)
#focus_filter_vy_150_ar = tile_vy.copy(deep=True, data=focus_filter_vy_150)
#focus_filter_vy_300_ar = tile_vy.copy(deep=True, data=focus_filter_vy_300)
#focus_filter_vy_450_ar = tile_vy.copy(deep=True, data=focus_filter_vy_450)
#focus_filter_vy_af_ar = tile_vy.copy(deep=True, data=focus_filter_vy_af)
# Calculate the velocity gradients
#dvx_dx_ar, dvx_dy_ar = focus_filter_vx_300_ar.differentiate(
# coord='x'), focus_filter_vx_300_ar.differentiate(coord='y')
#dvy_dx_ar, dvy_dy_ar = focus_filter_vy_300_ar.differentiate(
# coord='x'), focus_filter_vy_300_ar.differentiate(coord='y')
# Interpolate (note: nans can be produced near boundaries)
v_data = tile_v.interp(y=northings_rgi_id_ar, x=eastings_rgi_id_ar, method="nearest").data
v_filter_50_data = focus_filter_v50_ar.interp(y=northings_rgi_id_ar, x=eastings_rgi_id_ar, method='nearest').data
v_filter_100_data = focus_filter_v100_ar.interp(y=northings_rgi_id_ar, x=eastings_rgi_id_ar, method='nearest').data
v_filter_150_data = focus_filter_v150_ar.interp(y=northings_rgi_id_ar, x=eastings_rgi_id_ar, method='nearest').data
v_filter_300_data = focus_filter_v300_ar.interp(y=northings_rgi_id_ar, x=eastings_rgi_id_ar, method='nearest').data
v_filter_450_data = focus_filter_v450_ar.interp(y=northings_rgi_id_ar, x=eastings_rgi_id_ar, method='nearest').data
v_filter_af_data = focus_filter_vfa_ar.interp(y=northings_rgi_id_ar, x=eastings_rgi_id_ar, method='nearest').data
'''
vx_data = tile_vx.interp(y=northings_rgi_id_ar, x=eastings_rgi_id_ar, method="nearest").data
vy_data = tile_vy.interp(y=northings_rgi_id_ar, x=eastings_rgi_id_ar, method="nearest").data
vx_filter_50_data = focus_filter_vx_50_ar.interp(y=northings_rgi_id_ar, x=eastings_rgi_id_ar,
method='nearest').data
vx_filter_100_data = focus_filter_vx_100_ar.interp(y=northings_rgi_id_ar, x=eastings_rgi_id_ar,
method='nearest').data
vx_filter_150_data = focus_filter_vx_150_ar.interp(y=northings_rgi_id_ar, x=eastings_rgi_id_ar,
method='nearest').data
vx_filter_300_data = focus_filter_vx_300_ar.interp(y=northings_rgi_id_ar, x=eastings_rgi_id_ar,
method='nearest').data
vx_filter_450_data = focus_filter_vx_450_ar.interp(y=northings_rgi_id_ar, x=eastings_rgi_id_ar,
method='nearest').data
vx_filter_af_data = focus_filter_vx_af_ar.interp(y=northings_rgi_id_ar, x=eastings_rgi_id_ar,
method='nearest').data
vy_filter_50_data = focus_filter_vy_50_ar.interp(y=northings_rgi_id_ar, x=eastings_rgi_id_ar,
method='nearest').data
vy_filter_100_data = focus_filter_vy_100_ar.interp(y=northings_rgi_id_ar, x=eastings_rgi_id_ar,
method='nearest').data
vy_filter_150_data = focus_filter_vy_150_ar.interp(y=northings_rgi_id_ar, x=eastings_rgi_id_ar,
method='nearest').data
vy_filter_300_data = focus_filter_vy_300_ar.interp(y=northings_rgi_id_ar, x=eastings_rgi_id_ar,
method='nearest').data
vy_filter_450_data = focus_filter_vy_450_ar.interp(y=northings_rgi_id_ar, x=eastings_rgi_id_ar,
method='nearest').data
vy_filter_af_data = focus_filter_vy_af_ar.interp(y=northings_rgi_id_ar, x=eastings_rgi_id_ar,
method='nearest').data
dvx_dx_data = dvx_dx_ar.interp(y=northings_rgi_id_ar, x=eastings_rgi_id_ar, method='nearest').data
dvx_dy_data = dvx_dy_ar.interp(y=northings_rgi_id_ar, x=eastings_rgi_id_ar, method='nearest').data
dvy_dx_data = dvy_dx_ar.interp(y=northings_rgi_id_ar, x=eastings_rgi_id_ar, method='nearest').data
dvy_dy_data = dvy_dy_ar.interp(y=northings_rgi_id_ar, x=eastings_rgi_id_ar, method='nearest').data
'''
# some checks
assert v_data.shape == v_filter_50_data.shape, "NSIDC interp something wrong!"
assert v_data.shape == v_filter_100_data.shape, "NSIDC interp something wrong!"
assert v_data.shape == v_filter_150_data.shape, "NSIDC interp something wrong!"
assert v_data.shape == v_filter_300_data.shape, "NSIDC interp something wrong!"
assert v_data.shape == v_filter_450_data.shape, "NSIDC interp something wrong!"
assert v_data.shape == v_filter_af_data.shape, "NSIDC interp something wrong!"
# Fill dataframe with NSIDC velocities
# Note this vectors may contain nans from interpolation close to margin/nunatak
glathida.loc[indexes_id, 'v50'] = v_filter_50_data
glathida.loc[indexes_id, 'v100'] = v_filter_100_data
glathida.loc[indexes_id, 'v150'] = v_filter_150_data
glathida.loc[indexes_id, 'v300'] = v_filter_300_data
glathida.loc[indexes_id, 'v450'] = v_filter_450_data
glathida.loc[indexes_id, 'vgfa'] = v_filter_af_data
#glathida.loc[indexes_id, 'vx'] = vx_data
#glathida.loc[indexes_id, 'vy'] = vy_data
#glathida.loc[indexes_id, 'vx_gf50'] = vx_filter_50_data
#glathida.loc[indexes_id, 'vx_gf100'] = vx_filter_100_data
#glathida.loc[indexes_id, 'vx_gf150'] = vx_filter_150_data
#glathida.loc[indexes_id, 'vx_gf300'] = vx_filter_300_data
#glathida.loc[indexes_id, 'vx_gf450'] = vx_filter_450_data
#glathida.loc[indexes_id, 'vx_gfa'] = vx_filter_af_data
#glathida.loc[indexes_id, 'vy_gf50'] = vy_filter_50_data
#glathida.loc[indexes_id, 'vy_gf100'] = vy_filter_100_data
#glathida.loc[indexes_id, 'vy_gf150'] = vy_filter_150_data
#glathida.loc[indexes_id, 'vy_gf300'] = vy_filter_300_data
#glathida.loc[indexes_id, 'vy_gf450'] = vy_filter_450_data
#glathida.loc[indexes_id, 'vy_gfa'] = vy_filter_af_data
#glathida.loc[indexes_id, 'dvx_dx'] = dvx_dx_data
#glathida.loc[indexes_id, 'dvx_dy'] = dvx_dy_data
#glathida.loc[indexes_id, 'dvy_dx'] = dvy_dx_data
#glathida.loc[indexes_id, 'dvy_dy'] = dvy_dy_data
"Now we can interpolate BedMachine to fill ith_m for rgi 19"
tqdm.write(f"Begin ice thickness for rgi {rgi}")
# get NSIDC
file_ith_NSIDC = f"{args.NSIDC_icethickness_folder_Antarctica}BedMachineAntarctica-v3.nc"
mosaic_ith_NSIDC = rioxarray.open_rasterio(file_ith_NSIDC, masked=False)
# Nb: ith_NSIDC nodata is 9.96921e+36. Also it contains zeros. All will to be converted to nans
ith_NSIDC = mosaic_ith_NSIDC.thickness
for i, id_rgi in tqdm(enumerate(ids_rgi), total=len(ids_rgi), desc=f"rgi {rgi} Glathida ID", leave=True):
glathida_id = glathida_rgi.loc[glathida_rgi['GlaThiDa_ID'] == id_rgi]
indexes_id = glathida_id.index.tolist()
eastings_id, northings_id = (Transformer.from_crs("EPSG:4326", vx_NSIDC.rio.crs)
.transform(glathida_id['POINT_LAT'], glathida_id['POINT_LON']))
eastings_rgi_id_ar = xarray.DataArray(eastings_id)
northings_rgi_id_ar = xarray.DataArray(northings_id)
minE, maxE = min(eastings_id), max(eastings_id)
minN, maxN = min(northings_id), max(northings_id)
ris_metre_nsidc = ith_NSIDC.rio.resolution()[0] # 500m
eps = 15000
try:
ith_NSIDC_focus = ith_NSIDC.rio.clip_box(minx=minE - eps, miny=minN - eps, maxx=maxE + eps,
maxy=maxN + eps)
except:
tqdm.write(f'{i} No ith NSIDC data for rgi {rgi} GlaThiDa_ID {id_rgi}')
continue