-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_nwm_3dhp.qmd
2010 lines (1718 loc) · 74.7 KB
/
test_nwm_3dhp.qmd
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
---
title: "NWM on 3DHP testing"
author: "[email protected]"
date: "`r Sys.Date()`"
format:
html:
embed-resources: true
theme: yeti
code-fold: true
toc: true
toc-location: left
grid:
sidebar-width: 180px
body-width: 1100px
margin-width: 20px
---
to-do
- culverts
- test length*slope (width?) as non-dollar relative 'cost' indicator
- hydgeo scaling (on upstream length as DA proxy) for est width & depth - but can/should be able to get directly from DEM?
- stream type
- tabulations
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE, fig.width = 8, fig.height = 8)
library("tidyverse", quietly = T)
library("sf")
library("patchwork")
library("gt")
theme_set(theme_minimal())
dir_data_common <- "~/T/DFW-Team WDFW Watershed Synthesis - data_common"
epsg <- 2927 #WA state standard; NAD83(HARN)/ft
load("test_nwm_3dhp.RData")
```
# objects
```{r lines_3dhp, eval=FALSE}
# sf::st_layers(file.path(dir_data_common, "3dhp/17110008_EDH_230605.gdb"))
# #after initial read before select()
# as_tibble(lines) |> #glimpse()
# #count(FClass, EClass) #Fclass all 1, Eclass 0,2,3
# #count(Source) #all "Lidar YYYY", mostly 2017 and 2013
# #count(Method) #all "Flow direction and accumulation combined with proprietary methods"
# #count(UserCode) #all NA except 2 " "
# #count(Comments) #mostly NA, sort of interesting but probably not standard, in USGS?
# count(GNIS_Name) #100 names and a few versions of blanks and nulls
# #test if multilinestring is actually more than single line
# #not, anywhere in the full set actually
# any(map_int(st_geometry(lines_3dhp), length) > 1)
#in 2927, 74K, note XYZ-ness
lines_3dhp <- sf::st_read(file.path(dir_data_common, "3dhp/17110008_EDH_230605.gdb"), layer = "Lines") |>
select(-c(FClass, Method, UserCode, Comments)) |>
sf::st_cast("LINESTRING")
# lines_3dhp |>
# #as_tibble() |> glimpse()
# ggplot() + geom_sf(aes(color = Source))
# #not clear exactly where this is...
# cat_3dhp <- sf::st_read(file.path(dir_data_common, "3dhp/1711000802_catchments/1711000802_catchments.shp"))
```
could add custom function to `slope_xyz` to calc max gradient along reach rather than length-weighted default
```{r add_slope_est_convex_hull, eval=FALSE}
lines_3dhp <- lines_3dhp |>
mutate(
across(SHAPE, list(
zslope_est = ~slopes::slope_xyz(., directed = T),
zmax = ~map_dbl(., ~slopes::z_max(.x))
), .names = "{.fn}")
)
# lines_3dhp |>
# st_centroid() |>
# ggplot() + geom_sf(aes(color = zslope_est), size = 0.5, alpha = 0.5) + wacolors::scale_color_wa_c("forest_fire")
#slightly tighter than bbox
lines_3dhp_uch <- lines_3dhp |> st_union() |> st_convex_hull()
```
cut nhdp to 3dhp & associate comid
```{r sf_nhdp_wa, eval=FALSE}
# #med res NHDplus, 230K polys including non-WA, no attrib but FEATUREID==COMID for StreamCat join
# sf_nhdp <- sf::read_sf(file.path(dir_data_common, "NHDPlus17/NHDPlusCatchment/Catchment.shp")) |>
# sf::st_transform(crs = sf::st_crs(epsg)) |>
# select(COMID = FEATUREID, areasqkm = AreaSqKM)
#
# #use StreamCat for WA to nonspatially subset catchment polys
# sf_nhdp_wa <- inner_join(
# sf_nhdp |> mutate(comid = as.character(COMID))
# ,
# StreamCatTools::sc_nlcd(state = "WA", year = "2019", aoi = 'riparian_watershed') |>
# rename_with(tolower) |> as_tibble() |>
# mutate(comid = as.character(comid)) |>
# select(comid, state)
# ,
# by = "comid")
#
# saveRDS(sf_nhdp_wa, "~/T/DFW-Team WDFW Watershed Synthesis - flow_trees_heat/sf_nhdp_wa.rds")
sf_nhdp_wa <- readRDS("~/T/DFW-Team WDFW Watershed Synthesis - flow_trees_heat/sf_nhdp_wa.rds")
```
```{r sf_nhdp_wa_3dhp, eval=FALSE}
#sf_nhdp_wa_3dhp <- sf_nhdp_wa[st_as_sfc(st_bbox(lines_3dhp)),] #1464 of 57313
sf_nhdp_wa_3dhp <- sf_nhdp_wa[lines_3dhp_uch,] #959
#not bad, maybe ~1min?
lines_3dhp <- st_join(
lines_3dhp,
sf_nhdp_wa_3dhp |> select(-state),
join = st_intersects, #st_crosses?
largest = T
)
```
cut FPDSI culvert subset down to 3dhp
```{r sf_fpb, eval=FALSE}
#also: tbl(con_fpdsi, "SiteFishPassageViewSpatial") for current but need to revisit permissions for full schema
sf_fpb <- sf::read_sf(
file.path(dir_data_common,"WdfwFishPassage.gdb"),
layer = "WDFW_FishPassageSite") |>
sf::st_transform(epsg) |>
rename_with(.cols = starts_with("FishPassage"), .fn = ~str_replace(., "FishPassage","FP")) |>
filter(
FPFeatureTypeCode==1 #culverts
# #!is.na(BarrierCorrectionTypeCode)
# !is.na(BarrierCorrectionYearsText)
) |>
mutate(
fish_use = case_when(
FishUseCode == 10 ~ "yes",
FishUseCode == 20 ~ "no",
FishUseCode == 99 ~ "unk"
)
) |>
left_join(
tibble(
OwnerTypeCode = c(1:7,9,10,12),
owner = c("city", "county", "federal", "private", "state", "tribal", "other", "drainage_dist", "diking_dist", "unk")
),
by = "OwnerTypeCode"
)
```
```{r sf_fpb_3dhp, eval=FALSE}
#sf_fpb_3dhp <- sf_fpb[st_as_sfc(st_bbox(lines_3dhp)),] #this is 2221
sf_fpb_3dhp <- sf_fpb[lines_3dhp_uch,] #1374
#as_tibble(sf_fpb_3dhp) |> count(fish_use)
#sf_fpb_3dhp |> ggplot() + geom_sf(aes(shape = fish_use, color = fish_use)) + geom_sf(data = lines_3dhp_uch, fill = NA, color = "hotpink")
```
add a basic barrier attribute count to NHDcats
```{r sf_nhdp_wa_3dhp_fpb, eval=FALSE}
sf_nhdp_wa_3dhp_fpb <- sf_nhdp_wa_3dhp |>
select(-state) |>
left_join(
st_join(sf_fpb_3dhp, sf_nhdp_wa_3dhp) |> #pt in poly, not expanding
as_tibble() |>
count(comid, fish_use) |>
pivot_wider(names_from = fish_use, values_from = n)
,
by = "comid"
)
# {ggplot() + geom_sf(data = sf_nhdp_wa_3dhp_fpb, aes(fill = yes), color = NA) +
# geom_sf(data = lines_3dhp_uch, fill = NA, color = "hotpink") +
# wacolors::scale_fill_wa_c("forest_fire", na.value = "grey90")
# }+{ggplot() + geom_sf(data = sf_nhdp_wa_3dhp_fpb, aes(fill = no), color = NA) +
# geom_sf(data = lines_3dhp_uch, fill = NA, color = "hotpink") +
# wacolors::scale_fill_wa_c("ferries", na.value = "grey90")} +
# plot_layout(ncol = 1) +
# plot_annotation(subtitle = "Fish passage barriers per 1:100NHDplus catchment by 'fish use' \n pink hull shows 3DHP extent")
```
trim NHDplusHighRes down to 3DHP general extent (convex hull of unioned lines)
```{r sf_nhdphr_flw_3dhp, eval=FALSE}
sf_nhdphr_flw_3dhp <- st_read(file.path(dir_data_common, "nhdphr/17/NHDPLUS_H_1711_HU4_GDB.gdb/"), layer = "NHDFlowline") |>
select(Permanent_Identifier, GNIS_Name:ReachCode, FCode, Shape_Length, NHDPlusID) |>
st_cast("LINESTRING") |>
left_join(
read_csv(file.path(dir_data_common, "nhdphr/brinkerhoffetal2024_results_archive/results_1711.csv"))
,
by = "NHDPlusID") |>
drop_na(percQEph_reach) |>
st_zm() |>
st_transform(st_crs(lines_3dhp))
sf_nhdphr_flw_3dhp <- sf_nhdphr_flw_3dhp[lines_3dhp_uch,] #23785
```
cut 3dhp to focal comid(s) & build test network
```{r lines_3dhp_to_lsfn, eval=FALSE}
# #where is the greatest density of 3dhp lines in NHDplus MR catchments?
# sf_nhdp_wa_3dhp |>
# left_join(
# lines_3dhp |> as_tibble() |> count(comid, name = "n_3dhp") |> arrange(desc(n_3dhp))
# , by = "comid"
# ) |>
# drop_na(n_3dhp) |>
# ggplot() + geom_sf(aes(color = n_3dhp, fill = n_3dhp)) +
# wacolors::scale_color_wa_c("sea", reverse = T, aesthetics = c("color","fill")) +
# labs(title = "Pilot 3DHP lines per med res NHDplus catchments")
#
# #for now just take the comid with the greatest number of associated 3dhp line units: "24275471"
# lines_3dhp |> as_tibble() |> count(comid, name = "n_3dhp") |> arrange(desc(n_3dhp)) |> slice(1:10)
# #spatial bounds initially generate a 'rooted forest' with GIS artifact strays
# ggplot() +
# geom_sf(data = st_as_sf(lsfn, "edges"), col = "lightblue", linewidth = 0.3) +
# geom_sf(
# data = lsfn |>
# tidygraph::activate(nodes) |>
# filter(tidygraph::node_is_root()) |>
# st_as_sf("nodes")
# ,
# color = "orange"
# )
#create sfnetwork object with nodes and edges that have from/to attributes added...
#identical feature count, follows from length(geometry()) test
#the convert to_largest_component drops GIS artifact strays from initial 'rooted forest'
#then adds calc'd topological and length weighted distance for nodes which are then associated to 'to' of edges
#map inspection that the ground distance versions are 'from downstream node to downstream [root] node'
lsfn <- lines_3dhp |>
filter(comid == "24275471") |>
select(uid = UniqueID, shape_length = SHAPE_Length, comid, desc = Desc) |>
sfnetworks::as_sfnetwork() |>
tidygraph::activate(nodes) |>
tidygraph::convert(
tidygraph::to_largest_component,
.clean = T #this drops the .tidygraph_node_index/edge_index that no longer apply & are potentially confusing
) |>
mutate(
idn = seq_along(SHAPE),
#raindrop perspective paths from nodes to root
d_root = tidygraph::node_distance_to(tidygraph::node_is_root()),
d_root_ft = tidygraph::node_distance_to(tidygraph::node_is_root(), weights = shape_length),
d_root_km = 0.0003 * d_root_ft,
#looking 'up' perspective to perimeter from per-node 'me'
in_n = tidygraph::local_size(order = nrow(tidygraph::.N()), mode = "in")
)
#associate the immediately upstream streamlength from edges to each 'to' node
#summed over both upstream tribs
#also add 'below_culvert' logical:
# every culvert edge has a single 'to' node,
# but each of those 'to' nodes has potentially 2 incoming edges
# one of which may be a non-culvert
# and there is a potential case of 2 converging culverts
# so need logic to define per-node state in
# {no-incoming, not, culvert, not+not, culvert+not, culvert+culvert}
lsfn <- lsfn |>
tidygraph::activate(nodes) |>
left_join(
select(as_tibble(as_tibble(lsfn, active = "edges")), uid, idn = to, shape_length, desc) |>
summarise(
below_culvert = if_else(any(str_detect(desc, "ulvert")), T, F),
in_ft_first_order = sum(shape_length),
.by = "idn"),
by = c("idn")
)
#ensure whole thing is directed acyclic to root
tidygraph::with_graph(lsfn, tidygraph::graph_is_dag()) #true, good
#now per-node, define upstream neighborhood and sum over first-order incoming lengths of neighborhood members
#sweet: https://tidygraph.data-imaginist.com/reference/map_local.html
#this may not be the most efficient approach but...
#no appreciable speed diff between order = 3,10,max
lsfn_order <- tidygraph::with_graph(lsfn, tidygraph::graph_order())
lsfn <- lsfn |>
tidygraph::activate(nodes) |>
mutate(
in_ft = tidygraph::map_local_dbl(
order = lsfn_order, mode = "in",
.f = function(neighborhood, ...){
sum(as_tibble(neighborhood, active = 'nodes')$in_ft_first_order, na.rm = T)
}
),
in_km = 0.0003 * in_ft
)
#and then add node attributes back to edge by 'to'
lsfn <- lsfn |>
tidygraph::activate(edges) |>
mutate(culvert = str_detect(desc, "ulvert")) |>
left_join(
select(as_tibble(as_tibble(lsfn, active = "nodes")), to = idn, d_root, ends_with("_km"))
,
by = c("to")
) |>
tidygraph::activate(nodes)
## unused but keeping handy for now
## temporarily converting edges to nodes
# lsfn |>
# tidygraph::morph(
# tidygraph::to_linegraph
# ) |>
# mutate(
# d_root = tidygraph::node_distance_to(tidygraph::node_is_root())
# ) |>
# tidygraph::unmorph()
```
```{r func_prep_sfn}
#little wrapper to pull out 3dhp for a given catchment
#then make into attributed sfnetwork
#follow above flow in chunk lines_3dhp_to_lsfn
prep_sfn <- function(cat){
l <- lines_3dhp |>
filter(comid == cat) |>
select(uid = UniqueID, shape_length = SHAPE_Length, comid, desc = Desc, zslope_est, zmax) |>
sfnetworks::as_sfnetwork() |>
tidygraph::activate(nodes) |>
tidygraph::convert(
tidygraph::to_largest_component,
.clean = T #this drops the .tidygraph_node_index/edge_index that no longer apply & are potentially confusing
) |>
mutate(
idn = seq_along(SHAPE),
#raindrop perspective paths from nodes to root
d_root = tidygraph::node_distance_to(tidygraph::node_is_root()),
d_root_ft = tidygraph::node_distance_to(tidygraph::node_is_root(), weights = shape_length),
d_root_km = 0.0003 * d_root_ft,
#looking 'up' perspective to perimeter from per-node 'me'
in_n = tidygraph::local_size(order = nrow(tidygraph::.N()), mode = "in")
)
#ensure whole thing is directed acyclic to root
if(!tidygraph::with_graph(l, tidygraph::graph_is_dag())) {stop();print("Not DAG")}
#associate the immediately upstream streamlength from edges to each 'to' node
#summed over both upstream tribs; also add 'below_culvert' logical:
# defining per-node state in {no-incoming, not, culvert, not+not, culvert+not, culvert+culvert}
l <- l |>
tidygraph::activate(nodes) |>
left_join(
select(as_tibble(as_tibble(l, active = "edges")), uid, idn = to, shape_length, desc, zslope_est, zmax) |>
summarise(
below_culvert = if_else(any(str_detect(desc, "ulvert")), T, F),
in_slope_mean = mean(zslope_est),
in_ft_first_order = sum(shape_length),
.by = "idn"),
by = c("idn")
)
#now per-node, define upstream neighborhood and sum over first-order incoming lengths of neighborhood members
l_order <- tidygraph::with_graph(l, tidygraph::graph_order())
l <- l |>
tidygraph::activate(nodes) |>
mutate(
in_ft = tidygraph::map_local_dbl(
order = l_order, mode = "in",
.f = function(neighborhood, ...){
sum(as_tibble(neighborhood, active = 'nodes')$in_ft_first_order, na.rm = T)
}
),
in_km = 0.0003 * in_ft
)
#and then add node attributes back to edge by 'to'
l <- l |>
tidygraph::activate(edges) |>
mutate(culvert = str_detect(desc, "ulvert")) |>
left_join(
select(as_tibble(as_tibble(l, active = "nodes")), to = idn, d_root, ends_with("_km"))
,
by = c("to")
) |>
tidygraph::activate(nodes)
return(l)
}
lsfn <- prep_sfn("24275471")
```
# perfuse fixed root value
## alt1: topology + channel distance
playing with reverse "contributing" + "travel time" to get a cfs-unit value 'up'
the "in_km" built from topology and edge geometry length is proxy, not true 'drainage area', especially over very large domains or other (lithology, land cover) factors that cause adjoining subbasins to have very different drainage density/dissection.
Need to progress iteratively from network perimeter down, at a multi-COMID scale?
This first pass going to create big flow 'jumps' where mainstem catchments join?
```{r dumb_instant_travel_perfuse}
z <- as_tibble(lsfn, active = 'nodes')
#z |> sf::st_zm() |> select(-in_node) |> mapview::mapview(zcol = "in_ft")
#hot damn
ggplot() +
geom_sf(data = as_tibble(lsfn, active = "edges"), color = "lightblue", linewidth = 0.5) +
geom_sf(data = z, aes(color = log10(in_ft)), alpha = 0.8) +
wacolors::scale_color_wa_b()
#try for super dumb demo of 'spreading a fixed volume up network'?
#good: decay is appropriately at power-law rate,
# so is this capturing nested/recursive/cumulative contribution more or less correctly?
#bad/weird: this is showing a weird thing, unclear what it means in flow units
# "if the flow at the outlet is 1000, then this is the independent portion contributed by each network position"
z |>
#as_tibble() |>
arrange(desc(in_km)) |>
mutate(
in_km_pct = in_km / sum(in_km),
q1k = 1000*in_km_pct,
q1k_log10 = log10(q1k)
) |>
#arrange(q1k) |> filter(!is.infinite(q1k_log10))
#pull(q1k) |> sum(na.rm = T)
ggplot() +
geom_sf(data = st_as_sf(lsfn, "edges"), col = "lightblue", linewidth = 0.3) +
geom_sf(aes(color = q1k_log10)) + wacolors::scale_color_wa_b("ferries", reverse = T)
#check summing upstream in subgraph
#this is somewhat reassuring: the 'outlet' flow is scaling appropriately within-network
lsfn <- lsfn |>
tidygraph::activate("nodes") |>
mutate(
in_km_pct = in_km / sum(in_km),
q1k = 1000*in_km_pct,
q1k_log10 = log10(q1k)
)
z <- lsfn |>
tidygraph::activate("nodes") |>
mutate(
q_recalc = tidygraph::map_local_dbl(
order = lsfn_order, mode = "in",
.f = function(neighborhood, ...){
sum(as_tibble(neighborhood, active = 'nodes')$q1k, na.rm = T)
}
)
)
{
as_tibble(z, active = 'nodes') |> #pull(q_recalc) |> summary()
ggplot() +
geom_sf(data = st_as_sf(lsfn, "edges"), col = "lightblue", linewidth = 0.3) +
geom_sf(aes(color = q_recalc), size = 0.5) +
wacolors::scale_color_wa_c("ferries", reverse = T) +
labs(
title = "Assuming instantaneous travel time, \n
if outlet flow is 1000 cfs/cms/etc, and independent network contributions are uniform, \n
then this is the (instant) value everywhere in the network, \n
with Q per node summed from upstream subgraph (in-neighborhood)
")
}+{
as_tibble(z, active = 'nodes') |>
ggplot() +
geom_sf(data = st_as_sf(lsfn, "edges"), col = "lightblue", linewidth = 0.3) +
geom_sf(aes(color = log10(q_recalc)), size = 0.5) +
wacolors::scale_color_wa_b("ferries", n.breaks = 6, reverse = T) +
labs(title = "same, log10 to show power law decay")
} + plot_layout(ncol = 1)
ggsave(filename = "figures/f_ins_tt_unif_contrib_1k.png", width = 7, height = 11, dpi = 150, bg = "white")
```
## alt2a: alt1 + gradient
loop back to, but paused pending further review of [Brinkerhoff et al.](https://github.com/craigbrinkerhoff/CONUS_ephemeral)
# what about desc==culvert (& vs fpb)
> "The elevation derived hydrography specification calls for the segmentation and distinction of culvert features from the rest of the flowline network. Culvert features were automatically identified by comparing the monotonically enforced elevation values to the elevation ground model. Vertices that are misaligned with the DEM surface after monotonic Z smoothing and in close proximity to ancillary road and culvert data were extracted and used to classify culverts within the network. This segmentation process was manually reviewed. Additional culverts were manually extracted as necessary." -- NV5 Geospatial, pilot project report "Stillaguamish Watershed Lidar-derived 3DHP", June 9, 2023
"Connector: culvert" reaches (edges) in terms of the upstream network km
```{r func_gg_culv}
#conn_culvert_upstream
# as_tibble(lsfn, "edges") |>
# #as_tibble() |> count(desc)
# #ggplot() + geom_sf(aes(color = desc)) + scale_color_manual(values = c("grey","orange","lightblue"))
# ggplot() + geom_sf(aes(color = culvert)) + scale_color_manual(values = c("lightblue","orange"))
#
# as_tibble(lsfn, active = "nodes") |> ggplot() + geom_sf(aes(color = below_culvert))
#
# as_tibble(lsfn, "edges") |> st_zm() |> mapview::mapview(zcol = "culvert", burst = T)
# ggplot() +
# geom_sf(data = as_tibble(lsfn, "edges") |> filter(!culvert), linewidth = 0.2, color = "lightblue") +
# geom_sf(data = as_tibble(lsfn, "nodes") |> filter(below_culvert), aes(color = in_km, size = in_km)) +
# scale_color_gradient(low = "white", high = "purple") + scale_size_area(max_size = 4) +
# theme(line = element_blank(), axis.text = element_blank()) +
# ggspatial::annotation_scale(location = "bl")
gg_culv <- function(){
ggplot() +
geom_sf(data = as_tibble(lsfn, "edges") |> filter(!culvert), linewidth = 0.2, color = "lightblue") +
geom_sf(data = as_tibble(lsfn, "nodes") |> filter(below_culvert),
#aes(color = in_km, size = 1 / d_root_km)) +
aes(size = in_km, color = 1 / d_root_km)) +
#scale_color_gradient(low = "tan", high = "purple") +
wacolors::scale_color_wa_b("puget", n.breaks = 8, reverse = T) +
scale_size_area(max_size = 5) +
theme(line = element_blank(), axis.text = element_blank()) +
ggspatial::annotation_scale(location = "bl") +
labs(subtitle = paste("3DHP for NHD comid", as_tibble(lsfn, "edges")$comid[1]))
}
#gg_culv()
# lsfn |>
# mutate(
# ac = tidygraph::centrality_alpha()
# ) |> filter(in_n != ac)
```
```{r culv_eda}
#first couple cats not in 3dhp, train on 24275405 32+5
sf_nhdp_wa_3dhp_fpb[lines_3dhp_uch,] |> arrange(desc(yes+no))
fcat <- "24275405"
lsfn <- prep_sfn(fcat)
#can should instead reverse join poly comid on point...
lsfn_fpb <- sf_fpb_3dhp[filter(sf_nhdp_wa_3dhp_fpb, comid == fcat),]
gg_culv() +
geom_sf(
data = lsfn_fpb, aes(shape = fish_use),
color = "grey30", alpha = 0.5) + scale_shape_manual(values = c(3,4))
mapview::mapview(st_zm(as_tibble(lsfn, "edges")), zcol = "culvert", burst = T, color = c("lightblue","hotpink")) +
mapview::mapview(lsfn_fpb, zcol = "fish_use", burst = T)
#compare field assessed slope for a match: uid 65142
#https://apps.wdfw.wa.gov/fishpassagephotos/Reports/LP27_Report.pdf
#slope 1.03%
# #remotes::install_github("ropensci/slopes")
# #from slope_matrix workhorse help "The output value is a proportion representing the change in elevation for a given change in horizontal movement along the linestring. 0.02, for example, represents a low gradient of 2% while 0.08 represents a steep gradient of 8%."
# z <- as_tibble(lsfn, "edges") |> filter(uid == "65142")
#
# slopes::z_value(z)
# slopes::slope_xyz(z, directed = T)
# #need to confirm that in reaches/edges
# #first point is upstream/max
# #last point is downstream/min
# z |> mutate(
# across(SHAPE, list(
# zslope_est = ~slopes::slope_xyz(., directed = T),
# z1 = ~slopes::z_start(.),
# z2 = ~slopes::z_end(.),
# #zmin = ~slopes::z_min(.), #bug, calls max(), issue created
# zmin = ~min(slopes::z_value(.)),
# zmax = ~slopes::z_max(.)
# ))
# ) |> select(uid, contains("z"))
#
# #cannot get to scatter against FPDSI slope without different version of those data (not going to review individual level A reports)
# #but can still start to look at (mis)match...
# #inflections at ~20ft buffer distance
# tibble(d = seq(0, 50, by = 2)) |>
# mutate(
# n_intsct = d |>
# map_int(
# #st_intersection(
# ~st_intersects(
# as_tibble(lsfn, "edges") |> filter(culvert),
# lsfn_fpb |> st_buffer(dist = .x)
# ) |> unlist() |> length()
# )
# ) |>
# ggplot() + geom_col(aes(d, n_intsct))
#
# d_buff <- 20
#
# #if just inner_join wanted can use st_intersection
# #but this preserves non-matches as NA
# z <- st_join(
# as_tibble(lsfn, "edges") |> filter(culvert),
# lsfn_fpb |> st_buffer(dist = d_buff)
# ) |>
# mutate(
# across(SHAPE, list(
# zslope_est = ~slopes::slope_xyz(., directed = T),
# zmax = ~slopes::z_max(.)
# ), .names = "{.fn}")
# )
#
# z |>
# ggplot(aes(fish_use, zslope_est)) +
# geom_jitter(width = 0.2, alpha = 0.6) +
# geom_violin(fill = NA)
lines_3dhp_culv <- lines_3dhp |>
filter(str_detect(Desc, "ulvert"))
#full set? (FAST!?!)
sf_3dhp_culv_fpb <- st_join(
lines_3dhp_culv
,
sf_fpb_3dhp |> st_buffer(dist = d_buff)
) |>
mutate(
across(SHAPE, list(
zslope_est = ~slopes::slope_xyz(., directed = T),
zmax = ~slopes::z_max(.)
), .names = "{.fn}")
) |>
select(
uid = UniqueID, shape_length = SHAPE_Length, comid, desc = Desc,
SiteId, FeatureType, fish_use, FishUseCriteriaCode, FPBarrierStatusCode, FPBarrierReasonCode, PercentFishPassableCode, SurveyDate,
zslope_est, zmax
)
sf_3dhp_culv_fpb |> #summary()
filter(zslope_est <= 0) |> #drop a single edge with a positive slope (assume this is artifact)
ggplot(aes(fish_use, zslope_est)) +
geom_jitter(width = 0.2, alpha = 0.6) +
geom_violin(fill = NA)
#plot coerced to centroid point for better vis
{
ggplot() +
geom_sf(
data = sf_3dhp_culv_fpb |>
filter(is.na(SiteId), zslope_est <= 0) |> #nrow()
st_centroid(),
aes(color = zslope_est), shape = 18, alpha = 0.6
) +
wacolors::scale_color_wa_c("foothills") +
labs(subtitle = "8,332 3DHP without (20ft buffer) matches to fish passage inventory culverts")
}+{
ggplot() +
geom_sf(
data = sf_3dhp_culv_fpb |>
drop_na(SiteId) |>
filter(zslope_est <= 0) |> #nrow() #drop a single edge with a positive slope (assume this is artifact)
st_centroid(),
aes(color = zslope_est, shape = fish_use), alpha = 0.6
) +
wacolors::scale_color_wa_c("foothills") +
scale_shape_manual(values = c(19,10,15)) +
labs(subtitle = "462 3DHP with (20ft buffer) matches")
} + {
ggplot() +
geom_sf(
data = sf_fpb_3dhp |>
anti_join(as_tibble(sf_3dhp_culv_fpb) |> drop_na(SiteId), by = "SiteId")
,
aes(shape = fish_use), alpha = 0.6
) +
geom_sf(data = lines_3dhp_uch, fill = NA, color = "hotpink") +
scale_shape_manual(values = c(19,10,15)) +
labs(subtitle = "915 fish passage inventory culverts without 3DHP barrier matches \n (including those within convex hull but outside current 3DHP linework extent)")
} +
plot_layout(ncol = 1) +
plot_annotation(
title = "Estimated slopes for 3DHP 'connector: culvert' reaches vs fish passage inventory culverts",
subtitle = "Approx. ~5% of 3DHP 'connector: culvert' (462 of 8794) with barrier matches")
ggsave(filename = "figures/f_culv_slope_compare.png", width = 7, height = 11, dpi = 150, bg = "white")
#examine survey date/source for nonmatches/far distances
sf_fpb_3dhp |>
as_tibble() |>
#semi_join(as_tibble(sf_3dhp_culv_fpb), by = "SiteId") |>
anti_join(as_tibble(sf_3dhp_culv_fpb), by = "SiteId") |>
count(DataSource) |> arrange(desc(n))
#Euclidean distances from all fpb to any/culvert 3dhp lines
#takes a minute, returns n-barriers by n-reaches matrix
#need/want to integrate st_nearest_feature?
d_fpb_culv <- st_distance(
sf_fpb_3dhp, #barrier points
lines_3dhp_culv, #culvert line sections only
)
#per barrier, along rows
sf_fpb_3dhp$d_culv <- round(apply(d_fpb_culv, 1, min), 2)
sum(sf_fpb_3dhp$d_culv <= 20) #matches st_intersect on st_buffer(20) in st_join
plot.ecdf(sf_fpb_3dhp$d_culv)
#worst issues appear due to using convex_hull to constrain barrier set
sf_fpb_3dhp |>
mutate(d_in20 = d_culv <= 20) |>
#filter(d_culv < 1000) |>
ggplot() + geom_sf(aes(color = log10(d_culv))) + facet_wrap(~d_in20, ncol = 1)
#can also test against full linework set for barriers that are on/close to 'stream' reaches (missing in 3DHP?)
#distributions of distances to nearest culvert line by source
sf_fpb_3dhp |>
filter(d_culv < 1000) |>
ggplot() +
geom_boxplot(aes(d_culv, DataSource), varwidth = T)
#unique(nchar(sf_fpb_3dhp$SurveyDate))
sf_fpb_3dhp$date = as.Date(sf_fpb_3dhp$SurveyDate, format = "%m/%d/%Y")
#sf_fpb_3dhp |> filter(is.na(date)) |> select(SiteId, DataSource, SurveyDate)
sf_fpb_3dhp |>
ggplot() +
geom_point(aes(year(date), d_culv, color = DataSource))
```
```{r needs_work}
lines_3dhp_culv <- lines_3dhp |>
filter(str_detect(Desc, "ulvert"))
as_tibble(lines_3dhp_culv) |> #summary()
rename(length = SHAPE_Length) |>
ggplot() +
geom_point(aes(length, zmax, color = abs(zslope_est)), alpha = 0.3) +
scale_x_log10() + scale_y_log10()
#try the whole thing
#goal would be to supplement above ordination of culvert reaches by elevation and slope with up/downstream network distances
#pretty fast, "directed acyclic multigraph with 22 components"
lines_3dhp_sfn <- lines_3dhp |>
sfnetworks::as_sfnetwork()
lines_3dhp_sfn <- lines_3dhp_sfn |>
tidygraph::activate(nodes) |>
mutate(ng = tidygraph::group_components())
#non-primary components appear appropriately peripheral?
as_tibble(lines_3dhp_sfn, "nodes") |>
#as_tibble() |> count(ng) |> arrange(desc(n)) |> print(n=Inf)
filter(ng > 1) |> mutate(ng = letters[ng]) |>
#ggplot() + geom_sf(aes(color = ng))
st_zm() |> mapview::mapview(zcol = "ng", burst = T)
#this results in 'directed acyclic multigraph with 1 component'
lines_3dhp_sfn <- lines_3dhp_sfn |>
tidygraph::convert(
tidygraph::to_largest_component,
.clean = T
)
#need to reduce (multiedges) to tree to calc node_distance_to
tidygraph::with_graph(lines_3dhp_sfn, tidygraph::graph_is_tree())
# #have tidygraph option and sfnetwork extension, latter seems preferable for control on 'attribute_summary' arg
# #but other tidygraph 'to_*_tree' options
# lines_3dhp_sfn |> tidygraph::convert(tidygraph::to_simple)
lines_3dhp_sfn <- lines_3dhp_sfn |> tidygraph::convert(sfnetworks::to_spatial_simple, .clean = T)
#also have https://luukvdmeer.github.io/sfnetworks/reference/simplify_network.html
#but looks like needs package update? sfnetworks::simplify_network(lines_3dhp_sfn)
#but still not a tree
tidygraph::with_graph(lines_3dhp_sfn, tidygraph::graph_is_tree())
tidygraph::with_graph(lines_3dhp_sfn, tidygraph::node_is_root()) |> any()
lines_3dhp_sfn |> filter(tidygraph::node_is_root())
#may need to work with dominator tree? https://tidygraph.data-imaginist.com/reference/node_topology.html
#however, there is an edge with a lowest elevation Z-val...
as_tibble(lines_3dhp_sfn, "edges") |> as_tibble() |> arrange(zmax)
#the 'to' node is 73095 and/but it has no 'from'
as_tibble(lines_3dhp_sfn, "edges") |> filter(from == 73095)
#looks like maybe still some 'extra' edges? lsfn has 1 more node than edges, this has 41
lines_3dhp_sfn |>
tidygraph::activate("nodes") |>
mutate(idn = seq_along(SHAPE)) |>
arrange(tidygraph::node_topo_order())
#okay so a small number of 'from' nodes appear twice, likely the issue?
as_tibble(lines_3dhp_sfn, "edges") |> as_tibble() |>
#count(to) |> arrange(desc(n)) |> count(n) #all either 1 or 2
count(from) |> arrange(desc(n)) |>
#count(n)
filter(n > 1)
#yes, have same node going to 2 different other nodes
#and have a split path
bind_rows(
as_tibble(lines_3dhp_sfn, "edges") |> filter(from == 27590)
,
as_tibble(lines_3dhp_sfn, "edges") |> filter(to == 27590)
,
as_tibble(lines_3dhp_sfn, "edges") |> filter(from == 25192),
as_tibble(lines_3dhp_sfn, "edges") |> filter(from == 13639),
as_tibble(lines_3dhp_sfn, "edges") |> filter(from == 8703),
as_tibble(lines_3dhp_sfn, "edges") |> filter(from == 8704)
,
as_tibble(lines_3dhp_sfn, "edges") |> filter(from == 28273)
) |>
select(-COMID) |> st_zm() |> mapview::mapview()
#there are non-junction 'in-line' nodes - indeed, many are 'connector: culvert'
#which explains the count(to) n==1
bind_rows(
as_tibble(lines_3dhp_sfn, "edges") |> filter(to == 1)
,
as_tibble(lines_3dhp_sfn, "edges") |> filter(from == 1)
,
as_tibble(lines_3dhp_sfn, "edges") |> filter(to == 341),
as_tibble(lines_3dhp_sfn, "edges") |> filter(to == 340) #from is 25530, which appears to be leaf
#no rows/edges: as_tibble(lines_3dhp_sfn, "edges") |> filter(to == 25530)
) |>
select(-COMID) |> st_zm() |> mapview::mapview()
#for each of the nodes with multiple 'from' drop one of the split paths?
as_tibble(lines_3dhp_sfn, "edges") |> as_tibble() |>
semi_join(
as_tibble(lines_3dhp_sfn, "edges") |> as_tibble() |> count(from) |> arrange(desc(n)) |> filter(n > 1),
by = "from"
)
#could try defining 'root' by lowest elevation node (73095)
#tidygraph::bfs_dist and similar need a root defined...
lines_3dhp_sfn |>
mutate(depth = tidygraph::bfs_dist(root = 73095, mode = "in")) |> as_tibble("nodes") |> as_tibble() |> count(depth) |> print(n = 40)
lines_3dhp_sfn <- lines_3dhp_sfn |>
mutate(
idn = seq_along(SHAPE),
#raindrop perspective paths from nodes to root
#d_root = tidygraph::node_distance_to(tidygraph::node_is_root()),
d_root = tidygraph::node_distance_to(73095),
#d_root_ft = tidygraph::node_distance_to(tidygraph::node_is_root(), weights = shape_length),
#d_root_km = 0.0003 * d_root_ft,
#looking 'up' perspective to perimeter from per-node 'me'
in_n = tidygraph::local_size(order = nrow(tidygraph::.N()), mode = "in")
)
as_tibble(lines_3dhp_sfn, "nodes") |> arrange(desc(d_root))
#illustrates complexity of lower system distributary/slough structure
as_tibble(lines_3dhp_sfn, "nodes") |> arrange(d_root) |> slice(1:10) |> st_zm() |> mapview::mapview()
as_tibble(lines_3dhp_sfn, "edges") |> select(-COMID) |>
filter(to %in% {as_tibble(lines_3dhp_sfn, "nodes") |> arrange(d_root) |> slice(1:50) |> pull(idn)}
) |>
st_zm() |> mapview::mapview()
```
```{r predef_rooted_tree}
#dev 'tree-based' workflow from a priori determined root
#acknowledging that split paths and divergences are biogeo correct
#but need categorically distinct handling?
#def root
#manual via QGIS inspection; start with Pilchuck Creek
root_edge_uid <- 73853
# #node id in of root_edge in original, pre-convert indexing
# filter(as_tibble(sfn, "edges"), uid == root_edge_uid)$to
#need separate declarations to assure node ID in to_local_neighborhood
#and less importantly the order to search over
#also have sfnetworks::to_spatial_neighborhood,
#node = filter(as_tibble(sfn, "edges"), uid == root_edge_uid)$to,
#threshold = , #in sf units; untested whether it would work to use edge attribute as: weights = length_ft
sfn <- lines_3dhp |>
select(comid, desc = Desc, uid = UniqueID, GNIS_Name,
length_ft = SHAPE_Length, zmax, zslope_est) |>
sfnetworks::as_sfnetwork()
sfn <- sfn |>
tidygraph::convert(
tidygraph::to_local_neighborhood,
node = filter(as_tibble(sfn, "edges"), uid == root_edge_uid)$to,
mode = "in",
order = tidygraph::with_graph(sfn, tidygraph::graph_order())
,
.clean = T
)
# #already 'directed acyclic simple graph with 1 component'
# #seems unlikely that 3DHP would have loops/multiples?
# #can add back to pipe if seems needed for certainty
# tidygraph::convert(sfnetworks::to_spatial_simple, .clean = T)
# #however, Pilchuck has a valid split path at node 1033
# as_tibble(sfn, "edges") |> as_tibble() |> count(from) |> arrange(desc(n)) |> filter(n > 1)
# list(
# edge = as_tibble(sfn, "edges") |> st_zm(),
# node = as_tibble(sfn, "nodes") |> st_zm() |> rowid_to_column("idn") |> mutate(issplit = if_else(idn==1033,T,F))
# ) |> mapview::mapview(zcol = list(NULL, "issplit"))
#this still works but now has a different index value (from 73858 to 7131) due to `convert`
root_node_idn <- filter(as_tibble(sfn, "edges"), uid == root_edge_uid)$to
sfn <- sfn |>
tidygraph::activate("nodes") |>
mutate(
idn = seq_along(SHAPE),
#raindrop perspective paths from nodes to root
d_root = tidygraph::node_distance_to(root_node_idn),
d_root_ft = tidygraph::node_distance_to(root_node_idn, weights = length_ft),
d_root_km = 0.0003 * d_root_ft,
#looking 'up' perspective to perimeter from per-node 'me'
in_n = tidygraph::local_size(order = tidygraph::graph_order(), mode = "in", mindist = 1)
) |>
arrange(d_root) |>
#as in 'prep_sfn'
#associate the immediately upstream streamlength from edges to each 'to' node
#summed over both upstream tribs; also add 'below_culvert' logical:
# defining per-node state in {no-incoming, not, culvert, not+not, culvert+not, culvert+culvert}
left_join(
select(as_tibble(as_tibble(sfn, active = "edges")), uid, idn = to, length_ft, desc, zslope_est, zmax) |>
summarise(
node_below_culvert = if_else(any(str_detect(desc, "ulvert")), T, F),
in_slope_max = max(zslope_est),
in_ft = sum(length_ft),
.by = "idn"),
by = "idn"
)
#wait to add 'above' neighborhood length until pruned by slope
#2421 NA node_below_culvert at upstream end of perimeter edges
as_tibble(as_tibble(sfn, "nodes")) |> count(node_below_culvert)
#prune periphery by slope
#interesting options to consider.
#more efficient to begin from root and breadth-first-search up, stopping at any reach over a gradient threshold?
plot.ecdf(as_tibble(sfn, "nodes")$in_slope_max)
slope_threshold <- -0.3
#some slopes >100%, but actually appear to be valid (e.g., )
list(
edge = as_tibble(sfn, "edges") |> st_zm(),
node = as_tibble(sfn, "nodes") |> st_zm()
) |>
#mapview::mapview(zcol = list("length_ft", "in_slope_max"))
mapview::mapview(zcol = list("length_ft", "node_below_culvert"))
# #480 ft, 2455-1969=486ft drop, so actually the >100% estimate is not off...
# #and some individual point-to-points are well over that
# m <- filter(lines_3dhp, UniqueID==69444) |> pull(SHAPE) |> st_coordinates()
# slopes::slope_matrix_weighted(m, lonlat = F)
# slopes::slope_matrix(m, lonlat = F)
# (p <- filter(lines_3dhp, UniqueID==69444) |> pull(SHAPE) |> st_cast("POINT") |> st_as_sf() |> rename(g = x) |>
# mutate(
# g2 = lead(g),
# grnd_dist = st_distance(g, g2, by_element = T),
# e1 = st_coordinates(g)[,"Z"],
# e2 = st_coordinates(g2)[,"Z"],
# elev_drop = e1 - e2,
# slp = elev_drop / grnd_dist
# ))
# #ignoring routedness 'strands' some lower gradient components
# #and mostly trims leaf nodes with NA 'in_slope_max'
# x <- sfn |>
# tidygraph::activate("nodes") |>
# filter(in_slope_max > slope_threshold)
#
# list(
# trim = as_tibble(x, "edges") |> st_zm(),
# full = as_tibble(sfn, "edges") |> st_zm()
# ) |> mapview::mapview(color = c("orange","blue"))
#
# #cleaner to filter out edges then just reduce to the component that includes root?
# y <- sfn |>
# tidygraph::activate("edges") |>