-
Notifications
You must be signed in to change notification settings - Fork 1
/
Appendix B - source code.qmd
2146 lines (1878 loc) · 87.4 KB
/
Appendix B - source code.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: Making use of spatially biased variables in ecosystem condition accounting – a GIS based workflow
author:
- name: Anders Lorentzen Kolstad
email: anders.kolstad@nina.no
orchid: https://orcid.org/0000-0002-9623-9491
affiliations:
- id: nina
name: Norwegian Institute for Nature Research
department: Department of Terrestrial Ecology
address: Pb 5685 Torgarden
city: Trondheim
postal-code: 7485
attributes:
corresponding: true
- name: Matthew Grainger
email: matthew.grainger@nina.no
orchid: https://orcid.org/0000-0001-8426-6495
affiliations:
- ref: nina
- name: Marianne Evju
email: marianne.evju@nina.no
orchid: https://orcid.org/0000-0001-7338-5376
affiliations:
- id: nina2
name: Norwegian Institute for Nature Research
department: NINA Oslo
address: Sognsveien 68
city: Oslo
postal-code: NO-0855
abstract: |
Ecosystem Condition Accounts (ECA) should reflect the integrity or quality of all nature inside the scope of the account, and therefore rely on spatially representative indicators for condition. All ECAs are subject to data constraints in some way. Therefore, being able to make use of spatially biased data sets would be very valuable. For national ECAs, modelling approaches can in some cases be used to control for sampling biases. For local ECAs however, like at the scale of individual municipalities of development projects, this is often not an option as it involves spatial extrapolation using data from outside the ecosystem accounting area. In this study we develop three ecosystem condition indicators from the same spatially biased data set based on nature type mapping of Norwegian mires. The indicators are Alien species, Trenching and Anthropogenic Disturbance to Soil and Vegetation. We test our approach in three municipalities in south Norway. We discretised a spatial variable representing infrastructure prevalence, and we refer to this new map as Homogeneous Impact Areas (HIAs). To facilitate reliable estimation of indicator uncertainties, even in cases with very low sample sizes, we use a Bayesian updating method and produce probability distributions for the area-weighted mean indicator values in each HIA separately. Then we use area-weighted resampling and produce indicator probability distributions for each municipality. With this Bayesian updating and resampling approach, small sample sizes can be compensated by correspondingly large uncertainty ranges, as long as the full dataset is large enough to estimate the true population standard deviation. This paper demonstrates the use of a GIS-based workflow to control for some of the most problematic biases in an opportunistic field survey so that the data can be used for indicators in ECAs. The workflow can be used at any scale, including national scale. Because indicator values are calculated for unique spatial strata, local governments or others can target their data acquisition towards strata with low sample sizes, and thus achieve higher cost effectiveness and ultimately better spatial indicator coverage.
keywords:
- alien species
- disturbance
- ecosystem accounting
- ecosystem condition
- horizontal aggregation
- indicator
- mire
- peatlands
- SEEA EA
- wetlands
date: last-modified
bibliography: bibliography.bib
format:
elsevier-pdf:
keep-tex: true
journal:
name: EcoEvoRxiv
formatting: preprint
model: 3p
cite-style: authoryear
include-in-header:
text: '\usepackage{lineno}\linenumbers'
editor:
markdown:
wrap: sentence
execute:
echo: false
include: false
eval: false
warning: false
message: false
header-includes:
- |
\usepackage{pdflscape}
\newcommand{\blandscape}{\begin{landscape}}
\newcommand{\elandscape}{\end{landscape}}
---
```{r setup}
#| eval: true
library(tidyverse)
library(knitr)
library(sf)
library(tmap)
library(tmaptools)
library(stars)
library(terra)
library(tidyterra)
library(ggtext)
library(cowplot)
library(units)
library(rnaturalearth)
library(rnaturalearthdata)
library(ggmagnify)
library(ggridges)
library(eaTools) #https://ninanor.github.io/eaTools/ version 0.0.0.9000
library(ggpubr)
library(kableExtra)
myCRS <- 25832
```
```{r paths}
#| eval: true
# Conditional file directory
dir <- substr(getwd(), 1, 2)
# Some directories
# Ecosystem delineation map
path_mire <- "P:/41201785_okologisk_tilstand_2022_2023/data/Myrmodell/myrmodell90pros.tif"
# infrastructure index (i.e. land use intensity index)
path_infrastructure <- ifelse(dir == "C:",
"R:/GeoSpatialData/Utility_governmentalServices/Norway_Infrastructure_Index/Original/Infrastrukturindeks_UTM33/infra_tiff.tif",
"/data/R/GeoSpatialData/Utility_governmentalServices/Norway_Infrastructure_Index/Original/Infrastrukturindeks_UTM33/infra_tiff.tif"
)
# field survey
# # downloaded from https://kartkatalog.geonorge.no/metadata/naturtyper-miljoedirektoratets-instruks/eb48dd19-03da-41e1-afd9-7ebc3079265c
path_naturetypes <- "../data/survey.gdb"
# municipality outline
path_muni <- "../data/Basisdata_0000_Norge_25833_Kommuner_FGDB.gdb"
# path to local caching folder
path_temp <- ifelse(dir == "C:",
"P:/41201785_okologisk_tilstand_2022_2023/data/cache/",
"/data/P-Prosjekter2/41201785_okologisk_tilstand_2022_2023/data/cache/"
)
```
```{r import}
#| eval: true
#| cache: true
# I already did some work to identify the relevant nature types
# summary file (https://github.com/NINAnor/ecosystemCondition/blob/main/data/naturetypes/natureType_summary.rds)
naturetypes_summary <- readRDS("../data/natureType_summary.rds")
# Survey data
# The data is too big to be stored on GitHub
# Import polygon data set
st_layers(path_naturetypes)
naturetypes <- sf::st_read(dsn = path_naturetypes, layer = "naturtyper_nin_omr")
# 142k polygons (2023)
# Impart survey coverage map
coverage <- sf::st_read(dsn = path_naturetypes, layer = "naturtyper_nin_dekning") |>
st_transform(myCRS)
# Outline of norway (coastline)
outline <- sf::read_sf("../data/outlineOfNorway_EPSG25833.shp") |>
st_transform(myCRS)
# Municipalities
# find the correct layer
st_layers(path_muni)
# read inn data and transform
muni <- sf::read_sf(path_muni, layer = "kommune") |>
st_transform(myCRS)
# Infrastructure index (read proxy)
infra <- stars::read_stars(path_infrastructure)
```
```{r terraLoad}
#| eval: true
# Mire data
# Spat rasters cannot be cached
mire_terra <- terra::rast(path_mire)
```
```{r getRelevantNTs}
#| eval: true
myVars <- c("7TK", "7SE", "PRTK", "PRSL", "7FA", "7GR-GI")
nts <- naturetypes_summary %>%
rowwise() %>%
mutate(keepers = sum(c_across(
all_of(myVars))>0, na.rm=T)) |>
filter(
keepers >0,
Ecosystem == "våtmark"
) |>
pull(Nature_type)
```
```{r natureTypeData}
#| eval: true
#| cache: true
# Clean the survey data
naturetypes <- naturetypes |>
# keep only wetlands
filter(
hovedøkosystem == "våtmark",
naturtype %in% nts,
naturtype != "Kalkrik helofyttsump"
) |>
# calculate the areas (m2) of the polygons
mutate(area = SHAPE |> st_area()) |>
# the variable codes and values are all in the same column
separate_rows(ninBeskrivelsesvariable, sep = ",") |>
separate(
col = ninBeskrivelsesvariable,
into = c("NiN_variable_code", "NiN_variable_value"),
sep = "_",
remove = F
) |>
mutate(NiN_variable_value = as.numeric(NiN_variable_value)) |>
filter(NiN_variable_code %in% myVars) |>
select(
id = identifikasjon_lokalId,
municipality = kommunenummer,
year = kartleggingsår,
mosaic = mosaikk,
quality = lokalitetskvalitet,
biodiversity = naturmangfold,
condition = tilstand,
natureType = naturtype,
variable = NiN_variable_code,
value = NiN_variable_value,
area
) |>
st_transform(myCRS) # Choosing this to match the EDM (se further down)
# 19k obs.
```
```{r}
#| eval: false
# Plot to show what the most common nature types in the data set are
naturetypes |>
as_tibble() |>
count(natureType, sort=T) |>
mutate(natureType = fct_reorder(natureType, n)) |>
ggplot(aes(x = natureType, y = n))+
geom_col()+
coord_flip()
```
```{r convertToPercent}
#| eval: true
# I now want to take the variables and normalise them before I can then combine
# them despite them being on different scales.
# I will first normalise by converting into % (not for 7GR-GI).
# Remember the ordinal categories represents frequency ranges
# The data is strongly right skewed, so simply taking the center value of each
# bin will not work:
naturetypes %>%
ggplot() +
theme_bw() +
geom_histogram(aes(x = value),
binwidth = 1
) +
facet_wrap(. ~ variable,
scales = "free"
)
# I will use the lower bound for each bin instead.
# The exception in when the variable is 1, because then the lower bound
# is 0, same as when the variable is 0.
# For these I will set manually a slightly higher value.
naturetypes <- naturetypes %>%
mutate(value = case_when(
# selecting the variables that follow the same 4 step scale
variable %in% c("7TK", "7SE", "7FA") ~
case_match(
value,
0 ~ 0,
1 ~ mean(c(0, 1 / 16)) * 100,
2 ~ 1 / 16 * 100,
3 ~ 50
), # note that it is not possible to get a value of 1
# selecting the eight step variables
variable %in% c("PRTK", "PRSL") ~
case_match(
value,
0 ~ 0,
1 ~ 1.5,
2 ~ 3,
3 ~ 6.25,
4 ~ 12.5,
5 ~ 25,
6 ~ 50,
7 ~ 75
),
.default = value
))
naturetypes %>%
filter(variable != "7GR-GI") |>
ggplot() +
theme_bw() +
geom_histogram(aes(x = value),
binwidth = 1,
color = "orange",
fill = "orange"
) +
xlab("%") +
facet_wrap(. ~ variable,
scales = "free"
)
```
```{r}
#| eval: true
# Now I make the data wide, and remove 7TK and 7SE if PRTK or PRSL are present,
# respectively
naturetypes_wide <- naturetypes |>
filter(variable %in% c("7TK", "7SE", "PRTK", "PRSL")) |>
# Column names starting with a number is problematic, so adding a prefix
mutate(variable = paste0("var_", variable)) |>
pivot_wider(
names_from = "variable",
values_from = "value",
id_cols = "id") |>
as_tibble()
head(naturetypes_wide, 10)
```
```{r}
#| eval: true
# First I will combine 7TK and PRTK, and also 7SE and PRSL.
naturetypes_wide <- naturetypes_wide %>%
mutate(
TK = if_else(
is.na(var_PRTK), var_7TK, var_PRTK
),
SE = if_else(
is.na(var_PRSL), var_7SE, var_PRSL
)
)
plot_grid(
naturetypes_wide %>%
as_tibble() |>
count(SE,
name = "sum"
) |>
ggplot(
aes(
x = factor(SE),
y = sum
)
) +
geom_bar(
stat = "identity",
fill = "grey",
colour = "black"
) +
theme_bw(base_size = 12) +
labs(
x = "7SE or PRSL score",
y = "Number of localities"
),
naturetypes_wide %>%
as_tibble() |>
count(TK,
name = "sum"
) |>
ggplot(
aes(
x = factor(TK),
y = sum
)
) +
geom_bar(
stat = "identity",
fill = "grey",
colour = "black"
) +
theme_bw(base_size = 12) +
labs(
x = "7TK or PRTK score",
y = "Number of localities"
)
)
# The NA's represents localities where just one of the two variables
# (then thinking 7SE and PRSL as the same variable)
# is recorded.
# To combine these into one metric, ADSV, I could take the
# one with the highest value (worst-rule) or the sum.
# Sum is problematic as not all locations have two values to sum together.
# But the other option is problematic since I think field workers often
# tend to split the effects over two variables is they have that option.
# And if we have 50% vehicle damage and 50% hiking damage, that is no doubt
# worst than just having 50% of either. So I will use the sum, despite its issues.
```
```{r}
#| eval: true
# Taking the sum of 7SE and 7TK (incl the PR.. variables)
naturetypes_wide <- naturetypes_wide |>
rowwise() |>
mutate(ADSV = sum(c(SE, TK), na.rm = TRUE))
naturetypes_wide %>%
as_tibble() |>
count(ADSV,
name = "sum"
) |>
ggplot(
aes(
x = ADSV,
y = sum
)
) +
geom_bar(
stat = "identity",
fill = "grey",
colour = "black"
) +
theme_bw(base_size = 12) +
labs(
x = "Summed ADVS score",
y = "Number of localities"
) +
scale_x_continuous(
labels = scales::label_number(accuracy = 1)
)
```
```{r}
#| eval: true
# Now I will copy these ADVS-values into the sf object again, keeping things in wide format
naturetypes <- naturetypes |>
pivot_wider(
names_from = "variable",
values_from = "value"
) |>
left_join(naturetypes_wide |> select(id, ADSV), by = "id") |>
select(!c("7TK", "7SE", "PRSL", "PRTK"))
head(naturetypes)
```
```{r rescale}
#| eval: true
# Now I rescale the now continuous variables using reference and threshold values
# I will use the same reference levels/values for all of Norway for ADSV and alien species:
upper <- 0
lower <- 100
threshold <- 10
# For 7GR-GI I use this
upper2 <- 1
lower2 <- 5
threshold2 <- 2.5 # = observable effect. Value 3 indicates a shift to a new type (grunntype)
scale1 <- eaTools::ea_normalise(data = naturetypes,
vector = "ADSV",
upper_reference_level = lower,
lower_reference_level = upper,
break_point = threshold,
plot=T,
reverse = T
) +
labs(x = "ADVS (converted to %)") +
ylim(0,1)
# There is no point yet making this a time series
# I will assign all the indicator value to the same time (2018-2022)
# same for 7FA
scale2 <- eaTools::ea_normalise(data = naturetypes,
vector = "7FA",
upper_reference_level = lower,
lower_reference_level = upper,
break_point = threshold,
plot=T,
reverse = T
) +
labs(x = "7FA (converted to %)",
y = "") +
ylim(0,1)
# The variables are really coarse
scale3 <- eaTools::ea_normalise(data = naturetypes,
vector = "7GR-GI",
upper_reference_level = lower2,
lower_reference_level = upper2,
break_point = threshold2,
plot=T,
reverse = T
)+
labs(x = "7GR-GI (original units)",
y = "") +
ylim(0,1)
(scaling_plot <- ggarrange(scale1,
scale2,
scale3,
ncol=3)
)
#ggsave(plot = scaling_plot,
# "../images/scaling-plot.jpg",
# width=8,
# height=5)
```
```{r}
#| eval: true
# Adding scaled indicator values to the dataset
# Same code as above, but with plot=F.
naturetypes$i_ADSV <- eaTools::ea_normalise(
data = naturetypes,
vector = "ADSV",
upper_reference_level = lower,
lower_reference_level = upper,
break_point = threshold,
reverse = T
)
naturetypes$i_alien <- eaTools::ea_normalise(
data = naturetypes,
vector = "7FA",
upper_reference_level = lower,
lower_reference_level = upper,
break_point = threshold,
reverse = T
)
naturetypes$i_ditch <- eaTools::ea_normalise(
data = naturetypes,
vector = "7GR-GI",
upper_reference_level = lower2,
lower_reference_level = upper2,
break_point = threshold2,
reverse = T
)
```
```{r getMunicipalities}
#| eval: true
# Preparing the outlines for the three municipalieties
# The data contains some multisurfaces
# table(st_geometry_type(muni))
# Here is a function to make sure that multipolygons are returned
ensure_multipolygons <- function(X) {
tmp1 <- tempfile(fileext = ".gpkg")
tmp2 <- tempfile(fileext = ".gpkg")
st_write(X, tmp1)
gdalUtilities::ogr2ogr(tmp1, tmp2, f = "GPKG", nlt = "MULTIPOLYGON")
Y <- st_read(tmp2)
st_sf(st_drop_geometry(X), geom = st_geometry(Y))
}
muni <- ensure_multipolygons(muni)
# table(st_geometry_type(muni)) #OK
# subset of the three target municipalities
muni3 <- muni |>
filter(kommunenummer %in% c(
"3020", # Nordre Follo
"3451", # Nord-Aurdal
"3446" # Gran
)) |>
mutate(Municipality = case_when(
kommunenummer == "3020" ~ "Nordre Follo",
kommunenummer == "3451" ~ "Nord-Aurdal",
kommunenummer == "3446" ~ "Gran"
))
# To crop EDM, I need the three municipalities seprately.
nf <- muni3 |>
filter(kommunenummer == "3020")
na <- muni3 |>
filter(kommunenummer == "3451")
gr <- muni3 |>
filter(kommunenummer == "3446")
```
```{r prepPolygons}
#| eval: true
# I need to intersect the naturetypes data with the municipalities
nature3 <- naturetypes |>
st_intersection(muni3)
nature3 |>
as_tibble() |>
count(municipality,
sort = TRUE,
name = "Number of polygons")
# There where some polygons that spanned municipal borders.
# It's not a problem
# and also to get the data coverage polygon.
coverage3 <- coverage |>
st_intersection(muni3)
```
```{r prepSomeMoreMunicipalityShapes}
#| eval: true
# Simplified coastline / terrestrial area
terrestrial <- outline |>
st_intersection(muni3)
# Polygons for the oceans in each municipality
ocean <- muni3 |>
st_difference(outline)
# calculate stats - terrestrial area
terrestrial <- terrestrial |>
mutate(
area_t = geometry |> st_area(),
t_area_km =
round(units::drop_units(area_t * 1e-6))
)
```
```{r positionMap}
#| eval: true
# Make map to show where the three municipalities are
world <- ne_countries(scale = "medium", returnclass = "sf") |>
st_transform(myCRS) |>
filter(admin %in% c("Norway", "Sweden")) |>
st_make_valid()
# get centroids
centroids <- muni3 |>
st_centroid()
inc <- 200000
myBbox <- st_bbox(centroids)
myBbox[1:2] <- myBbox[1:2]-inc
myBbox[3:4] <- myBbox[3:4]+inc
(positionMap <-
tm_shape(world,
bbox = myBbox) +
tm_polygons() +
tm_shape(muni3) +
tm_polygons(col = "green") +
tm_shape(centroids) +
tm_text(
text = "Municipality",
just= "left",
size = .8,
xmod = 1,
ymod = 0
) +
tm_grid(projection = 4326) +
tm_layout(
bg.color = "skyblue",
outer.margins = c(0.01, .02, .02, .02))+
tm_compass()+
tm_scale_bar()
)
tmap_save(tm = positionMap,
"../images/positionMap.jpg")
```
```{r distanceBetweenMunis}
#| eval: true
# what is the distance between Nordre Follo and Nord-Aurdal
(km_distance <- centroids |>
st_distance() |>
max() |>
set_units("km") |>
drop_units() |>
round())
```
```{r mireTerra}
#| eval: false
# I first tried to import and crop the mire data using stars,
# but that failed (see pre 21 feb 2023).
# Trying { terra } instead
# convert municipal outline to vect via st
nf_vect <- as(nf, "Spatial") |>
terra::vect()
gr_vect <- as(gr, "Spatial") |>
terra::vect()
na_vect <- as(na, "Spatial") |>
terra::vect()
# crop and mask (very fast!)
mire_terra_nf <- mire_terra |>
terra::crop(nf_vect) |>
terra::mask(nf_vect)
mire_terra_gr <- mire_terra |>
terra::crop(gr_vect) |>
terra::mask(gr_vect)
mire_terra_na <- mire_terra |>
terra::crop(na_vect) |>
terra::mask(na_vect)
# Plot to check overlap
# ggplot()+
# geom_spatraster(data = mire_nf_terra)+
# geom_spatvector(data = nf_vect,
# fill = NA)
# The cropping and masking worked.
# # I like the stars, sf and tmap combo better, so I return to stars
mire_stars_nf <- mire_terra_nf |>
st_as_stars()
mire_stars_gr <- mire_terra_gr |>
st_as_stars()
mire_stars_na <- mire_terra_na |>
st_as_stars()
par(mfrow=c(3,1))
plot(mire_stars_nf)
plot(mire_stars_gr)
plot(mire_stars_na)
saveRDS(mire_stars_nf, "manual_cache/mire_stars_nf.RDS")
saveRDS(mire_stars_gr, "manual_cache/mire_stars_gr.RDS")
saveRDS(mire_stars_na, "manual_cache/mire_stars_na.RDS")
```
```{r terraToSTars}
#| eval: true
mire_stars_nf <- readRDS("manual_cache/mire_stars_nf.RDS")
mire_stars_gr <- readRDS("manual_cache/mire_stars_gr.RDS")
mire_stars_na <- readRDS("manual_cache/mire_stars_na.RDS")
mire_terra_nf <- rast(mire_stars_nf)
mire_terra_gr <- rast(mire_stars_gr)
mire_terra_na <- rast(mire_stars_na)
```
```{r dk2-CoverageMaps}
#| eval: true
#| cache: true
# calculate area of survey coverage maps
# values goes into summary table in the ms
dk2 <- coverage3 |>
group_by(Municipality) |>
summarise(SHAPE = st_union(SHAPE)) |>
mutate(
dk_area_km = SHAPE |> st_area(),
dk_area_km = round(units::drop_units(dk_area_km * 1e-6))
)
```
```{r mireArea}
#| eval: true
#| cache: true
# calculate area of the mires in each municipality
# -- Nordre Follo
(mireArea <- mire_terra_nf |>
global(c("mean", "sum"), na.rm = T) |>
add_column("Municipality" = "Nordre Follo") |>
mutate(
mirePercent = round(mean * 100, 1),
mire_km2 = sum / 1e+4
))
# -- Gran
mireArea2 <- mire_terra_gr |>
global(c("mean", "sum"), na.rm = T) |>
add_column("Municipality" = "Gran") |>
mutate(
mirePercent = round(mean * 100, 1),
mire_km2 = sum / 1e+4
)
# -- Nord-Aurdal
mireArea3 <- mire_terra_na |>
global(c("mean", "sum"), na.rm = T) |>
add_column("Municipality" = "Nord-Aurdal") |>
mutate(
mirePercent = round(mean * 100, 1),
mire_km2 = sum / 1e+4
)
mireArea <- mireArea |>
rbind(mireArea2, mireArea3)
# Calculate the area of mire inside the coverage maps
# -- Nordre Follo
mire_in_dk <- mire_terra_nf |>
terra::mask(dk2 |> filter(Municipality == "Nordre Follo")) |>
global("sum", na.rm = T) |>
mutate(mireInSurvey_km2 = sum / 1e+4) |>
add_column(Municipality = "Nordre Follo")
mire_in_dk2 <- mire_terra_gr |>
terra::mask(dk2 |> filter(Municipality == "Gran")) |>
global("sum", na.rm = T) |>
mutate(mireInSurvey_km2 = sum / 1e+4) |>
add_column(Municipality = "Gran")
mire_in_dk3 <- mire_terra_na |>
terra::mask(dk2 |> filter(Municipality == "Nord-Aurdal")) |>
global("sum", na.rm = T) |>
mutate(mireInSurvey_km2 = sum / 1e+4) |>
add_column(Municipality = "Nord-Aurdal")
mire_in_dk <- mire_in_dk |>
rbind(mire_in_dk2, mire_in_dk3)
```
```{r infrastructureIndex}
#| eval: false
# this data is on a 100x100m grid
infra <- infra |>
# , which is more then we need - warp it to 1x1km
st_warp(
cellsize = c(1000, 1000),
crs = st_crs(nf),
use_gdal = TRUE,
method = "average"
) |>
setNames("infrastructureIndex") |>
st_transform(myCRS) |>
mutate(infrastructureIndex = case_when(
infrastructureIndex < 1 ~ 0,
infrastructureIndex < 6 ~ 1,
infrastructureIndex < 12 ~ 2,
infrastructureIndex >= 12 ~ 3
)) |>
# taking away point in the sea
st_crop(outline)
# This step might seem rather stupid. We want to vectorize a rather large
# raster. This makes it a quite big data object. The reason is that there is no
# really good way to burn polygon data on to raster grid cells after the disuse
# of the raster package. It was not straight forward then either. But
# calculating intersections between polygons is very fast and easy.
infra <- eaTools::ea_homogeneous_area(infra,
groups = infrastructureIndex
)
saveRDS(infra, paste0(path_temp, "infrastructureIndex_discrete_vectorized.rds"))
```
```{r InfraStructureIndex}
#| eval: true
# read cached vetorized infrastructure data
infra <- readRDS(paste0(path_temp, "infrastructureIndex_discrete_vectorized.rds"))
```
```{r}
#| eval: true
# Calculate area
infra <- infra |>
mutate(
area = geometry |> st_area(),
area_km = area |> set_units("km2")
)
# show the summered area per HIA
infra |>
as_tibble() |>
group_by(infrastructureIndex) |>
summarise(area_km = sum(area_km)) |>
ggplot(aes(
x = infrastructureIndex,
y = area_km
)) +
geom_col()
# intersect with the three municipalities
# and calculate area
infraMuni3 <- infra |>
st_intersection(muni3) |>
mutate(area = geometry |> st_area())
# Turn m2 into km2
# and sum the total area per HIA
(infraMuni3_tbl <- infraMuni3 |>
as.data.frame() |>
mutate(area_HIA_km2 = units::drop_units(area) * 1e-6) |>
group_by(Municipality, infrastructureIndex) |>
summarise(total_area_HIAs_km2 = round(sum(area_HIA_km2))))
# Calculate the area weighted mean HIA value per municipality
infraMuni3_summary <- infraMuni3_tbl |>
group_by(Municipality) |>
summarise(
meanHIA =
round(
weighted.mean(
infrastructureIndex, total_area_HIAs_km2
), 2
)
)
# Make a plot to check that it has worked
(infra_dist_plot <- infraMuni3_tbl |>
ggplot() +
geom_bar(
aes(
x = infrastructureIndex,
y = total_area_HIAs_km2,
fill = factor(infrastructureIndex),
colour = factor(infrastructureIndex)
),
stat = "identity",
lwd = 1.2
) +
scale_fill_manual(values = RColorBrewer::brewer.pal(4, "YlOrBr")) +
scale_color_manual(values = RColorBrewer::brewer.pal(5, "YlOrBr")[-1]) +
theme_minimal_hgrid() +
labs(
x = "Homogeneous Impact Areas",
y = "Area (km<sup>2</sup>)"
) +
theme(
axis.title.x = element_textbox_simple(
width = NULL,
padding = margin(4, 4, 4, 4),
margin = margin(4, 0, 0, 0),
linetype = 1,
r = grid::unit(8, "pt"),
fill = "azure1"
),
axis.title.y = element_textbox_simple(
width = NULL,
padding = margin(4, 4, 4, 4),
margin = margin(4, 0, 0, 0),
linetype = 1,
orientation = "left-rotated",
r = grid::unit(8, "pt"),
fill = "azure1"
),
strip.background = element_blank(),
strip.text = element_textbox(
size = 12,
color = "white", fill = "#5D729D", box.color = "#4A618C",
halign = 0.5, linetype = 1, r = unit(5, "pt"), width = unit(1, "npc"),
padding = margin(2, 0, 1, 0), margin = margin(3, 3, 3, 3)
)
) +
guides(fill = "none", colour = "none") +
#scale_y_log10() +
facet_grid(cols = vars(Municipality))
)
#ggsave(plot = infra_dist_plot,
# "../images/infra-dist-plot.jpg")
```
```{r corrCheck}
#| eval: true
#| cache: true
# Now I want to see if the indicator values depend on the HIA is a predictable
# way to justify the stratification
corrCheck <- st_intersection(naturetypes, infra)
```
```{r HIA-validate}
#| eval: false
# A first look
corrCheck |>
mutate(
i_ADSV_fct = floor(round(i_ADSV * 10, 2)) / 10,
i_alien_fct = floor(round(i_alien * 10, 2)) / 10,
i_ditch_fct = floor(round(i_ditch * 10, 2)) / 10
) |>
pivot_longer(
cols = c(i_ADSV_fct, i_alien_fct, i_ditch_fct),
values_to = "indicatorValue",
names_to = "indicator",
values_drop_na = T
) |>
ggplot(aes(
x = factor(infrastructureIndex),
fill = factor(indicatorValue)
)) +
geom_bar(
position = "fill"
) +
theme_bw(base_size = 12) +
guides(fill = guide_legend("Scaled indicator values")) +
ylab("Fraction of data points") +
xlab("HIA") +
scale_fill_brewer(palette = "RdYlGn") +
facet_grid(indicator ~ year)
# After this I also tried chaning the color gradient,