-
Notifications
You must be signed in to change notification settings - Fork 11
/
StreamCat_functions.py
1409 lines (1225 loc) · 53.4 KB
/
StreamCat_functions.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
""" __ __
_____/ /_________ ____ ____ ___ _________ _/ /_
/ ___/ __/ ___/ _ \/ __ `/ __ `__ \/ ___/ __ `/ __/
(__ ) /_/ / / __/ /_/ / / / / / / /__/ /_/ / /_
/____/\__/_/ \___/\__,_/_/ /_/ /_/\___/\__,_/\__/
Functions for standardizing landscape rasters, allocating landscape metrics
to NHDPlusV2 catchments, accumulating metrics for upstream catchments, and
writing final landscape metric tables
Authors: Marc Weber<[email protected]>
Ryan Hill<[email protected]>
Darren Thornbrugh<[email protected]>
Rick Debbout<[email protected]>
Tad Larsen<[email protected]>
Date: October 2015
"""
import os
import sys
import time
from collections import OrderedDict, defaultdict, deque
from typing import Generator
import numpy as np
import pandas as pd
import rasterio
#from gdalconst import *
from osgeo import gdal, ogr, osr
from rasterio import transform
if rasterio.__version__[0] == "0":
from rasterio.warp import RESAMPLING, calculate_default_transform, reproject
if rasterio.__version__[0] == "1":
from rasterio.warp import calculate_default_transform, reproject, Resampling
import fiona
import geopandas as gpd
from geopandas.tools import sjoin
os.environ["PATH"] += r";C:\Program Files\ArcGIS\Pro\bin"
sys.path.append(r"C:\Program Files\ArcGIS\Pro\Resources\ArcPy")
import arcpy
from arcpy.sa import TabulateArea, ZonalStatisticsAsTable
##############################################################################
class LicenseError(Exception):
pass
##############################################################################
def UpcomDict(nhd, interVPUtbl, zone):
"""
__author__ = "Marc Weber <[email protected]>"
"Ryan Hill <[email protected]>"
Creates a dictionary of all catchment connections in a major NHDPlus basin.
For example, the function combines all from-to typology tables in the Mississippi
Basin if 'MS' is provided as 'hydroregion' argument.
Arguments
---------
nhd : the directory contining NHDPlus data
interVPUtbl : the table that holds the inter-VPU connections to manage connections and anomalies in the NHD
"""
# Returns UpCOMs dictionary for accumulation process
# Provide either path to from-to tables or completed from-to table
flow = dbf2DF(f"{nhd}/NHDPlusAttributes/PlusFlow.dbf")[["TOCOMID", "FROMCOMID"]]
flow = flow[(flow.TOCOMID != 0) & (flow.FROMCOMID != 0)]
# check to see if out of zone values have FTYPE = 'Coastline'
fls = dbf2DF(f"{nhd}/NHDSnapshot/Hydrography/NHDFlowline.dbf")
coastfl = fls.COMID[fls.FTYPE == "Coastline"]
flow = flow[~flow.FROMCOMID.isin(coastfl.values)]
# remove these FROMCOMIDs from the 'flow' table, there are three COMIDs here
# that won't get filtered out
remove = interVPUtbl.removeCOMs.values[interVPUtbl.removeCOMs.values != 0]
flow = flow[~flow.FROMCOMID.isin(remove)]
# find values that are coming from other zones and remove the ones that
# aren't in the interVPU table
out = np.setdiff1d(flow.FROMCOMID.values, fls.COMID.values)
out = out[np.nonzero(out)]
flow = flow[~flow.FROMCOMID.isin(np.setdiff1d(out, interVPUtbl.thruCOMIDs.values))]
# Now table is ready for processing and the UpCOMs dict can be created
fcom, tcom = flow.FROMCOMID.values, flow.TOCOMID.values
UpCOMs = defaultdict(list)
for i in range(0, len(flow), 1):
from_comid = fcom[i]
if from_comid == 0:
continue
else:
UpCOMs[tcom[i]].append(from_comid)
# add IDs from UpCOMadd column if working in ToZone, forces the flowtable connection though not there
for interLine in interVPUtbl.values:
if interLine[6] > 0 and interLine[2] == zone:
UpCOMs[int(interLine[6])].append(int(interLine[0]))
return UpCOMs
##############################################################################
def children(token, tree, chkset=None):
"""
__author__ = "Marc Weber <[email protected]>"
"Ryan Hill <[email protected]>"
returns a list of every child
Arguments
---------
token : a single COMID
tree : Full dictionary of list of upstream COMIDs for each COMID in the zone
chkset : set of all the NHD catchment COMIDs used to remove flowlines with no associated catchment
"""
visited = set()
to_crawl = deque([token])
while to_crawl:
current = to_crawl.popleft()
if current in visited:
continue
visited.add(current)
node_children = set(tree[current])
to_crawl.extendleft(node_children - visited)
# visited.remove(token)
if chkset != None:
visited = visited.intersection(chkset)
return list(visited)
##############################################################################
def bastards(token, tree):
"""
__author__ = "Marc Weber <[email protected]>"
"Ryan Hill <[email protected]>"
returns a list of every child w/ out father (key) included
Arguments
---------
token : a single COMID
tree : Full dictionary of list of upstream COMIDs for each COMID in the zone
chkset : set of all the NHD catchment COMIDs, used to remove flowlines with no associated catchment
"""
visited = set()
to_crawl = deque([token])
while to_crawl:
current = to_crawl.popleft()
if current in visited:
continue
visited.add(current)
node_children = set(tree[current])
to_crawl.extendleft(node_children - visited)
visited.remove(token)
return list(visited)
##############################################################################
def getRasterInfo(FileName):
"""
__author__ = "Marc Weber <[email protected]>"
"Ryan Hill <[email protected]>"
returns basic raster information for a given raster
Arguments
---------
FileName : a raster file
"""
SourceDS = gdal.Open(FileName, GA_ReadOnly)
NDV = SourceDS.GetRasterBand(1).GetNoDataValue()
stats = SourceDS.GetRasterBand(1).GetStatistics(True, True)
xsize = SourceDS.RasterXSize
ysize = SourceDS.RasterYSize
GeoT = SourceDS.GetGeoTransform()
prj = SourceDS.GetProjection()
Projection = osr.SpatialReference(wkt=prj)
Proj_projcs = Projection.GetAttrValue("projcs")
# if Proj_projcs == None:
# Proj_projcs = 'Not Projected'
Proj_geogcs = Projection.GetAttrValue("geogcs")
DataType = SourceDS.GetRasterBand(1).DataType
DataType = gdal.GetDataTypeName(DataType)
return (NDV, stats, xsize, ysize, GeoT, Proj_projcs, Proj_geogcs, DataType)
##############################################################################
def GetRasterValueAtPoints(rasterfile, shapefile, fieldname):
"""
__author__ = "Marc Weber <[email protected]>"
returns raster values at points in a point shapefile
assumes same projection in shapefile and raster file
Arguments
---------
rasterfile : a raster file with full pathname and extension
shapefile : a shapefile with full pathname and extension
fieldname : field name in the shapefile to identify values
"""
src_ds = gdal.Open(rasterfile)
no_data = src_ds.GetRasterBand(1).GetNoDataValue()
gt = src_ds.GetGeoTransform()
rb = src_ds.GetRasterBand(1)
df = pd.DataFrame(columns=(fieldname, "RasterVal"))
ds = ogr.Open(shapefile)
lyr = ds.GetLayer()
data = []
for feat in lyr:
geom = feat.GetGeometryRef()
name = feat.GetField(fieldname)
mx, my = geom.GetX(), geom.GetY() # coord in map units
# Convert from map to pixel coordinates.
# Only works for geotransforms with no rotation.
px = int((mx - gt[0]) / gt[1]) # x pixel
py = int((my - gt[3]) / gt[5]) # y pixel
intval = rb.ReadAsArray(px, py, 1, 1)
if intval == no_data:
intval = -9999
data.append((name, float(intval)))
df = pd.DataFrame(data, columns=(fieldname, "RasterVal"))
return df
##############################################################################
def Reclass(inras, outras, reclass_dict, dtype=None):
"""
__author__ = "Marc Weber <[email protected]>"
"Ryan Hill <[email protected]>"
reclass a set of values in a raster to another value
Arguments
---------
inras : an input raster file
outras : an output raster file
reclass_dict : dictionary of lookup values read in from lookup csv file
in_nodata : Returned no data values from
out_dtype : the data type of the raster, i.e. 'float32', 'uint8' (string)
"""
with rasterio.open(inras) as src:
# Set dtype and nodata values
if dtype is None: # If no dtype defined, use input dtype
nd = src.meta["nodata"]
dtype = src.meta["dtype"]
else:
try:
nd = eval("np.iinfo(np." + dtype + ").max")
except:
nd = eval("np.finfo(np." + dtype + ").max")
# exec 'nd = np.iinfo(np.'+out_dtype+').max'
kwargs = src.meta.copy()
kwargs.update(
driver="GTiff",
count=1,
compress="lzw",
nodata=nd,
dtype=dtype,
bigtiff="YES", # Output will be larger than 4GB
)
windows = src.block_windows(1)
with rasterio.open(outras, "w", **kwargs) as dst:
for idx, window in windows:
src_data = src.read(1, window=window)
# Convert values
# src_data = np.where(src_data == in_nodata, nd, src_data).astype(dtype)
for inval, outval in reclass_dict.iteritems():
if np.isnan(outval).any():
# src_data = np.where(src_data != inval, src_data, kwargs['nodata']).astype(dtype)
src_data = np.where(src_data == inval, nd, src_data).astype(
dtype
)
else:
src_data = np.where(src_data == inval, outval, src_data).astype(
dtype
)
# src_data = np.where(src_data == inval, outval, src_data)
dst_data = src_data
dst.write_band(1, dst_data, window=window)
##############################################################################
def rasterMath(inras, outras, expression=None, out_dtype=None):
"""
__author__ = "Marc Weber <[email protected]>"
"Ryan Hill<[email protected]>"
Applies arithmetic operation to a raster by a given value and returns raster
in a specified data type - ideas from https://sgillies.net/page3.html
Arguments
---------
inras : an input raster file (string)
outras : an output raster file (string)
expression : string of mathematical expression to be used that includes the input raster
as variable. If no expression provided, raster is copied. Function can be
used to change dtype of original raster.
Example:
inras = 'C:/some_locat_raster.tif'
expression = 'log(' + inras + '+1)' or inras + ' * 100'
out_dtype : the data type of the raster, i.e. 'float32', 'uint8' (string)
"""
expression = expression.replace(inras, "src_data")
with rasterio.drivers():
with rasterio.open(inras) as src:
# Set dtype and nodata values
if out_dtype is None: # If no dtype defined, use input dtype
nd = src.meta["nodata"]
dt = src.meta["dtype"]
else:
try:
nd = eval("np.iinfo(np." + out_dtype + ").max")
except:
nd = eval("np.finfo(np." + out_dtype + ").max")
# exec 'nd = np.iinfo(np.'+out_dtype+').max'
dt = out_dtype
kwargs = src.meta.copy()
kwargs.update(driver="GTiff", count=1, compress="lzw", dtype=dt, nodata=nd)
windows = src.block_windows(1)
with rasterio.open(outras, "w", **kwargs) as dst:
for idx, window in windows:
src_data = src.read(1, window=window)
# Where src not eq to orig nodata, multiply by val, else set to new nodata. Set dtype
if expression == None:
# No expression produces copy of original raster (can use new data type)
dst_data = np.where(
src_data != src.meta["nodata"], src_data, kwargs["nodata"]
).astype(dt)
else:
dst_data = np.where(
src_data != src.meta["nodata"],
eval(expression),
kwargs["nodata"],
).astype(dt)
dst.write_band(1, dst_data, window=window)
##############################################################################
def Project(inras, outras, dst_crs, template_raster, nodata):
"""
__author__ = "Marc Weber <[email protected]>"
"Ryan Hill <[email protected]>"
reprojects and resamples a raster using rasterio
Arguments
---------
inras : an input raster with full path name
outras : an output raster with full path name
outproj : projection to apply to output raster in EPSG format, i.e. EPSG:5070
resamp : resampling method to use - either nearest or bilinear
"""
with rasterio.open(inras) as src:
with rasterio.open(template_raster) as tmp:
affine, width, height = calculate_default_transform(
src.crs, dst_crs, src.width, src.height, *tmp.bounds
)
kwargs = src.meta.copy()
kwargs.update(
{
"crs": dst_crs,
"transform": affine,
"affine": affine,
"width": width,
"height": height,
"driver": "GTiff",
}
)
with rasterio.open(outras, "w", **kwargs) as dst:
reproject(
source=rasterio.band(src, 1),
destination=rasterio.band(dst, 1),
src_transform=src.affine,
src_crs=src.crs,
src_nodata=nodata,
dst_transform=affine,
dst_crs=dst_crs,
)
##############################################################################
def ShapefileProject(InShp, OutShp, CRS):
"""
__author__ = "Marc Weber <[email protected]>"
reprojects a shapefile with Fiona
Arguments
---------
InShp : an input shapefile as a string, i.e. 'C:/Temp/inshape.shp'
OutShp : an output shapefile as a string, i.e. 'C:/Temp/outshape.shp'
CRS : the output CRS in Fiona format
"""
# Open a file for reading
with fiona.open(InShp, "r") as source:
sink_schema = source.schema.copy()
sink_schema["geometry"] = "Point"
# Open an output file, using the same format driver and passing the desired
# coordinate reference system
with fiona.open(
OutShp,
"w",
crs=CRS,
driver=source.driver,
schema=sink_schema,
) as sink:
for f in source:
# Write the record out.
sink.write(f)
# The sink's contents are flushed to disk and the file is closed
# when its ``with`` block ends. This effectively executes
# ``sink.flush(); sink.close()``.
##############################################################################
def Resample(inras, outras, resamp_type, resamp_res):
"""
__author__ = "Marc Weber <[email protected]>"
"Ryan Hill <[email protected]>"
Resamples a raster using rasterio
Arguments
---------
inras : an input raster with full path name
outras : an output raster with full path name
resamp_type : resampling method to use - either nearest or bilinear
resamp_res : resolution to apply to output raster
"""
with rasterio.open(inras) as src:
affine, width, height = calculate_default_transform(
src.crs, src.crs, src.width, src.height, *src.bounds, resolution=resamp_res
)
kwargs = src.meta.copy()
kwargs.update(
{
"crs": src.crs,
"transform": affine,
"affine": affine,
"width": width,
"height": height,
"driver": "GTiff",
}
)
with rasterio.open(outras, "w", **kwargs) as dst:
if resamp_type == "bilinear":
reproject(
source=rasterio.band(src, 1),
destination=rasterio.band(dst, 1),
src_transform=src.affine,
src_crs=src.crs,
dst_transform=src.affine,
dst_crs=dst_crs,
resampling=RESAMPLING.bilinear,
compress="lzw",
)
elif resamp_type == "nearest":
reproject(
source=rasterio.band(src, 1),
destination=rasterio.band(dst, 1),
src_transform=affine,
src_crs=src.crs,
dst_transform=affine,
dst_crs=src.crs,
resampling=RESAMPLING.nearest,
compress="lzw",
)
##############################################################################
def ProjectResamp(inras, outras, out_proj, resamp_type, out_res):
"""
__author__ = "Marc Weber <[email protected]>"
"Ryan Hill <[email protected]>"
reprojects and resamples a raster using rasterio
Arguments
---------
inras : an input raster with full path name
outras : an output raster with full path name
outproj : projection to apply to output raster in EPSG format, i.e. EPSG:5070
resamp : resampling method to use - either nearest or bilinear
"""
with rasterio.drivers():
with rasterio.open(inras) as src:
affine, width, height = calculate_default_transform(
src.crs, out_proj, src.width, src.height, *src.bounds
)
kwargs = src.meta.copy()
kwargs.update(
{
"crs": out_proj,
"transform": affine,
"affine": affine,
"width": width,
"height": height,
"driver": "GTiff",
}
)
windows = src.block_windows(1)
with rasterio.open(outras, "w", **kwargs) as dst:
for idx, window in windows:
if resamp_type == "bilinear":
reproject(
source=rasterio.band(src, 1),
destination=rasterio.band(dst, 1),
src_transform=src.affine,
src_crs=src.crs,
dst_transform=transform.from_origin(
affine[2],
affine[5],
dist.transform[0],
dst.transform[0],
),
dst_crs=dst_crs,
resampling=RESAMPLING.bilinear,
)
elif resamp_type == "nearest":
reproject(
source=rasterio.band(src, 1),
destination=rasterio.band(dst, 1),
src_transform=src.transform,
src_crs=src.crs,
dst_transform=transform.from_origin(
dst.transform[0],
dst.transform[3],
dst.transform[1],
dst.transform[1],
),
dst_crs=dst.crs,
resampling=RESAMPLING.nearest,
)
##############################################################################
def get_raster_value_at_points(
points, rasterfile, fieldname=None, val_name=None, out_df=False
):
"""
Find value at point (x,y) for every point in points of the given
rasterfile.
Arguments
---------
points: str | gpd.GeoDataFrame | generator
path to point file, or point GeoDataFrame, or generator of (x,y) tuples
rasterfile: str
path to raster
fieldname: str
attribute in points that identifies name given to index
out_df: bool
return pd.DataFrame of values, index will match `fieldname` if used,
else the index will be equivalent to `range(len(points))`
Returns
---------
list | pd.DataFrame
Values of rasterfile | if `out_df` True, dataframe of values.
"""
if isinstance(points, str):
points = gpd.read_file(points)
if isinstance(points, gpd.GeoDataFrame):
assert points.geometry.type.all() == "Point"
if fieldname:
points.set_index(fieldname)
points = points.geometry.apply(lambda g: (g.x, g.y))
if isinstance(points, Generator):
pass
with rasterio.open(rasterfile) as src:
data = [s[0] for s in src.sample(points)]
if out_df:
return pd.DataFrame(index=points.index, data={val_name: data})
else:
return data
def mask_points(points, mask_dir, INPUTS, nodata_vals=[0, -2147483648.0]):
"""
Filter points to those that only lie within the mask.
Arguments
---------
points: gpd.GeoDataFrame
point GeoDataFrame to be filtered
mask_dir: str
path to folder holding masked rasters for every VPU
INPUTS: collections.OrderedDict
dictionary of vector processing units and hydroregions from NHDPlusV21
nodata_vals: list
values of the raster that exist outside of the mask zone
Returns
---------
gpd.GeoDataFrame
filtered points that only lie within the masked areas
"""
temp = pd.DataFrame(index=points.index)
for zone, hydroregion in INPUTS.items():
pts = get_raster_value_at_points(points, f"{mask_dir}/{zone}.tif", out_df=True)
temp = temp.merge(~pts.isin(nodata_vals), left_index=True, right_index=True)
xx = temp.sum(axis=1)
return points.iloc[xx.loc[xx == 1].index]
def PointInPoly(points, vpu, catchments, pct_full, mask_dir, appendMetric, summary):
"""
Filter points to those that only lie within the mask.
Arguments
---------
points: gpd.GeoDataFrame
point GeoDataFrame
vpu: str
Vector Processing Unit from NHDPlusV21
catchments: collections.OrderedDict
dictionary of vector processing units and hydroregions from NHDPlusV21
pct_full: pd.DataFrame
DataFrame with `PCT_FULL` calculated from catchments that
intersect the US border from TIGER files
mask_dir: str
path to folder holding masked rasters for every VPU else empty
appendMetric: str
string to be appended to metrics from ControlTable_StreamCat.csv
summary: list
strings that identify columns from the attribute table in the points
GeoDataFrame to be summed in returned DataFrame if `summary` is defined
Returns
---------
pd.DataFrame
Table with count of spatial points in every catchment feature
optionally with the summary of attributes from the points attribute
table
"""
polys = gpd.GeoDataFrame.from_file(catchments)
polys.to_crs(points.crs, inplace=True)
if mask_dir:
rat = dbf2DF(f"{mask_dir}/{vpu}.tif.vat.dbf")
rat["AreaSqKM"] = ((rat.COUNT * 900) * 1e-6).fillna(0)
polys = pd.merge(
polys.drop("AreaSqKM", axis=1),
rat[["VALUE", "AreaSqKM"]],
left_on="GRIDCODE",
right_on="VALUE",
how="left",
)
# Get list of lat/long fields in the table
points["latlon_tuple"] = tuple(
zip(
points.geometry.map(lambda point: point.x),
points.geometry.map(lambda point: point.y),
)
)
# Remove duplicate points for 'Count'
points2 = points.drop_duplicates("latlon_tuple")
try:
point_poly_join = sjoin(points2, polys, how="left", op="within")
fld = "GRIDCODE"
except:
polys["link"] = np.nan
point_poly_join = polys
fld = "link"
# Create group of all points in catchment
grouped = point_poly_join.groupby("FEATUREID")
point_poly_count = grouped[fld].count()
point_poly_count.name = "COUNT"
# Join Count column on to NHDCatchments table and keep only
# ['COMID','CatAreaSqKm','CatCount']
final = polys.join(point_poly_count, on="FEATUREID", lsuffix="_", how="left")
final = final[["FEATUREID", "AreaSqKM", "COUNT"]].fillna(0)
cols = ["COMID", f"CatAreaSqKm{appendMetric}", f"CatCount{appendMetric}"]
if not summary == None: # Summarize fields including duplicates
point_poly_dups = sjoin(points, polys, how="left", op="within")
grouped2 = point_poly_dups.groupby("FEATUREID")
for x in summary: # Sum the field in summary field list for each catchment
point_poly_stats = grouped2[x].sum()
point_poly_stats.name = x
final = final.join(point_poly_stats, on="FEATUREID", how="left").fillna(0)
cols.append("Cat" + x + appendMetric)
final.columns = cols
# Merge final table with Pct_Full table based on COMID and fill NA's with 0
final = pd.merge(final, pct_full, on="COMID", how="left")
if len(mask_dir) > 0:
if not summary == None:
final.columns = (
["COMID", "CatAreaSqKmRp100", "CatCountRp100"]
+ ["Cat" + y + appendMetric for y in summary]
+ ["CatPctFullRp100"]
)
else:
final.columns = [
"COMID",
"CatAreaSqKmRp100",
"CatCountRp100",
"CatPctFullRp100",
]
final[f"CatPctFull{appendMetric}"] = final[f"CatPctFull{appendMetric}"].fillna(100)
for name in final.columns:
if "AreaSqKm" in name:
area = name
final.loc[(final[area] == 0), final.columns[2:]] = np.nan
return final
##############################################################################
def rat_to_dict(inraster, old_val, new_val):
"""
__author__ = "Matt Gregory <[email protected]>"
"Marc Weber <[email protected]>"
Given a GDAL raster attribute table, convert to a pandas DataFrame. Idea from
Matt Gregory's gist: https://gist.github.com/grovduck/037d815928b2a9fe9516
Arguments
---------
in_rat : input raster
old_val : current value in raster
new_val : lookup value to use to replace current value
"""
# Open the raster and get a handle on the raster attribute table
# Assume that we want the first band's RAT
ds = gdal.Open(inraster)
rb = ds.GetRasterBand(1)
rat = rb.GetDefaultRAT()
# Read in each column from the RAT and convert it to a series infering
# data type automatically
s = [
pd.Series(rat.ReadAsArray(i), name=rat.GetNameOfCol(i))
for i in xrange(rat.GetColumnCount())
]
# Convert the RAT to a pandas dataframe
df = pd.concat(s, axis=1)
# Close the dataset
ds = None
# Write out the lookup dictionary
reclass_dict = pd.Series(df[new_val].values, index=df[old_val]).to_dict()
return reclass_dict
##############################################################################
def interVPU(tbl, cols, accum_type, zone, Connector, interVPUtbl):
"""
Loads watershed values for given COMIDs to be appended to catResults table for accumulation.
Arguments
---------
tbl : Watershed Results table
cols : list of columns from Cat Results table needed to overwrite onto Connector table
accum_type : type metric to be accumulated, i.e. 'Categorical', 'Continuous', 'Count'
zone : an NHDPlusV2 VPU number, i.e. 10, 16, 17
Connector : Location of the connector file
InterVPUtbl : table of interVPU exchanges
"""
# Create subset of the tbl with a COMID in interVPUtbl
throughVPUs = (
tbl[tbl.COMID.isin(interVPUtbl.thruCOMIDs.values)].set_index("COMID").copy()
)
# Create subset of InterVPUtbl that identifies the zone we are working on
interVPUtbl = interVPUtbl.loc[interVPUtbl.FromZone.values == zone]
throughVPUs.columns = cols
# COMIDs in the toCOMID column need to swap values with COMIDs in other
# zones, those COMIDS are then sorted in toVPUS
if any(interVPUtbl.toCOMIDs.values > 0):
interAlloc = "%s_%s.csv" % (
Connector[: Connector.find("_connectors")],
interVPUtbl.ToZone.values[0],
)
tbl = pd.read_csv(interAlloc).set_index("COMID")
toVPUs = tbl[tbl.index.isin([x for x in interVPUtbl.toCOMIDs if x > 0])].copy()
for _, row in interVPUtbl.iterrows():
# Loop through sub-setted interVPUtbl to make adjustments to COMIDS listed in the table
if row.toCOMIDs > 0:
AdjustCOMs(toVPUs, int(row.toCOMIDs), int(row.thruCOMIDs), throughVPUs)
if row.AdjustComs > 0:
AdjustCOMs(throughVPUs, int(row.AdjustComs), int(row.thruCOMIDs), None)
if row.DropCOMID > 0:
throughVPUs = throughVPUs.drop(int(row.DropCOMID))
if any(interVPUtbl.toCOMIDs.values > 0):
con = pd.read_csv(Connector).set_index("COMID")
con.columns = map(str, con.columns)
toVPUs = pd.concat([toVPUs,con], axis=0, ignore_index=False)
toVPUs.to_csv(Connector)
if os.path.exists(Connector): # if Connector already exists, read it in and append
con = pd.read_csv(Connector).set_index("COMID")
con.columns = map(str, con.columns)
throughVPUs = pd.concat([throughVPUs, con], axis=0, ignore_index=False)
throughVPUs.to_csv(Connector)
##############################################################################
def AdjustCOMs(tbl, comid1, comid2, tbl2=None):
"""
Adjusts values for COMIDs where values from one need to be subtracted from another.
Depending on the type of accum, subtracts values for each column in the table other than COMID and Pct_Full
Arguments
---------
tbl : throughVPU table from InterVPU function
comid1 : COMID which will be adjusted
comid2 : COMID whose values will be subtracted from comid1
tbl2 : toVPU table from InterVPU function in the case where a COMID comes from a different zone
"""
if tbl2 is None: # might be able to fix this in the arguments
tbl2 = tbl.copy()
for idx in tbl.columns[:-1]:
tbl.loc[comid1, idx] = tbl.loc[comid1, idx] - tbl2.loc[comid2, idx]
##############################################################################
def Accumulation(tbl, comids, lengths, upstream, tbl_type, icol="COMID"):
"""
__author__ = "Ryan Hill <[email protected]>"
"Marc Weber <[email protected]>"
Uses the 'Cat' and 'UpCat' columns to caluculate watershed values and returns those values in 'Cat' columns
so they can be appended to 'CatResult' tables in other zones before accumulation.
Arguments
---------
arr : table containing watershed values
comids : numpy array of all zones comids
lengths : numpy array with lengths of upstream comids
upstream : numpy array of all upstream arrays for each COMID
tbl_type : string value of table metrics to be returned
icol : column in arr object to index
"""
# RuntimeWarning: invalid value encountered in double_scalars
np.seterr(all="ignore")
coms = tbl[icol].values.astype("int32") # Read in comids
indices = swapper(coms, upstream) # Get indices that will be used to map values
del upstream # a and indices are big - clean up to minimize RAM
cols = tbl.columns[1:] # Get column names that will be accumulated
z = np.zeros(comids.shape) # Make empty vector for placing values
data = np.zeros((len(comids), len(tbl.columns)))
data[:, 0] = comids # Define first column as comids
accumulated_indexes = np.add.accumulate(lengths)[:-1]
# Loop and accumulate values
for index, column in enumerate(cols, 1):
col_values = tbl[column].values.astype("float")
all_values = np.split(col_values[indices], accumulated_indexes)
if tbl_type == "Ws":
# add identity value to each array for full watershed
all_values = np.array(
[np.append(val, col_values[idx]) for idx, val in enumerate(all_values)],
dtype=object,
)
# all_values = [np.append(val, col_values[idx]) for idx, val in enumerate(all_values)]
if index == 1:
area = all_values.copy()
if "PctFull" in column:
values = [
np.ma.average(np.nan_to_num(val), weights=w)
for val, w in zip(all_values, area)
]
elif "MIN" in column or "MAX" in column:
func = np.max if "MAX" in column else np.min
# initial is necessary to eval empty upstream arrays
# these values will be overwritten w/ nan later
# initial = -999 if "MAX" in column else 999999
initial = -999999 if "MAX" in column else 999999
values = np.array([func(val, initial=initial) for val in all_values])
values[lengths == 0] = col_values[lengths == 0]
else:
values = np.array([np.nansum(val) for val in all_values])
data[:, index] = values
data = data[np.in1d(data[:, 0], coms), :] # Remove the extra comids
outDF = pd.DataFrame(data)
prefix = "UpCat" if tbl_type == "Up" else "Ws"
outDF.columns = [icol] + [c.replace("Cat", prefix) for c in cols.tolist()]
areaName = outDF.columns[outDF.columns.str.contains("Area")][0]
# identifies that there is no area in catchment mask,
# then NA values for everything past Area, covers upcats w. no area AND
# WS w/ no area
no_area_rows, na_columns = (outDF[areaName] == 0), outDF.columns[2:]
outDF.loc[no_area_rows, na_columns] = np.nan
return outDF
##############################################################################
def createCatStats(
accum_type,
LandscapeLayer,
inZoneData,
out_dir,
zone,
by_RPU,
mask_dir,
NHD_dir,
hydroregion,
appendMetric,
):
"""
__author__ = "Marc Weber <[email protected]>"
"Ryan Hill <[email protected]>"
Uses the arcpy tools to perform ZonalStatisticsAsTable or TabulateArea based on accum_type and then formats
the results into a Catchment Results table with 'PctFull'Calculated
Arguments
---------
accum_type : type metric to be accumulated, i.e. 'Categorical', 'Continuous', 'Count'
LandscapeLayer : string of the landscape raster name
inZoneData : string to the NHD catchment grid
out_dir : string to directory where output is being stored
zone : string of an NHDPlusV2 VPU zone, i.e. 10L, 16, 17
"""
try:
arcpy.env.cellSize = "30"
arcpy.env.snapRaster = inZoneData
if by_RPU == 0:
if LandscapeLayer.count(".tif") or LandscapeLayer.count(".img"):
outTable = "%s/DBF_stash/zonalstats_%s%s%s.dbf" % (
out_dir,
LandscapeLayer.split("/")[-1].split(".")[0],
appendMetric,
zone,
)
else:
outTable = "%s/DBF_stash/zonalstats_%s%s%s.dbf" % (
out_dir,
LandscapeLayer.split("/")[-1],
appendMetric,
zone,
)
if not os.path.exists(outTable):
if accum_type == "Categorical":
TabulateArea(
inZoneData, "VALUE", LandscapeLayer, "Value", outTable, "30"
)
if accum_type == "Continuous":
ZonalStatisticsAsTable(
inZoneData, "VALUE", LandscapeLayer, outTable, "DATA", "ALL"
)
try:
table = dbf2DF(outTable)
except fiona.errors.DriverError as e:
# arc occassionally doesn't release the file and fails here
print(e, "\n\n!EXCEPTION CAUGHT! TRYING AGAIN!")
time.sleep(60)
table = dbf2DF(outTable)
if by_RPU == 1:
hydrodir = "/".join(inZoneData.split("/")[:-2]) + "/NEDSnapshot"
rpuList = []
for subdirs in os.listdir(hydrodir):