-
Notifications
You must be signed in to change notification settings - Fork 1
/
funcs_v2.py
3380 lines (2689 loc) · 146 KB
/
funcs_v2.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 on Wed Dec 7 14:51:45 2016
@author: sam.lamont
"""
# import math
import subprocess
# import timeit
import numpy as np
from numpy import asarray
import logging
from scipy.ndimage import label
# from scipy.stats import gaussian_kde # TEST
# from scipy.optimize import curve_fit # TEST
from scipy import signal
from scipy.ndimage import percentile_filter
import os
# import ntpath
from math import atan, ceil, floor
import sys
from math import isinf, sqrt
import rasterio
import rasterio.mask
from rasterio.warp import transform
from rasterio.warp import calculate_default_transform, reproject, Resampling
from rasterio.features import shapes
from rasterio import features
from functools import partial
import multiprocessing as mp
# import whitebox
# wbt = whitebox.WhiteboxTools()
# import matplotlib
# matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
plt.style.use('ggplot')
# from mpl_toolkits.mplot3d import Axes3D
# from matplotlib import cm
# from affine import Affine
import pandas as pd
import geopandas as gpd
# from scipy import ndimage
# from shapely.geometry import Point,
from shapely.geometry import shape, mapping, LineString, MultiLineString, Point, MultiPoint
from shapely.ops import split
# from jenks import jenks
# from PyQt4 import QtGui, QtCore
# import scipy.io as sio
import fiona
# from fiona import collection
# from fiona.crs import from_epsg
# import jenkspy
# import gospatial as gs
np.seterr(over='raise')
# plt.ion()
# from shapely import speedups
# if speedups.available:
# speedups.enable() # enable performance enhancements written in C
# LOGGER SETUP #
# logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG, format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
# does this need to be set? level=logging.DEBUG,
# logging.debug('This message should go to the log file')
# logging.info('So should this')
# logging.warning('And this, too')
# END LOGGER SETUP #
# ===============================================================================
# Utility functions
# ===============================================================================
# def open_mat_files():
#
# # Loads a MATLAB file (.mat) using SciPy...
# test = sio.loadmat(r'C:\USGS_TerrainBathymetry_Project\CBP_analysis\field_data\FieldData\smith\AtGageAB_US.mat')
#
# arr_data = test['AtGageAB_US'] #numpy array
#
# return
# def rotate(x_center, x_orig, y_center, y_orig, theta):
# x_rot = np.cos(theta)*(x_orig-x_center) - np.sin(theta)*(y_orig-y_center) + x_center
# y_rot = np.sin(theta)*(x_orig-x_center) + np.cos(theta)*(y_orig-y_center) + y_center
# return x_rot, y_rot
# lstThisSegmentRows, lstThisSegmentCols, midpt_x, midpt_y, p_fpxnlen
def open_memory_tif(arr, meta):
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 breach_road_crossings(str_nhd_path, str_roads_path, str_dem_path):
# Build the kernel:
# https://stackoverflow.com/questions/39272267/local-maxima-with-circular-window
radius = 25 # num pixels
kernel = np.zeros((2 * radius + 1, 2 * radius + 1))
y, x = np.ogrid[-radius:radius + 1, -radius:radius + 1]
mask2 = x ** 2 + y ** 2 <= radius ** 2
kernel[mask2] = 1
# Get the DEM:
with rasterio.open(str_dem_path) as ds_dem:
profile = ds_dem.profile.copy()
arr_dem = ds_dem.read(1)
# Apply the filter:
import scipy.ndimage as sc
arr_min = sc.minimum_filter(arr_dem, footprint=kernel)
# Create in-memory dataset using arr_min:
ds_min = open_memory_tif(arr_min, profile)
# Get the line layers:
gdf_nhd = gpd.read_file(str_nhd_path)
gdf_roads = gpd.read_file(str_roads_path)
# Buffer:
gdf_nhd['geometry'] = gdf_nhd['geometry'].buffer(25) # projected units (m)
gdf_roads['geometry'] = gdf_roads['geometry'].buffer(50) # projected units (m)
# Intersect:
gdf_int = gpd.overlay(gdf_nhd, gdf_roads, how='intersection')
# rasterio.mask.mask in-memory dataset and buffer intersects
int_poly = gdf_int['geometry'].iloc[0] # is there only one?
arr_mask, trans_mask = rasterio.mask.mask(ds_min, int_poly, crop=True, nodata=nodata,
all_touched=True)
# mosaic with rasterio.merge?
ds_mask = open_memory_tif(arr_mask, profile)
from rasterio.merge import merge
arr_merge, trans_merge = merge([ds_dem, ds_mask])
# write to arr_merge to tif:
with rasterio.open(output_tif_path, 'w', **profile) as ds_out:
ds_out.write(arr_merge)
def rasterize_gdf(gdf, str_ingrid_path, str_tempgrid, str_outgrid, huc_poly):
'''
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 = features.rasterize(shapes=shapes, fill=0, out=out_arr, transform=out.transform)
out.write_band(1, arr_burned)
# w_pts, trans_pts = rasterio.mask.mask(ds_pts, huc_mask, crop=True, nodata=nodata, all_touched=True)
# out_mask, out_trans=rasterio.mask.mask(out, [mapping(huc_poly)], crop=True, nodata=0) #, all_touched=True)
# out.write_band(1, out_mask)
#
# with rasterio.open(str_outgrid, 'w', **meta) as ds_out:
# ds_out.write_band(1, out_mask[0])
return
def compress_grids(str_in_grid, str_out_grid, logger):
'''
:param str_in_grid:
:param str_out_grid:
:param logger:
:return:
'''
# Access the interp pts .tif file:
with rasterio.open(str_in_grid) as ds_in:
meta_in = ds_in.meta.copy()
meta_in.update(compress='lzw')
meta_in.update(dtype=rasterio.float32)
arr = ds_in.read(1)
logger.info('Applying percentile filter...')
arr = percentile_filter(arr, 50., size=3)
logger.info('Compressing and saving as regular TIFF...')
with rasterio.Env(GDAL_CACHEMAX=256, GDAL_NUM_THREADS='ALL_CPUS', BIGTIFF='NO'):
with rasterio.open(str_out_grid, 'w', tiled=True, blockxsize=512, blockysize=512, **meta_in) as ds_out:
ds_out.write(arr.astype(rasterio.float32), indexes=1)
# ================================================================================
# For wavelet curvature calculation (Chandana)
# ================================================================================
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])
# if (max(lstThisSegmentCols) - min(lstThisSegmentCols) < 3):
# m_init = 9999.0
# elif (max(lstThisSegmentRows) - min(lstThisSegmentRows) < 3):
# m_init = 0.0001
# else:
# LinFit = np.polyfit(lstThisSegmentCols,lstThisSegmentRows,1) # NOTE: could just use basic math here instead?!
# m_init = LinFit[0]
# 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, logger):
logger.info('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):
""" Resolution is a pixel value as a tuple"""
logger.info('Reprojecting grid layer...')
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)
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)
# ==========================================================================
# Reproject a vector layer using geopandas
# ==========================================================================
def reproject_vector_layer(str_path_to_file, str_target_proj4, logger):
logger.info('Reprojecting vector layer...')
gdf = gpd.read_file(str_path_to_file)
gdf = gdf.to_crs(str_target_proj4)
str_out_path = str_path_to_file[:-4] + '_proj.shp'
gdf.to_file(str_out_path)
return str_out_path
# ==========================================================================
# For dissolving line features
# ==========================================================================
def dissolve_line_features(str_lines_path, output_filename, logger):
logger.info('Dissolve line features...')
lst_all = []
with fiona.open(str_lines_path) as lines:
crs = lines.crs
schema = {'geometry': 'MultiLineString', 'properties': {'linkno': 'int:6'}}
with fiona.open(output_filename, 'w', 'ESRI Shapefile', schema, crs) as output:
for line in lines:
lst_all.append(line['geometry']['coordinates'])
output.write(
{'properties': {'linkno': 9999}, 'geometry': {'type': 'MultiLineString', 'coordinates': lst_all}})
return
# ==========================================================================
# For points along line feature at uniform distance
# ==========================================================================
def points_along_line_features(str_diss_lines_path, output_filename, logger):
logger.info('Points along line features...')
p_interp_spacing = 1000
with fiona.open(str_diss_lines_path) as line:
crs = line.crs
line = line[0]
schema = {'geometry': 'Point', 'properties': {'id': 'int:6'}}
with fiona.open(output_filename, 'w', 'ESRI Shapefile', schema, crs) as output:
line_shply = MultiLineString(line['geometry']['coordinates'])
length = line_shply.length # units depend on crs
step_lens = np.arange(0, length, p_interp_spacing) # p_interp_spacing in projection units?
for i, step in enumerate(step_lens): # lambda here instead?
i_pt = np.array(line_shply.interpolate(step))
output.write({'properties': {'id': i}, 'geometry': {'type': 'Point', 'coordinates': i_pt}})
return
# ==========================================================================
# For points along line feature at uniform distance
# ==========================================================================
def taudem_gagewatershed(str_pts_path, str_d8fdr_path, logger):
logger.info('Points along line features...')
inputProc = str(4)
str_output_path = r'D:\Terrain_and_Bathymetry\USGS\CBP_analysis\DifficultRun\raw\dr3m_test_sheds.tif'
cmd = 'mpiexec -n ' + inputProc + ' GageWatershed -p ' + '"' + str_d8fdr_path + '"' + ' -o ' + '"' + str_pts_path + '"' + ' -gw ' + '"' + str_output_path + '"'
# Submit command to operating system
logger.info('Running TauDEM GageWatershed...')
os.system(cmd)
# Capture the contents of shell command and logger.info it to the arcgis dialog box
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
message = "\n"
for line in process.stdout.readlines():
if isinstance(line, bytes): # true in Python 3
line = line.decode()
message = message + line
logger.info(message)
return
# ==========================================================================
# For clipping features
# ==========================================================================
def clip_features_using_grid(str_lines_path, output_filename, str_dem_path, logger):
logger.info('Clipping streamlines to site DEM...')
# # Build the output file name...
# path_to_dem, dem_filename = os.path.split(str_dem_path)
# output_filename = path_to_dem + '\\' + dem_filename[:-4]+'_nhdhires.shp'
# 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': {'test': v}, 'geometry': s}
for i, (s, v)
in enumerate(
shapes(arr_dem, mask=mask, transform=ds_dem.transform)))
poly = next(results)
poly_shp = shape(poly['geometry'])
# Now clip/intersect the streamlines file with results via Shapely...
with fiona.open(str_lines_path) as lines:
# Get the subset that falls within bounds of polygon...
subset = lines.filter(bbox=shape(poly['geometry']).bounds)
lines_schema = lines.schema
lines_crs = lines.crs
with fiona.open(output_filename, 'w', 'ESRI Shapefile', lines_schema, lines_crs) as dst:
for line in subset:
if shape(line['geometry']).within(poly_shp):
dst.write(line)
return output_filename
# ===============================================================================
# Callback for GoSpatial tool messages
# If a callback is not provided, it will simply logger.info the output stream.
# A provided callback allows for custom processing of the output stream.
# ===============================================================================
def callback(s, logger):
try:
# logger.info("{}".format(s))
if "%" in s:
str_array = s.split(" ")
# label = s.replace(str_array[len(str_array)-1], "")
progress = int(str_array[len(str_array) - 1].replace("%", "").strip())
logger.info("Progress: {}%".format(progress))
else:
if "error" in s.lower():
logger.info("ERROR: {}".format(s))
else:
logger.info("{}".format(s))
except:
logger.info(s)
# ===============================================================================
# Create weight file for TAuDEM D8 FAC
# ===============================================================================
def create_wg_from_streamlines(str_streamlines_path, str_dem_path, str_danglepts_path, logger):
logger.info('Creating weight grid from streamlines...')
lst_coords = []
lst_pts = []
lst_x = []
lst_y = []
with fiona.open(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:
col, row = ~ds_dem.transform * (
coords[0], coords[1]) # BUT you have to convert coordinates from hires to dem
try:
arr_danglepts[int(row), int(col)] = 1
except:
continue
# # Could save these points here for later use building the streamlines??
# tpl_pts=(row,col)
# lst_finalpts_rowcols.append(tpl_pts)
# 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
# ===============================================================================
# Get row/col coords of start pts from weight grid
# ===============================================================================
# def get_rowcol_from_wg(str_danglepts_path):
#
# logger.info('Reading weight grid...')
# with rasterio.open(str_danglepts_path) as ds_wg:
# wg_rast = ds_wg.read(1) # numpy array
# wg_crs = ds_wg.crs
# wg_affine = ds_wg.affine
#
# logger.info('Getting indices...')
# row_cols = np.where(wg_rast>0)
#
# return row_cols
# ===============================================================================
# For calling GoSpatial funcs
# ===============================================================================
def default_callback(str, logger):
logger.info(str)
def run_gospatial_whiteboxtool(tool_name, args, exe_path, exe_name, wd, logger, callback=default_callback):
try:
os.chdir(exe_path)
cmd = []
cmd.append("." + os.path.sep + exe_name)
if len(wd) > 0:
cmd.append("-cwd=\"{}\"".format(wd))
cmd.append("-run={}".format(tool_name))
args_str = ""
for s in args:
args_str += s.replace("\"", "") + ";"
args_str = args_str[:-1]
cmd.append("-args=\"{}\"".format(args_str))
ps = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1,
universal_newlines=True)
while True:
line = ps.stdout.readline()
if line != '':
callback(line.strip())
else:
break
return 0
except Exception as e:
logger.info(e)
return 1
def run_rust_whiteboxtool(tool_name, args, exe_path, exe_name, wd, callback=default_callback):
try:
os.chdir(exe_path)
args2 = []
args2.append("." + os.path.sep + exe_name)
args2.append("--run=\"{}\"".format(tool_name))
if wd.strip() != "":
args2.append("--wd=\"{}\"".format(wd))
for arg in args:
args2.append(arg)
# args_str = args_str[:-1]
# a.append("--args=\"{}\"".format(args_str))
# if self.verbose:
# args2.append("-v")
proc = subprocess.Popen(args2, shell=False, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, bufsize=1, universal_newlines=True)
while True:
line = proc.stdout.readline()
sys.stdout.flush()
if line != '':
callback(line.strip())
# if not self.cancel_op:
# callback(line.strip())
# else:
# self.cancel_op = False
# proc.terminate()
# return 2
else:
break
return 0
except (OSError, ValueError, subprocess.CalledProcessError) as err:
callback(str(err))
return 1
# ===============================================================================
# Mega-function for processing a raw DEM
# 1. Breaching and filling
# 2. TauDEM functions
# ===============================================================================
def preprocess_dem(str_dem_path, str_nhdhires_path, dst_crs, str_mpi_path, str_taudem_path, str_whitebox_path,
run_whitebox, run_wg, run_taudem, logger):
try:
# Split DEM path and filename... # NOT OS INDEPENDENT??
path_to_dem, dem_filename = os.path.split(str_dem_path)
# Set this for a custom output folder:
# path_to_dem = '/home/sam/drb_preprocess_2018.08.28'
inputProc = str(2) # number of cores to use for TauDEM processes
# << Define all filenames here >>
str_danglepts_path = os.path.join(path_to_dem, dem_filename[:-4] + '_wg.tif')
dem_filename_tif = dem_filename[:-4] + '.tif'
breach_filename_dep = dem_filename[:-4] + '_breach.dep'
breach_filename_tif = dem_filename[:-4] + '_breach.tif'
breach_filepath_tif = os.path.join(path_to_dem, breach_filename_tif)
breach_filepath_tif_proj = breach_filepath_tif[:-4] + '_proj.tif'
str_dem_path_tif = os.path.join(path_to_dem, dem_filename[:-4] + '.tif')
# fel = path_to_dem + '\\' + dem_filename[:-4]+'_breach.tif'
fel_pitremove = os.path.join(path_to_dem, breach_filename_tif[:-4] + '_fel.tif')
p = os.path.join(path_to_dem, breach_filename_tif[:-4] + '_p.tif')
sd8 = os.path.join(path_to_dem, breach_filename_tif[:-4] + '_sd8.tif')
ad8_wg = os.path.join(path_to_dem, breach_filename_tif[:-4] + '_ad8_wg.tif')
# wtgr = os.path.join(str_danglepts_path)
ad8_no_wg = os.path.join(path_to_dem, breach_filename_tif[:-4] + '_ad8_no_wg.tif')
ord_g = os.path.join(path_to_dem, breach_filename_tif[:-4] + '_ord_g.tif')
tree = os.path.join(path_to_dem, breach_filename_tif[:-4] + '_tree')
coord = os.path.join(path_to_dem, breach_filename_tif[:-4] + '_coord')
net = os.path.join(path_to_dem, breach_filename_tif[:-4] + '_net.shp')
w = os.path.join(path_to_dem, breach_filename_tif[:-4] + '_w.tif')
slp = os.path.join(path_to_dem, breach_filename_tif[:-4] + '_slp.tif')
ang = os.path.join(path_to_dem, breach_filename_tif[:-4] + '_ang.tif')
dd = os.path.join(path_to_dem, breach_filename_tif[:-4] + '_hand.tif')
# # ==================== TauDEM Paths =========================
# # Hardcode paths from user input...
# mpipath = os.path.join(str_mpi_path) #r'"C:\Program Files\Microsoft MPI\Bin\mpiexec.exe"'
# d8flowdir = '"' + str_taudem_path + '\D8FlowDir.exe"' # r'"C:\Program Files\TauDEM\TauDEM5Exe\D8FlowDir.exe"'
# areaD8 = '"' + str_taudem_path + '\AreaD8.exe"'
# streamnet = '"' + str_taudem_path + '\StreamNet.exe"'
# dinfflowdir = '"' + str_taudem_path + '\DinfFlowDir.exe"'
# dinfdistdown = '"' + str_taudem_path + '\DinfDistDown.exe"'
# ========== << 1. Breach Depressions with GoSpatial/Whitebox Tool >> ==========
'''
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?
'''
# =================== << Whitebox Functions >> =====================
if run_whitebox:
# Whitebox python:
wbt.set_working_dir(path_to_dem)
# wbt.feature_preserving_denoise(dem_filename_tif, "smoothed.tif", filter=9)
wbt.breach_depressions(dem_filename, breach_filename_tif)
# logger.info('Whitebox .exe path: ' + 'r' + '"' + str_whitebox_path + '"')
# str_whitebox_dir, str_whitebox_exe = os.path.split(str_whitebox_path)
#
# # << Run the BreachDepressions tool, specifying the arguments >>
# name = "BreachDepressions"
# args = [dem_filename_tif, breach_filename_dep, '-1', '-1', 'True', 'True'] # GoSpatial verion. NOTE: Make these last four variables accessible to user?
# args = ['--dem='+dem_filename, '-o='+breach_filename_dep] # Rust version
#
# ret = run_gospatial_whiteboxtool(name, args, str_whitebox_dir, str_whitebox_exe, path_to_dem, callback)
# ret = run_rust_whiteboxtool(name, args, str_whitebox_dir, str_whitebox_exe, path_to_dem, callback)
# if ret != 0:
# logger.info("ERROR: return value={}".format(ret))
#
# # << Convert .dep to .tif here? >> NOTE: Only for DRB hack when using .dep files
# name = "WhiteBox2GeoTiff"
# args = [breach_filename_dep, breach_filename_tif]
#
# ret = run_gospatial_whiteboxtool(name, args, str_whitebox_dir, str_whitebox_exe, path_to_dem, callback)
# if ret != 0:
# logger.info("ERROR: return value={}".format(ret))
#
# # The converted TIFF file is saved without a crs, so save a projected version:
# define_grid_projection(breach_filepath_tif, dst_crs, breach_filepath_tif_proj)
#
# # Remove native Whitebox files and unprojected tif:
# dep_path=path_to_dem + '\\' + breach_filename_dep
# tas_path=path_to_dem + '\\' + breach_filename_dep[:-3]+'tas'
# os.remove(dep_path)
# os.remove(tas_path)
# os.remove(breach_filepath_tif)
# # Rust version...
# name = "ConvertRasterFormat"
# args = ['--input='+breach_filename_dep, '-o='+breach_filename_tif]
# ret = run_rust_whiteboxtool(name, args, str_whitebox_dir, str_whitebox_exe, path_to_dem, callback)
# # << Also convert original DEM .dep to a .tif >>
# name = "WhiteBox2GeoTiff"
# args = [dem_filename, dem_filename_tif]
#
# ret = run_gospatial_whiteboxtool(name, args, str_whitebox_dir, str_whitebox_exe, path_to_dem, callback)
# if ret != 0:
# logger.info("ERROR: return value={}".format(ret))
# Rust version...
# name = "ConvertRasterFormat"
# args = ['--input='+dem_filename, '-o='+dem_filename_tif]
# ret = run_rust_whiteboxtool(name, args, str_whitebox_dir, str_whitebox_exe, path_to_dem, callback)
if run_wg:
create_wg_from_streamlines(str_nhdhires_path, p, str_danglepts_path)
if run_taudem:
# Testing...
# mpipath = 'r' + '"' + mpipath + '"'
# fel = 'r' + '"' + fel + '"'
# logger.info('mpipath: ' + mpipath)
# logger.info('fel: ' + fel_breach)
# logger.info(' ')
# # ============== << 1. Pit Filling with TauDEM >> ================
# cmd = 'mpiexec' + ' -n ' + inputProc + ' PitRemove -z ' + '"' + breach_filepath_tif + '"' + ' -fel ' + '"' + fel_pitremove + '"'
#
# # Submit command to operating system
# logger.info('Running TauDEM PitRemove...')
# os.system(cmd)
#
# # Capture the contents of shell command and logger.info it to the arcgis dialog box
# process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
#
# # Get some feedback from the process to logger.info out...
# message = "\n"
# for line in process.stdout.readlines():
# line = line.decode()
# if isinstance(line, bytes): # true in Python 3
# line = line.decode()
# message = message + line
# logger.info(message)
#
# # ============== << 2. D8 FDR with TauDEM >> ================ YES
# cmd = '"' + mpipath + '"' + ' -n ' + inputProc + ' ' + d8flowdir + ' -fel ' + '"' + str_dem_path + '"' + ' -p ' + '"' + p + '"' + \
# ' -sd8 ' + '"' + sd8 + '"'
#
# cmd = 'mpiexec' + ' -n ' + inputProc + ' d8flowdir -fel ' + '"' + str_dem_path + '"' + ' -p ' + '"' + p + '"' + \
# ' -sd8 ' + '"' + sd8 + '"'
#
# # Submit command to operating system
# logger.info('Running TauDEM D8 Flow Direction...')
# os.system(cmd)
#
# # Capture the contents of shell command and logger.info it to the arcgis dialog box
# process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
#
# # Get some feedback from the process to logger.info out...
# message = "\n"
# for line in process.stdout.readlines():
# line = line.decode()
# if isinstance(line, bytes): # true in Python 3
# line = line.decode()
# message = message + line
# logger.info(message)
#
# # # ============= << 3.a AD8 with weight grid >> ================ YES
# # cmd = 'mpiexec -n ' + inputProc + ' AreaD8 -p ' + '"' + p + '"' + ' -ad8 ' + '"' + ad8_wg + '"' + ' -wg ' + '"' + wtgr + '"' + ' -nc '
# cmd = '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)...')
# os.system(cmd)
# # Capture the contents of shell command and logger.info it to the arcgis dialog box
# process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
#
# message = "\n"
# for line in process.stdout.readlines():
# if isinstance(line, bytes): # true in Python 3
# line = line.decode()
# message = message + line
# logger.info(message)
# ============= << 3.b AD8 no weight grid >> ================
# cmd = 'mpiexec -n ' + inputProc + ' AreaD8 -p ' + '"' + p + '"' + ' -ad8 ' + '"' + ad8_no_wg + '"' + ' -nc '
cmd = 'mpiexec -n ' + inputProc + ' AreaD8 -p ' + '"' + p + '"' + ' -ad8 ' + '"' + ad8_no_wg + '"' + ' -nc '
# Submit command to operating system
logger.info('Running TauDEM D8 FAC (no weights)...')
os.system(cmd)
# Capture the contents of shell command and logger.info it to the arcgis dialog box
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
message = "\n"
for line in process.stdout.readlines():
if isinstance(line, bytes): # true in Python 3
line = line.decode()
message = message + line
logger.info(message)
# ============= << 4 StreamReachandWatershed with TauDEM >> ================
cmd = 'mpiexec -n ' + inputProc + ' StreamNet -fel ' + '"' + breach_filepath_tif + '"' + ' -p ' + '"' + p + '"' + \
' -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...')
os.system(cmd)
# Capture the contents of shell command and logger.info it to the arcgis dialog box
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
message = "\n"
for line in process.stdout.readlines():
if isinstance(line, bytes): # true in Python 3
line = line.decode()
message = message + line
logger.info(message)
# Let's get rid of some output that we are not currently using...
try:
# os.remove(w)
os.remove(coord)
os.remove(tree)
os.remove(ord_g)
except:
logger.info('Warning: Problem removing files!')
pass
# # ============= << 5. Dinf with TauDEM >> ============= YES
# logger.info('Running TauDEM Dinfinity...')
# cmd = 'mpiexec -n ' + inputProc + ' DinfFlowDir -fel ' + '"' + breach_filepath_tif + '"' + ' -ang ' + '"' + ang + '"' + \
# ' -slp ' + '"' + slp + '"'
#
# # Submit command to operating system
# os.system(cmd)
#
# # Capture the contents of shell command and logger.info it to the arcgis dialog box
# process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
#
# # Get some feedback from the process to logger.info out...
# message = "\n"
# for line in process.stdout.readlines():
# line = line.decode()
# # if isinstance(line, bytes): # true in Python 3
# # line = line.decode()
# message = message + line
# logger.info(message)
#
# # ============= << 6. DinfDistanceDown (HAND) with TauDEM >> ============= YES
# distmeth = 'v'
# statmeth = 'ave'
#
# # Use original DEM here...
# logger.info('Running TauDEM Dinf Distance Down...') # Use Breached or Raw DEM here?? Currently using Raw
# cmd = 'mpiexec -n ' + inputProc + ' DinfDistDown -fel ' + '"' + str_dem_path_tif + '"' + ' -ang ' + '"' + ang + '"' + \
# ' -src ' + '"' + ad8_wg + '"' + ' -dd ' + '"' + dd + '"' + ' -m ' + statmeth + ' ' + distmeth
#
# # Submit command to operating system
# os.system(cmd)
#
# # Get some feedback from the process to logger.info out...
# process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
#
# message = "\n"
# for line in process.stdout.readlines():
# line = line.decode()
# # if isinstance(line, bytes): # true in Python 3
# # line = line.decode()
# message = message + line
#
# logger.info(message)
except: