-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfuncs.py
2867 lines (2336 loc) · 117 KB
/
funcs.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
# -*- coding: utf-8 -*-
"""
Created: 6/7/2019
License: Creative Commons Attribution 4.0 International (CC BY 4.0)
http://creativecommons.org/licenses/by/4.0/
Python version: Tested on Python 3.7x (x64)
PURPOSE
------------------------------------------------------------------------------
[Floodplain and Channel Evaluation Toolkit]
FACET is a standalone Python tool that uses open source modules to map the
floodplain extent and compute stream channel and floodplain geomorphic metrics
such as channel width, streambank height, active floodplain width,
and stream slope from DEMs.
NOTES
------------------------------------------------------------------------------
"""
from math import atan, ceil, isinf, sqrt
from pathlib import Path
from time import strftime
from timeit import default_timer as timer
import itertools
import logging
import os
import shutil
import subprocess
import sys
import numpy as np
from scipy import signal
from scipy.ndimage import label
import scipy.ndimage as sc
import fiona
import geopandas as gpd
from geopandas.tools import sjoin
import pandas as pd
import rasterio
import rasterio.features
from rasterio import merge, mask
from rasterio.features import shapes
from rasterio.warp import calculate_default_transform, reproject, Resampling, transform
from shapely.geometry import shape, mapping, LineString, Point, Polygon
from shapely.ops import unary_union
import whitebox
np.seterr(over='raise')
# import whitebox
WBT = whitebox.WhiteboxTools()
WBT.verbose = False
def setup_logging(hucID, huc_dir):
# clean logging handlers
clear_out_logger()
# construct time stamps and log file name
st_tstamp = strftime("%a, %d %b %Y %I:%M:%S %p") # e.g. Thu, 19 Sep 2019 12:20:41 PM
log_name = hucID + strftime('_%y%m%d.log')
log_file = huc_dir / log_name
# delete old log file - it will not delete old logs from previous dates
if log_file.is_file():
os.remove(log_file)
return log_file, st_tstamp
def initialize_logger(log_file):
logger = logging.getLogger('logger_loader')
logging.basicConfig(filename=log_file, filemode='a')
logger.setLevel(logging.INFO)
formatter = logging.Formatter(
'%(asctime)s %(levelname)s [%(lineno)d] - %(message)s',
'%m/%d/%Y %I:%M:%S %p'
)
handler = logging.StreamHandler()
handler.setLevel(logging.INFO)
handler.setFormatter(formatter)
logger.addHandler(handler)
return logger
def clear_out_logger():
# Remove all handlers associated with the root logger object.
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
def breach_dem(str_dem_path, breach_output, logger):
# breach dem
st = timer()
WBT.breach_depressions(str_dem_path, breach_output, fill_pits=False)
end = round((timer() - st)/60.0, 2)
logger.info(f'{breach_output}: breach output successfully created. Time elapsed: {end} mins')
def run_tauDEM(cmd, logger):
''' execute tauDEM commands '''
try:
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
output, err = p.communicate()
# Get some feedback from the process to print out:
if err is None:
text = output.decode()
print('\n', text, '\n')
else:
print(err)
except subprocess.CalledProcessError as e:
logger.critical(f'failed to return code: {e}')
except OSError as e:
logger.critical(f'failed to execute shell: {e}')
except IOError as e:
logger.critical(f'failed to read file(s): {e}')
def open_memory_tif(arr, meta):
from rasterio.io import MemoryFile
# with rasterio.Env(GDAL_CACHEMAX=256, GDAL_NUM_THREADS='ALL_CPUS'):
with MemoryFile() as memfile:
with memfile.open(**meta) as dataset:
dataset.write(arr, indexes=1)
return memfile.open()
def my_callback(value):
if not "%" in value:
print(value)
# ===============================================================================
# Hydrologically condition DEM to allow breaching road & stream x-cross sections
# ===============================================================================
def pre_breach_DEM_conditioning(
huc_dir, hucID, str_dem_path,
str_nhd_path, census_roads, census_rails,
mask, logger):
# pre-breach DEM conditioning
st = timer()
# construct paths for temp & final files
tmp_roads = huc_dir / 'tmp_roads.shp'
tmp_rails = huc_dir / 'tmp_rails.shp'
x_sect_pts = str(huc_dir / 'x_section_pts.shp')
x_sect_polys = str(huc_dir / 'x_section_polys.shp')
ds_min_filter = str(huc_dir / 'ds_min_filter.tif')
ds_min_clip = str(huc_dir / 'ds_min_clip.tif')
dem_merge = str(huc_dir / 'dem_road_stream.tif')
# clip census roads and rails by HUC mask
shps = [(census_roads, str(tmp_roads)),
(census_rails, str(tmp_rails))]
for shp in shps:
# whitebox clip
inSHP, outSHP = shp[0], shp[1]
WBT.clip(inSHP, mask, outSHP, callback=my_callback)
# Read line layers:
gdf_nhd = gpd.read_file(str(str_nhd_path))
gdf_roads = gpd.read_file(str(tmp_roads))
if tmp_rails.is_file():
gdf_rails = gpd.read_file(str(tmp_rails))
###---If rail roads exist within the HUC---###
# find unary_unions as points for streams x roads and rails
pts_0 = gdf_roads.unary_union.intersection(gdf_nhd.unary_union)
pts_1 = gdf_rails.unary_union.intersection(gdf_nhd.unary_union)
# convert shapely geometries to gpd dataframe
pts_list = []
for pt in [pts_0, pts_1]:
# if geometry is a single point:
if pt.geom_type == 'Point':
x_coord, y_coord = pt.coords[0]
p = [{'properties': {'pt_id': 0}, 'geometry': mapping(Point(x_coord, y_coord))}]
else:
p = [
{'properties': {'pt_id': x}, 'geometry': mapping(Point(i.x, i.y))}
for x, i in enumerate(pt.geoms)
]
p_gdf = gpd.GeoDataFrame.from_features(p)
pts_list.append(p_gdf)
# merge both points gdfs, update crs and write out files
points = pd.concat(pts_list).pipe(gpd.GeoDataFrame)
points.crs = gdf_nhd.crs
points.to_file(str(x_sect_pts))
gdf_x_pts = points
# Buffer:
gdf_nhd['geometry'] = gdf_nhd['geometry'].buffer(25) # projected units (m)
gdf_roads['geometry'] = gdf_roads['geometry'].buffer(50) # projected units (m)
gdf_rails['geometry'] = gdf_rails['geometry'].buffer(50) # projected units (m)
gdf_x_pts['geometry'] = gdf_x_pts['geometry'].buffer(50) # projected units (m)
# check to see if streams and roads intersect with valid results
try:
# Intersect nhd x roads and nhd x rails
nhd_x_roads = gpd.overlay(gdf_nhd, gdf_roads, how='intersection') # nhd x roads
nhd_x_rails = gpd.overlay(gdf_nhd, gdf_rails, how='intersection') # nhd x roads
except KeyError:
pass
try:
buff_xs_x_roads = gpd.overlay(gdf_x_pts, nhd_x_roads, how='intersection') # nhd x roads
# nhd x roads x rails
buff_xs_x_rails = gpd.overlay(gdf_x_pts, nhd_x_rails, how='intersection')
merge_list = [buff_xs_x_roads, buff_xs_x_rails]
except (KeyError, NameError, AttributeError):
merge_list = [buff_xs_x_roads]
gdf_x_sect_polys = pd.concat(merge_list, sort=True).pipe(gpd.GeoDataFrame)
gdf_x_sect_polys.crs = gdf_nhd.crs
else:
###---If no rail roads within the HUC---###
# find unary_unions as points for streams x roads
pts_0 = gdf_roads.unary_union.intersection(gdf_nhd.unary_union)
# convert shapely geometries to gpd dataframe
p = [
{'properties': {'pt_id': x}, 'geometry': mapping(Point(i.x, i.y))}
for x, i in enumerate(pts_0.geoms)
]
p_gdf = gpd.GeoDataFrame.from_features(p)
# write out point files
points = p_gdf.copy()
points.crs = gdf_nhd.crs
points.to_file(str(x_sect_pts))
gdf_x_pts = points.copy()
# Buffer:
gdf_nhd['geometry'] = gdf_nhd['geometry'].buffer(25) # projected units (m)
gdf_roads['geometry'] = gdf_roads['geometry'].buffer(50) # projected units (m)
gdf_x_pts['geometry'] = gdf_x_pts['geometry'].buffer(50) # projected units (m)
# Intersect nhd x roads
nhd_x_roads = gpd.overlay(gdf_nhd, gdf_roads, how='intersection') # nhd x roads
# Intersect nhd x roads by buffered intersection points
buff_xs_x_roads = gpd.overlay(gdf_x_pts, nhd_x_roads, how='intersection') # nhd x roads
gdf_x_sect_polys = buff_xs_x_roads.copy()
gdf_x_sect_polys.crs = gdf_nhd.crs
if not gdf_x_sect_polys.empty:
# Add common ID field
# gdf_x_sect_polys['id'] = np.arange(gdf_x_sect_polys.shape[0])
gdf_x_sect_polys['id'] = 1
try:
gdf_x_sect_polys = gdf_x_sect_polys.dissolve(by='id')
except ValueError:
# if TopologyException then buffer geometry by 0.01m before dissolving
# projected units (m)
gdf_x_sect_polys['geometry'] = gdf_x_sect_polys['geometry'].buffer(0.01)
gdf_x_sect_polys = gdf_x_sect_polys.dissolve(by='id')
gdf_x_sect_polys.to_file(x_sect_polys)
''' passing circular kernel as footprint arg slows down:
scipy.ndimge.minimum_filter(), so pass 150,150
square window dims'''
# Apply the filter:
# Get the DEM:
with rasterio.open(str(str_dem_path)) as ds_dem:
profile = ds_dem.profile.copy()
arr_dem = ds_dem.read(1)
# Get the nodata val mask:
mask = arr_dem == ds_dem.nodata
# Assign nodata vals to some huge number:
arr_dem[mask] = 999999.
# apply local minima filter
arr_min = sc.minimum_filter(arr_dem, size=(150, 150)) # footprint=kernel
# Re-assign nodata vals:
arr_min[mask] = ds_dem.nodata
# Write out min. filtered DEM
with rasterio.open(ds_min_filter, 'w', **profile) as dst:
dst.write_band(1, arr_min)
# clip ds_min_filter.tif by x-section polys
WBT.clip_raster_to_polygon(
ds_min_filter,
x_sect_polys,
ds_min_clip,
maintain_dimensions=True
)
# Read DEMs
dem_min = open_memory_tif(rasterio.open(ds_min_clip, 'r').read(1), profile)
base_dem = open_memory_tif(rasterio.open(str(str_dem_path), 'r').read(1), profile)
with rasterio.open(dem_merge, 'w', **profile) as dst:
# merge happens in sequence of rasters
arr_merge, arr_trans = merge.merge([dem_min, base_dem])
dst.write(arr_merge)
# logger
end = round((timer() - st)/60.0, 2)
logger.info(f'Pre-breach DEM successfully conditioned. Time elapsed: {end} mins')
return dem_merge
# ================================================================================
# For wavelet curvature calculation
# Chandana Gangodagame
# Wavelet-Compressed Representation of Landscapes for Hydrologic and Geomorphologic Applications
# March 2016IEEE Geoscience and Remote Sensing Letters 13(4):1-6
# DOI: 10.1109/LGRS.2015.2513011
# ================================================================================
def gauss_kern(sigma):
""" Returns a normalized 2D gauss kernel array for convolutions """
sigma = int(sigma)
x, y = np.mgrid[-5 * sigma:5 * sigma, -5 * sigma:5 * sigma]
g2x = (1 - x ** 2 / sigma ** 2) * np.exp(-(x ** 2 + y ** 2) / 2 / sigma ** 2) * 1 / np.sqrt(
2 * np.pi * sigma ** 2) / 4 / sigma * np.exp(float(0.5))
g2y = (1 - y ** 2 / sigma ** 2) * np.exp(-(x ** 2 + y ** 2) / 2 / sigma ** 2) * 1 / np.sqrt(
2 * np.pi * sigma ** 2) / 4 / sigma * np.exp(float(0.5))
return g2x, g2y
# ================================================================================
# For 2D cross sectional measurement
# ================================================================================
def build_xns(lstThisSegmentRows, lstThisSegmentCols, midPtCol, midPtRow, p_xnlength):
slopeCutoffVertical = 20 # another check
# Find initial slope:
if abs(lstThisSegmentCols[0] - lstThisSegmentCols[-1]) < 3:
m_init = 9999.0
elif abs(lstThisSegmentRows[0] - lstThisSegmentRows[-1]) < 3:
m_init = 0.0001
else:
m_init = (lstThisSegmentRows[0] - lstThisSegmentRows[-1]) / (lstThisSegmentCols[0] - lstThisSegmentCols[-1])
# Check for zero or infinite slope:
if m_init == 0:
m_init = 0.0001
elif isinf(m_init):
m_init = 9999.0
# Find the orthogonal slope:
m_ortho = -1 / m_init
xn_steps = [-float(p_xnlength), float(p_xnlength)] # just the end points
lst_xy = []
for r in xn_steps:
# Make sure it's not too close to vertical:
# NOTE X-Y vs. Row-Col here:
if abs(m_ortho) > slopeCutoffVertical:
tpl_xy = (midPtCol, midPtRow + r)
else:
fit_col_ortho = (midPtCol + (float(r) / (sqrt(1 + m_ortho ** 2))))
tpl_xy = float(((midPtCol + (float(r) / (sqrt(1 + m_ortho ** 2)))))), float(
((m_ortho) * (fit_col_ortho - midPtCol) + midPtRow))
lst_xy.append(tpl_xy) # A list of two tuple endpts
return lst_xy
def get_xn_length_by_order(i_order, bool_isvalley):
# Settings for channel cross-sections:
if not bool_isvalley:
if i_order == 1:
p_xnlength = 20
p_fitlength = 3
elif i_order == 2:
p_xnlength = 23
p_fitlength = 6
elif i_order == 3:
p_xnlength = 40
p_fitlength = 9
elif i_order == 4:
p_xnlength = 60
p_fitlength = 12
elif i_order == 5:
p_xnlength = 80
p_fitlength = 15
elif i_order >= 6:
p_xnlength = 150
p_fitlength = 20
# Settings for floodplain cross-sections:
elif bool_isvalley:
if i_order == 1:
p_xnlength = 50
p_fitlength = 5
elif i_order == 2:
p_xnlength = 75
p_fitlength = 8
elif i_order == 3:
p_xnlength = 100
p_fitlength = 12
elif i_order == 4:
p_xnlength = 150
p_fitlength = 20
elif i_order == 5:
p_xnlength = 200
p_fitlength = 30
elif i_order >= 6:
p_xnlength = 500
p_fitlength = 40
return p_xnlength, p_fitlength
def get_cell_size(str_grid_path):
with rasterio.open(str(str_grid_path)) as ds_grid:
cs_x, cs_y = ds_grid.res
return cs_x
def rugosity(arr, res, logger):
'''
Actual 3D area divided by 2D planar area gives a measure
of terrain complexity or roughness
'''
try:
area3d = ((res ** 2) * (1 + np.gradient(arr) ** 2) ** 0.5).sum() # actual surface area
area2d = len(arr) * res ** 2 # planar surface area
rug = area3d / area2d
except:
logger.info(f'Error in rugosity. arr.shape: {arr.shape}')
return -9999.
return rug
# ==========================================================================
# Reproject a grid layer using rasterio
# ==========================================================================
def define_grid_projection(str_source_grid, dst_crs, dst_file):
print('Defining grid projection:')
with rasterio.open(str_source_grid, 'r') as src:
kwargs = src.meta.copy()
kwargs.update({
'crs': dst_crs,
})
arr_src = src.read(1)
with rasterio.open(dst_file, 'w', **kwargs) as dst:
dst.write(arr_src, indexes=1)
# ==========================================================================
# Reproject a grid layer using rasterio
# ==========================================================================
def reproject_grid_layer(str_source_grid, dst_crs, dst_file, resolution, logger):
# reproject raster plus resample if needed
# Resolution is a pixel value as a tuple
try:
st = timer()
with rasterio.open(str_source_grid) as src:
transform, width, height = calculate_default_transform(
src.crs, dst_crs, src.width, src.height, *src.bounds, resolution=resolution)
kwargs = src.meta.copy()
kwargs.update({
'crs': dst_crs,
'transform': transform,
'width': width,
'height': height
})
with rasterio.open(dst_file, 'w', **kwargs) as dst:
for i in range(1, src.count + 1):
reproject(
source=rasterio.band(src, i),
destination=rasterio.band(dst, i),
src_transform=src.transform,
src_crs=src.crs,
dst_transform=transform,
dst_crs=dst_crs,
resampling=Resampling.bilinear)
end = round((timer() - st)/60.0, 2)
logger.info(f'Reprojected DEM. Time elapsed: {end} mins')
return dst_file
except:
logger.critical(f'{str_source_grid}: failed to reproject.')
sys.exit(1)
# ==========================================================================
# Reproject a vector layer using geopandas
# ==========================================================================
def reproject_vector_layer(in_shp, str_target_proj4, logger):
print(f'Reprojecting vector layer: {in_shp}')
proj_shp = in_shp.parent / f'{in_shp.stem}_proj.shp'
if proj_shp.is_file():
logger.info(f'{proj_shp} reprojected file already exists\n')
return str(proj_shp)
else:
gdf = gpd.read_file(str(in_shp))
# fix float64 to int64
float64_2_int64 = ['NHDPlusID', 'Shape_Area', 'DSContArea', 'USContArea']
for col in float64_2_int64:
try:
gdf[col] = gdf[col].astype(np.int64)
except KeyError:
pass
gdf_proj = gdf.to_crs(str_target_proj4)
gdf_proj.to_file(str(proj_shp))
logger.info(f'{proj_shp} successfully reprojected\n')
return str(proj_shp)
# ==========================================================================
# For clipping features
# ==========================================================================
def clip_features_using_grid(
str_lines_path, output_filename, str_dem_path, in_crs, logger, mask_shp):
# clip features using HUC mask, if the mask doesn't exist polygonize DEM
mask_shp = Path(mask_shp)
if mask_shp.is_file():
st = timer()
# whitebox clip
WBT.clip(str_lines_path, mask_shp, output_filename)
end = round((timer() - st)/60.0, 2)
logger.info(f'Streams clipped by {mask_shp}. Time Elapsed: {end} mins')
else:
st = timer()
logger.warning(f'''
{mask_shp} does not file exists. Creating new mask from DEM.
This step can be error prone please review the output.
''')
# Polygonize the raster DEM with rasterio:
with rasterio.open(str(str_dem_path)) as ds_dem:
arr_dem = ds_dem.read(1)
arr_dem[arr_dem > 0] = 100
mask = arr_dem == 100
results = (
{'properties': {'raster_val': v}, 'geometry': s}
for i, (s, v) in enumerate(shapes(arr_dem, mask=mask, transform=ds_dem.transform))
)
poly = list(results)
poly_df = gpd.GeoDataFrame.from_features(poly)
poly_df.crs = in_crs
# poly_df = poly_df[poly_df.raster_val == 100.0]
# tmp_shp = os.path.dirname(str_dem_path) + "/mask.shp" # tmp huc mask
poly_df.to_file(str(mask_shp))
# whitebox clip
WBT.clip(str_lines_path, str(mask_shp), output_filename)
end = round((timer() - st)/60.0, 2)
logger.info(f'Streams clipped by {mask_shp}. Time Elapsed: {end} mins')
# ==========================================================================
# Polygonize watersheds
# ==========================================================================
def watershed_polygonize(in_tif, out_shp, dst_crs, logger):
logger.info("Polygonizing reach catchments")
tmp = os.path.dirname(in_tif) + "\\breach_w_tmp.shp" # tmp DEM mask
# convert the raster to polygon
mask = None
with rasterio.open(in_tif) as src:
image = src.read(1)
results = (
{'properties': {'raster_val': v}, 'geometry': s}
for i, (s, v) in enumerate(shapes(image, mask=mask, transform=src.transform))
)
# write raster vals to polygon
driver = 'Shapefile'
crs = dst_crs
schema = {'properties': [('raster_val', 'int')], 'geometry': 'Polygon'}
with fiona.open(str(tmp), 'w', driver=driver, crs=crs, schema=schema) as dst:
dst.writerecords(results)
# original sauce: https://gis.stackexchange.com/questions/149959/dissolving-polygons-based-on-attributes-with-python-shapely-fiona
# dissolve and remove nodata vals
with fiona.open(tmp) as input:
meta = input.meta # copy tmp files metadata
with fiona.open(out_shp, 'w', **meta) as output:
# sort and then perform groupby on raster_vals
by_vals = sorted(input, key=lambda k: k['properties']['raster_val'])
# group by 'raster_val'
for key, group in itertools.groupby(
by_vals, key=lambda x: x['properties']['raster_val']):
properties, geom = zip(*[(feature['properties'], shape(feature['geometry'])) for feature in group])
# perform check and exclude nodata value
if properties[0]['raster_val'] >= 0:
# capture & exclude geometries that throw ValueError performing geometry union
try:
geom = [g if g.is_valid else g.buffer(0.0) for g in geom]
test_unary = unary_union(geom)
# write the feature, computing the unary_union of the elements...
# ...in the group with the properties of the first element in the group
output.write(
{'geometry': mapping(unary_union(geom)), 'properties': properties[0]}
)
except ValueError:
logger.warning(f'''
catchment value ({properties[0]['raster_val']})
encountered a topology exception error.
Attempting to fix geometry...
''')
""" if union fails then loop through geom,
simplify geometry, append to a new geom and then perform
union -- should resolve most self-intersecting points"""
new_geom = []
for g in geom:
g_2_list = mapping(g)['coordinates'][0]
simplified_geom_lst = list(Polygon(g_2_list).simplify(0).exterior.coords)
new_geom.append(Polygon(simplified_geom_lst))
# write out updated geometry
output.write(
{'geometry': mapping(unary_union(new_geom)), 'properties': properties[0]}
)
# log warning about fixed geometry
logger.warning(f'''
catchment value ({properties[0]['raster_val']}) topology error fixed.
Please review catchment file.
''')
# ==========================================================================
# join watersheds attributes
# ==========================================================================
def join_watershed_attrs(w, physio, net, output, logger):
# 1 - read in watershed polygons
wsheds = gpd.read_file(str(w)) # watershed grid shp
points = wsheds.copy() #
# 2 - polygons to centroid points
points.geometry = points['geometry'].centroid # get centroids
points.crs = wsheds.crs # copy poly crs
# 3 - spatial join points to physiographic regions
physio = gpd.read_file(str(physio))
pointsInPhysio = sjoin(points, physio, how='left') # spatial join
# 4 - merge attrs to watershed polygons
net = gpd.read_file(str(net))
# 4.1 - rename columns
wsheds = wsheds.rename(columns={'raster_val': 'LINKNO'})
pointsInPhysio = pointsInPhysio.rename(columns={'raster_val': 'LINKNO'})
# 4.2 - drop geometry from pointsInPhysio & net files
pointsInPhysio = pointsInPhysio.drop(['geometry'], axis=1)
net = net.drop(['geometry'], axis=1)
# 4.3 - merge pointsInPhysio & net files to wsheds
wshedsMerge = wsheds.merge(pointsInPhysio, on='LINKNO') # merge 1
wshedsMerge = wshedsMerge.merge(net, on='LINKNO') # merge 2
wshedsMerge.to_file(str(output))
logger.info('Stream and Physio attributes successfully joined to Catchments')
def rasterize_gdf(str_net_path, str_ingrid_path, str_tempgrid):
gdf = gpd.read_file(str(str_net_path))
'''
Thanks to:
https://gis.stackexchange.com/questions/151339/rasterize-a-shapefile-with-geopandas-or-fiona-python
'''
with rasterio.open(str_ingrid_path) as rst:
meta = rst.meta.copy()
meta.update(compress='lzw')
meta.update(dtype=rasterio.int32)
meta.update(nodata=0)
with rasterio.open(str_tempgrid, 'w+', **meta) as out:
out_arr = out.read(1)
# this is where we create a generator of geom, value pairs to use in rasterizing
shapes = ((geom, value) for geom, value in zip(gdf.geometry, gdf['LINKNO']))
arr_burned = rasterio.features.rasterize(
shapes=shapes, fill=0, out=out_arr, transform=out.transform
)
out.write_band(1, arr_burned)
return
# ===============================================================================
# Create weight file for TauDEM D8 FAC
# ===============================================================================
def create_wg_from_streamlines(str_streamlines_path, str_dem_path, str_danglepts_path):
print('Creating weight grid from streamlines:')
lst_coords = []
lst_pts = []
lst_x = []
lst_y = []
with fiona.open(str(str_streamlines_path)) as lines:
streamlines_crs = lines.crs # to use in the output grid
# Get separate lists of start and end points:
for line in lines:
if line['geometry']['type'] == 'LineString': # Make sure it's a LineString
# Add endpts:
lst_coords.append(line['geometry']['coordinates'][-1])
# Add startpts:
lst_pts.append(line['geometry']['coordinates'][0])
# If a start point is not also in the endpt list, it's first order:
for pt in lst_pts:
if pt not in lst_coords:
lst_x.append(pt[0])
lst_y.append(pt[1])
# Open DEM to copy metadata and write a Weight Grid (WG):
with rasterio.open(str_dem_path) as ds_dem:
out_meta = ds_dem.meta.copy()
out_meta.update(compress='lzw')
out_meta.update(dtype=rasterio.int16)
out_meta.update(nodata=-9999)
out_meta.update(crs=lines.crs) # shouldn't be necessary
# Construct the output array:
arr_danglepts = np.zeros([out_meta['height'], out_meta['width']], dtype=out_meta['dtype'])
tpl_pts = transform(streamlines_crs, out_meta['crs'], lst_x, lst_y)
lst_dangles = zip(tpl_pts[0], tpl_pts[1])
for coords in lst_dangles:
# BUT you have to convert coordinates from hires to dem
col, row = ~ds_dem.transform * (coords[0], coords[1])
try:
arr_danglepts[int(row), int(col)] = 1
except:
continue
# Now write the new grid using this metadata:
with rasterio.open(str_danglepts_path, "w", **out_meta) as dest:
dest.write(arr_danglepts, indexes=1)
return
# ===============================================================================
# Mega-function for processing a raw DEM
# 1. Breaching and filling
# 2. TauDEM functions
# ===============================================================================
def preprocess_dem(
root, str_streamlines_path, dst_crs,
run_wg, run_taudem, physio,
hucID, breach_filepath, inputProc,
logger):
try:
st = timer()
# << Define all filenames here >>
str_dem_path = str(root / f'{hucID}_dem_proj.tif')
str_danglepts_path = str(root / f'{hucID}_wg.tif')
p = str(root / f'{hucID}_breach_p.tif')
sd8 = str(root / f'{hucID}_breach_sd8.tif')
ad8_wg = str(root / f'{hucID}_breach_ad8_wg.tif')
ad8_no_wg = str(root / f'{hucID}_breach_ad8_no_wg.tif')
ord_g = str(root / f'{hucID}_breach_ord_g.tif')
tree = str(root / f'{hucID}_breach_tree')
coord = str(root / f'{hucID}_breach_coord')
net = str(root / f'{hucID}_network.shp')
w = str(root / f'{hucID}_breach_w.tif')
w_shp = str(root / f'{hucID}_breach_w.shp')
slp = str(root / f'{hucID}_breach_slp.tif')
ang = str(root / f'{hucID}_breach_ang.tif')
dd = str(root / f'{hucID}_hand.tif')
wshed_physio = str(root / f'{hucID}_breach_w_diss_physio.shp')
# for debugging
# print ("01", str_dem_path)
# print ("02", breach_filepath_tif_tmp)
# print ("03", breach_filepath_tif_proj)
# print ("04", breach_filepath_dep)
# print ("05", str_danglepts_path)
# print ("11", p)
# print ("12", sd8)
# print ("13", ad8_wg)
# print ("15", ad8_no_wg)
# print ("16", ord_g)
# print ("17", tree)
# print ("18", coord)
# print ("19", net)
# print ("20", w)
# print ("21", slp)
# print ("22", ang)
# print ("23", dd)
'''
This tool is used to remove the sinks (i.e. topographic depressions and flat areas) from
digital elevation models (DEMs) using a highly efficient and flexible breaching,
or carving, method.
Arg Name: InputDEM, type: string, Description: The input DEM name with file extension
Arg Name: OutputFile, type: string, Description: The output filename with file extension
Arg Name: MaxDepth, type: float64, Description: The maximum breach channel depth (-1 to ignore)
Arg Name: MaxLength, type: int, Description: The maximum length of a breach channel (-1 to ignore)
Arg Name: ConstrainedBreaching, type: bool, Description: Use constrained breaching
Arg Name: SubsequentFilling, type: bool, Description: Perform post-breach filling
'''
if run_wg:
create_wg_from_streamlines(str_streamlines_path, str_dem_path, str_danglepts_path)
if run_taudem:
# ============== << 2. D8 FDR with TauDEM >> ================ YES
d8_flow_dir = f'mpiexec -n {inputProc} d8flowdir -fel "{breach_filepath}" -p "{p}" -sd8 "{sd8}"'
# Submit command to operating system
logger.info('Running TauDEM D8 Flow Direction...')
run_tauDEM(d8_flow_dir, logger)
logger.info('D8 Flow Direction successfully completed')
# ============= << 3.a AD8 with weight grid >> ================ YES
# flow accumulation with NHD end nodes is used to derive stream network
d8_flow_acc_w_grid = f'mpiexec -n {inputProc} AreaD8 -p "{p}" -ad8 "{ad8_wg}" -wg "{str_danglepts_path}" -nc'
# Submit command to operating system
logger.info('Running TauDEM D8 FAC (with weight grid)...')
run_tauDEM(d8_flow_acc_w_grid, logger)
logger.info('D8 FAC (with weight grid) successfully completed')
# ============= << 3.b AD8 no weight grid >> ================
# flow accumulation with-OUT NHD end nodes is used to derive sub-watersheds
d8_flow_acc_wo_grid = f'mpiexec -n {inputProc} AreaD8 -p "{p}" -ad8 "{ad8_no_wg}" -nc'
# Submit command to operating system
logger.info('Running TauDEM D8 FAC (no weights)...')
run_tauDEM(d8_flow_acc_wo_grid, logger)
logger.info('D8 FAC (no weights) successfully completed')
# ============= << 4 StreamReachandWatershed with TauDEM >> ================
reach_and_watershed = f'mpiexec -n {inputProc} StreamNet -fel "{breach_filepath}" -p "{p}" ' \
f'-ad8 "{ad8_no_wg}" -src "{ad8_wg}" -ord "{ord_g}" -tree "{tree}" -coord "{coord}" -net "{net}" -w "{w}"'
# Submit command to operating system
logger.info('Running TauDEM Stream Reach and Watershed...')
run_tauDEM(reach_and_watershed, logger)
logger.info('Stream Reach and Watershed successfully completed')
# ============= << 5. Dinf with TauDEM >> ============= YES
dInf_flow_dir = f'mpiexec -n {inputProc} DinfFlowDir -fel "{breach_filepath}" -ang "{ang}" -slp "{slp}"'
# Submit command to operating system
logger.info('Running TauDEM Dinfinity...')
run_tauDEM(dInf_flow_dir, logger)
logger.info('Dinfinity successfully completed')
# ============= << 6. DinfDistanceDown (HAND) with TauDEM >> ============= YES
# Use original DEM here
distmeth = 'v'
statmeth = 'ave'
dInf_dist_down = f'mpiexec -n {inputProc} DinfDistDown -fel "{str_dem_path}" -ang "{ang}" -src "{ad8_wg}" -dd "{dd}" -m {statmeth} {distmeth}'
logger.info('Running TauDEM Dinf Distance Down...')
# Submit command to operating system
run_tauDEM(dInf_dist_down, logger)
logger.info('Dinf Distance Down successfully completed')
# polygonize watersheds
watershed_polygonize(w, w_shp, dst_crs, logger)
# create watershed polys with physiographic attrs
join_watershed_attrs(w_shp, physio, net, wshed_physio, logger)
end = round((timer() - st)/60.0, 2)
logger.info(f'TauDEM preprocessing steps complete. Time elapsed: {end} mins')
except:
logger.critical("Unexpected error:", sys.exc_info()[0])
raise
return
def interpolate(arr_in, ind_val):
if ind_val == np.ceil(ind_val):
out_val = arr_in[int(np.ceil(ind_val))]
else:
# it will always be divided by 1
out_val = arr_in[int(ind_val)] + (ind_val - int(ind_val)) * (
arr_in[int(np.ceil(ind_val))] - arr_in[int(ind_val)])
return out_val
# Count the number of features in a vector file:
def get_feature_count(str_shp_path):
with fiona.open(str(str_shp_path), 'r') as features:
i_count = len(features)
return i_count
def hand_analysis_chsegs(
str_hand_path, str_chanmet_segs, str_src_path,
str_fp_path, str_dem_path, logger):
"""
Calculation of floodplain metrics by analyzing HAND using 2D cross-sections and
differentiating between channel pixels and floodplain pixels.
:param str_hand_path: Path to the HAND grid .tif
:param str_chanmet_segs: Path to the output of the channel_width_from_bank_pixels() func
:param str_src_path: Path to the .tif file where stream reaches correspond to linkno values
:param str_fp_path: Path to the floodplain grid .tif
:param logger: Logger instance for messaging
:return: Writes out additional attributes to the file in str_chanmet_segs
"""
# Open the stream network segments layer with channel metrics:
gdf_segs = gpd.read_file(str(str_chanmet_segs))
lst_linkno = []
# Channel metrics:
lst_bnk_ht = []
lst_chn_wid = []
lst_chn_shp = []
lst_geom = [] # for testing/creating a new output file
# FP metrics:
lst_fpmin = []
lst_fpmax = []
lst_fpstd = []
lst_fprug = []
lst_fpwid = []
lst_fprange = []
lst_fpmin_e = []
lst_fpmax_e = []
lst_fpstd_e = []
lst_fprange_e = []
# Open the hand layer:
with rasterio.open(str(str_hand_path)) as ds_hand:
out_meta = ds_hand.meta.copy()
arr_chn = np.empty([out_meta['height'], out_meta['width']], dtype=out_meta['dtype'])
arr_chn[:, :] = out_meta['nodata']
# Access the src layer for excluding channel pixels:
with rasterio.open(str(str_src_path)) as ds_src:
res = ds_hand.res[0]
# Access the floodplain grid:
with rasterio.open(str(str_fp_path)) as ds_fp:
with rasterio.open(str(str_dem_path)) as ds_dem:
# Loop over each segment:
for tpl in gdf_segs.itertuples():
try:
# if tpl.linkno != 3343:
# continue
logger.info(f'\t{tpl.Index}')
# Get Xn length based on stream order:
p_xnlength, p_fitlength = get_xn_length_by_order(tpl.order, False)
x, y = zip(*mapping(tpl.geometry)['coordinates'])
# Get the segment midpoint:
# Can also use this to identify the channel blob
midpt_x = x[int(len(x) / 2)] # This isn't actually midpt by distance
midpt_y = y[int(len(y) / 2)]
# Build a 1D cross-section from the end points:
lst_xy = build_xns(y, x, midpt_x, midpt_y, p_xnlength)
try:
# Turn the cross-section into a linestring:
fp_ls = LineString([Point(lst_xy[0]), Point(lst_xy[1])])
except Exception as e:
logger.info(f'Error converting Xn endpts to LineString: {str(e)}')
pass
# Buffer the cross section to form a 2D rectangle:
# about half of the line segment...
# ...straight line distance --> AFFECTS LABELLED ARRAY!
buff_len = tpl.dist_sl / 2.5
geom_fpls_buff = fp_ls.buffer(buff_len, cap_style=2)
xn_buff = mapping(geom_fpls_buff)
# Mask the hand grid for each feature: