-
Notifications
You must be signed in to change notification settings - Fork 100
/
test_prepro.py
2525 lines (2050 loc) · 95.7 KB
/
test_prepro.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 warnings
warnings.filterwarnings("once", category=DeprecationWarning) # noqa: E402
import oggm
import oggm.utils
import unittest
import os
import shutil
from distutils.version import LooseVersion
import pytest
import shapely.geometry as shpg
import numpy as np
import pandas as pd
import geopandas as gpd
import salem
import xarray as xr
import rasterio
# Local imports
from oggm.core import (gis, inversion, climate, centerlines, flowline,
massbalance)
import oggm.cfg as cfg
from oggm import utils
from oggm.utils import get_demo_file, tuple2int
from oggm.tests.funcs import get_test_dir, patch_url_retrieve_github
from oggm import workflow
pytestmark = pytest.mark.test_env("prepro")
_url_retrieve = None
def setup_module(module):
module._url_retrieve = utils._urlretrieve
utils._urlretrieve = patch_url_retrieve_github
def teardown_module(module):
utils._urlretrieve = module._url_retrieve
def read_svgcoords(svg_file):
"""Get the vertices coordinates out of a SVG file"""
from xml.dom import minidom
doc = minidom.parse(svg_file)
coords = [path.getAttribute('d') for path
in doc.getElementsByTagName('path')]
doc.unlink()
_, _, coords = coords[0].partition('C')
x = []
y = []
for c in coords.split(' '):
if c == '':
continue
c = c.split(',')
x.append(np.float(c[0]))
y.append(np.float(c[1]))
x.append(x[0])
y.append(y[0])
return np.rint(np.asarray((x, y)).T).astype(np.int64)
class TestGIS(unittest.TestCase):
def setUp(self):
# test directory
self.testdir = os.path.join(get_test_dir(), 'tmp')
if not os.path.exists(self.testdir):
os.makedirs(self.testdir)
self.clean_dir()
# Init
cfg.initialize()
cfg.set_intersects_db(get_demo_file('rgi_intersect_oetztal.shp'))
cfg.PATHS['dem_file'] = get_demo_file('hef_srtm.tif')
cfg.PATHS['working_dir'] = self.testdir
def tearDown(self):
self.rm_dir()
def rm_dir(self):
shutil.rmtree(self.testdir)
def clean_dir(self):
shutil.rmtree(self.testdir)
os.makedirs(self.testdir)
def test_define_region(self):
hef_file = get_demo_file('Hintereisferner_RGI5.shp')
entity = gpd.read_file(hef_file).iloc[0]
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir)
gis.define_glacier_region(gdir, entity=entity)
extent = gdir.extent_ll
tdf = gpd.read_file(gdir.get_filepath('outlines'))
myarea = tdf.geometry.area * 10**-6
np.testing.assert_allclose(myarea, np.float(tdf['Area']), rtol=1e-2)
self.assertTrue(os.path.exists(gdir.get_filepath('intersects')))
# From string
gdir = oggm.GlacierDirectory(gdir.rgi_id, base_dir=self.testdir)
# This is not guaranteed to be equal because of projection issues
np.testing.assert_allclose(extent, gdir.extent_ll, atol=1e-5)
# Change area
prev_area = gdir.rgi_area_km2
cfg.PARAMS['use_rgi_area'] = False
entity = gpd.read_file(hef_file).iloc[0]
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir,
reset=True)
gis.define_glacier_region(gdir, entity=entity)
np.testing.assert_allclose(gdir.rgi_area_km2, prev_area, atol=0.01)
assert gdir.status == 'Glacier or ice cap'
def test_divides_as_glaciers(self):
hef_rgi = gpd.read_file(get_demo_file('divides_alps.shp'))
hef_rgi = hef_rgi.loc[hef_rgi.RGIId == 'RGI50-11.00897']
# Rename the RGI ID
hef_rgi['RGIId'] = ['RGI50-11.00897' + d for d in
['_d01', '_d02', '_d03']]
# Just check that things are working
gdirs = workflow.init_glacier_regions(hef_rgi)
workflow.gis_prepro_tasks(gdirs)
assert gdirs[0].rgi_id == 'RGI50-11.00897_d01'
assert gdirs[-1].rgi_id == 'RGI50-11.00897_d03'
def test_dx_methods(self):
hef_file = get_demo_file('Hintereisferner_RGI5.shp')
entity = gpd.read_file(hef_file).iloc[0]
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir)
# Test fixed method
cfg.PARAMS['grid_dx_method'] = 'fixed'
cfg.PARAMS['fixed_dx'] = 50
gis.define_glacier_region(gdir, entity=entity)
mygrid = salem.Grid.from_json(gdir.get_filepath('glacier_grid'))
np.testing.assert_allclose(np.abs(mygrid.dx), 50.)
# Test linear method
cfg.PARAMS['grid_dx_method'] = 'linear'
cfg.PARAMS['d1'] = 5.
cfg.PARAMS['d2'] = 10.
cfg.PARAMS['dmax'] = 100.
gis.define_glacier_region(gdir, entity=entity)
targetdx = np.rint(5. * gdir.rgi_area_km2 + 10.)
targetdx = np.clip(targetdx, 10., 100.)
mygrid = salem.Grid.from_json(gdir.get_filepath('glacier_grid'))
np.testing.assert_allclose(mygrid.dx, targetdx)
# Test square method
cfg.PARAMS['grid_dx_method'] = 'square'
cfg.PARAMS['d1'] = 5.
cfg.PARAMS['d2'] = 10.
cfg.PARAMS['dmax'] = 100.
gis.define_glacier_region(gdir, entity=entity)
targetdx = np.rint(5. * np.sqrt(gdir.rgi_area_km2) + 10.)
targetdx = np.clip(targetdx, 10., 100.)
mygrid = salem.Grid.from_json(gdir.get_filepath('glacier_grid'))
np.testing.assert_allclose(mygrid.dx, targetdx)
def test_repr(self):
from textwrap import dedent
expected = dedent("""\
<oggm.GlacierDirectory>
RGI id: RGI50-11.00897
Region: 11: Central Europe
Subregion: 11-01: Alps
Name: Hintereisferner
Glacier type: Glacier
Terminus type: Land-terminating
Area: 8.036 km2
Lon, Lat: (10.7584, 46.8003)
Grid (nx, ny): (159, 114)
Grid (dx, dy): (50.0, -50.0)
""")
hef_file = get_demo_file('Hintereisferner_RGI5.shp')
entity = gpd.read_file(hef_file).iloc[0]
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir)
gis.define_glacier_region(gdir, entity=entity)
self.assertEqual(gdir.__repr__(), expected)
def test_glacierdir(self):
hef_file = get_demo_file('Hintereisferner_RGI5.shp')
entity = gpd.read_file(hef_file).iloc[0]
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir)
gis.define_glacier_region(gdir, entity=entity)
# this should simply run
oggm.GlacierDirectory(entity.RGIId, base_dir=self.testdir)
def test_glacier_masks(self):
# The GIS was double checked externally with IDL.
hef_file = get_demo_file('Hintereisferner_RGI5.shp')
entity = gpd.read_file(hef_file).iloc[0]
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir)
gis.define_glacier_region(gdir, entity=entity)
gis.glacier_masks(gdir)
gis.interpolation_masks(gdir)
with utils.ncDataset(gdir.get_filepath('gridded_data')) as nc:
glacier_mask = nc.variables['glacier_mask'][:]
glacier_ext = nc.variables['glacier_ext'][:]
glacier_ext_erosion = nc.variables['glacier_ext_erosion'][:]
ice_divides = nc.variables['ice_divides'][:]
area = np.sum(glacier_mask * gdir.grid.dx**2)
np.testing.assert_allclose(area*10**-6, gdir.rgi_area_km2,
rtol=1e-1)
assert np.all(glacier_mask[glacier_ext == 1])
assert np.all(glacier_mask[glacier_ext_erosion == 1])
assert np.all(glacier_ext[ice_divides == 1])
assert np.all(glacier_ext_erosion[ice_divides == 1])
np.testing.assert_allclose(np.std(glacier_ext_erosion - glacier_ext),
0, atol=0.1)
@pytest.mark.skipif((LooseVersion(rasterio.__version__) <
LooseVersion('1.0')),
reason='requires rasterio >= 1.0')
def test_simple_glacier_masks(self):
# The GIS was double checked externally with IDL.
hef_file = get_demo_file('Hintereisferner_RGI5.shp')
entity = gpd.read_file(hef_file).iloc[0]
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir)
gis.define_glacier_region(gdir, entity=entity)
gis.simple_glacier_masks(gdir)
with utils.ncDataset(gdir.get_filepath('gridded_data')) as nc:
area = np.sum(nc.variables['glacier_mask'][:] * gdir.grid.dx**2)
np.testing.assert_allclose(area*10**-6, gdir.rgi_area_km2,
rtol=1e-1)
# Check that HEF doesn't "badly" need a divide
mask = nc.variables['glacier_mask'][:]
ext = nc.variables['glacier_ext'][:]
dem = nc.variables['topo'][:]
np.testing.assert_allclose(np.max(dem[mask.astype(bool)]),
np.max(dem[ext.astype(bool)]),
atol=10)
df = utils.glacier_characteristics([gdir], path=False)
np.testing.assert_allclose(df['dem_max_elev_on_ext'],
df['dem_max_elev'],
atol=10)
assert np.all(df['dem_max_elev'] > df['dem_max_elev_on_ext'])
dfh = pd.read_csv(gdir.get_filepath('hypsometry'))
np.testing.assert_allclose(dfh['Slope'], entity.Slope, atol=0.5)
np.testing.assert_allclose(dfh['Aspect'], entity.Aspect, atol=5)
np.testing.assert_allclose(dfh['Zmed'], entity.Zmed, atol=20)
np.testing.assert_allclose(dfh['Zmax'], entity.Zmax, atol=20)
np.testing.assert_allclose(dfh['Zmin'], entity.Zmin, atol=20)
bins = []
for c in dfh.columns:
try:
int(c)
bins.append(c)
except ValueError:
pass
dfr = pd.read_csv(get_demo_file('Hintereisferner_V5_hypso.csv'))
dfh.index = ['oggm']
dft = dfh[bins].T
dft['ref'] = dfr[bins].T
assert dft.sum()[0] == 1000
assert utils.rmsd(dft['ref'], dft['oggm']) < 5
@pytest.mark.skipif((LooseVersion(rasterio.__version__) <
LooseVersion('1.0')),
reason='requires rasterio >= 1.0')
def test_glacier_masks_other_glacier(self):
# This glacier geometry is simplified by OGGM
# https://github.com/OGGM/oggm/issues/451
entity = gpd.read_file(get_demo_file('RGI60-14.03439.shp')).iloc[0]
cfg.PATHS['dem_file'] = get_demo_file('RGI60-14.03439.tif')
cfg.PARAMS['border'] = 1
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir)
gis.define_glacier_region(gdir, entity=entity)
gis.glacier_masks(gdir)
# The test below does NOT pass on OGGM
shutil.copyfile(gdir.get_filepath('gridded_data'),
os.path.join(self.testdir, 'default_masks.nc'))
gis.simple_glacier_masks(gdir)
with utils.ncDataset(gdir.get_filepath('gridded_data')) as nc:
area = np.sum(nc.variables['glacier_mask'][:] * gdir.grid.dx**2)
np.testing.assert_allclose(area*10**-6, gdir.rgi_area_km2,
rtol=1e-1)
shutil.copyfile(gdir.get_filepath('gridded_data'),
os.path.join(self.testdir, 'simple_masks.nc'))
dfh = pd.read_csv(gdir.get_filepath('hypsometry'))
np.testing.assert_allclose(dfh['Slope'], entity.Slope, atol=1)
np.testing.assert_allclose(dfh['Aspect'], entity.Aspect, atol=10)
np.testing.assert_allclose(dfh['Zmed'], entity.Zmed, atol=20)
np.testing.assert_allclose(dfh['Zmax'], entity.Zmax, atol=20)
np.testing.assert_allclose(dfh['Zmin'], entity.Zmin, atol=20)
def test_intersects(self):
hef_file = get_demo_file('Hintereisferner_RGI5.shp')
entity = gpd.read_file(hef_file).iloc[0]
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir)
gis.define_glacier_region(gdir, entity=entity)
self.assertTrue(os.path.exists(gdir.get_filepath('intersects')))
class TestCenterlines(unittest.TestCase):
def setUp(self):
# test directory
self.testdir = os.path.join(get_test_dir(), 'tmp')
if not os.path.exists(self.testdir):
os.makedirs(self.testdir)
self.clean_dir()
# Init
cfg.initialize()
cfg.set_intersects_db(get_demo_file('rgi_intersect_oetztal.shp'))
cfg.PATHS['dem_file'] = get_demo_file('hef_srtm.tif')
cfg.PARAMS['border'] = 10
def tearDown(self):
self.rm_dir()
def rm_dir(self):
shutil.rmtree(self.testdir)
def clean_dir(self):
shutil.rmtree(self.testdir)
os.makedirs(self.testdir)
def test_filter_heads(self):
f = get_demo_file('glacier.svg')
coords = read_svgcoords(f)
polygon = shpg.Polygon(coords)
hidx = np.array([3, 9, 80, 92, 108, 116, 170, len(coords)-12])
heads = [shpg.Point(*c) for c in coords[hidx]]
heads_height = np.array([200, 210, 1000., 900, 1200, 1400, 1300, 250])
radius = 25
_heads, _ = centerlines._filter_heads(heads, heads_height, radius,
polygon)
_headsi, _ = centerlines._filter_heads(heads[::-1],
heads_height[::-1],
radius, polygon)
self.assertEqual(_heads, _headsi[::-1])
self.assertEqual(_heads, [heads[h] for h in [2, 5, 6, 7]])
def test_mask_to_polygon(self):
from oggm.core.centerlines import _mask_to_polygon
mask = np.zeros((5, 5))
mask[1, 1] = 1
p1, p2 = _mask_to_polygon(mask)
assert p1 == p2
mask = np.zeros((5, 5))
mask[1:-1, 1:-1] = 1
p1, p2 = _mask_to_polygon(mask)
assert p1 == p2
mask = np.zeros((5, 5))
mask[1:-1, 1:-1] = 1
mask[2, 2] = 0
p1, _ = _mask_to_polygon(mask)
assert len(p1.interiors) == 1
assert p1.exterior == p2.exterior
for i_line in p1.interiors:
assert p2.contains(i_line)
n = 30
for i in range(n):
mask = np.zeros((n, n))
mask[1:-1, 1:-1] = 1
_, p2 = _mask_to_polygon(mask)
for i in range(n*2):
mask[np.random.randint(2, n-2), np.random.randint(2, n-2)] = 0
p1, _ = _mask_to_polygon(mask)
assert len(p1.interiors) > 1
assert p1.exterior == p2.exterior
for i_line in p1.interiors:
assert p2.contains(i_line)
def test_centerlines(self):
hef_file = get_demo_file('Hintereisferner_RGI5.shp')
entity = gpd.read_file(hef_file).iloc[0]
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir)
gis.define_glacier_region(gdir, entity=entity)
gis.glacier_masks(gdir)
centerlines.compute_centerlines(gdir)
cls = gdir.read_pickle('centerlines')
for cl in cls:
for j, ip, ob in zip(cl.inflow_indices, cl.inflow_points,
cl.inflows):
self.assertEqual(cl.line.coords[j], ip.coords[0])
self.assertEqual(ob.flows_to_point.coords[0],
ip.coords[0])
self.assertEqual(cl.line.coords[ob.flows_to_indice],
ip.coords[0])
self.assertEqual(len(cls), 3)
self.assertEqual(set(cls), set(centerlines.line_inflows(cls[-1])))
def test_downstream(self):
hef_file = get_demo_file('Hintereisferner_RGI5.shp')
entity = gpd.read_file(hef_file).iloc[0]
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir)
gis.define_glacier_region(gdir, entity=entity)
gis.glacier_masks(gdir)
centerlines.compute_centerlines(gdir)
centerlines.initialize_flowlines(gdir)
centerlines.compute_downstream_line(gdir)
d = gdir.read_pickle('downstream_line')
cl = gdir.read_pickle('inversion_flowlines')[-1]
self.assertEqual(
len(d['full_line'].coords) - len(d['downstream_line'].coords),
cl.nx)
def test_downstream_bedshape(self):
hef_file = get_demo_file('Hintereisferner_RGI5.shp')
entity = gpd.read_file(hef_file).iloc[0]
default_b = cfg.PARAMS['border']
cfg.PARAMS['border'] = 80
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir)
gis.define_glacier_region(gdir, entity=entity)
gis.glacier_masks(gdir)
centerlines.compute_centerlines(gdir)
centerlines.initialize_flowlines(gdir)
centerlines.compute_downstream_line(gdir)
centerlines.compute_downstream_bedshape(gdir)
out = gdir.read_pickle('downstream_line')
for o, h in zip(out['bedshapes'], out['surface_h']):
assert np.all(np.isfinite(o))
assert np.all(np.isfinite(h))
tpl = gdir.read_pickle('inversion_flowlines')[-1]
c = gdir.read_pickle('downstream_line')['downstream_line']
c = centerlines.Centerline(c, dx=tpl.dx)
# Independant reproduction for a few points
o = out['bedshapes']
i0s = [0, 5, 10, 15, 20]
for i0 in i0s:
wi = 11
i0 = int(i0)
cur = c.line.coords[i0]
n1, n2 = c.normals[i0]
line = shpg.LineString([shpg.Point(cur + wi / 2. * n1),
shpg.Point(cur + wi / 2. * n2)])
from oggm.core.centerlines import line_interpol
from scipy.interpolate import RegularGridInterpolator
points = line_interpol(line, 0.5)
with utils.ncDataset(gdir.get_filepath('gridded_data')) as nc:
topo = nc.variables['topo_smoothed'][:]
x = nc.variables['x'][:]
y = nc.variables['y'][:]
xy = (np.arange(0, len(y) - 0.1, 1), np.arange(0, len(x) - 0.1, 1))
interpolator = RegularGridInterpolator(xy, topo)
zref = [interpolator((p.xy[1][0], p.xy[0][0])) for p in points]
myx = np.arange(len(points))
myx = (myx - np.argmin(zref)) / 2 * gdir.grid.dx
myz = o[i0] * myx**2 + np.min(zref)
# In this case the fit is simply very good (plot it if you want!)
assert utils.rmsd(zref, myz) < 20
cfg.PARAMS['border'] = default_b
@pytest.mark.slow
def test_baltoro_centerlines(self):
cfg.PARAMS['border'] = 2
cfg.PARAMS['dmax'] = 100
cfg.PATHS['dem_file'] = get_demo_file('baltoro_srtm_clip.tif')
b_file = get_demo_file('baltoro_wgs84.shp')
entity = gpd.read_file(b_file).iloc[0]
kienholz_file = get_demo_file('centerlines_baltoro_wgs84.shp')
kdf = gpd.read_file(kienholz_file)
# add fake attribs
del entity['RGIID']
entity.RGIId = 'RGI50-00.00000'
entity['GLIMSId'] = entity['GLIMSID']
entity['Area'] = entity['AREA']
entity['CenLat'] = entity['CENLAT']
entity['CenLon'] = entity['CENLON']
entity.BgnDate = 0
entity.Name = 'Baltoro'
entity.GlacType = '0000'
entity.Status = '0'
entity.O1Region = '01'
entity.O2Region = '01'
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir)
gis.define_glacier_region(gdir, entity=entity)
gis.glacier_masks(gdir)
centerlines.compute_centerlines(gdir)
my_mask = np.zeros((gdir.grid.ny, gdir.grid.nx), dtype=np.uint8)
cls = gdir.read_pickle('centerlines')
sub = centerlines.line_inflows(cls[-1])
self.assertEqual(set(cls), set(sub))
assert sub[-1] is cls[-1]
sub = centerlines.line_inflows(cls[-2])
assert set(sub).issubset(set(cls))
np.testing.assert_equal(np.unique(sorted([cl.order for cl in sub])),
np.arange(cls[-2].order+1))
assert sub[-1] is cls[-2]
# Mask
for cl in cls:
x, y = tuple2int(cl.line.xy)
my_mask[y, x] = 1
# Transform
kien_mask = np.zeros((gdir.grid.ny, gdir.grid.nx), dtype=np.uint8)
from shapely.ops import transform
for index, entity in kdf.iterrows():
def proj(lon, lat):
return salem.transform_proj(salem.wgs84, gdir.grid.proj,
lon, lat)
kgm = transform(proj, entity.geometry)
# Interpolate shape to a regular path
e_line = []
for distance in np.arange(0.0, kgm.length, gdir.grid.dx):
e_line.append(*kgm.interpolate(distance).coords)
kgm = shpg.LineString(e_line)
# Transform geometry into grid coordinates
def proj(x, y):
return gdir.grid.transform(x, y, crs=gdir.grid.proj)
kgm = transform(proj, kgm)
# Rounded nearest pix
def project(x, y):
return (np.rint(x).astype(np.int64),
np.rint(y).astype(np.int64))
kgm = transform(project, kgm)
x, y = tuple2int(kgm.xy)
kien_mask[y, x] = 1
# We test the Heidke Skill score of our predictions
rest = kien_mask + 2 * my_mask
# gr.plot_array(rest)
na = len(np.where(rest == 3)[0])
nb = len(np.where(rest == 2)[0])
nc = len(np.where(rest == 1)[0])
nd = len(np.where(rest == 0)[0])
denom = np.float((na+nc)*(nd+nc)+(na+nb)*(nd+nb))
hss = np.float(2.) * ((na*nd)-(nb*nc)) / denom
if cfg.PARAMS['grid_dx_method'] == 'linear':
self.assertTrue(hss > 0.53)
if cfg.PARAMS['grid_dx_method'] == 'fixed': # quick fix
self.assertTrue(hss > 0.41)
class TestGeometry(unittest.TestCase):
def setUp(self):
# test directory
self.testdir = os.path.join(get_test_dir(), 'tmp')
if not os.path.exists(self.testdir):
os.makedirs(self.testdir)
self.clean_dir()
# Init
cfg.initialize()
cfg.set_intersects_db(get_demo_file('rgi_intersect_oetztal.shp'))
cfg.PATHS['dem_file'] = get_demo_file('hef_srtm.tif')
cfg.PARAMS['border'] = 10
def tearDown(self):
self.rm_dir()
def rm_dir(self):
shutil.rmtree(self.testdir)
def clean_dir(self):
shutil.rmtree(self.testdir)
os.makedirs(self.testdir)
def test_catchment_area(self):
hef_file = get_demo_file('Hintereisferner_RGI5.shp')
entity = gpd.read_file(hef_file).iloc[0]
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir)
gis.define_glacier_region(gdir, entity=entity)
gis.glacier_masks(gdir)
centerlines.compute_centerlines(gdir)
centerlines.catchment_area(gdir)
cis = gdir.read_pickle('catchment_indices')
# The catchment area must be as big as expected
with utils.ncDataset(gdir.get_filepath('gridded_data')) as nc:
mask = nc.variables['glacier_mask'][:]
mymask_a = mask * 0
mymask_b = mask * 0
for i, ci in enumerate(cis):
mymask_a[tuple(ci.T)] += 1
mymask_b[tuple(ci.T)] = i+1
self.assertTrue(np.max(mymask_a) == 1)
np.testing.assert_allclose(mask, mymask_a)
def test_flowlines(self):
hef_file = get_demo_file('Hintereisferner_RGI5.shp')
entity = gpd.read_file(hef_file).iloc[0]
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir)
gis.define_glacier_region(gdir, entity=entity)
gis.glacier_masks(gdir)
centerlines.compute_centerlines(gdir)
centerlines.initialize_flowlines(gdir)
cls = gdir.read_pickle('inversion_flowlines')
for cl in cls:
for j, ip, ob in zip(cl.inflow_indices, cl.inflow_points,
cl.inflows):
self.assertEqual(cl.line.coords[j], ip.coords[0])
self.assertEqual(ob.flows_to_point.coords[0], ip.coords[0])
self.assertEqual(cl.line.coords[ob.flows_to_indice],
ip.coords[0])
self.assertEqual(len(cls), 3)
x, y = map(np.array, cls[0].line.xy)
dis = np.sqrt((x[1:] - x[:-1])**2 + (y[1:] - y[:-1])**2)
np.testing.assert_allclose(dis * 0 + cfg.PARAMS['flowline_dx'], dis,
rtol=0.01)
d = gdir.get_diagnostics()
assert d['perc_invalid_flowline'] > 0.1
df = utils.glacier_characteristics([gdir], path=False)
assert np.all(df['dem_source'] == 'USER')
assert np.all(df['perc_invalid_flowline'] > 0.1)
assert np.all(df['dem_perc_area_above_max_elev_on_ext'] < 0.1)
def test_geom_width(self):
hef_file = get_demo_file('Hintereisferner_RGI5.shp')
entity = gpd.read_file(hef_file).iloc[0]
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir)
gis.define_glacier_region(gdir, entity=entity)
gis.glacier_masks(gdir)
centerlines.compute_centerlines(gdir)
centerlines.initialize_flowlines(gdir)
centerlines.catchment_area(gdir)
centerlines.catchment_intersections(gdir)
centerlines.catchment_width_geom(gdir)
def test_width(self):
hef_file = get_demo_file('Hintereisferner_RGI5.shp')
entity = gpd.read_file(hef_file).iloc[0]
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir)
gis.define_glacier_region(gdir, entity=entity)
gis.glacier_masks(gdir)
centerlines.compute_centerlines(gdir)
centerlines.initialize_flowlines(gdir)
centerlines.catchment_area(gdir)
centerlines.catchment_width_geom(gdir)
centerlines.catchment_width_correction(gdir)
area = 0.
otherarea = 0.
hgt = []
harea = []
cls = gdir.read_pickle('inversion_flowlines')
for cl in cls:
harea.extend(list(cl.widths * cl.dx))
hgt.extend(list(cl.surface_h))
area += np.sum(cl.widths * cl.dx)
with utils.ncDataset(gdir.get_filepath('gridded_data')) as nc:
otherarea += np.sum(nc.variables['glacier_mask'][:])
with utils.ncDataset(gdir.get_filepath('gridded_data')) as nc:
mask = nc.variables['glacier_mask'][:]
topo = nc.variables['topo_smoothed'][:]
rhgt = topo[np.where(mask)][:]
tdf = gpd.read_file(gdir.get_filepath('outlines'))
np.testing.assert_allclose(area, otherarea, rtol=0.1)
area *= (gdir.grid.dx) ** 2
otherarea *= (gdir.grid.dx) ** 2
np.testing.assert_allclose(area * 10**-6, np.float(tdf['Area']),
rtol=1e-4)
# Check for area distrib
bins = np.arange(utils.nicenumber(np.min(hgt), 50, lower=True),
utils.nicenumber(np.max(hgt), 50)+1,
50.)
h1, b = np.histogram(hgt, weights=harea, density=True, bins=bins)
h2, b = np.histogram(rhgt, density=True, bins=bins)
self.assertTrue(utils.rmsd(h1*100*50, h2*100*50) < 1)
# Check that utility function is doing what is expected
hh, ww = gdir.get_inversion_flowline_hw()
new_area = np.sum(ww * cl.dx * gdir.grid.dx)
np.testing.assert_allclose(new_area * 10**-6, np.float(tdf['Area']))
def test_nodivides_correct_slope(self):
# Init
cfg.initialize()
cfg.set_intersects_db(get_demo_file('rgi_intersect_oetztal.shp'))
cfg.PATHS['dem_file'] = get_demo_file('hef_srtm.tif')
cfg.PATHS['climate_file'] = get_demo_file('histalp_merged_hef.nc')
cfg.PARAMS['border'] = 40
hef_file = get_demo_file('Hintereisferner_RGI5.shp')
entity = gpd.read_file(hef_file).iloc[0]
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir)
gis.define_glacier_region(gdir, entity=entity)
gis.glacier_masks(gdir)
centerlines.compute_centerlines(gdir)
centerlines.initialize_flowlines(gdir)
fls = gdir.read_pickle('inversion_flowlines')
min_slope = np.deg2rad(cfg.PARAMS['min_slope'])
for fl in fls:
dx = fl.dx * gdir.grid.dx
slope = np.arctan(-np.gradient(fl.surface_h, dx))
self.assertTrue(np.all(slope >= min_slope))
class TestClimate(unittest.TestCase):
def setUp(self):
# test directory
self.testdir = os.path.join(get_test_dir(), 'tmp_prepro')
if not os.path.exists(self.testdir):
os.makedirs(self.testdir)
self.testdir_cru = os.path.join(get_test_dir(), 'tmp_prepro_cru')
if not os.path.exists(self.testdir_cru):
os.makedirs(self.testdir_cru)
self.clean_dir()
# Init
cfg.initialize()
cfg.set_intersects_db(get_demo_file('rgi_intersect_oetztal.shp'))
cfg.PATHS['working_dir'] = self.testdir
cfg.PATHS['dem_file'] = get_demo_file('hef_srtm.tif')
cfg.PATHS['climate_file'] = get_demo_file('histalp_merged_hef.nc')
cfg.PARAMS['border'] = 10
cfg.PARAMS['run_mb_calibration'] = True
cfg.PARAMS['baseline_climate'] = ''
def tearDown(self):
self.rm_dir()
def rm_dir(self):
shutil.rmtree(self.testdir)
shutil.rmtree(self.testdir_cru)
def clean_dir(self):
shutil.rmtree(self.testdir)
os.makedirs(self.testdir)
shutil.rmtree(self.testdir_cru)
os.makedirs(self.testdir_cru)
def test_distribute_climate(self):
hef_file = get_demo_file('Hintereisferner_RGI5.shp')
entity = gpd.read_file(hef_file).iloc[0]
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir)
gis.define_glacier_region(gdir, entity=entity)
climate.process_custom_climate_data(gdir)
ci = gdir.read_pickle('climate_info')
self.assertEqual(ci['baseline_hydro_yr_0'], 1802)
self.assertEqual(ci['baseline_hydro_yr_1'], 2003)
with utils.ncDataset(get_demo_file('histalp_merged_hef.nc')) as nc_r:
ref_h = nc_r.variables['hgt'][1, 1]
ref_p = nc_r.variables['prcp'][:, 1, 1]
ref_t = nc_r.variables['temp'][:, 1, 1]
f = os.path.join(gdir.dir, 'climate_monthly.nc')
with utils.ncDataset(f) as nc_r:
self.assertTrue(ref_h == nc_r.ref_hgt)
np.testing.assert_allclose(ref_t, nc_r.variables['temp'][:])
np.testing.assert_allclose(ref_p, nc_r.variables['prcp'][:])
def test_distribute_climate_grad(self):
hef_file = get_demo_file('Hintereisferner_RGI5.shp')
cfg.PARAMS['temp_use_local_gradient'] = True
entity = gpd.read_file(hef_file).iloc[0]
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir)
gis.define_glacier_region(gdir, entity=entity)
climate.process_custom_climate_data(gdir)
ci = gdir.read_pickle('climate_info')
self.assertEqual(ci['baseline_hydro_yr_0'], 1802)
self.assertEqual(ci['baseline_hydro_yr_1'], 2003)
with xr.open_dataset(gdir.get_filepath('climate_monthly')) as ds:
grad = ds['gradient'].data
assert np.std(grad) > 0.0001
cfg.PARAMS['temp_use_local_gradient'] = False
def test_distribute_climate_parallel(self):
hef_file = get_demo_file('Hintereisferner_RGI5.shp')
entity = gpd.read_file(hef_file).iloc[0]
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir)
gis.define_glacier_region(gdir, entity=entity)
climate.process_custom_climate_data(gdir)
ci = gdir.read_pickle('climate_info')
self.assertEqual(ci['baseline_hydro_yr_0'], 1802)
self.assertEqual(ci['baseline_hydro_yr_1'], 2003)
with utils.ncDataset(get_demo_file('histalp_merged_hef.nc')) as nc_r:
ref_h = nc_r.variables['hgt'][1, 1]
ref_p = nc_r.variables['prcp'][:, 1, 1]
ref_t = nc_r.variables['temp'][:, 1, 1]
f = os.path.join(gdir.dir, 'climate_monthly.nc')
with utils.ncDataset(f) as nc_r:
self.assertTrue(ref_h == nc_r.ref_hgt)
np.testing.assert_allclose(ref_t, nc_r.variables['temp'][:])
np.testing.assert_allclose(ref_p, nc_r.variables['prcp'][:])
def test_distribute_climate_cru(self):
hef_file = get_demo_file('Hintereisferner_RGI5.shp')
entity = gpd.read_file(hef_file).iloc[0]
gdirs = []
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir)
gis.define_glacier_region(gdir, entity=entity)
gdirs.append(gdir)
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir_cru)
gis.define_glacier_region(gdir, entity=entity)
gdirs.append(gdir)
climate.process_custom_climate_data(gdirs[0])
cru_dir = get_demo_file('cru_ts3.23.1901.2014.tmp.dat.nc')
cru_dir = os.path.dirname(cru_dir)
cfg.PATHS['climate_file'] = ''
cfg.PATHS['cru_dir'] = cru_dir
cfg.PARAMS['baseline_climate'] = 'CRU'
climate.process_cru_data(gdirs[1])
cfg.PATHS['cru_dir'] = ''
cfg.PATHS['climate_file'] = get_demo_file('histalp_merged_hef.nc')
ci = gdir.read_pickle('climate_info')
self.assertEqual(ci['baseline_hydro_yr_0'], 1902)
self.assertEqual(ci['baseline_hydro_yr_1'], 2014)
gdh = gdirs[0]
gdc = gdirs[1]
f1 = os.path.join(gdh.dir, 'climate_monthly.nc')
f2 = os.path.join(gdc.dir, 'climate_monthly.nc')
with xr.open_dataset(f1) as nc_h:
with xr.open_dataset(f2) as nc_c:
# put on the same altitude
# (using default gradient because better)
temp_cor = nc_c.temp - 0.0065 * (nc_h.ref_hgt - nc_c.ref_hgt)
totest = temp_cor - nc_h.temp
self.assertTrue(totest.mean() < 0.5)
# precip
totest = nc_c.prcp - nc_h.prcp
self.assertTrue(totest.mean() < 100)
def test_distribute_climate_histalp_new(self):
hef_file = get_demo_file('Hintereisferner_RGI5.shp')
entity = gpd.read_file(hef_file).iloc[0]
gdirs = []
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir)
gis.define_glacier_region(gdir, entity=entity)
gdirs.append(gdir)
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir_cru)
gis.define_glacier_region(gdir, entity=entity)
gdirs.append(gdir)
climate.process_custom_climate_data(gdirs[0])
cru_dir = get_demo_file('HISTALP_precipitation_all_abs_1801-2014.nc')
cru_dir = os.path.dirname(cru_dir)
cfg.PATHS['climate_file'] = ''
cfg.PATHS['cru_dir'] = cru_dir
cfg.PARAMS['baseline_climate'] = 'HISTALP'
cfg.PARAMS['baseline_y0'] = 1850
cfg.PARAMS['baseline_y1'] = 2003
climate.process_histalp_data(gdirs[1])
cfg.PATHS['cru_dir'] = ''
cfg.PATHS['climate_file'] = get_demo_file('histalp_merged_hef.nc')
ci = gdir.read_pickle('climate_info')
self.assertEqual(ci['baseline_hydro_yr_0'], 1851)
self.assertEqual(ci['baseline_hydro_yr_1'], 2003)
gdh = gdirs[0]
gdc = gdirs[1]
f1 = os.path.join(gdh.dir, 'climate_monthly.nc')
f2 = os.path.join(gdc.dir, 'climate_monthly.nc')
with xr.open_dataset(f1) as nc_h:
with xr.open_dataset(f2) as nc_c:
nc_hi = nc_h.isel(time=slice(49*12, 2424))
np.testing.assert_allclose(nc_hi['temp'], nc_c['temp'])
# for precip the data changed in between versions, we
# can't test for absolute equality
np.testing.assert_allclose(nc_hi['prcp'].mean(),
nc_c['prcp'].mean(),
atol=1)
np.testing.assert_allclose(nc_hi.ref_pix_dis,
nc_c.ref_pix_dis)
def test_sh(self):
hef_file = get_demo_file('Hintereisferner_RGI5.shp')
entity = gpd.read_file(hef_file).iloc[0]
# We have to make a non cropped custom file
fpath = cfg.PATHS['climate_file']
ds = xr.open_dataset(fpath)
ds = ds.sel(time=slice('1802-01-01', '2002-12-01'))
nf = os.path.join(self.testdir, 'testdata.nc')
ds.to_netcdf(nf)
cfg.PATHS['climate_file'] = nf
gdirs = []
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir)
# Trick
assert gdir.hemisphere == 'nh'
gdir.hemisphere = 'sh'
gis.define_glacier_region(gdir, entity=entity)
gdirs.append(gdir)
gdir = oggm.GlacierDirectory(entity, base_dir=self.testdir_cru)
assert gdir.hemisphere == 'nh'
gdir.hemisphere = 'sh'
gis.define_glacier_region(gdir, entity=entity)
gdirs.append(gdir)
climate.process_custom_climate_data(gdirs[0])
ci = gdirs[0].read_pickle('climate_info')