-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path5.PedogenonModelingForeach_NoVegetation.R
2595 lines (1986 loc) · 105 KB
/
5.PedogenonModelingForeach_NoVegetation.R
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
#############################################################################################################################################
### Method for optimizing pedogenon classes as soil districts for the Basque Country
### in the context of the European soil Monitoring Law
### In this script: Modeling and optimization the number of clusters and covariate selection
### EXCLUDING POTENTIAL VEGETATION
### Desired extent: Basque Country
### Resolution: 25m
### CRS: EPSG=25830
### Author: Mercedes Roman Dobarco
### Date: 30/04/2024
####### Load packages
### Spatial
library(sf)
library(terra)
library(gdalUtilities)
library(XML)
library(reproducible)
### Visualization
library(lattice)
library(ggplot2)
library(viridis) # color palettes
library(scales)
library(rasterVis)
library(gridExtra)
library(rasterVis)
library(RColorBrewer)
library(tmap) # for static and interactive maps
library(leaflet) # for interactive maps
library(mapview) # for interactive maps
library(shiny) # for web applications
###Data carpentry
library(dplyr)
library(tidyverse)
library(Hmisc)
library(corrplot)
### Parallel computing
library(foreach)
library(parallel)
library(doParallel)
### clustering
#install.packages("remotes")
#remotes::install_github("andrewthomasjones/tkmeans")
library(ClusterR)
library(clusterSim)
### Steps in pedogenon mapping:
### Load the helper functions
source("C:/Users/mercedes.roman/Desktop/SELVANS/WP1/R_scripts/Euskadi/5.PedogenonModeling_helper.R")
# ### 1. Tentative number of pedogenons -----------------------------------
### 1. Tentative number of pedogenons determined by:
### 1.a combination of soil order, environmental zone (1), geology and major vegetation group.
### 1.b number of soil map units from traditional soil map.
### 1.c Guo et al (2003) equations applied to the Basque Country
### 1.d Minimum number of observations per pedogenon class required for validation (~10)
### something between 2 to 140 classes
search_space <- c(2:50)
# ### 2. Selection of SCORPAN variables --------------------------------------
### Number of variables per soil-forming factor:
### Soil variables: clay/silt, clay/sand, silt/sand, CEC - between 2-3
### the spatial patterns of the SoilGrids mapsdiffered considerably from the
### texture maps elaborated by the Basque Government in 2019, at a smaller resolution and produced
### with a regional dataset.
### The particle size fractions and SOC stock maps for the 0-30 cm depth interval were produced with
### around 12,000 observationsand covariates of parent material, land use, climate, and relief, following
### a digital soil mapping approach and scorpan modeling.
### (https://www.euskadi.eus/mapa-de-existencias-de-carbono-y-mapa-de-textura-para-los-suelos-de-la-capv/web01-a2inglur/es/)
### Climate = 5 variables selected from correlation plots
### and variable importance for predicting soil properties
setwd("C:/Users/mercedes.roman/Desktop/SELVANS/WP1/R_output/4.CovariateSelection/scaled/")
clim.vars <- c("clim_bio1.tif","clim_bio4.tif","clim_bio5.tif","clim_bio12.tif","clim_bio15.tif")
clim.r <- rast(clim.vars)
plot(clim.r)
### Relief: between 5 to 10 - These will be selected with iterations
setwd("C:/Users/mercedes.roman/Desktop/SELVANS/WP1/R_output/4.CovariateSelection/scaled/")
relief.fixed <- c("relief_dem.tif")
#dem <- rast(relief.fixed)
### Variables that logically limit soil CAPACITY for performing functions
### and their resilience to disturbance:
relief.potential <-list.files(pattern="relief")
relief.potential <- c("relief_slope.tif","relief_slope_5.tif","relief_slope_10.tif", # slope
"relief_northerness.tif","relief_easterness.tif", ### aspect
"relief_north_slope.tif", ### aspect x slope. This variable is correlated with northness so we may want to keep one of both
"relief_twi.tif","relief_mrrtf.tif","relief_mrvbf.tif", # my preferred is TWI
"relief_valley_depth.tif","relief_st_height.tif", # Preferred hydrological variables
"relief_mid_slope.tif","relief_norm_height.tif","relief_slope_height.tif", ### Other hydrological variables
"relief_p_curv.tif", "relief_pr_curv_5.tif", "relief_pr_curv_10.tif", # profile curvature (3,5,10)
"relief_pl_curv_5.tif", "relief_pl_curv_10.tif", # planar curvature (5,10)
"relief_lg_curv_5.tif", "relief_lg_curv_10.tif", # longitudinal curvature (5,10)
"relief_t_curv.tif", "relief_cs_curv_5.tif", "relief_cs_curv_10.tif", # tangential curvature (3) cross-sectional curvature (5,10) (same)
"relief_tpi_8_3.tif") ## I eliminate "relief_tpi_20_5.tif",
relief.r <- rast(c(relief.fixed,relief.potential))
names(relief.r) <- paste0("r_",names(relief.r))
### Vegetation: 4 or 5 PCs of MVG PCA scores (54-66 % variance)
# setwd("C:/Covariates/Euskadi/Organisms/")
# vegetation.vars <- c("MVG_PC1.tif","MVG_PC2.tif","MVG_PC3.tif","MVG_PC4.tif","MVG_PC5.tif")
# vegetation.r <- rast(vegetation.vars)
# names(vegetation.r) <- paste0("o_",names(vegetation.r))
### Parent material: 8 or 50 % of variance
setwd("C:/Users/mercedes.roman/Desktop/SELVANS/WP1/R_output/1.CovariatesEus/")
parentmaterial.vars <- c("pm_mca_1.tif","pm_mca_2.tif","pm_mca_3.tif",
"pm_mca_4.tif","pm_mca_5.tif","pm_mca_6.tif",
"pm_mca_7.tif","pm_mca_8.tif")
parentmaterial.r <- rast(parentmaterial.vars)
### All variables
scorpan <- c(clim.r, relief.r, parentmaterial.r)
### 2.a Take sample
### Regular sample
set.seed(2233)
scorpanSample <- terra::spatSample(x = scorpan,
size=50000,
method="regular",
as.df=TRUE,
xy=TRUE)
### Only complete cases
scorpanSample <- scorpanSample[complete.cases(scorpanSample),]
dim(scorpanSample)
coords.scorpanSample <- scorpanSample[,1:2] ### Keep coordinates separately
# ### 2.b Extract covariates at soil observations -------------------------
### 2.b Extract covariates at soil observations, that will be also used to
### Table with soil data and covariates, with same names as in the dataframe used for clustering
### Load the soil datasets
load("C:/Users/mercedes.roman/Desktop/SELVANS/WP1/R_output/1.SoilDatasets/SoilDataInputPedM.RData")
### I keep Soil.df.harmonised and Soil.df.harmonised_sf - splined data
### soil_datasets_3 (before splines and with correct coordinates for BASONET) is also an option
### Think if I want to use newID or just myID - all years? just 2021?
### Same for LUCAS - subset one year?
### Transform soil_datasets_3 to spatial, extracting only BASONET data for either
### for 2001 (but coordinates may not be entirely correct)
### or 2021 (coordinates are correct but I don´t know if I put the texture data too)
BASONET.soil <- soil_datasets_3[soil_datasets_3$Dataset== "BASONET",]
BASONET.soil.sf <-st_as_sf(BASONET.soil, coords = c("UTM_X","UTM_Y"), crs = 25830)
#BASONET.soil.WGS84 <- st_transform(BASONET.soil.sf, 4326)
### Extract
soil.covariates <- terra::extract(x=scorpan, y=Soil.df.harmonised_sf, method="simple")
BASONET.covariates <- terra::extract(x=scorpan, y=BASONET.soil.sf, method="simple")
### Bind to the soil data
Soil.df.harmonised.scorpan <- cbind(Soil.df.harmonised,soil.covariates)
BASONET.scorpan <- cbind(BASONET.soil,BASONET.covariates)
summary(Soil.df.harmonised.scorpan)
summary(BASONET.scorpan)
### We can work with these two dataframes:
### Soil.df.harmonised.scorpan Splined dataframe, all datasets
### BASONET.scorpan Basonet dataframe, before splines (0-20 cm and 20-40 cm)
### Should we consider all years from BASONET and LUCAS?
### TEXTURE from 2009 for LUCAS
unique(Soil.df.harmonised.scorpan[Soil.df.harmonised.scorpan$Dataset =="LUCAS" & !is.na(Soil.df.harmonised.scorpan$Silt),]$Date)
### For BASONET, let´s use 2021 in terms of coordinates, they are more accurate
unique(BASONET.scorpan[!is.na(BASONET.scorpan$Silt),]$Date)
### Texture has been duplicated in 2021, no problem
### I exclude BASONET 2001 from both datasets to eliminate duplicity for texture on Pedogenon centroids
Soil.df.harmonised.scorpan <- Soil.df.harmonised.scorpan[!(Soil.df.harmonised.scorpan$Dataset == "BASONET" &
Soil.df.harmonised.scorpan$Date == 2001),]
BASONET.scorpan <- BASONET.scorpan[BASONET.scorpan$Date != 2001,]
### With LUCAS there is no problem because TEXTURE is only available for 2009
### Eliminate rows without covariates
Soil.df.harmonised.scorpan <- Soil.df.harmonised.scorpan[complete.cases(Soil.df.harmonised.scorpan[,colnames(soil.covariates)]),]
BASONET.scorpan <- BASONET.scorpan[complete.cases(BASONET.scorpan[,colnames(soil.covariates)]),]
### Which climate variables are correlated?
par(mfrow=c(1,1))
library(Hmisc)
library(corrplot)
Soil.df.harmonised.scorpan[,c("Sand","Silt","Clay","pH","TOC")] %>%
cor(., use = "pairwise.complete.obs") %>%
corrplot.mixed(.,upper = "ellipse",
lower = "number",
number.cex=0.7, tl.cex=0.6, tl.col = "black")
BASONET.scorpan[,c("Sand","Silt","Clay","CECef",
"TOC","Carbonates","pH","EC",
"TN_ppm","P_ppm","K_ppm",
"Ca_ppm","Mg_ppm","Na_ppm")] %>%
cor(., use = "pairwise.complete.obs") %>%
corrplot.mixed(.,upper = "ellipse",
order = 'hclust',
lower = "number",
number.cex=0.7,
tl.cex=0.6,
tl.col = "black")
### Do not use P_ppm, Na_ppm, Mg_ppm because there are a lot of missing observations
### I use CECef and exclude Ca_ppm because they are highly correlated
### I use TOC and exclude TN_ppm because they are correlated
### Then I use Silt, Clay, pH, CECef, EC, TOC.
# ### 2.c Create all combinations of relief covariates --------------------
### 2.c Create all combinations of relief covariates
### Taking n=5, ... n =10
### function combn from package utils
library(utils)
relief.potential <- names(relief.r)[-1] ### Take out DEM, which will be fixed
### My choice, "expernt knowledge" or just my personal preference
relief.preferred <- c("r_slope","r_northerness","r_easterness","r_north_slope",
"r_twi","r_valley_depth","r_st_height")
# ### Split by 3,5,10 window
# relief.potential.3 <- c("r_slope",
# "r_northerness","r_easterness","r_north_slope",
# "r_twi","r_mrrtf","r_mrvbf",
# "r_valley_depth","r_st_height","r_mid_slope",
# "r_norm_height","r_slope_height",
# "r_p_curv","r_t_curv","r_tpi_8_3")
#
# relief.potential.5 <- c("r_slope_5",
# "r_northerness","r_easterness","r_north_slope",
# "r_twi","r_mrrtf","r_mrvbf",
# "r_valley_depth","r_st_height","r_mid_slope",
# "r_norm_height","r_slope_height",
# "r_pr_curv_5","r_pl_curv_5","r_lg_curv_5","r_cs_curv_5",
# "r_tpi_8_3")
#
# relief.potential.10 <- c("r_slope_10",
# "r_northerness","r_easterness","r_north_slope",
# "r_twi","r_mrrtf","r_mrvbf",
# "r_valley_depth","r_st_height","r_mid_slope",
# "r_norm_height","r_slope_height",
# "r_pr_curv_10","r_pl_curv_10","r_lg_curv_10","r_cs_curv_10",
# "r_tpi_8_3")
### n=4
### I start from my subset of preferred variables
combn.4.relief <- utils::combn(x=relief.preferred, m = 4)
### this gives 35 combinations
combn.4.relief <- t(combn.4.relief)
### eliminate those where "r_north_slope" and "r_northerness" are together
subv <- c("r_northerness","r_north_slope")
conds <- apply(X = combn.4.relief, MARGIN = 1, FUN = function(x){sum(subv %in% x)!=2})
combn.4.relief <- combn.4.relief[conds,]
### This reduces that to 25 possible combinations
combn.4.relief <- cbind(combn.4.relief, matrix(data=NA, nrow=nrow(combn.4.relief), ncol = 2))
combn.5.relief <- utils::combn(x=relief.preferred, m = 5)
### this gives 21 combinations
combn.5.relief <- t(combn.5.relief)
### eliminate those where "r_north_slope" and "r_northerness" are together
subv <- c("r_northerness","r_north_slope")
conds <- apply(X = combn.5.relief, MARGIN = 1, FUN = function(x){sum(subv %in% x)!=2})
combn.5.relief <- combn.5.relief[conds,]
combn.5.relief <- cbind(combn.5.relief, matrix(data=NA, nrow=nrow(combn.5.relief), ncol = 1))
combn.6.relief <- utils::combn(x=relief.preferred, m = 6)
### this gives 21 combinations
combn.6.relief <- t(combn.6.relief)
### eliminate those where "r_north_slope" and "r_northerness" are together
subv <- c("r_northerness","r_north_slope")
conds <- apply(X = combn.6.relief, MARGIN = 1, FUN = function(x){sum(subv %in% x)!=2})
combn.6.relief <- combn.6.relief[conds,]
### bind matrices
relief.combi <- rbind(combn.4.relief,combn.5.relief,combn.6.relief)
### (expand later with more possible combinations of curvatures, etc.)
### Collapse to vector
relief.combi.v <- apply(X = relief.combi, MARGIN = 1, FUN = function(x){paste(x,collapse=",")})
### Keep the combination in a cata.frame with a code
relief.combi.df <- data.frame (ID = 1:nrow(relief.combi), relief.combi = relief.combi.v)
### fixed variables ### I eliminate vegetation
fixed.columns <- c(names(clim.r),"r_dem",names(parentmaterial.r))
### directory to store the models
OutDir <- "C:/Users/mercedes.roman/Desktop/SELVANS/WP1/R_output/5.PedogenonModelingNoVegetation/"
### Delete temporal files
tmpFiles(current = FALSE,orphan = TRUE,old = TRUE,remove = TRUE)
# ### 3. For each combination of relief covariates: -----------------------
### some did not finished running...
#relief.combi <- relief.combi[c(27:38),]
### 3. For each combination of relief covariates:
kquality_combi_list <- list() ### List with the dataframes of internal quality and soil-profile derived indices
#icq_df_combi_list <- list() ### this list will store the internal clustering quality indices
### for each combination of environmental covariates
#BASONET_df_combi_list <- list() ### this list will store the soil profile indices -
### Only BASONET 2021 data
### for each combination of environmental covariates
#SoilHarmonised_df_combi_list <- list() ### this list will store the soil profile indices
### All datasets
### for each combination of environmental covariates
#cluster_assignment_combi_list <- list() ### this list will store the dataframe for combination j,
### with all the cluster assignments from the search space
### List to store the dataframes with BASONET and HARMONISED soil datasets cluster assignments for different j combinations
BASONET.dfs <- list()
HARMONISED.dfs <- list()
### Create a for loop to test the different metrics with different soil datasets
#j <- 5
for(j in 1:nrow(relief.combi)) {
setwd(OutDir)
dir.create(paste0("scorpan_combi_",j))
}
#
# cl <- makePSOCKcluster(20) # I defined cl by this commend
# registerDoParallel(cl)
# clusterExport(cl, varlist = c("terra","ClusterR", "clusterSim","lowmemtkmeans", "tidyverse","dplyr"))
# clusterEvalQ(cl, .libPaths("~/C:/Users/mercedes.roman/AppData/Local/R/win-library/4.3")) # pass libpath
# clusterEvalQ(cl, library(ClusterR)) # pass My package which includes Rcpp functions
# stopCluster(cl)
# print("FinishCL")# for testing that cl works
library(doParallel)
library(foreach)
tic <- Sys.time()
detectCores()
cl <- makeCluster(20) ###
registerDoParallel(cl)
getDoParWorkers()
kquality_scorpan_combis <- foreach(j = 1:nrow(relief.combi),
.packages=c("terra","ClusterR", "clusterSim","lowmemtkmeans", "tidyverse","dplyr"),
.export = c("OutDir", "fixed.columns","relief.combi",
"relief.combi.df", "relief.combi.v",
"scorpanSample", "BASONET.scorpan", "search_space",
"Soil.df.harmonised.scorpan","Dintra.function", "Dinter.function")) %dopar% {
#for(j in 1:nrow(relief.combi)) {
# ### a. SCORPAN sample, input for clustering for this combination --------
### a. SCORPAN sample, input for clustering for this combination of covariates
setwd(paste0(OutDir,"scorpan_combi_",j,"/"))
print(paste0("Working on scorpan combination ",j))
### Subset variables in scorpan dataset
#fixed.columns <- c(names(clim.r), names(vegetation.r), "r_dem", names(parentmaterial.r))
var.columns <- c(t(relief.combi)[,j])
var.columns <- var.columns[!is.na(var.columns)] ### eliminate NA if any
### scorpan dataframe for the combination j
scorpanSample.j <- scorpanSample[,c(fixed.columns,var.columns)]
### a.1 Perform Cholesky transformation to decorrelate the data
# The basic Euclidean distance treats each variable as equally important in calculating the distance.
# An alternative approach is to scale the contribution of individual variables to the distance value according
# to the variability of each variable. This approach is illustrated by the Mahalanobis distance,
# which is a measure of the distance between each observation in a multidimensional cloud of points and
# the centroid of the cloud.
### Calculate the Mahalanobis distance, as Euclidean distance after applying the Cholesky decomposition
# # Rescale the data
C.j <- chol(var(as.matrix(scorpanSample.j)))
scorpanSample.j.rs <- as.matrix(scorpanSample.j) %*% solve(C.j)
### Output of transformation of the sampled scorpan dataset for variable combination j: scorpanSample.j.rs
# scorpanSample.j.rs
### Variance-Covariance matrix of the scorpan dataset for variable combination j: C.j
# C.j
### I may be better working with arrays (ncombiJ x nIndices x search_space_K).
### Dataframe to store the results of the clustering - internal quality indices
### These will be the results for this variable combination
out.clustering.indices <- as.data.frame(matrix(data=NA, ncol=length(search_space)+1, nrow= 5))
colnames(out.clustering.indices) <- c("Index", paste0("K.",search_space))
#out.clustering.indices$Index <- c("Total SSE", "Sum WCSE","BetweenSS to TotalSS","Calinski-Harbasz","Silhouette","BIC")
out.clustering.indices$Index <- c("Total SSE", "Sum WCSE","BetweenSS to TotalSS","Calinski-Harbasz","BIC")
# ### b. JUST BASONET - 430 sites ---------------------------------------
### b. JUST BASONET - 430 sites
### N = 430 soil profiles with 1 or 2 horizons
### copy the soil dataframe
BASONET.scorpan.j <- as.data.frame(BASONET.scorpan)
### Columns to store cluster assignment
kassignments <- as.data.frame(matrix(data=NA,
nrow=nrow(BASONET.scorpan.j),
ncol = length(search_space)))
colnames(kassignments) <- paste0("K.",search_space)
knames <- paste0("K.",search_space)
BASONET.scorpan.j <- cbind(BASONET.scorpan.j, kassignments)
rm(kassignments)
### Now decorrelate the SCORPAN variables at the locations of the soil observations
### scorpan variables corresponding to combination j
B.scorpan.j <- BASONET.scorpan.j[,c(fixed.columns,var.columns)]
### Rescale the data
B.scorpan.j.rs <- as.matrix(B.scorpan.j) %*% solve(C.j)
### Dataframe to store output quality indices
### I may be better working with arrays (ncombiJ x nIndices x search_space_K).
### Dataframe to store the results of the clustering - soil data profile indicators - BASONET
### These will be the results for this variable combination
out.indices.BASONET <- as.data.frame(matrix(data=NA, ncol=length(search_space)+1, nrow= 6))
colnames(out.indices.BASONET) <- c("Index",paste0("K.",search_space))
out.indices.BASONET$Index <- c("B_N_PdGn_sites", # Number of pedogenons with any soil observation
"B_Perc_PdGn_sites", ## What percentage of the number of classes do have observations?
"B_Min_sites", # Min number of observations per pedogenon (of those with any)
"B_Median_sites", # Median number of observations per pedogenon (of those with any)
"B_Max_sites", # Min number of observations per pedogenon (of those with any)
"B_Din_Dex" # Ratio of SOIL PROFILE intra cluster distance to between cluster distance
### Din is average distance from each observation to the centroid of the cluster
### Dex is the average distance between cluster centroids
)
# ### c. ALL DATASETS - -----------------------------------------------
### c. ALL DATASETS -
### copy the soil dataframe
Soil.df.harmonised.scorpan.j <- as.data.frame(Soil.df.harmonised.scorpan)
### Columns to store cluster assignment
kassignments <- as.data.frame(matrix(data=NA,
nrow=nrow(Soil.df.harmonised.scorpan.j),
ncol = length(search_space)))
colnames(kassignments) <- paste0("K.",search_space)
knames <- paste0("K.",search_space)
Soil.df.harmonised.scorpan.j <- cbind(Soil.df.harmonised.scorpan.j, kassignments)
rm(kassignments)
### Now decorrelate the SCORPAN variables at the locations of the soil observations
### scorpan variables corresponding to combination j
SH.scorpan.j <- Soil.df.harmonised.scorpan.j[,c(fixed.columns,var.columns)]
### Rescale the data
SH.scorpan.j.rs <- as.matrix(SH.scorpan.j) %*% solve(C.j)
### I may be better working with arrays (ncombiJ x nIndices x search_space_K).
### Dataframe to store the results of the clustering - soil data profile indicators -
### subset of selected properties within pedogenon: sand, silt, clay, TOC, pH, Mg, Ca, K, N
### These will be the results for this variable combination
out.indices.SoilHarmonised <- as.data.frame(matrix(data=NA, ncol=length(search_space)+1, nrow= 6))
colnames(out.indices.SoilHarmonised) <- c("Index",paste0("K.",search_space))
out.indices.SoilHarmonised$Index <- c("SH_N_PdGn_sites", # Number of pedogenons with any soil observation
"SH_Perc_PdGn_sites", ## What percentage of the number of classes do have observations?
"SH_Min_sites", # Min number of observations per pedogenon (of those with any)
"SH_Median_sites", # Median number of observations per pedogenon (of those with any)
"SH_Max_sites", # Min number of observations per pedogenon (of those with any)
"SH_Din_Dex") # Ratio of SOIL PROFILE intra cluster distance to between cluster distance
### Din is average distance from each observation to the centroid of the cluster
### Dex is the average distance between cluster centroids
setwd(paste0(OutDir,"scorpan_combi_",j,"/"))
gc()
# ### 4. for each k in the search space, search_space: ------------------
### 4. for each k in the search space, search_space:
#k <- 30
for( k in 1:length(search_space)){
print(paste0("Calculating indices for k=",search_space[[k]]))
### Note, I can repeat this step 30 or 100 times (or as many as I want)
### by changing the seed for clustering, to obtain median estimates of the clustering indices
### 4.a Run k-means clustering and calculate
set.seed(1990)
kmeans_clorpt.jk <- ClusterR::KMeans_rcpp(scorpanSample.j.rs,
clusters = search_space[[k]],
num_init = 20,
max_iters = 10000,
fuzzy = FALSE,
initializer = 'kmeans++',
verbose = F)
### 4.b total SSE, sum of within cluster SE, between-cluster SSE / total SSE
### Output from function ClusterR::KMeans_rcpp
Tot_SSE_jk <- kmeans_clorpt.jk$total_SSE
sumWCSE_jk <- sum(kmeans_clorpt.jk$WCSS_per_cluster,na.rm=TRUE)
Btwcse_jk <- kmeans_clorpt.jk$between.SS_DIV_total.SS
### 4.c Internal cluster quality indices like:
require(clusterSim)
### - Calinski-Harbasz
icqG1.jk <- clusterSim::index.G1(x=scorpanSample.j.rs,
cl=kmeans_clorpt.jk$clusters,
centrotypes="centroids")
### - Silhouette - This is very memory demanding, so I use a subset of the data of 20,000 observations
# icqS.jk <- clusterSim::index.S(d=dist(scorpanSample.j.rs),
# cl=kmeans_clorpt.jk$clusters)
### - Bayesian information criterion to penalize larger number of clusters (cluster_BIC {lowmemtkmeans})
require(lowmemtkmeans)
BIC.jk <- lowmemtkmeans::cluster_BIC(data=as.matrix(scorpanSample.j.rs),
centres=as.matrix(kmeans_clorpt.jk$centroids))
### 4.d Store the results of the clustering indices
#out.clustering.indices[,k+1] <- c(Tot_SSE_jk,sumWCSE_jk,Btwcse_jk,icqG1.jk,icqS.jk,BIC.jk)
out.clustering.indices[,k+1] <- c(Tot_SSE_jk,sumWCSE_jk,Btwcse_jk,icqG1.jk,BIC.jk)
# Save the k-means model and centroids
save(kmeans_clorpt.jk, file=paste0(OutDir,"scorpan_combi_",j,"/kmeans_scorpanID",j,".k",search_space[[k]],".RData"))
gc()
# ### 5. Predict cluster assignment to soil profiles BASONET--------
### 5. Predict cluster assignment to soil properties observations - BASONET dataset:
### Extract the index of the dataframe rows that are na/nan/Inf
df.na <- which(apply(B.scorpan.j.rs,
MARGIN = 1,
FUN = function(x) {any(is.na(x))}))
if(length(df.na) ==0) {
### Predict cluster assignment - BASONET
cluster <- predict_KMeans(data = B.scorpan.j.rs, CENTROIDS = kmeans_clorpt.jk$centroids)
### Assign to the dataframe with soil observations
BASONET.scorpan.j[,knames[[k]]] <- cluster
} else if (length(df.na) > 0) {
cluster <- predict_KMeans(data = B.scorpan.j.rs[-df.na,], CENTROIDS = kmeans_clorpt.jk$centroids)
BASONET.scorpan.j[-df.na, knames[[k]]] <- cluster
}
### 6. Summarise number of observations per cluster: average, min and max.
### Here I only use observations from 2021, so there is no problem of double counting same coordinates and different years
### 6.a Subset of soil properties, those "more stable" - for BASONET, I decided (seeing also the correlation plots)
target.vars.BASONET <- c("Silt","Clay","CECef")
### Create the variable "Layer_depth"
BASONET.scorpan.j$Layer_depth <- ifelse(BASONET.scorpan.j$Lower_limit == 19, "000_020_cm", "020_040_cm" )
### subset data for the Dintra and Dinter calculations
Soil.df.BASONET <- BASONET.scorpan.j[,c("newID","Dataset","Layer_depth","Date", ### In this case either newID or myID design unique location
knames[[k]],
target.vars.BASONET)]
### Change name of pedogenon column
colnames(Soil.df.BASONET)[colnames(Soil.df.BASONET) ==knames[[k]]] <- "PdGn"
### Subset only complete observations
Soil.df.BASONET <- Soil.df.BASONET[complete.cases(Soil.df.BASONET),]
### Number of observations per pedogenon? Individual locations (unique coordinates + date)
### subset only one year for BASONET and LUCAS - Done
summary.PdGn.BASONET <- Soil.df.BASONET[,c("newID","PdGn")] %>% distinct(.,newID,PdGn) %>% count(., PdGn)
#out.indices.BASONET$Index
#hist(summary.PdGn.BASONET$n, breaks=20)
### How many of the pedogenons have any observation?
B_N_PdGn_sites <- length(unique(summary.PdGn.BASONET$PdGn))
### What percentage does this represent from all the classes?
B_Perc_PdGn_sites <- round(B_N_PdGn_sites/search_space[[k]]*100, digits=1)
B_Min_sites <- min(summary.PdGn.BASONET$n)
B_Median_sites <- median(summary.PdGn.BASONET$n)
B_Max_sites <- max(summary.PdGn.BASONET$n)
# 5.b Dintra/Dinter BASONET -----------------------------------------------
### 6.b Din/Dex
### Din is average distance from each observation to the centroid of its cluster
### Dex is the average distance between cluster centroids
### Calculate with functions from "5.PedogenonModeling_helper.R"
BASONET.DF.intra <- Dintra.function(df.soil = Soil.df.BASONET,
uniqueID = "newID",
depth.var = "Layer_depth",
target.vars = target.vars.BASONET)
### Average Distance between each observation to their centroid.
Dintra.BASONET <- mean(BASONET.DF.intra$dist_to_centroid, na.rm=TRUE)
BASONET.DF.inter <- Dinter.function(df.soil = Soil.df.BASONET,
uniqueID = "newID",
depth.var = "Layer_depth",
target.vars = target.vars.BASONET)
### Calculate average distance between centroids.
### These are the distances between centroids.
Dinter.BASONET <- mean(BASONET.DF.inter, na.rm=TRUE)
### Ratio Din to Dex
Din_Dex_BASONET <- Dintra.BASONET/Dinter.BASONET
### Store the results of the soil profile distances indices
out.indices.BASONET[,k+1] <- c(round(B_N_PdGn_sites, digits=0),
round(B_Perc_PdGn_sites, digits=1),
round(B_Min_sites, digits=0),
round(B_Median_sites, digits=0),
round(B_Max_sites, digits=0),
round(Din_Dex_BASONET, digits=3))
gc()
# ### 6. Predict cluster assignment to soil profiles HARMONISED DATASET--------
### 6. Predict cluster assignment to soil properties observations - HARMONISED dataset:
### Extract the index of the dataframe rows that are na/nan/Inf
df.na <- which(apply(SH.scorpan.j.rs,
MARGIN = 1,
FUN = function(x) {any(is.na(x))}))
if(length(df.na) ==0) {
### Predict cluster assignment - HARMONISED
cluster <- predict_KMeans(data = SH.scorpan.j.rs, CENTROIDS = kmeans_clorpt.jk$centroids)
### Assign to the dataframe with soil observations
Soil.df.harmonised.scorpan.j[,knames[[k]]] <- cluster
} else if (length(df.na) > 0) {
cluster <- predict_KMeans(data = SH.scorpan.j.rs[-df.na,], CENTROIDS = kmeans_clorpt.jk$centroids)
Soil.df.harmonised.scorpan.j[-df.na, knames[[k]]] <- cluster
}
### 6. Summarise number of observations per cluster: average, min and max.
### Here I only use observations from 2021, so there is no problem of double counting same coordinates and different years
### and because I require soil texture, only LUCAS 2009 is taken into account
### 6.a Subset of soil properties, those with more observations
target.vars.HARMONISED <- c("Silt","Clay","TOC","pH")
### subset data for the Dintra and Dinter calculations
Soil.df.HARMONISED <- Soil.df.harmonised.scorpan.j[,c("newID","Dataset","Layer_depth","Date",
### In this case either newID or myID design unique location
knames[[k]],
target.vars.HARMONISED)]
### Change name of pedogenon column
colnames(Soil.df.HARMONISED)[colnames(Soil.df.HARMONISED) ==knames[[k]]] <- "PdGn"
### Subset only complete observations
Soil.df.HARMONISED <- Soil.df.HARMONISED[complete.cases(Soil.df.HARMONISED),]
### Number of observations per pedogenon? Individual locations (unique coordinates + date)
### subset only one year for BASONET and LUCAS - Done
summary.PdGn.HARMONISED <- Soil.df.HARMONISED[,c("newID","PdGn")] %>% distinct(.,newID,PdGn) %>% count(., PdGn)
#out.indices.SoilHarmonised$Index
#hist(summary.PdGn.BASONET$n, breaks=20)
### How many of the pedogenons have any observation?
SH_N_PdGn_sites <- length(unique(summary.PdGn.HARMONISED$PdGn))
### What percentage does this represent from all the classes?
SH_Perc_PdGn_sites <- round(SH_N_PdGn_sites/search_space[[k]]*100, digits=1)
SH_Min_sites <- min(summary.PdGn.HARMONISED$n)
SH_Median_sites <- median(summary.PdGn.HARMONISED$n)
SH_Max_sites <- max(summary.PdGn.HARMONISED$n)
# 6.b Dintra/Dinter HARMONISED -----------------------------------------------
### 6.b Din/Dex
### Din is average distance from each observation to the centroid of its cluster
### Dex is the average distance between cluster centroids
### Calculate with functions from "5.PedogenonModeling_helper.R"
# centroids.test <- centroids.SoilVars.Pedogenon.fun(df.soil =Soil.df.HARMONISED,
# depth.var = "Layer_depth",
# target.vars = target.vars.HARMONISED )
### DEBUG THIS FUNCTION
HARMONISED.DF.intra <- Dintra.function(df.soil = Soil.df.HARMONISED,
uniqueID = "newID",
depth.var = "Layer_depth",
target.vars = target.vars.HARMONISED)
### Average Distance between each observation to their centroid.
Dintra.HARMONISED <- mean(HARMONISED.DF.intra$dist_to_centroid, na.rm=TRUE)
HARMONISED.DF.inter <- Dinter.function(df.soil = Soil.df.HARMONISED,
uniqueID = "newID",
depth.var = "Layer_depth",
target.vars = target.vars.HARMONISED)
### Calculate average distance between centroids.
### These are the distances between centroids.
Dinter.HARMONISED <- mean(HARMONISED.DF.inter, na.rm=TRUE)
### Ratio Din to Dex
Din_Dex_HARMONISED <- Dintra.HARMONISED/Dinter.HARMONISED
### Store the results of the soil profile distances indices
out.indices.SoilHarmonised[,k+1] <- c(round(SH_N_PdGn_sites, digits=0),
round(SH_Perc_PdGn_sites, digits=1),
round(SH_Min_sites, digits=0),
round(SH_Median_sites, digits=0),
round(SH_Max_sites, digits=0),
round(Din_Dex_HARMONISED, digits=3))
gc()
}
### Now we run through all the K
### Store the results in the same dataframe
indices.j <- rbind(out.clustering.indices,out.indices.BASONET,out.indices.SoilHarmonised)
### Write csv file in case foreach crashes
write.csv(indices.j, file = paste0(OutDir,"scorpan_combi_",j,"/cl_indices_comb",j,".csv"))
### Keep in a list outside the loop
kquality_combi_list[[j]] <- indices.j
### Export BASONET dataframe with cluster assignments
BASONET.dfs[[j]] <- BASONET.scorpan.j
write.csv(BASONET.scorpan.j, file = paste0(OutDir,"scorpan_combi_",j,"/BASONET_assign_",j,".csv"))
### Export harmonised soil dataframe with cluster assignments
HARMONISED.dfs[[j]] <- Soil.df.harmonised.scorpan.j
write.csv(Soil.df.harmonised.scorpan.j, file = paste0(OutDir,"scorpan_combi_",j,"/HARMONISED_assign_",j,".csv"))
tmpFiles(current = FALSE, orphan = TRUE, old = TRUE, remove = TRUE)
gc()
indices.j ### We return this
}
stopCluster(cl)
tac <- Sys.time()
tac-tic
### Does not exist
### save.image("C:/Users/mercedes.roman/Desktop/SELVANS/WP1/R_output/5.PedogenonModelingNoVegetation/relief_noVeg_combi27032024.RData")
# 8. Create HEATMAPS of cluster quality for each k and each covari --------
### 8. Create HEATMAPS of cluster quality for each k and each covariate combination and choose optimal k and covariate combination
### 26/04/2024
### load("C:/Users/mercedes.roman/Desktop/SELVANS/WP1/R_output/5.PedogenonModelingNoVegetation/relief_noVeg_combi27032024.RData")
OutDir <- "C:/Users/mercedes.roman/Desktop/SELVANS/WP1/R_output/5.PedogenonModelingNoVegetation/"
setwd(OutDir)
### Load the tables with clustering indices results in a for loop
for(j in 1:nrow(relief.combi)) {
if(j == 1) {
setwd(paste0(OutDir,"scorpan_combi_",j))
table.1 <- read.csv(paste0("cl_indices_comb",j,".csv"))
table.1$scorpan_comb <- j
} else if (j >1) {
setwd(paste0(OutDir,"scorpan_combi_",j))
table.j <- read.csv(paste0("cl_indices_comb",j,".csv"))
table.j$scorpan_comb <- j
table.1 <- rbind(table.1,table.j)
}
}
dim(table.1)
### Rename table
table_indices <- table.1
rm(table.1, table.j,j)
### Make heatmaps in for loop
indices <- unique(table_indices$Index)
dir.create("C:/Users/mercedes.roman/Desktop/SELVANS/WP1/R_output/5.PedogenonModelingNoVegetation/Plots")
setwd("C:/Users/mercedes.roman/Desktop/SELVANS/WP1/R_output/5.PedogenonModelingNoVegetation/Plots/")
for(index in 1:length(indices)){
### Select index
index.table <- table_indices[table_indices$Index == indices[[index]], ]
### Columns to rows
index.table.long <- tidyr::pivot_longer(index.table,
cols = starts_with("K."),
names_to = "clusters",
values_to = "index")
index.table.long$clusters <- factor(index.table.long$clusters,
levels=unique(index.table.long$clusters))
plot.index <- ggplot(index.table.long,
aes(x =scorpan_comb, y = clusters, fill = index)) +
geom_tile() +
scale_fill_viridis() +
labs(title = paste0(indices[[index]]))+
labs(x="SCORPAN combination")+
labs(y="Number of clusters")+
theme(
axis.title.x = element_text(size = 16),
axis.text.x = element_text(size = 12),
axis.title.y = element_text(size = 16),
axis.text.y = element_text(size = 8),
legend.text=element_text(size=16), #change font size of legend text
legend.title=element_text(size=16),
plot.title=element_text(size=20))
file_name = paste("index_plot_",indices[[index]] , ".jpeg", sep="")
jpeg(file_name, width = 1200, height = 900, units = "px")
print(plot.index)
dev.off()
}
### 9. Preferred options ---------------------------------------------------
### I am searching for the combination that:
### - has at least 3 observations per pedogenon class
### - has the smallest Din/Dex with BASONET and the complete dataset
### - has a large Calinski-Harbasz index
index.table <- table_indices[table_indices$Index %in%
c("Calinski-Harbasz","B_Min_sites",
"SH_Min_sites","B_Din_Dex","SH_Din_Dex"), ]
index.table.long <- tidyr::pivot_longer(index.table,
cols = starts_with("K."),
names_to = "clusters",
values_to = "index")
index.table.wide <- tidyr::pivot_wider(index.table.long,
id_cols=c(scorpan_comb ,clusters ),
names_from = "Index",
values_from = "index")
colnames(index.table.wide)<- c("scorpan_comb","clusters","Calinski_Harbasz",
"B_Min_sites","B_Din_Dex","SH_Min_sites","SH_Din_Dex")
### At least 3 onservations per pedogenon class
index.table.wide <- index.table.wide[index.table.wide$B_Min_sites >= 3,]
#index.table.wide <- index.table.wide[index.table.wide$scorpan_comb != 38,] ### This one has a weird result
### The Din/Dex smaller than 1 (at least the same dispersion, no more!)
index.table.wide <- index.table.wide[index.table.wide$B_Din_Dex <=1,]
### Arrange
index.table.wide <- arrange(index.table.wide, B_Din_Dex, desc(Calinski_Harbasz))
write.csv(index.table.wide, file="CH_BDinDex_Min3.csv")
index.table.wide[1:10,]
index.table.wide$clusters <- factor(index.table.wide$clusters,
levels=paste0("K.",c(4:10)))
index.table.wide <- arrange(index.table.wide, B_Din_Dex, desc(Calinski_Harbasz))
ggplot(index.table.wide,
aes(x =scorpan_comb, y = clusters, fill = B_Din_Dex)) +
geom_tile() +
scale_fill_viridis() +
labs(title = "Din/Dex BASONET")+
labs(x="SCORPAN combination")+
labs(y="Number of clusters")+
theme(
axis.title.x = element_text(size = 16),
axis.text.x = element_text(size = 12),
axis.title.y = element_text(size = 16),
axis.text.y = element_text(size = 8),
legend.text=element_text(size=16),
legend.title=element_text(size=16),
plot.title=element_text(size=20))
ggplot(index.table.wide,
aes(x =scorpan_comb, y = clusters, fill = Calinski_Harbasz)) +
geom_tile() +
scale_fill_viridis(direction=-1) +
labs(title = "Calinski-Harbasz BASONET")+
labs(x="SCORPAN combination")+
labs(y="Number of clusters")+
theme(
axis.title.x = element_text(size = 16),
axis.text.x = element_text(size = 12),
axis.title.y = element_text(size = 16),
axis.text.y = element_text(size = 8),
legend.text=element_text(size=16),
legend.title=element_text(size=16),
plot.title=element_text(size=20))
#sort(unique(index.table.wide$scorpan_comb))
index.table.wide$scorpan_comb_f <- factor(index.table.wide$scorpan_comb,
levels = sort(unique(index.table.wide$scorpan_comb)))
ggplot(index.table.wide,
aes(x = B_Din_Dex, y = Calinski_Harbasz,
color=scorpan_comb_f, shape=clusters)) +
geom_point(size=4) +
scale_shape_manual(values = c('K.4'= 0,'K.5'= 8,'K.6'=15, 'K.7'=18, 'K.8'=16,
'K.9'=17,'K.10'=1)) +
# # scale_color_viridis(discrete=TRUE)+
labs(title = "Calinski-Harbasz index and Din/Dex")+
theme(
axis.title.x = element_text(size = 16),
axis.text.x = element_text(size = 12),
axis.title.y = element_text(size = 16),
axis.text.y = element_text(size = 8),
legend.text=element_text(size=16),
legend.title=element_text(size=16),
plot.title=element_text(size=14))
top <- data.s[data.s$bi_class %in% c("4-4"),]
index.table.wide$DinDexNeg <- index.table.wide$B_Din_Dex * (-1)
data <- bi_class(top, x = "Calinski_Harbasz", y = "DinDexNeg",
style = "equal", dim = 3)
data <- as.data.frame(data)
write.csv(data, file="biscale_Basonet_equal.csv")
ggplot(data,
aes(x =scorpan_comb, y = clusters, fill = bi_class)) +
geom_tile() +
bi_scale_fill(pal = "DkBlue2", dim = 3) +
labs(title = "Calinski-Harbasz index and Din/Dex")+
labs(x="SCORPAN combination")+
labs(y="Number of clusters")+
theme(
axis.title.x = element_text(size = 16),
axis.text.x = element_text(size = 12),
axis.title.y = element_text(size = 16),
axis.text.y = element_text(size = 8),
legend.text=element_text(size=16),
legend.title=element_text(size=16),
plot.title=element_text(size=14))
# sample 4x4 legend
legend <- bi_legend(pal = "DkBlue2",
dim = 3,
xlab = "Calinski-Harbasz",
ylab = "- Din/Dex",
size = 16)
bi_pal(pal="DkBlue2", dim = 4, preview = TRUE, flip_axes = FALSE, rotate_pal = FALSE)