forked from GLIMS-RGI/rgitools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_rgitools.py
More file actions
430 lines (312 loc) · 13.6 KB
/
test_rgitools.py
File metadata and controls
430 lines (312 loc) · 13.6 KB
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
"""All rgitools tests.
We use the pytest package to run them.
"""
import os
import shutil
from distutils.version import LooseVersion
import pytest
import pandas as pd
import geopandas as gpd
import numpy as np
from numpy.testing import assert_equal, assert_allclose
import rgitools
from rgitools import funcs
from rgitools.funcs import get_demo_file, mkdir
def get_iceland_df(reduced=False):
df = gpd.read_file(get_demo_file('RGI6_icecap.shp'))
if reduced:
df = df.loc[(df.CenLon < -19.45) & (df.CenLat < 63.7)]
return df
def test_install():
assert LooseVersion(rgitools.__version__) >= LooseVersion('0.0.0')
assert rgitools.__isreleased__ in [False, True]
def test_correct_geometries(tmpdir):
# Simple ice cap
test_of = os.path.join(str(tmpdir), 'interfile.shp')
df = get_iceland_df(reduced=True)
out = funcs.check_geometries(df.copy(), to_file=test_of, job_id='test')
assert len(out) == len(df)
assert os.path.exists(test_of)
assert np.all(out.check_geom == '')
# All
test_of = os.path.join(str(tmpdir), 'interfile2.shp')
df = get_iceland_df()
out = funcs.check_geometries(df.copy(), to_file=test_of, job_id='test')
assert len(out) == len(df)
assert os.path.exists(test_of)
assert np.all(g.is_valid for g in out.geometry)
def test_correct_geometries_cli_args(tmpdir):
from rgitools.cli import correct_geometries
kwargs = correct_geometries.parse_args(['--input-dir', 'dd1',
'--output-dir', 'dd2',
])
assert kwargs['input_dir'] == 'dd1'
assert kwargs['output_dir'] == 'dd2'
assert kwargs['replace_str'] is None
assert kwargs['n_processes'] is None
kwargs = correct_geometries.parse_args(['--input-dir', 'dd1',
'--output-dir', 'dd2',
'--replace-str', 'r1', 'r2',
'--n-processes', '8',
])
assert kwargs['input_dir'] == 'dd1'
assert kwargs['output_dir'] == 'dd2'
assert kwargs['n_processes'] == 8
assert kwargs['replace_str']('1r1') == '1r2'
with pytest.raises(ValueError):
correct_geometries.parse_args([])
with pytest.raises(ValueError):
correct_geometries.parse_args(['--input-dir', 'dd1'])
with pytest.raises(ValueError):
correct_geometries.parse_args(['--input-dir', 'dd1',
'--output-dir', 'dd2',
'--replace-str', 'r1',
]
)
def test_correct_geometries_cli(tmpdir):
from rgitools.cli import correct_geometries
rgi_dir = os.path.join(str(tmpdir), 'RGIV60')
rgi_reg_dir = os.path.join(str(tmpdir), 'RGIV60', '06_rgi60_Iceland')
mkdir(rgi_reg_dir)
for e in ['.shp', '.prj', '.dbf', '.shx']:
shutil.copyfile(get_demo_file('RGI6_icecap' + e),
os.path.join(rgi_reg_dir, '06_rgi60_Iceland' + e))
out_dir = os.path.join(str(tmpdir), 'RGIV61')
def replace(s):
return s.replace('rgi60', 'rgi61')
correct_geometries.run(rgi_dir, out_dir, replace_str=replace)
outf = os.path.join(out_dir, '06_rgi61_Iceland', '06_rgi61_Iceland.shp')
assert os.path.exists(outf)
# All
df = get_iceland_df()
out = gpd.read_file(outf)
assert len(out) == len(df)
assert np.all(g.is_valid for g in out.geometry)
assert np.any(out.check_geom != '')
def test_intersects(tmpdir):
# Simple ice cap
df = get_iceland_df(reduced=True)
test_of = os.path.join(str(tmpdir), 'interfile.shp')
out = funcs.compute_intersects(df, to_file=test_of, job_id='test')
assert len(out) >= len(df)
assert os.path.exists(test_of)
# All elements should have an intersect with something
all_ids = np.append(out.RGIId_1.values, out.RGIId_2.values)
all_ids = np.sort(np.unique(all_ids))
assert_equal(np.sort(np.unique(df.RGIId.values)), all_ids)
def test_intersects_cli_args(tmpdir):
from rgitools.cli import compute_intersects
kwargs = compute_intersects.parse_args(['--input-dir', 'dd1',
'--output-dir', 'dd2',
])
assert kwargs['input_dir'] == 'dd1'
assert kwargs['output_dir'] == 'dd2'
assert kwargs['n_processes'] is None
kwargs = compute_intersects.parse_args(['--input-dir', 'dd1',
'--output-dir', 'dd2',
'--n-processes', '8',
])
assert kwargs['input_dir'] == 'dd1'
assert kwargs['output_dir'] == 'dd2'
assert kwargs['n_processes'] == 8
with pytest.raises(ValueError):
compute_intersects.parse_args([])
with pytest.raises(ValueError):
compute_intersects.parse_args(['--input-dir', 'dd1'])
def test_intersects_cli(tmpdir):
from rgitools.cli import compute_intersects
rgi_dir = os.path.join(str(tmpdir), 'RGIV60')
rgi_reg_dir = os.path.join(str(tmpdir), 'RGIV60', '06_rgi60_Iceland')
mkdir(rgi_reg_dir)
for e in ['.shp', '.prj', '.dbf', '.shx']:
shutil.copyfile(get_demo_file('RGI6_icecap' + e),
os.path.join(rgi_reg_dir, '06_rgi60_Iceland' + e))
out_dir = os.path.join(str(tmpdir), 'RGIV60_intersects')
compute_intersects.run(rgi_dir, out_dir)
assert os.path.exists(os.path.join(out_dir, '06_rgi60_Iceland',
'intersects_06_rgi60_Iceland.shp'))
def test_find_clusters():
# Simple ice cap
df = get_iceland_df(reduced=True)
idf = funcs.compute_intersects(df)
# Add dummy entries for testing
idf = idf.append({'RGIId_1': 'd1', 'RGIId_2': 'd2'}, ignore_index=True)
idf = idf.append({'RGIId_1': 'd1', 'RGIId_2': 'd3'}, ignore_index=True)
out = funcs.find_clusters(idf)
assert len(out) == 2
assert len(out['d1']) == 3
def test_merge_clusters():
# Simple ice cap
df = get_iceland_df(reduced=True)
# Save the area for testing later
area_ref = df.Area.sum()
# Add dummy entries for testing
from shapely.affinity import translate
idf = df.iloc[0].copy()
idf['geometry'] = translate(idf.geometry, xoff=0.15, yoff=0.0)
idf['RGIId'] = 'd1'
df = df.append(idf, ignore_index=True)
idf = df.iloc[1].copy()
idf['geometry'] = translate(idf.geometry, xoff=0.15, yoff=0.01)
idf['RGIId'] = 'd2'
df = df.append(idf, ignore_index=True)
# Intersects and go
idf = funcs.compute_intersects(df)
out = funcs.merge_clusters(df, idf)
assert len(out) == 3
assert_allclose(out.iloc[0].Area, area_ref)
s1 = df.iloc[-2]
s2 = out.loc[out.RGIId == 'd1'].iloc[0]
assert_equal(s1.CenLat, s2.CenLat)
assert_equal(s1.CenLon, s2.CenLon)
assert s1.geometry.equals(s2.geometry)
def test_merge_clusters_all():
# All
df = get_iceland_df()
# Intersects and go
idf = funcs.compute_intersects(df)
out = funcs.merge_clusters(df, idf)
assert np.all(g.is_valid for g in out.geometry)
assert np.all(g.type == 'Polygon' for g in out.geometry)
def test_zip_cli_args(tmpdir):
from rgitools.cli import zip_rgi_dir
kwargs = zip_rgi_dir.parse_args(['--input-dir', 'dd1',
'--output-file', 'dd2',
])
assert kwargs['input_dir'] == 'dd1'
assert kwargs['output_file'] == 'dd2'
with pytest.raises(ValueError):
zip_rgi_dir.parse_args([])
with pytest.raises(ValueError):
zip_rgi_dir.parse_args(['--input-dir', 'dd1'])
def test_zip_cli(tmpdir):
from rgitools.cli import zip_rgi_dir
rgi_dir = os.path.join(str(tmpdir), 'rgi_61')
outf = os.path.join(str(tmpdir), 'rgi_61')
regdirs = ['06_rgi61_Iceland', '07_rgi61_Scandinavia']
for regdir in regdirs:
rgi_reg_dir = os.path.join(rgi_dir, regdir)
mkdir(rgi_reg_dir)
for e in ['.shp', '.prj', '.dbf', '.shx']:
shutil.copyfile(get_demo_file('RGI6_icecap' + e),
os.path.join(rgi_reg_dir, '01_rgi61_Iceland' + e))
zip_rgi_dir.run(rgi_dir, outf)
assert os.path.exists(outf)
def test_hypsometry(tmpdir):
from oggm.utils import rmsd
rgi_df = gpd.read_file(get_demo_file('rgi_oetztal.shp'))
rgi_df = rgi_df.loc[['_d' not in rid for rid in rgi_df.RGIId]]
outf = os.path.join(str(tmpdir), 'rgi_62')
# Make if fail somewhere
from shapely.affinity import translate
geo = rgi_df.iloc[0, -1]
rgi_df.iloc[0, -1] = translate(geo, xoff=10)
rgi_df.loc[1, 'RGIFlag'] = '2909'
def set_oggm_params(cfg):
cfg.PATHS['dem_file'] = get_demo_file('srtm_oetztal.tif')
cfg.PARAMS['use_multiprocessing'] = False
df, gdf = funcs.hypsometries(rgi_df, set_oggm_params=set_oggm_params,
to_file=outf)
assert np.all(df.loc[0, df.columns[3:]] == -9)
assert np.all(df.loc[1, df.columns[3:]] == -9)
assert not np.isfinite(gdf.loc[0, 'Aspect'])
assert gdf.loc[1, 'Aspect'] == rgi_df.loc[1, 'Aspect']
df = df.iloc[2:]
assert np.all(df[df.columns[3:]].sum(axis=1) == 1000)
gdf = gdf.iloc[2:]
rgi_df = rgi_df.iloc[2:]
assert rmsd(gdf['Zmed'], rgi_df['Zmed']) < 25
assert rmsd(gdf['Zmin'], rgi_df['Zmin']) < 25
assert rmsd(gdf['Zmax'], rgi_df['Zmax']) < 25
assert rmsd(gdf['Slope'], rgi_df['Slope']) < 2
# For aspect test for cos / sin because of 0 360 thing
us = np.cos(np.deg2rad(gdf.Aspect))
ref = np.cos(np.deg2rad(rgi_df.Aspect))
assert rmsd(us, ref) < 0.3
us = np.sin(np.deg2rad(gdf.Aspect))
ref = np.sin(np.deg2rad(rgi_df.Aspect))
assert rmsd(us, ref) < 0.3
##
df = pd.read_csv(outf + '_hypso.csv')
gdf = gpd.read_file(outf + '.shp')
assert np.all(df.loc[0, df.columns[3:]] == -9)
assert np.all(df.loc[1, df.columns[3:]] == -9)
assert not np.isfinite(gdf.loc[0, 'Aspect'])
df = df.iloc[2:]
assert np.all(df[df.columns[3:]].sum(axis=1) == 1000)
gdf = gdf.iloc[2:]
assert rmsd(gdf['Zmed'], rgi_df['Zmed']) < 25
assert rmsd(gdf['Zmin'], rgi_df['Zmin']) < 25
assert rmsd(gdf['Zmax'], rgi_df['Zmax']) < 25
assert rmsd(gdf['Slope'], rgi_df['Slope']) < 2
# For aspect test for cos / sin because of 0 360 thing
us = np.cos(np.deg2rad(gdf.Aspect))
ref = np.cos(np.deg2rad(rgi_df.Aspect))
assert rmsd(us, ref) < 0.3
us = np.sin(np.deg2rad(gdf.Aspect))
ref = np.sin(np.deg2rad(rgi_df.Aspect))
assert rmsd(us, ref) < 0.3
def set_oggm_params(cfg):
cfg.PATHS['dem_file'] = get_demo_file('srtm_oetztal.tif')
def test_correct_hypsometries_cli_args(tmpdir):
from rgitools.cli import compute_hypsometries
kwargs = compute_hypsometries.parse_args(['--input-dir', 'dd1',
'--output-dir', 'dd2',
])
assert kwargs['input_dir'] == 'dd1'
assert kwargs['output_dir'] == 'dd2'
assert kwargs['replace_str'] is None
assert kwargs['n_processes'] is None
kwargs = compute_hypsometries.parse_args(['--input-dir', 'dd1',
'--output-dir', 'dd2',
'--replace-str', 'r1', 'r2',
'--n-processes', '8',
])
assert kwargs['input_dir'] == 'dd1'
assert kwargs['output_dir'] == 'dd2'
assert kwargs['n_processes'] == 8
assert kwargs['replace_str']('1r1') == '1r2'
with pytest.raises(ValueError):
compute_hypsometries.parse_args([])
with pytest.raises(ValueError):
compute_hypsometries.parse_args(['--input-dir', 'dd1'])
with pytest.raises(ValueError):
compute_hypsometries.parse_args(['--input-dir', 'dd1',
'--output-dir', 'dd2',
'--replace-str', 'r1',
]
)
def test_hypsometries_cli(tmpdir):
from rgitools.cli import compute_hypsometries, correct_geometries
rgi_dir = os.path.join(str(tmpdir), 'RGIV60')
rgi_reg_dir = os.path.join(str(tmpdir), 'RGIV60', '11_rgi60_Europe')
mkdir(rgi_reg_dir)
for e in ['.shp', '.prj', '.dbf', '.shx']:
shutil.copyfile(get_demo_file('rgi_oetztal' + e),
os.path.join(rgi_reg_dir, '11_rgi60_Europe' + e))
tmp_dir = os.path.join(str(tmpdir), 'RGIV61')
def replace(s):
return s.replace('rgi60', 'rgi61')
correct_geometries.run(rgi_dir, tmp_dir, replace_str=replace)
outf = os.path.join(tmp_dir, '11_rgi61_Europe', '11_rgi61_Europe.shp')
assert os.path.exists(outf)
# All
df = gpd.read_file(get_demo_file('rgi_oetztal.shp'))
out = gpd.read_file(outf)
assert len(out) == len(df)
assert np.all(g.is_valid for g in out.geometry)
assert np.any(out.check_geom != '')
out_dir = os.path.join(str(tmpdir), 'RGIV62')
def replace(s):
return s.replace('rgi61', 'rgi62')
compute_hypsometries.run(tmp_dir, out_dir,
replace_str=replace,
set_oggm_params=set_oggm_params)
outf = os.path.join(out_dir, '11_rgi62_Europe', '11_rgi62_Europe.shp')
assert os.path.exists(outf)
outf = os.path.join(out_dir, '11_rgi62_Europe',
'11_rgi62_Europe_hypso.csv')
assert os.path.exists(outf)
outf = os.path.join(out_dir, '11_rgi62_Europe',
'11_rgi62_Europe_hypso.csv')
assert os.path.exists(outf)