-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path00_HelperFunction.R
1550 lines (1371 loc) · 61.4 KB
/
00_HelperFunction.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
### Helper functions ####
library(dplyr)
# -------------------------------- #
`%notin%` = function(a, b){!(a %in% b)}
which.na = function(x){which(is.na(x))}
# Digit sum
digitsum <- function(x) sum(floor(x / 10^(0:(nchar(x) - 1))) %% 10)
myLog <- function(...) {
cat(paste0("[Processing] ", Sys.time(), " | ", ..., "\n"))
}
trapezoid = function(x, y)
{ # computes the integral of y with respect to x using trapezoidal integration.
idx = 2:length(x)
return (as.double( (x[idx] - x[idx-1]) %*% (y[idx] + y[idx-1])) / 2)
}
# Mape function
mape <- function(observed, predicted, type = 'normal', denim = 1){
assert_that(length(observed)==length(predicted))
if(type == 'normal'){
return(
mean(
abs((observed - predicted)/observed)
,na.rm = TRUE) * 100
)
} else {
# Calculate symetric map https://en.wikipedia.org/wiki/Symmetric_mean_absolute_percentage_error
return(
(100 / length(observed)) * sum( abs( predicted - observed ) / (( abs(predicted) + abs(observed) )*denim),na.rm = TRUE)
)
}
}
# Backtransform logit
inv_logit <- function(f, a){
a <- (1-2*a)
(a*(1+exp(f))+(exp(f)-1))/(2*a*(1+exp(f)))
}
# Mode
Mode <- function(x,...) {
ux <- unique(x,...)
ux[which.max(tabulate(match(x, ux)))]
}
normalize <- function(x)
{
if (length(x) == 1)
return(1)
y <- suppressWarnings((x - min(x, na.rm = TRUE))/(max(x,
na.rm = TRUE) - min(x, na.rm = TRUE)))
if (any(is.nan(y)))
return(x)
else return(y)
}
# Do filter history and construct sequence
filterTraj <- function(df, group ) {
stopifnot(group %in% ex$history)
# Construct history trajectories
ex %>% arrange(year) %>%
filter(history %in% c(group)) %>%
group_by(SSBS) %>%
summarize(Trajectory = paste0(unique(value.label),collapse = "_"))
}
# Standard error of the mean
sem <- function (x)
{
sqrt(var(x, na.rm = TRUE)/length(na.omit(x)))
}
vif.mer <- function (fit)
{
require(lme4)
v <- vcov(fit)
nam <- names(fixef(fit))
ns <- sum(1 * (nam == "Intercept" | nam == "(Intercept)"))
if (ns > 0) {
v <- v[-(1:ns), -(1:ns), drop = FALSE]
nam <- nam[-(1:ns)]
}
d <- diag(v)^0.5
v <- diag(solve(v/(d %o% d)))
names(v) <- nam
v
}
# Get standardized coefficients for lmer
lm.beta.lmer <- function(mod) {
b <- fixef(mod)[-1]
sd.x <- apply(getME(mod,"X")[,-1],2,sd)
sd.y <- sd(getME(mod,"y"))
b*sd.x/sd.y
}
# Describe function
describe <- function(x) {Hmisc::describe(x)} # Convenience describe function
# Not in function
'%notin%' <- function(x,y)!('%in%'(x,y))
#' Calculates the coeffiecient of variation
co.var <- function(x,na.rm=T,multiplier = 1) {
if(is.vector(x)){
cv = (multiplier * sd(x,na.rm=na.rm)/mean(x,na.rm=na.rm) )
} else {
stop("Input is not a vector")
}
return(cv)
}
# ---------------------------------------
# Function to isolate stable periods from time series - cpt.varmean
stabPer <- function(x,cp){
cp.l <- cpts(cp) # Location of changepoints
# Return a list of subsets
o <- list(x[1:cp.l[1]]) # The first one
cp.l <- c(cp.l, length(x)) # Remove the first and add the last
for(i in 1:(length(cp.l)-1)){
o[[i+1]] <- x[cp.l[i]:cp.l[i+1]]
}
return(o)
}
new.freq <- function(d, freq = 46) {
y <- as.Date(cut(range(d), "years")) + c(0, 366)
yd <- seq(y[1], y[2], "year")
yy <- as.numeric(format(yd, "%Y"))
floor(freq * approx(yd, yy, xout = d)$y) / freq
}
# Load in al MODIS BRDF Bands
readInFormat <- function(x,idv = "SSBS"){
require(data.table)
val = as.data.frame(data.table::fread(x,showProgress = T))[,-1] %>% dplyr::select(-.geo,-latitude, -longitude) %>%
reshape2::melt(., id.vars = idv) %>%
distinct() %>% mutate(variable = as.character(variable)) %>%
mutate(year = as.numeric( str_sub(variable,13,16)), # Get year out of file name
month = as.numeric( str_sub(variable,18,19) ), # get month
day = as.numeric( str_sub(variable,21,22) )) %>% # get day
# Make a date column
mutate(date = ymd(paste(year,month,day,sep="-")))
return(val)
}
# Function to convert from MODIS QA scores - BRDF Albedo band scores
# Inspired by MODISTools -> Tuck et al.
BRDFconvertQAScores <- function(qsc,band=NA,QualityThreshold=3){
#MCD43A4 = c(0,4294967294,4294967295), # BRDF albedo band quality, taken from MCD43A2, for reflectance data
QualityScores <- qsc
if(max(QualityScores,na.rm = T) == 0) num.binary.digits <- 1
if(max(QualityScores,na.rm = T) != 0) num.binary.digits <- floor(log(max(QualityScores,na.rm = T), base = 2)) + 1
binary.set<- matrix(nrow = length(QualityScores), ncol = num.binary.digits)
for(n in 1:num.binary.digits){
binary.set[ ,(num.binary.digits - n) + 1] <- QualityScores %% 2
QualityScores <- QualityScores %/% 2
}
# Construct quality binary score
quality.binary <- apply(binary.set, 1, function(x) paste(x, collapse = ""))
rm(binary.set)
if(!is.na(band)){
band.num <- as.numeric(substr(band, nchar(band), nchar(band)))
# Select respective subset of quality score
qa.binary <- substr(quality.binary, (nchar(quality.binary) - (((band.num - 1) * 2) + 2)),
(nchar(quality.binary) - ((band.num - 1) * 2)))
# Make a result vector
qa.int <- numeric(length(qa.binary))
qa.int[qa.binary == "000"] <- 0 # best quality, full inversion (WoDs, RMSE majority good)
qa.int[qa.binary == "001"] <- 1 # good quality, full inversion
qa.int[qa.binary == "010"] <- 2 # Magnitude inversion (numobs >=7)
qa.int[qa.binary == "011"] <- 3 # Magnitude inversion (numobs >=3&<7)
qa.int[qa.binary == "100"] <- 4 # Fill value
qa.int[qa.binary == "ANA" | is.na(qa.binary) ] <- NA # NA
# Finally replace everything above the treshold with NA
qa.int[qa.int > QualityThreshold] <- NA
# And return
return(qa.int)
} else {
# If band score is NA, it is assumed that we intend to calcualte the solar zenith angle
# Solar zenith information is stored between 8-14
qa.binary <- substr(quality.binary,8,14)
qa.binary[qa.binary == "ANANANA"] <- NA
x = strtoi(qa.binary, base = 2)
# Which values have to high zenith values -> Encode with 1 otherwise 0
x = ifelse(x>QualityThreshold,1,0)
}
}
# Backtransformation of asin(sqrt)
bt.asin <- function(x) {
z <- sin(x)^2
return(z)
}
#### Max CCF ####
# Returns the maximal value of the crosscorrelation function,
# thus indicating the time when there is a certain lag
aMaxCCF <- function(a,b,lt = 5)
{
d <- ccf(a, b, plot = FALSE, lag.max = length(a)-lt)
cor = d$acf[,,1]
abscor = abs(d$acf[,,1])
lag = d$lag[,,1]
res = data.frame(cor,lag)
absres = data.frame(abscor,lag)
absres_max = res[which.max(absres$abscor),]
return(absres_max)
}
#### LME4 functions ####
# Non-Convergence
checkConv <- function(mod){
gg <- mod@optinfo$derivs$grad
hh <- mod@optinfo$derivs$Hessian
vv <- sqrt(diag(solve(hh/2)))
cat("Should be smaller or around ~ e-05 --> ",mean(abs(gg*vv)),"\n")
# the numbers printed here should be very small (examples that the developers deemed acceptable were around e-05.
relgrad <- with(mod@optinfo$derivs,solve(Hessian,gradient))
cat("Should be smaller than 0.001 --> ",max(abs(relgrad)),"\n") # this number should ideally be < 0.001.
}
# Convergence boolean test
checkConvTest <- function(mod){
gg <- mod@optinfo$derivs$grad
hh <- mod@optinfo$derivs$Hessian
# In case system is exactly singular
try( vv <- sqrt(diag(solve(hh/2))), silent=T )
if(exists("vv")){
if( any(is.nan(vv))) { return(FALSE)}
# Otherwise test for degenerated Hessians
try( relgrad <- with(mod@optinfo$derivs,solve(Hessian,gradient)),silent=T )
if(!exists("relgrad")) {return(FALSE)}
if( all( mean(abs(gg*vv)) < 0.00001,max(abs(relgrad)) < 0.001 ) ){
return(TRUE)
} else {
return(FALSE)
}
} else {return(FALSE)}
}
## Check for overdispersion
overdisp_fun <- function(model) {
## number of variance parameters in
## an n-by-n variance-covariance matrix
vpars <- function(m) {
nrow(m)*(nrow(m)+1)/2
}
model.df <- sum(sapply(VarCorr(model),vpars))+length(fixef(model))
rdf <- nrow(model.frame(model))-model.df
rp <- residuals(model,type="pearson")
Pearson.chisq <- sum(rp^2)
prat <- Pearson.chisq/rdf
pval <- pchisq(Pearson.chisq, df=rdf, lower.tail=FALSE)
c(chisq=Pearson.chisq,ratio=prat,rdf=rdf,p=pval)
}
#### Compdis update #####
# Requires a full predicts subset
CompDissim2 <- function (data, metric,binary=F)
{
require(vegan)
require(data.table)
data <- as.data.table(data) # For speed improvement
if (metric == "SorAbd") {
data <- data[data$Diversity_metric_type == "Abundance",
]
}
if (metric == "SorCorr") {
data <- data[((data$Diversity_metric == "abundance") &
(data$Diversity_metric_unit == "individuals")), ]
}
if (metric == "BCVeg" & binary == F) {
data <- data[data$Diversity_metric_type == "Abundance",]
}
if (metric == "BrayCurt" & binary == F) {
data <- data[data$Diversity_metric_type == "Abundance",]
}
data <- subset(data, select = c("SS", "SSBS", "Measurement",
"Taxon_name_entered"))
data <- na.omit(data)
if (metric == "SorCorr") {
study.all.int.meas <- tapply(data$Measurement, data$SS,
function(m) all(floor(m) == m))
int.meas <- study.all.int.meas[match(data$SS, names(study.all.int.meas))]
data <- data[int.meas, ]
}
# Results
result <- list()
for (st in unique(data$SS)) {
cat(paste("Processing ", st, "\n", sep = ""))
sub.data <- data[data$SS == st, ]
if (metric != "SorCorr") {
sub.data <- sub.data[sub.data$Measurement > 0, ]
}
if(metric == "SorVeg"){
if(length(unique(sub.data$SSBS)) < 2) next()
m <- reshape2::acast(data=sub.data,SSBS~Taxon_name_entered,value.var = "Measurement",fill = 0) # Fill with zero assuming absence
sites.matrix <- as.matrix( suppressWarnings( vegan::betadiver(m,method = "sor",binary=binary) ) )
#sites.matrix[upper.tri(sites.matrix)] <- -9999
diag(sites.matrix) <- NA # Set diagonal to NA
#mat_a <- reshape2::melt(sites.matrix) %>% rename(SSBS_x = Var1, SSBS_y = Var2 ) %>% #Melt and rename
# mutate(SSBS_x = as.character(SSBS_x), SSBS_y = as.character(SSBS_y)) # format again
#mat_a <- mat_a[-which(mat_a$value==-9999),] # remove triangle and missing data
#mat_a$SS <- st # Finally append the study ID
result[[st]] <- sites.matrix#mat_a
} else if(metric == "BCVeg"){
if(binary==T) stop("Binary should be FALSE for BcVEG")
if(length(unique(sub.data$SSBS)) < 2) next()
m <- reshape2::acast(data=sub.data,SSBS~Taxon_name_entered,value.var = "Measurement",fill = 0) # Fill with zero assuming absence
sites.matrix <- as.matrix( suppressWarnings( vegdist(m,method="bray",binary=binary,na.rm = T) ) )
#sites.matrix[upper.tri(sites.matrix)] <- -9999
diag(sites.matrix) <- NA # Set diagonal to NA
#mat_a <- reshape2::melt(sites.matrix) %>% rename(SSBS_x = Var1, SSBS_y = Var2 ) %>% #Melt and rename
# mutate(SSBS_x = as.character(SSBS_x), SSBS_y = as.character(SSBS_y)) # format again
#mat_a <- mat_a[-which(mat_a$value==-9999),] # remove triangle and missing data
#mat_a$SS <- st # Finally append the study ID
result[[st]] <- sites.matrix#mat_a
} else {
sites.matrix <- matrix(nrow = length(unique(sub.data$SSBS)),
ncol = length(unique(sub.data$SSBS)))
i1 <- 1
for (s1 in unique(sub.data$SSBS)) {
i2 <- 1
for (s2 in unique(sub.data$SSBS)) {
if (metric == "Sor") {
# sorrensen
u <- length(union(sub.data$Taxon_name_entered[sub.data$SSBS ==
s1], sub.data$Taxon_name_entered[sub.data$SSBS ==
s2]))
i <- length(intersect(sub.data$Taxon_name_entered[sub.data$SSBS ==
s1], sub.data$Taxon_name_entered[sub.data$SSBS ==
s2]))
sor <- (2 * i)/((2 * i) + (u - i))
}
else if (metric == "SorAbd") {
# abundance corrected sorrensen
u <- sum(sub.data$Measurement[(sub.data$SSBS ==
s1) & (sub.data$Taxon_name_entered %in% union(sub.data$Taxon_name_entered[sub.data$SSBS ==
s1], sub.data$Taxon_name_entered[sub.data$SSBS ==
s2]))])
v <- sum(sub.data$Measurement[(sub.data$SSBS ==
s2) & (sub.data$Taxon_name_entered %in% union(sub.data$Taxon_name_entered[sub.data$SSBS ==
s1], sub.data$Taxon_name_entered[sub.data$SSBS ==
s2]))])
sor <- (2 * u * v)/(u + v)
}
else if (metric == "SorBM") {
# abundance corrected sorrensen
# Sum of estimates of species recorded at both sites
A <- sum(sub.data$Measurement[union(sub.data$SSBS == s1,sub.data$SSBS == s2) &
(sub.data$Taxon_name_entered %in% union(sub.data$Taxon_name_entered[sub.data$SSBS ==
s1], sub.data$Taxon_name_entered[sub.data$SSBS ==
s2]))])
B <- sum(sub.data$Measurement[(sub.data$SSBS == s1) &
(sub.data$Taxon_name_entered %in% union(sub.data$Taxon_name_entered[sub.data$SSBS ==
s1], sub.data$Taxon_name_entered[sub.data$SSBS ==
s2]))])
C <- sum(sub.data$Measurement[(sub.data$SSBS == s2) &
(sub.data$Taxon_name_entered %in% union(sub.data$Taxon_name_entered[sub.data$SSBS ==
s1], sub.data$Taxon_name_entered[sub.data$SSBS ==
s2]))])
sor <- (2 * A)/(2*A + B + C)
}
else if (metric == "BrayCurt"){
# Bray curtis similarity
u <- sub.data$Measurement[(sub.data$SSBS ==
s1) & (sub.data$Taxon_name_entered %in% union(sub.data$Taxon_name_entered[sub.data$SSBS ==
s1], sub.data$Taxon_name_entered[sub.data$SSBS ==
s2]))]
v <- sub.data$Measurement[(sub.data$SSBS ==
s2) & (sub.data$Taxon_name_entered %in% union(sub.data$Taxon_name_entered[sub.data$SSBS ==
s1], sub.data$Taxon_name_entered[sub.data$SSBS ==
s2]))]
sor <- ( sum( abs(u - v) ) / ( sum(u) + sum(v) ) ) # Similarity 1- following Faith
# Tested and completly identical to vegan vegdist
}
else if (metric == "SorCorr") {
# Sampling corrected sorrensen
n <- sum(sub.data$Measurement[sub.data$SSBS ==
s1])
m <- sum(sub.data$Measurement[sub.data$SSBS ==
s2])
if ((n > 0) & (m > 0)) {
xi <- sub.data$Measurement[sub.data$SSBS ==
s1][(match(union(sub.data$Taxon_name_entered[sub.data$SSBS ==
s1], sub.data$Taxon_name_entered[sub.data$SSBS ==
s2]), sub.data$Taxon_name_entered[sub.data$SSBS ==
s1]))]
yi <- sub.data$Measurement[sub.data$SSBS ==
s2][(match(union(sub.data$Taxon_name_entered[sub.data$SSBS ==
s1], sub.data$Taxon_name_entered[sub.data$SSBS ==
s2]), sub.data$Taxon_name_entered[sub.data$SSBS ==
s2]))]
xi[is.na(xi)] <- 0
yi[is.na(yi)] <- 0
f1. <- length(which((xi == 1) & (yi > 0)))
f2. <- max(1, length(which((xi == 2) & (yi >
0))))
f.1 <- length(which((xi > 0) & (yi == 1)))
f.2 <- max(1, length(which((xi > 0) & (yi ==
2))))
p1 <- sum(xi[yi > 0]/n)
p2 <- ((m - 1)/m) * (f.1/(2 * f.2))
p3 <- sum(xi[yi == 1]/n)
u <- min(1, p1 + p2 * p3)
q1 <- sum(yi[xi > 0]/m)
q2 <- ((n - 1)/n) * (f1./(2 * f2.))
q3 <- sum(yi[xi == 1]/m)
v <- min(1, q1 + q2 * q3)
if ((u > 0) & (v > 0)) {
sor <- (2 * u * v)/(u + v)
}
else {
sor <- 0
}
}
else {
sor <- 0
}
}
else {
stop("Error: specfied dissimilarity metric is not supported")
}
if (s1 != s2)
sites.matrix[i1, i2] <- sor
i2 <- i2 + 1
}
i1 <- i1 + 1
}
#sites.matrix[upper.tri(sites.matrix)] <- -9999
#diag(sites.matrix) <- -9999 # Remove duplicates and set diagonal to -9999
rownames(sites.matrix) <- unique(sub.data$SSBS); colnames(sites.matrix) <- unique(sub.data$SSBS)
#mat_a <- reshape2::melt(sites.matrix) %>% rename(SSBS_x = Var1, SSBS_y = Var2 ) %>% #Melt and rename
# mutate(SSBS_x = as.character(SSBS_x), SSBS_y = as.character(SSBS_y)) # format again
#mat_a <- mat_a[-which(mat_a$value==-9999),] # remove triangle and missing data
#mat_a$SS <- st # Finally append the study ID
result[[st]] <- sites.matrix
}
}
return(result)
}
#### Other PREDICTS functions ####
# Tims function
SpatialAutocorrelationTest<-function(model,all.data,siteModel=TRUE){
if ("data" %in% names(model)){
model.data<-model$data
model.data$res<-residuals(model$model)
} else {
model.data<-model@frame
model.data$res<-residuals(model)
}
model.data$Longitude<-all.data$Longitude[match(model.data$SSBS,all.data$SSBS)]
model.data$Latitude<-all.data$Latitude[match(model.data$SSBS,all.data$SSBS)]
studies<-character()
failed<-character()
moran.i<-numeric()
moran.p<-numeric()
i=1
for (ss in unique(model.data$SS)){
cat(paste("\rProcessing study ",i," of ",length(unique(model.data$SS)),sep=""))
data.sub<-droplevels(model.data[model.data$SS==ss,])
if(!siteModel){
resids<-tapply(data.sub$res,data.sub$SSBS,mean)
long<-tapply(data.sub$Longitude,data.sub$SSBS,mean)
lat<-tapply(data.sub$Latitude,data.sub$SSBS,mean)
data.sub<-data.frame(res=resids,Longitude=long,Latitude=lat)
}
ds.nb<-try(dnearneigh(cbind(data.sub$Longitude,data.sub$Latitude),
d1=0.00000001,d2=10),silent=TRUE)
ds.listw<-try(nb2listw(ds.nb),silent=TRUE)
mt<-tryCatch(moran.test(data.sub$res,ds.listw),silent=TRUE,error=function(e) e,
warning=function(w) w)
if(class(mt)[1]=="htest"){
if ((!is.na(mt$statistic))){
studies<-c(studies,ss)
moran.i<-c(moran.i,mt$statistic)
moran.p<-c(moran.p,mt$p.value)
} else {
failed<-c(failed,ss)
}
} else {
failed<-c(failed,ss)
}
i<-i+1
}
return(list(studies=studies,I=moran.i,P=moran.p,failed=failed))
}
# My own functions for check spatial autocorrelation of sites within a study
# Requires a single linear model and dataset
checkMoran <- function(model, data){
assertthat::assert_that(has_name(data,'Longitude'))
require(spdep)
# Get residuals
data <- subset(data,select = c('Longitude','Latitude',all.vars(model$formula)[2] ))
data$residuals[which(!is.na( data[,all.vars(model$formula)[2]] ))] <- residuals(model)
data <- subset(data, complete.cases(data))
ds.nb <- try(
dnearneigh(
cbind(data$Longitude, data$Latitude),
d1 = 0.00000001, d2 = 10), silent = TRUE
)
ds.listw <- try(nb2listw(ds.nb),silent=TRUE)
mt <- tryCatch(moran.test(data$residuals,ds.listw),silent=TRUE,error=function(e) e,
warning=function(w) w)
return(c(
statistic = as.numeric(mt$statistic), p.value = as.numeric(mt$p.value)
))
}
#### Monthly functions ####
# File monthlyfunction.R
# Part of the hydroTSM R package, http://www.rforge.net/hydroTSM/ ;
# http://cran.r-project.org/web/packages/hydroTSM/
# Copyright 2008-2013 Mauricio Zambrano-Bigiarini
# Distributed under GPL 2 or later
################################################################################
# monthlyfunction: Generic function for applying any R function to #
# ALL the values in 'x' belonging to a given month #
################################################################################
# Author : Mauricio Zambrano-Bigiarini #
################################################################################
# Started: May 15th, 2009; #
# Updates: 31-Aug-2009 ; 25-Jul-2011 ; 08-Aug-2011 #
# 08-Apr-2013 #
################################################################################
# 'x ' : variable of type 'zoo' or 'data.frame', with daily or monthly frequency
# 'FUN' : Function that will be applied to ALL the values in 'x' belonging to each one of the 12 months of the year
# 'na.rm' : Logical. Should missing values be removed?
# TRUE : the monthly values are computed considering only those values in 'x' different from NA
# FALSE: if there is AT LEAST one NA within a month, the FUN and monthly values are NA
monthlyfunction <- function(x, ...) UseMethod("monthlyfunction")
monthlyfunction.default <- function(x, FUN, na.rm=TRUE,...) {
# Checking that 'x' is a zoo object
if ( !is.zoo(x) ) stop("Invalid argument: 'class(x)' must be in c('zoo', 'xts')")
monthlyfunction.zoo(x=x, FUN=FUN, na.rm=na.rm, ...)
} # 'monthlyfunction.default' end
################################################################################
# Author : Mauricio Zambrano-Bigiarini #
################################################################################
# Started: 25-Jul-2011 #
# Updates: 08-Aug-2011 #
# 05-Jun-2012 #
# 08-Apr-2013 #
# 28-Nov-2015 #
################################################################################
monthlyfunction.zoo <- function(x, FUN, na.rm=TRUE,...) {
# Checking that the user provied a valid argument for 'FUN'
if (missing(FUN)) stop("Missing argument: 'FUN' must be provided")
# Checking the user provide a valid value for 'x'
if (sfreq(x) %in% c("quarterly", "annual"))
stop("Invalid argument: 'x' is not a sub-daily, daily, weekly or monthly ts. 'x' is a ", sfreq(x), " ts" )
# Monthly index for 'x'
dates <- time(x)
m <- as.numeric(format( dates, "%m" ))
months <- factor( month.abb[m], levels=unique(month.abb[m]) )
# 'as.numeric' is necessary for being able to change the names to the output
totals <- aggregate(x, by= months, FUN=FUN, na.rm= na.rm, ... )
# Replacing the NaNs by 'NA.
# NaN's are obtained when using the FUN=mean with complete NA values
nan.index <- which(is.nan(totals))
if ( length(nan.index) > 0 ) totals[ nan.index] <- NA
# Replacing all the Inf and -Inf by NA's
# min(NA:NA, na.rm=TRUE) == Inf ; max(NA:NA, na.rm=TRUE) == -Inf
inf.index <- which(is.infinite(totals))
if ( length(inf.index) > 0 ) totals[inf.index] <- NA
# Giving meaningful names to the output
if ( (is.matrix(x)) | (is.data.frame(x)) ) {
totals <- t(totals) # For having the months' names as column names
colnames(totals) <- levels(months)
} #IF end
return(totals)
} # 'monthlyfunction.zoo' end
################################################################################
# Author : Mauricio Zambrano-Bigiarini #
################################################################################
# Started: 25-Jul-2011 #
# Updates: 08-Aug-2011 #
# 29-May-2013 ; 03-Jun-2013 #
################################################################################
# 'dates' : "numeric", "factor", "Date" indicating how to obtain the
# dates for correponding to the 'sname' station
# If 'dates' is a number, it indicates the index of the column in
# 'x' that stores the dates
# If 'dates' is a factor, it have to be converted into 'Date' class,
# using the date format specified by 'date.fmt'
# If 'dates' is already of Date class, the following line verifies that
# the number of days in 'dates' be equal to the number of element in the
# time series corresponding to the 'st.name' station
# 'date.fmt': format in which the dates are stored in 'dates'.
# ONLY required when class(dates)=="factor" or "numeric"
# 'out.type': string that define the desired type of output. Possible values are
# -) "data.frame": a data.frame, with 12 columns representing the months,
# and as many rows as stations are included in 'x'
# -) "db" : a data.frame, with 4 colums will be produced.
# The first column stores the ID of the station
# The second column stores the Year,
# The third column stores the ID of the station,
# The fourth column contains the monthly value corresponding to the year specified in the second column
# 'verbose' : logical; if TRUE, progress messages are printed
monthlyfunction.data.frame <- function(x, FUN, na.rm=TRUE,
dates=1, date.fmt="%Y-%m-%d",
out.type="data.frame",
verbose=TRUE,...) {
# Checking that the user provied a valid argument for 'out.type'
if (is.na(match( out.type, c("data.frame", "db") ) ) )
stop("Invalid argument: 'out.type' must be in c('data.frame', 'db'")
# Checking that the user provied a valid argument for 'FUN'
if (missing(FUN)) stop("Missing argument: 'FUN' must be provided")
# Checking that the user provied a valid argument for 'dates'
if (is.na(match(class(dates), c("numeric", "factor", "Date"))))
stop("Invalid argument: 'dates' must be of class 'numeric', 'factor', 'Date'")
# If 'dates' is a number, it indicates the index of the column of 'x' that stores the dates
# The column with dates is then substracted form 'x' for easening the further computations
if ( class(dates) == "numeric" ) {
tmp <- dates
dates <- as.Date(x[, dates], format= date.fmt)
x <- x[-tmp]
} # IF end
# If 'dates' is a factor, it have to be converted into 'Date' class,
# using the date format specified by 'date.fmt'
if ( class(dates) == "factor" ) dates <- as.Date(dates, format= date.fmt)
# If 'dates' is already of Date class, the following line verifies that
# the number of days in 'dates' be equal to the number of element in the
# time series corresponding to the 'st.name' station
if ( ( class(dates) == "Date") & (length(dates) != nrow(x) ) )
stop("Invalid argument: 'length(dates)' must be equal to 'nrow(x)'")
# Transforming 'x' into a zoo object
x <- zoo(x, dates)
##############################################################################
if (out.type == "data.frame") {
monthlyfunction.zoo(x=x, FUN=FUN, na.rm=na.rm, ...)
} else if (out.type == "db") {
# Amount of stations in 'x'
nstations <- ncol(x)
# ID of all the stations in 'x'
snames <- colnames(x)
if (is.null(snames)) snames <- paste("V", 1:nstations, sep="")
# Computing the Starting and Ending Year of the analysis
Starting.Year <- as.numeric(format(start(x), "%Y"))
Ending.Year <- as.numeric(format(end(x), "%Y"))
# Amount of Years belonging to the desired period
nyears <- Ending.Year - Starting.Year + 1
# Computing the numeric index of the resulting months
month.index <- unique(as.numeric(format( time(x), "%m" )))
# Amount of different months belonging to the desired period
nmonths <- length(month.index)
# Total amount of months belonging to the desired period
totalmonths <- nmonths*nyears
# Creating a vector with the names of the field that will be used for storing the results
field.names <- c("StationID", "Year", "Month", "Value" )
# Creating the data.frame that will store the computed averages for each subcatchment
z <- as.data.frame(matrix(data = NA, nrow = totalmonths*nstations, ncol = 4, byrow = TRUE, dimnames = NULL) )
for (j in 1:nstations) {
if (verbose) message( "[ Station: ", format(snames[j], width=10, justify="left"),
" : ", format(j, width=3, justify="left"), "/",
nstations, " => ",
format(round(100*j/nstations,2), width=6, justify="left"),
"% ]" )
# Computing the annual values
tmp <- monthlyfunction.default(x= x[,j], FUN=FUN, na.rm=na.rm, ...)
# Putting the annual/monthly values in the output data.frame
# The first column of 'x' corresponds to the Year
row.ini <- (j-1)*totalmonths + 1
row.fin <- j*totalmonths
z[row.ini:row.fin, 1] <- snames[j] # it is automatically repeted 'totalmonths' times
z[row.ini:row.fin, 2] <- rep(Starting.Year:Ending.Year, each=nmonths)
z[row.ini:row.fin, 3] <- month.abb[month.index]
z[row.ini:row.fin, 4] <- tmp
} # FOR end
colnames(z) <- field.names
return( z )
} # ELSE end
} #'monthlyfunction.data.frame' END
################################################################################
# Author : Mauricio Zambrano-Bigiarini #
################################################################################
# Started: 25-Jul-2011 #
# Updates: 08-Aug-2011 #
# 29-May-2013 #
################################################################################
monthlyfunction.matrix <- function(x, FUN, na.rm=TRUE,
dates=1, date.fmt="%Y-%m-%d",
out.type="data.frame",
verbose=TRUE,...) {
x <- as.data.frame(x)
#NextMethod("monthlyfunction")
monthlyfunction.data.frame(x=x, FUN=FUN, na.rm=na.rm,
dates=dates, date.fmt=date.fmt,
out.type=out.type,
verbose=verbose,...)
} # 'monthlyfunction.matrix' END
# File sfreq.R
# Part of the hydroTSM R package, http://www.rforge.net/hydroTSM/ ;
# http://cran.r-project.org/web/packages/hydroTSM/
# Copyright 2009-2013 Mauricio Zambrano-Bigiarini
# Distributed under GPL 2 or later
################################################################################
# sfreq: Sampling frequency of a ts/zoo object #
################################################################################
# This function generates a table indicating the number of days #
# with information (<>NA's) within a data.frame #
################################################################################
# Author : Mauricio Zambrano-Bigiarini #
################################################################################
# Started: 13-May-2009 #
# Updates: Mar 2009 #
# Nov 2010 #
# Apr 2011 ; 09-Aug-2011 #
# 18-Oct-2012 #
# 29-May-2013 #
################################################################################
sfreq <- function(x, min.year=1800) {
# Checking that 'class(x)'
valid.class <- c("xts", "zoo")
if (length(which(!is.na(match(class(x), valid.class )))) <= 0)
stop("Invalid argument: 'x' must be in c('xts', 'zoo')" )
out <- periodicity(x)$scale # xts::periodicity
if (out == "yearly") out <- "annual"
return(out)
} # 'sfreq' END
### Weekly function ###
weeklyfunction <- function(x, FUN, na.rm=TRUE,...) {
# Checking that the user provied a valid argument for 'FUN'
if (missing(FUN)) stop("Missing argument: 'FUN' must be provided")
# Checking the user provide a valid value for 'x'
if (sfreq(x) %in% c("quarterly", "annual"))
stop("Invalid argument: 'x' is not a sub-daily, daily, weekly or monthly ts. 'x' is a ", sfreq(x), " ts" )
# Monthly index for 'x'
dates <- time(x)
m <- as.numeric(format( dates, "%W" ))
# 'as.numeric' is necessary for being able to change the names to the output
totals <- aggregate(x, by= m, FUN=FUN, na.rm= na.rm, ... )
# Replacing the NaNs by 'NA.
# NaN's are obtained when using the FUN=mean with complete NA values
nan.index <- which(is.nan(totals))
if ( length(nan.index) > 0 ) totals[ nan.index] <- NA
# Replacing all the Inf and -Inf by NA's
# min(NA:NA, na.rm=TRUE) == Inf ; max(NA:NA, na.rm=TRUE) == -Inf
inf.index <- which(is.infinite(totals))
if ( length(inf.index) > 0 ) totals[inf.index] <- NA
return(totals)
}
simpson <- function(y, a, b, n = 100) {
# numerical integral of y from a to b
# using Simpson's rule with n subdivisions
#
# y is a function of a single variable
# we assume a < b and n is a positive even integer
n <- max(c(2*(n %/% 2), 4),na.rm=T)
h <- (b-a)/n
x.vec1 <- seq(a+h, b-h, by = 2*h)
x.vec2 <- seq(a+2*h, b-2*h, by = 2*h)
f.vec1 <- y[x.vec1]
f.vec2 <- y[x.vec2]
S <- h/3*(y[a] + y[b] + 4*sum(f.vec1,na.rm = T) + 2*sum(f.vec2,na.rm = T))
return(S)
}
eudis = function(x, y) { sqrt( sum( (x-y)^2 ) ) } # define Euclidean distance
trapezoid = function(x, y)
{ # computes the integral of y with respect to x using trapezoidal integration.
idx = 2:length(x)
return (as.double( (x[idx] - x[idx-1]) %*% (y[idx] + y[idx-1])) / 2)
}
# Jet Colors
jet.colors <-colorRampPalette(c("#00007F", "blue", "#007FFF", "cyan",
"#7FFF7F", "yellow", "#FF7F00", "red", "#7F0000"))
myvis.gam <- function (x, view = NULL, cond = list(), n.grid = 30, too.far = 0,
col = NA, color = "heat", contour.col = NULL, se = -1, type = "link",
plot.type = "persp", zlim = NULL, nCol = 50, ...)
{
fac.seq <- function(fac, n.grid) {
fn <- length(levels(fac))
gn <- n.grid
if (fn > gn)
mf <- factor(levels(fac))[1:gn]
else {
ln <- floor(gn/fn)
mf <- rep(levels(fac)[fn], gn)
mf[1:(ln * fn)] <- rep(levels(fac), rep(ln, fn))
mf <- factor(mf, levels = levels(fac))
}
mf
}
dnm <- names(list(...))
v.names <- names(x$var.summary)
if (is.null(view)) {
k <- 0
view <- rep("", 2)
for (i in 1:length(v.names)) {
ok <- TRUE
if (is.matrix(x$var.summary[[i]]))
ok <- FALSE
else if (is.factor(x$var.summary[[i]])) {
if (length(levels(x$var.summary[[i]])) <= 1)
ok <- FALSE
}
else {
if (length(unique(x$var.summary[[i]])) == 1)
ok <- FALSE
}
if (ok) {
k <- k + 1
view[k] <- v.names[i]
}
if (k == 2)
break
}
if (k < 2)
stop("Model does not seem to have enough terms to do anything useful")
}
else {
if (sum(view %in% v.names) != 2)
stop(gettextf("view variables must be one of %s",
paste(v.names, collapse = ", ")))
for (i in 1:2) if (!inherits(x$var.summary[[view[i]]],
c("numeric", "factor")))
stop("Don't know what to do with parametric terms that are not simple numeric or factor variables")
}
ok <- TRUE
for (i in 1:2) if (is.factor(x$var.summary[[view[i]]])) {
if (length(levels(x$var.summary[[view[i]]])) <= 1)
ok <- FALSE
}
else {
if (length(unique(x$var.summary[[view[i]]])) <= 1)
ok <- FALSE
}
if (!ok)
stop(gettextf("View variables must contain more than one value. view = c(%s,%s).",
view[1], view[2]))
if (is.factor(x$var.summary[[view[1]]]))
m1 <- fac.seq(x$var.summary[[view[1]]], n.grid)
else {
r1 <- range(x$var.summary[[view[1]]])
m1 <- seq(r1[1], r1[2], length = n.grid)
}
if (is.factor(x$var.summary[[view[2]]]))
m2 <- fac.seq(x$var.summary[[view[2]]], n.grid)
else {
r2 <- range(x$var.summary[[view[2]]])
m2 <- seq(r2[1], r2[2], length = n.grid)
}
v1 <- rep(m1, n.grid)
v2 <- rep(m2, rep(n.grid, n.grid))
newd <- data.frame(matrix(0, n.grid * n.grid, 0))
for (i in 1:length(x$var.summary)) {
ma <- cond[[v.names[i]]]
if (is.null(ma)) {
ma <- x$var.summary[[i]]
if (is.numeric(ma))
ma <- ma[2]
}
if (is.matrix(x$var.summary[[i]]))
newd[[i]] <- matrix(ma, n.grid * n.grid, ncol(x$var.summary[[i]]),
byrow = TRUE)
else newd[[i]] <- rep(ma, n.grid * n.grid)
}
names(newd) <- v.names
newd[[view[1]]] <- v1
newd[[view[2]]] <- v2
if (type == "link")
zlab <- paste("linear predictor")
else if (type == "response")
zlab <- type
else stop("type must be \"link\" or \"response\"")
fv <- predict.gam(x, newdata = newd, se.fit = TRUE, type = type)
z <- fv$fit
if (too.far > 0) {
ex.tf <- exclude.too.far(v1, v2, x$model[, view[1]],
x$model[, view[2]], dist = too.far)
fv$se.fit[ex.tf] <- fv$fit[ex.tf] <- NA
}
if (is.factor(m1)) {
m1 <- as.numeric(m1)
m1 <- seq(min(m1) - 0.5, max(m1) + 0.5, length = n.grid)
}
if (is.factor(m2)) {
m2 <- as.numeric(m2)
m2 <- seq(min(m1) - 0.5, max(m2) + 0.5, length = n.grid)
}
if (se <= 0) {
old.warn <- options(warn = -1)