-
Notifications
You must be signed in to change notification settings - Fork 101
/
utils.py
3606 lines (2948 loc) · 115 KB
/
utils.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
"""Some useful functions that did not fit into the other modules.
"""
# Builtins
import glob
import os
import tempfile
import gzip
import bz2
import json
import shutil
import zipfile
import sys
import math
import datetime
import logging
import pickle
import warnings
from collections import OrderedDict
from functools import partial, wraps
from time import gmtime, strftime
import time
import fnmatch
import platform
import struct
import importlib
from urllib.parse import urlparse
# External libs
import geopandas as gpd
import pandas as pd
import salem
from salem import lazy_property, read_shapefile
import numpy as np
import netCDF4
from scipy import stats
from shapely.ops import transform as shp_trafo
from salem import wgs84
import xarray as xr
import rasterio
from scipy.ndimage import filters
from scipy.signal import gaussian
from scipy.interpolate import interp1d
import shapely.geometry as shpg
from shapely.ops import linemerge
try:
# rasterio V > 1.0
from rasterio.merge import merge as merge_tool
except ImportError:
from rasterio.tools.merge import merge as merge_tool
import multiprocessing as mp
import requests
try:
ModuleNotFoundError
except NameError:
ModuleNotFoundError = ImportError
# Locals
from oggm import __version__
import oggm.cfg as cfg
from oggm.cfg import SEC_IN_YEAR, SEC_IN_MONTH
# Module logger
logger = logging.getLogger(__name__)
# Github repository and commit hash/branch name/tag name on that repository
# The given commit will be downloaded from github and used as source for
# all sample data
SAMPLE_DATA_GH_REPO = 'OGGM/oggm-sample-data'
SAMPLE_DATA_COMMIT = '999ebbf0a48d8892058b3e2323bd975eed8a56b5'
CRU_SERVER = ('https://crudata.uea.ac.uk/cru/data/hrg/cru_ts_4.01/cruts'
'.1709081022.v4.01/')
HISTALP_SERVER = 'http://www.zamg.ac.at/histalp/download/grid5m/'
_RGI_METADATA = dict()
DEM3REG = {
'ISL': [-25., -12., 63., 67.], # Iceland
'SVALBARD': [10., 34., 76., 81.],
'JANMAYEN': [-10., -7., 70., 72.],
'FJ': [36., 66., 79., 82.], # Franz Josef Land
'FAR': [-8., -6., 61., 63.], # Faroer
'BEAR': [18., 20., 74., 75.], # Bear Island
'SHL': [-3., 0., 60., 61.], # Shetland
# Antarctica tiles as UTM zones, large files
# '01-15': [-180., -91., -90, -60.],
# '16-30': [-91., -1., -90., -60.],
# '31-45': [-1., 89., -90., -60.],
# '46-60': [89., 189., -90., -60.],
# Greenland tiles
# 'GL-North': [-78., -11., 75., 84.],
# 'GL-West': [-68., -42., 64., 76.],
# 'GL-South': [-52., -40., 59., 64.],
# 'GL-East': [-42., -17., 64., 76.]
}
# Function
tuple2int = partial(np.array, dtype=np.int64)
# Global Lock
lock = mp.Lock()
# Shape factors
# TODO: how to handle zeta > 10? at the moment extrapolation
# Table 1 from Adhikari (2012) and corresponding interpolation functions
_ADHIKARI_TABLE_ZETAS = np.array([0.5, 1, 2, 3, 4, 5, 10])
_ADHIKARI_TABLE_RECTANGULAR = np.array([0.313, 0.558, 0.790, 0.884,
0.929, 0.954, 0.990])
_ADHIKARI_TABLE_PARABOLIC = np.array([0.251, 0.448, 0.653, 0.748,
0.803, 0.839, 0.917])
ADHIKARI_FACTORS_RECTANGULAR = interp1d(_ADHIKARI_TABLE_ZETAS,
_ADHIKARI_TABLE_RECTANGULAR,
fill_value='extrapolate')
ADHIKARI_FACTORS_PARABOLIC = interp1d(_ADHIKARI_TABLE_ZETAS,
_ADHIKARI_TABLE_PARABOLIC,
fill_value='extrapolate')
def _get_download_lock():
return lock
class NoInternetException(Exception):
pass
class HttpDownloadError(Exception):
def __init__(self, code):
self.code = code
class HttpContentTooShortError(Exception):
pass
def _call_dl_func(dl_func, cache_path):
"""Helper so the actual call to downloads cann be overridden
"""
return dl_func(cache_path)
def _cached_download_helper(cache_obj_name, dl_func, reset=False):
"""Helper function for downloads.
Takes care of checking if the file is already cached.
Only calls the actual download function when no cached version exists.
"""
cache_dir = cfg.PATHS['dl_cache_dir']
cache_ro = cfg.PARAMS['dl_cache_readonly']
try:
# this is for real runs
fb_cache_dir = os.path.join(cfg.PATHS['working_dir'], 'cache')
except KeyError:
fb_cache_dir = ''
if not cache_dir:
# Defaults to working directory: it must be set!
if not cfg.PATHS['working_dir']:
raise ValueError("Need a valid PATHS['working_dir']!")
cache_dir = fb_cache_dir
cache_ro = False
fb_path = os.path.join(fb_cache_dir, cache_obj_name)
if not reset and os.path.isfile(fb_path):
return fb_path
cache_path = os.path.join(cache_dir, cache_obj_name)
if not reset and os.path.isfile(cache_path):
return cache_path
if cache_ro:
cache_path = fb_path
if not cfg.PARAMS['has_internet']:
raise NoInternetException("Download required, but "
"`has_internet` is False.")
mkdir(os.path.dirname(cache_path))
try:
cache_path = _call_dl_func(dl_func, cache_path)
except BaseException:
if os.path.exists(cache_path):
os.remove(cache_path)
raise
return cache_path
def _requests_urlretrieve(url, path, reporthook):
"""Implements the required features of urlretrieve on top of requests
"""
chunk_size = 128 * 1024
chunk_count = 0
with requests.get(url, stream=True) as r:
if r.status_code != 200:
raise HttpDownloadError(r.status_code)
r.raise_for_status()
size = r.headers.get('content-length') or 0
size = int(size)
if reporthook:
reporthook(chunk_count, chunk_size, size)
with open(path, 'wb') as f:
for chunk in r.iter_content(chunk_size=chunk_size):
if not chunk:
continue
f.write(chunk)
chunk_count += 1
if reporthook:
reporthook(chunk_count, chunk_size, size)
if chunk_count * chunk_size < size:
raise HttpContentTooShortError()
def _urlretrieve(url, cache_obj_name=None, reset=False, reporthook=None):
"""Wrapper around urlretrieve, to implement our caching logic.
Instead of accepting a destination path, it decided where to store the file
and returns the local path.
"""
if cache_obj_name is None:
cache_obj_name = urlparse(url)
cache_obj_name = cache_obj_name.netloc + cache_obj_name.path
def _dlf(cache_path):
logger.info("Downloading %s to %s..." % (url, cache_path))
_requests_urlretrieve(url, cache_path, reporthook)
return cache_path
return _cached_download_helper(cache_obj_name, _dlf, reset)
def _progress_urlretrieve(url, cache_name=None, reset=False):
"""Downloads a file, returns its local path, and shows a progressbar."""
try:
from progressbar import DataTransferBar, UnknownLength
pbar = [None]
def _upd(count, size, total):
if pbar[0] is None:
pbar[0] = DataTransferBar()
if pbar[0].max_value is None:
if total > 0:
pbar[0].start(total)
else:
pbar[0].start(UnknownLength)
pbar[0].update(min(count * size, total))
sys.stdout.flush()
res = _urlretrieve(url, cache_obj_name=cache_name, reset=reset,
reporthook=_upd)
try:
pbar[0].finish()
except BaseException:
pass
return res
except (ImportError, ModuleNotFoundError):
return _urlretrieve(url, cache_obj_name=cache_name, reset=reset)
def aws_file_download(aws_path, cache_name=None, reset=False):
with _get_download_lock():
return _aws_file_download_unlocked(aws_path, cache_name, reset)
def _aws_file_download_unlocked(aws_path, cache_name=None, reset=False):
"""Download a file from the AWS drive s3://astgtmv2/
**Note:** you need AWS credentials for this to work.
Parameters
----------
aws_path: path relative to s3://astgtmv2/
"""
while aws_path.startswith('/'):
aws_path = aws_path[1:]
if cache_name is not None:
cache_obj_name = cache_name
else:
cache_obj_name = 'astgtmv2/' + aws_path
def _dlf(cache_path):
import boto3
import botocore
client = boto3.client('s3')
logger.info("Downloading %s from s3 to %s..." % (aws_path, cache_path))
try:
client.download_file('astgtmv2', aws_path, cache_path)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "404":
return None
else:
raise
return cache_path
return _cached_download_helper(cache_obj_name, _dlf, reset)
def file_downloader(www_path, retry_max=5, cache_name=None, reset=False):
"""A slightly better downloader: it tries more than once."""
local_path = None
retry_counter = 0
while retry_counter <= retry_max:
# Try to download
try:
retry_counter += 1
local_path = _progress_urlretrieve(www_path, cache_name=cache_name,
reset=reset)
# if no error, exit
break
except HttpDownloadError as err:
# This works well for py3
if err.code == 404:
# Ok so this *should* be an ocean tile
return None
elif err.code >= 500 and err.code < 600:
logger.info("Downloading %s failed with HTTP error %s, "
"retrying in 10 seconds... %s/%s" %
(www_path, err.code, retry_counter, retry_max))
time.sleep(10)
continue
else:
raise
except HttpContentTooShortError as err:
logger.info("Downloading %s failed with ContentTooShortError"
" error %s, retrying in 10 seconds... %s/%s" %
(www_path, err.code, retry_counter, retry_max))
time.sleep(10)
continue
# See if we managed (fail is allowed)
if not local_path or not os.path.exists(local_path):
logger.warning('Downloading %s failed.' % www_path)
return local_path
def empty_cache():
"""Empty oggm's cache directory."""
if os.path.exists(cfg.CACHE_DIR):
shutil.rmtree(cfg.CACHE_DIR)
os.makedirs(cfg.CACHE_DIR)
def expand_path(p):
"""Helper function for os.path.expanduser and os.path.expandvars"""
return os.path.expandvars(os.path.expanduser(p))
def del_empty_dirs(s_dir):
"""Delete empty directories."""
b_empty = True
for s_target in os.listdir(s_dir):
s_path = os.path.join(s_dir, s_target)
if os.path.isdir(s_path):
if not del_empty_dirs(s_path):
b_empty = False
else:
b_empty = False
if b_empty:
os.rmdir(s_dir)
return b_empty
def gettempdir(dirname='', reset=False):
"""Get a temporary directory.
Parameters
----------
dirname : str
if you want to give it a name
reset : bool
if it has to be emptied first.
Returns
-------
the path to the temporary directory
"""
return mkdir(os.path.join(tempfile.gettempdir(), 'OGGM', dirname),
reset=reset)
def get_sys_info():
"""Returns system information as a dict"""
blob = []
try:
(sysname, nodename, release,
version, machine, processor) = platform.uname()
blob.extend([
("python", "%d.%d.%d.%s.%s" % sys.version_info[:]),
("python-bits", struct.calcsize("P") * 8),
("OS", "%s" % (sysname)),
("OS-release", "%s" % (release)),
("machine", "%s" % (machine)),
("processor", "%s" % (processor)),
])
except BaseException:
pass
return blob
def show_versions(logger=None):
"""Prints the OGGM version and other system information.
Parameters
----------
logger : optional
the logger you want to send the printouts to. If None, will use stdout
"""
_print = print if logger is None else logger.info
sys_info = get_sys_info()
deps = [
# (MODULE_NAME, f(mod) -> mod version)
("oggm", lambda mod: mod.__version__),
("numpy", lambda mod: mod.__version__),
("scipy", lambda mod: mod.__version__),
("pandas", lambda mod: mod.__version__),
("geopandas", lambda mod: mod.__version__),
("netCDF4", lambda mod: mod.__version__),
("matplotlib", lambda mod: mod.__version__),
("rasterio", lambda mod: mod.__version__),
("fiona", lambda mod: mod.__version__),
("osgeo.gdal", lambda mod: mod.__version__),
("pyproj", lambda mod: mod.__version__),
]
deps_blob = list()
for (modname, ver_f) in deps:
try:
if modname in sys.modules:
mod = sys.modules[modname]
else:
mod = importlib.import_module(modname)
ver = ver_f(mod)
deps_blob.append((modname, ver))
except BaseException:
deps_blob.append((modname, None))
_print(" System info:")
for k, stat in sys_info:
_print("%s: %s" % (k, stat))
_print(" Packages info:")
for k, stat in deps_blob:
_print("%s: %s" % (k, stat))
def parse_rgi_meta(version=None):
"""Read the meta information (region and sub-region names)"""
global _RGI_METADATA
if version is None:
version = cfg.PARAMS['rgi_version']
if version in _RGI_METADATA:
return _RGI_METADATA[version]
# Parse RGI metadata
get_demo_file('rgi_regions.csv')
_d = os.path.join(cfg.CACHE_DIR,
'oggm-sample-data-%s' % SAMPLE_DATA_COMMIT,
'rgi_meta')
reg_names = pd.read_csv(os.path.join(_d, 'rgi_regions.csv'), index_col=0)
if version in ['4', '5']:
# The files where different back then
subreg_names = pd.read_csv(os.path.join(_d, 'rgi_subregions_V5.csv'),
index_col=0)
else:
f = os.path.join(_d, 'rgi_subregions_V{}.csv'.format(version))
subreg_names = pd.read_csv(f)
subreg_names.index = ['{:02d}-{:02d}'.format(s1, s2) for s1, s2 in
zip(subreg_names['O1'], subreg_names['O2'])]
subreg_names = subreg_names[['Full_name']]
# For idealized
reg_names.loc[0] = ['None']
subreg_names.loc['00-00'] = ['None']
_RGI_METADATA[version] = (reg_names, subreg_names)
return _RGI_METADATA[version]
class SuperclassMeta(type):
"""Metaclass for abstract base classes.
http://stackoverflow.com/questions/40508492/python-sphinx-inherit-
method-documentation-from-superclass
"""
def __new__(mcls, classname, bases, cls_dict):
cls = super().__new__(mcls, classname, bases, cls_dict)
for name, member in cls_dict.items():
if not getattr(member, '__doc__'):
try:
member.__doc__ = getattr(bases[-1], name).__doc__
except AttributeError:
pass
return cls
class LRUFileCache():
"""A least recently used cache for temporary files.
The files which are no longer used are deleted from the disk.
"""
def __init__(self, l0=None, maxsize=100):
"""Instanciate.
Parameters
----------
l0 : list
a list of file paths
maxsize : int
the max number of files to keep
"""
self.files = [] if l0 is None else l0
self.maxsize = maxsize
self.purge()
def purge(self):
"""Remove expired entries."""
if len(self.files) > self.maxsize:
fpath = self.files.pop(0)
if os.path.exists(fpath):
os.remove(fpath)
def append(self, fpath):
"""Append a file to the list."""
if fpath not in self.files:
self.files.append(fpath)
self.purge()
def download_oggm_files():
with _get_download_lock():
return _download_oggm_files_unlocked()
def _download_oggm_files_unlocked():
"""Checks if the demo data is already on the cache and downloads it."""
zip_url = 'https://github.com/%s/archive/%s.zip' % \
(SAMPLE_DATA_GH_REPO, SAMPLE_DATA_COMMIT)
odir = os.path.join(cfg.CACHE_DIR)
sdir = os.path.join(cfg.CACHE_DIR,
'oggm-sample-data-%s' % SAMPLE_DATA_COMMIT)
# download only if necessary
if not os.path.exists(sdir):
ofile = file_downloader(zip_url)
with zipfile.ZipFile(ofile) as zf:
zf.extractall(odir)
assert os.path.isdir(sdir)
# list of files for output
out = dict()
for root, directories, filenames in os.walk(sdir):
for filename in filenames:
if filename in out:
# This was a stupid thing, and should not happen
# TODO: duplicates in sample data...
k = os.path.join(os.path.basename(root), filename)
assert k not in out
out[k] = os.path.join(root, filename)
else:
out[filename] = os.path.join(root, filename)
return out
def _download_srtm_file(zone):
with _get_download_lock():
return _download_srtm_file_unlocked(zone)
def _download_srtm_file_unlocked(zone):
"""Checks if the srtm data is in the directory and if not, download it.
"""
# extract directory
tmpdir = cfg.PATHS['tmp_dir']
mkdir(tmpdir)
outpath = os.path.join(tmpdir, 'srtm_' + zone + '.tif')
# check if extracted file exists already
if os.path.exists(outpath):
return outpath
# Did we download it yet?
wwwfile = 'http://srtm.csi.cgiar.org/SRT-ZIP/SRTM_V41/' +\
'SRTM_Data_GeoTiff/srtm_' + zone + '.zip'
dest_file = file_downloader(wwwfile)
# None means we tried hard but we couldn't find it
if not dest_file:
return None
# ok we have to extract it
if not os.path.exists(outpath):
with zipfile.ZipFile(dest_file) as zf:
zf.extractall(tmpdir)
# See if we're good, don't overfill the tmp directory
assert os.path.exists(outpath)
cfg.get_lru_handler(tmpdir).append(outpath)
return outpath
def _download_dem3_viewpano(zone):
with _get_download_lock():
return _download_dem3_viewpano_unlocked(zone)
def _download_dem3_viewpano_unlocked(zone):
"""Checks if the DEM3 data is in the directory and if not, download it.
"""
# extract directory
tmpdir = cfg.PATHS['tmp_dir']
mkdir(tmpdir)
outpath = os.path.join(tmpdir, zone + '.tif')
# check if extracted file exists already
if os.path.exists(outpath):
return outpath
# OK, so see if downloaded already
# some files have a newer version 'v2'
if zone in ['R33', 'R34', 'R35', 'R36', 'R37', 'R38', 'Q32', 'Q33', 'Q34',
'Q35', 'Q36', 'Q37', 'Q38', 'Q39', 'Q40', 'P31', 'P32', 'P33',
'P34', 'P35', 'P36', 'P37', 'P38', 'P39', 'P40']:
ifile = 'http://viewfinderpanoramas.org/dem3/' + zone + 'v2.zip'
elif zone in ['01-15', '16-30', '31-45', '46-60']:
ifile = 'http://viewfinderpanoramas.org/ANTDEM3/' + zone + '.zip'
else:
ifile = 'http://viewfinderpanoramas.org/dem3/' + zone + '.zip'
dfile = file_downloader(ifile)
# None means we tried hard but we couldn't find it
if not dfile:
return None
# ok we have to extract it
with zipfile.ZipFile(dfile) as zf:
zf.extractall(tmpdir)
# Serious issue: sometimes, if a southern hemisphere URL is queried for
# download and there is none, a NH zip file is downloaded.
# Example: http://viewfinderpanoramas.org/dem3/SN29.zip yields N29!
# BUT: There are southern hemisphere files that download properly. However,
# the unzipped folder has the file name of
# the northern hemisphere file. Some checks if correct file exists:
if len(zone) == 4 and zone.startswith('S'):
zonedir = os.path.join(tmpdir, zone[1:])
else:
zonedir = os.path.join(tmpdir, zone)
globlist = glob.glob(os.path.join(zonedir, '*.hgt'))
# take care of the special file naming cases
if zone in DEM3REG.keys():
globlist = glob.glob(os.path.join(tmpdir, '*', '*.hgt'))
if not globlist:
raise RuntimeError("We should have some files here, but we don't")
# merge the single HGT files (can be a bit ineffective, because not every
# single file might be exactly within extent...)
rfiles = [rasterio.open(s) for s in globlist]
dest, output_transform = merge_tool(rfiles)
profile = rfiles[0].profile
if 'affine' in profile:
profile.pop('affine')
profile['transform'] = output_transform
profile['height'] = dest.shape[1]
profile['width'] = dest.shape[2]
profile['driver'] = 'GTiff'
with rasterio.open(outpath, 'w', **profile) as dst:
dst.write(dest)
for rf in rfiles:
rf.close()
# delete original files to spare disk space
for s in globlist:
os.remove(s)
del_empty_dirs(tmpdir)
# See if we're good, don't overfill the tmp directory
assert os.path.exists(outpath)
cfg.get_lru_handler(tmpdir).append(outpath)
return outpath
def _download_aster_file(zone, unit):
with _get_download_lock():
return _download_aster_file_unlocked(zone, unit)
def _download_aster_file_unlocked(zone, unit):
"""Checks if the aster data is in the directory and if not, download it.
You need AWS cli and AWS credentials for this. Quoting Timo:
$ aws configure
Key ID und Secret you should have
Region is eu-west-1 and Output Format is json.
"""
fbname = 'ASTGTM2_' + zone + '.zip'
dirbname = 'UNIT_' + unit
# extract directory
tmpdir = cfg.PATHS['tmp_dir']
mkdir(tmpdir)
obname = 'ASTGTM2_' + zone + '_dem.tif'
outpath = os.path.join(tmpdir, obname)
aws_path = 'ASTGTM_V2/' + dirbname + '/' + fbname
dfile = _aws_file_download_unlocked(aws_path)
if dfile is None:
# Ok so this *should* be an ocean tile
return None
if not os.path.exists(outpath):
# Extract
with zipfile.ZipFile(dfile) as zf:
zf.extract(obname, tmpdir)
# See if we're good, don't overfill the tmp directory
assert os.path.exists(outpath)
cfg.get_lru_handler(tmpdir).append(outpath)
return outpath
def _download_topo_file_from_cluster(fname):
with _get_download_lock():
return _download_topo_file_from_cluster_unlocked(fname)
def _download_topo_file_from_cluster_unlocked(fname):
"""Checks if the special topo data is in the directory and if not,
download it from the cluster.
"""
# extract directory
tmpdir = cfg.PATHS['tmp_dir']
mkdir(tmpdir)
outpath = os.path.join(tmpdir, fname)
url = 'https://cluster.klima.uni-bremen.de/~fmaussion/dems/'
url += fname + '.zip'
dfile = file_downloader(url)
if not os.path.exists(outpath):
logger.info('Extracting ' + fname + '.zip to ' + outpath + '...')
with zipfile.ZipFile(dfile) as zf:
zf.extractall(tmpdir)
# See if we're good, don't overfill the tmp directory
assert os.path.exists(outpath)
cfg.get_lru_handler(tmpdir).append(outpath)
return outpath
def _get_centerline_lonlat(gdir):
"""Quick n dirty solution to write the centerlines as a shapefile"""
cls = gdir.read_pickle('centerlines')
olist = []
for j, cl in enumerate(cls[::-1]):
mm = 1 if j == 0 else 0
gs = gpd.GeoSeries()
gs['RGIID'] = gdir.rgi_id
gs['LE_SEGMENT'] = np.rint(np.max(cl.dis_on_line) * gdir.grid.dx)
gs['MAIN'] = mm
tra_func = partial(gdir.grid.ij_to_crs, crs=wgs84)
gs['geometry'] = shp_trafo(tra_func, cl.line)
olist.append(gs)
return olist
def mkdir(path, reset=False):
"""Checks if directory exists and if not, create one.
Parameters
----------
reset: erase the content of the directory if exists
Returns
-------
the path
"""
if reset and os.path.exists(path):
shutil.rmtree(path)
try:
os.makedirs(path)
except FileExistsError:
pass
return path
def include_patterns(*patterns):
"""Factory function that can be used with copytree() ignore parameter.
Arguments define a sequence of glob-style patterns
that are used to specify what files to NOT ignore.
Creates and returns a function that determines this for each directory
in the file hierarchy rooted at the source directory when used with
shutil.copytree().
https://stackoverflow.com/questions/35155382/copying-specific-files-to-a-
new-folder-while-maintaining-the-original-subdirect
"""
def _ignore_patterns(path, names):
# This is our cuisine
bname = os.path.basename(path)
if 'divide' in bname or 'log' in bname:
keep = []
else:
keep = set(name for pattern in patterns
for name in fnmatch.filter(names, pattern))
ignore = set(name for name in names
if name not in keep and not
os.path.isdir(os.path.join(path, name)))
return ignore
return _ignore_patterns
def query_yes_no(question, default="yes"): # pragma: no cover
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is True for "yes" or False for "no".
Credits: http://code.activestate.com/recipes/577058/
"""
valid = {"yes": True, "y": True, "ye": True,
"no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while True:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' "
"(or 'y' or 'n').\n")
def tolist(arg, length=None):
"""Makes sure that arg is a list."""
try:
(e for e in arg)
except TypeError:
arg = [arg]
arg = list(arg)
if length is not None:
if len(arg) == 1:
arg *= length
elif len(arg) == length:
pass
else:
raise ValueError('Cannot broadcast len {} '.format(len(arg)) +
'to desired length: {}.'.format(length))
return arg
def haversine(lon1, lat1, lon2, lat2):
"""Great circle distance between two (or more) points on Earth
Parameters
----------
lon1 : float
scalar or array of point(s) longitude
lat1 : float
scalar or array of point(s) longitude
lon2 : float
scalar or array of point(s) longitude
lat2 : float
scalar or array of point(s) longitude
Returns
-------
the distances
Examples:
---------
>>> haversine(34, 42, 35, 42)
82633.46475287154
>>> haversine(34, 42, [35, 36], [42, 42])
array([ 82633.46475287, 165264.11172113])
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon / 2)**2
c = 2 * np.arcsin(np.sqrt(a))
return c * 6371000 # Radius of earth in meters
def interp_nans(array, default=None):
"""Interpolate NaNs using np.interp.
np.interp is reasonable in that it does not extrapolate, it replaces
NaNs at the bounds with the closest valid value.
"""
_tmp = array.copy()
nans, x = np.isnan(array), lambda z: z.nonzero()[0]
if np.all(nans):
# No valid values
if default is None:
raise ValueError('No points available to interpolate: '
'please set default.')
_tmp[:] = default
else:
_tmp[nans] = np.interp(x(nans), x(~nans), array[~nans])
return _tmp
def smooth1d(array, window_size=None, kernel='gaussian'):
"""Apply a centered window smoothing to a 1D array.
Parameters
----------
array : ndarray
the array to apply the smoothing to
window_size : int
the size of the smoothing window
kernel : str
the type of smoothing (`gaussian`, `mean`)
Returns
-------
the smoothed array (same dim as input)
"""
# some defaults
if window_size is None:
if len(array) >= 9:
window_size = 9
elif len(array) >= 7:
window_size = 7
elif len(array) >= 5:
window_size = 5
elif len(array) >= 3:
window_size = 3
if window_size % 2 == 0:
raise ValueError('Window should be an odd number.')
if isinstance(kernel, str):