-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSI_spatial_avg.Rmd
2218 lines (1893 loc) · 116 KB
/
SI_spatial_avg.Rmd
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: "Supporting Information: Species relationships in the extremes and their influence on community stability"
author: "Shyamolina Ghosh, Kathryn L. Cottingham, Daniel C. Reuman"
date: ""
fontsize: 11pt
geometry: "left=1.5cm,right=1.5cm,top=1cm,bottom=1.8cm"
output:
pdf_document:
number_sections: yes
keep_tex: yes
fig_caption: yes
header-includes:
- \usepackage{xr} \externaldocument[MT-]{MT_spatial_avg}
- \input{head_supp.sty}
mainfont: Times New Roman
tables: True
link-citations: True
urlcolor : blue
indent : True
csl: ecology-letters.csl
bibliography: REF_CSS.bib
---
\pagenumbering{roman}
\tableofcontents
\listoftables
\listoffigures
\pagenumbering{arabic}
<!--Basic setup-->
```{r setup, echo=F, message=FALSE}
knitr::opts_chunk$set(echo = TRUE, fig.pos = "H")
seed<-101 # common seed
library(dplyr)
library(kableExtra)
library(stringr)
library(rmarkdown)
#library(xfun)
# families<-c(1,3:10,13,14,16:20)
source("mtime.R") #A function needed for caching
```
<!-- reading raw data for hays and creates results folder for hays-->
```{r read hays_rawdata,echo=F,results="hide"}
# later add results="hide" , echo=F in chunk header
set.seed(seed)
# basal cover data
cover<-read.csv("./Data/HaysData/allrecords.csv") # this is basal cover
# quadrat sampling ? Yes or not
quadsamp<-read.csv("./Data/HaysData/quadrat_inventory.csv")
quad_info<-read.csv("./Data/HaysData/quadrat_info.csv")
count_quad_grazed<-table(quad_info$Grazing) #36 No grazing, 15 Yes grazed
quad_grazing<-quad_info$quadrat[which(quad_info$Grazing=="Yes")]
quad_grazing<-as.character(quad_grazing) # we plan to exclude these 15 plots later
# when calculating averaged basal cover for each species
# Information on species list
spinfo<-read.csv("./Data/HaysData/species_list.csv")
nonplant<-as.character(spinfo$species[which(spinfo$type=="remove")])
#These are not plant species as per metadata file (page 8 in pdf) for more info: though I doubt on mixed grass and polygonum spp.]
#"Bare ground" "Fragment" "Mixed grass" "Polygonum spp." "Unknown"
spinfo[which(spinfo$type=="remove"),] # for details
#-------creating results folder for hays data------------
if(!dir.exists("./Results/hays_results")){
dir.create("./Results/hays_results/")
}
if(!dir.exists("./Results/hays_results/skewness_results")){
dir.create("./Results/hays_results/skewness_results/")
}
```
<!-- preparing hays spatial average data in usual format for common+pseudo sp.-->
```{r prepare_hays_spaceavg,results="hide",echo=F,cache=T, cache.extra=list(seed,cover,spinfo,quad_grazing,nonplant)}
# later add results="hide" , echo=F in chunk header
set.seed(seed)
library(stringr)
py<-(cover$plotyear)
plots<-str_sub(string = py,start=1,end=str_length(py)-2) #extracting only plot no.
yrs<-str_sub(string = py,start=-2) #extracting last 2digit of an year
cover<-cbind(plot=plots,yr=as.numeric(yrs),cover)
uyr<-sort(unique(cover$yr)) # 41 unique years
uplot<-sort(unique(cover$plot)) # 51 unique quadrats
uplot<-as.character(uplot)
splist<-sort(unique(cover$species))
splist<-as.character(splist)
# check with raw data:
spcount<-as.data.frame(table(cover$species))
checkcount<-(spinfo$count==spcount$Freq)
all(checkcount=T) #These should be true
#sink("./Results/hays_results/hays_myquadsamplinginfo.txt", append=TRUE, split=TRUE)
hays_array<-array(Inf,dim=c(length(uyr),length(uplot),length(splist)),dimnames = list(uyr,uplot,splist))
for(iyr in 1:length(uyr)){
tempo<-subset(cover,cover$yr==uyr[iyr])
for(iplot in 1:length(uplot)){
tempo2<-subset(tempo,tempo$plot==uplot[iplot])
if(nrow(tempo2)==0){
cat("iyr = ",iyr, " Year : ",uyr[iyr], "iplot = ",iplot," plot : ",uplot[iplot],"Not surveyed : --NA--","\n")
hays_array[iyr,iplot,]<-NA # NA means this plot is not surveyed in that given year : so all species should get NA as basal cover
}else{
z<-split( tempo2 , f = tempo2$species ) # This will split the data tempo2 by its species levels (which is a factor)
for(isp in 1:length(z)){
cs<-sum(z[[isp]]$area) # if cs=0 that means that sp. is absent for that plot and for that given year
# it will sum over the area of a particular sp. taken from all ID in a quadrat
hays_array[iyr,iplot,isp]<-cs
}
}
}
}
#check with prepared data
# check1 : Total basal cover reported for any specific year from 1 sq. meter quadrat should be ~10000 cm^2
check_matcover<-apply(hays_array,FUN=sum,MARGIN=c(1,2),na.rm=T)
check_matcover[check_matcover==0]<-NA
# This check_matcover matrix contains entries either NA for plots not surveyed or 9999...value ~10000 cm^2
range(check_matcover,na.rm=T)
#hist(check_matcover,ylim=c(0,5),col="grey",breaks=100) # check with plot
#sink()
#It's a check : There should not be all zeros for all sp on any plot-year combination
s<-apply(hays_array,FUN = sum,MARGIN = c(1,2)) #This matrix should contain either NA or some +ve number
any(s==0,na.rm = T) #There should not be any zeros
saveRDS(hays_array,"./Results/hays_results/hays_array_41yr_51plot_151sp.RDS")
# Now calculate average basal cover over all plots (except 15 grazed) for any given year for all species
avg_cover_over_plots_hays<-matrix(Inf,nrow=length(uyr),ncol=length(splist))
rownames(avg_cover_over_plots_hays)<-c(1932:1972)
colnames(avg_cover_over_plots_hays)<-splist
avg_cover_over_plots_hays<-as.data.frame(avg_cover_over_plots_hays)
#check2:
#from raw data
plotsurveyed<-rowSums(!is.na(quadsamp))-1
#from prepared data
isp<-1 # This should be same for any species
numplot_surveyed_by_year<-apply(hays_array[,,isp], MARGIN = 1, function(x){sum(is.finite(x))})
all((plotsurveyed==numplot_surveyed_by_year)==T) #They are same.
for(isp in c(1:length(splist))){
m<-hays_array[,,isp]
id_grz<-which(colnames(m)%in%quad_grazing)
m<-m[,-id_grz] #these grazed plots should be excluded
idNA<-which(apply(m, 1, function(x) all(is.na(x)))) #This should be empty : means should not be all NA's along any row
if(length(idNA)==0){
cs<-apply(m,FUN = mean,MARGIN = 1,na.rm=T)
avg_cover_over_plots_hays[,isp]<-cs
}else{
cat("Caution : This means for a given year not any plot was surveyed!!!")
}
}
anyNA(avg_cover_over_plots_hays) #This should be FALSE
#---------saving a big matrix 41yrs by 151 sp. which has each sp (including non-plant) timeseries along each column : hays data------
saveRDS(avg_cover_over_plots_hays,"./Results/hays_results/timeseries_matrix_spatialavg_allsp_hays.RDS")
# Now screen the species for hays
count0<-apply(avg_cover_over_plots_hays,2,function(x){sum(x==0)}) # This is the count of zero
count0_allsp<-as.data.frame(count0)
id_nonplant<-which(colnames(avg_cover_over_plots_hays)%in%nonplant)
id_common_sp_hays<-which(count0_allsp$count0<=6) # sp. present for atleast 35 yrs
id_common_sp_hays<-setdiff(id_common_sp_hays,id_nonplant)
id_rare_sp_hays<-which(count0_allsp$count0>=39) # sp. present max. for 2 yrs
id_rare_sp_hays<-setdiff(id_rare_sp_hays,id_nonplant)
id_interm_sp_hays<-which(count0_allsp$count0<39 & count0_allsp>6)
id_interm_sp_hays<-setdiff(id_interm_sp_hays,id_nonplant)
# check
tot_sp_hays<-length(id_common_sp_hays)+length(id_interm_sp_hays)+length(id_rare_sp_hays)+length(id_nonplant)
tot_sp_hays==151
sp_category_hays<-as.data.frame(matrix(NA,nrow=length(splist),ncol=3))
colnames(sp_category_hays)<-c("id","sp","category")
sp_category_hays$id<-c(1:length(splist))
sp_category_hays$sp<-splist
sp_category_hays$category[id_common_sp_hays]<-"C" #common sp. for Hays data
sp_category_hays$category[id_interm_sp_hays]<-"I" # Intermediate sp. for Hays data
sp_category_hays$category[id_rare_sp_hays]<-"R" # rare sp. for Hays data
#---------saving a 151sp by 2 matrix indicating C/I/R category for each hays-sp (for non-plant = NA)---------
saveRDS(sp_category_hays,"./Results/hays_results/all_sp_category_spatialavg_hays.RDS")
# Now make hays_spaceavg data in your format
hays_spaceavg<-vector("list",1)
names(hays_spaceavg)<-"avg.basal.cover"
sp.screened.data<-vector("list",length(id_common_sp_hays))
names(sp.screened.data)<-splist[id_common_sp_hays]
for(isp in 1:length(id_common_sp_hays)){
sp.screened.data[[isp]]<-data.frame(Year=c(1932:1972),Dat=avg_cover_over_plots_hays[,id_common_sp_hays[isp]])
}
hays_spaceavg$avg.basal.cover<-sp.screened.data
# Append the pseudo species = merged sp. of I & R category
pseudo_hays_IR<-apply(X=avg_cover_over_plots_hays[,which(sp_category_hays$category%in%c("I","R"))],MARGIN = 1,FUN = sum)
pseudo_hays<-data.frame(Year=c(1932:1972),Dat=pseudo_hays_IR)
pseudo_hays<-list(pseudo_hays)
hays_spaceavg$avg.basal.cover<-append(hays_spaceavg$avg.basal.cover,pseudo_hays)
names(hays_spaceavg$avg.basal.cover)[[length(id_common_sp_hays)+1]]<-"pseudo_hays"
#---------saving the spatial avg. data for hays with whigh we will do taildep. analysis later----------------
saveRDS(hays_spaceavg,"./Results/hays_results/hays_spaceavg_data_CP.RDS")
#-----------saving a matrix with timeseries of common + 1 pseudo (all other merged into 1) sp. for hays------
ts_mat_CP_hays<-cbind(avg_cover_over_plots_hays[,id_common_sp_hays],pseudo_hays_IR)
saveRDS(ts_mat_CP_hays,"./Results/hays_results/skewness_results/ts_mat_CP_hays.RDS")
#------------------------- plot total timeseries for hays data ------------------------------------------------
pdf("./Results/hays_results/skewness_results/total_timeseries.pdf",height=6,width=6)
op<-par(mar=c(5.1, 5.1, 1.1, 2.1))
total_ts_C<-apply(X=avg_cover_over_plots_hays[,id_common_sp_hays],MARGIN = 1,FUN = sum)
total_ts_CI<-apply(X=avg_cover_over_plots_hays[,sort(c(id_common_sp_hays,id_interm_sp_hays))],MARGIN = 1,FUN = sum)
total_ts_CIR<-apply(X=avg_cover_over_plots_hays[,sort(c(id_common_sp_hays,id_interm_sp_hays,id_rare_sp_hays))],MARGIN = 1,FUN = sum)
total_ts<-cbind(total_ts_C,total_ts_CI,total_ts_CIR)
plot(c(1932:1972),total_ts[,1],ylim=c(range(total_ts)[1],10000),col=rgb(1,0,0,0.5),type="b",pch=16,xlab="Years",ylab=expression("Total basal cover, cm"^2),xlim=c(1932,1972),cex.lab=2,cex.axis=2)
lines(c(1932:1972),total_ts[,2],type="b",pch=16,col=rgb(0,1,0,0.5))
lines(c(1932:1972),total_ts[,3],type="b",col="black",pch=1)
legend("topright",c("common sp.","common + intermediate sp.","all sp. including rare"),lty=c(1,1,1),
col=c(rgb(1,0,0,0.5),rgb(0,1,0,0.5),"black"),pch=c(16,16,1),bty="n",cex=1.2)
par(op)
dev.off()
#------plot hays_spaceavg data for all screened sp for all yearspan-------------------------------
pdf("./Results/hays_results/hays_spaceavg_screenedsp_avgcover.pdf",height = 21,width=21)
op<-par(mfrow=c(6,5),mar=c(5,3,3,3))
for (i in c(1:length(hays_spaceavg$avg.basal.cover))){
plot(hays_spaceavg$avg.basal.cover[[i]]$Year,hays_spaceavg$avg.basal.cover[[i]]$Dat,col=rgb(0,0,1,0.3),pch=19,type="b",
ylim=c(0,max(hays_spaceavg$avg.basal.cover[[i]]$Dat,na.rm=T)),xlab="Year (1932-1972)")
abline(h=0)
n0<-sum(hays_spaceavg$avg.basal.cover[[i]]$Dat==0)
mtext(paste0("sp = ",i," : ",names(hays_spaceavg$avg.basal.cover)[i],", n0=",n0,sep=""))
}
par(op)
dev.off()
# ---------------------generate copula plots for all selected splist_hays_spaceavg--------------------
source("./vivj_matrix.R")
include_indep<-FALSE
good_sp<-c(1:length(hays_spaceavg[[1]]))
lensp<-length(good_sp)
pdf("./Results/hays_results/copula_hays_spaceavg.pdf",height=2*lensp,width = 2*lensp)
op<-par(mfrow=c(lensp,lensp),mar=c(3,3,3,3), mgp=c(1.5,0.5,0))
for(i in c(1:lensp)){
for(j in c(1:lensp)){
vivj_matrix(d_allsp=hays_spaceavg,loc=1,
i=good_sp[i],j=good_sp[j],level=0.05,
ploton=T,onbounds=T,lb=0,ub=0.5,include_indep=include_indep)
}
}
par(op)
dev.off()
```
<!-- non-parametric analysis for cor stat with common + pseudo sp. in hays-->
```{r npa_hays_spaceavg, echo=F, cache=T, cache.extra=list(seed,hays_spaceavg,mtime("NonParamStat.R"),mtime("vivj_matrix.R"),mtime("CopulaFunctions.R"), mtime("CopulaFunctions_flexible.R"))}
set.seed(seed)
source("./NonParamStat.R")
if(!dir.exists("./Results/hays_results/corstat_hays_spaceavg_results")){
dir.create("./Results/hays_results/corstat_hays_spaceavg_results")
}
resloc<-"./Results/hays_results/corstat_hays_spaceavg_results/"
nbin_hays<-2
include_indep<-FALSE
corstat_hays_spaceavg<-multcall(d_allsp=hays_spaceavg,
loc=1,
resloc=resloc,
good_sp=c(1:length(hays_spaceavg[[1]])),
nbin=nbin_hays,include_indep=include_indep)
saveRDS(corstat_hays_spaceavg,paste(resloc,file="corstat_hays_spaceavg_nbin_",nbin_hays,".RDS",sep=''))
```
<!-- genarating Corl - Coru plots from non-parametric analysis with common + pseudo sp. in hays-->
```{r plot_res_hays_npa_spaceavg, echo=F, results="hide",cache=T,warning=F, cache.extra=list(seed,hays_spaceavg,corstat_hays_spaceavg,nbin_hays,mtime("NonParamStat_matrixplot.R"),mtime("mycorrplot_with_sig.R"),mtime("tailsignif.R"),mtime("CopulaFunctions_flexible.R"))}
set.seed(seed)
source("./NonParamStat_matrixplot.R")
resloc<-"./Results/hays_results/corstat_hays_spaceavg_results/"
ub<-1/nbin_hays
numpts<-length(hays_spaceavg$avg.basal.cover[[1]]$Year) #for hays data 41years
numsims<-10000
CI<-c(0.025,0.975)
sigtest<-FALSE
include_indep<-FALSE
CorlmCoru_hays_spaceavg<-NonParamStat_matrixplot(data=corstat_hays_spaceavg,resloc=resloc,tagon=T,
type="lower",wd=13,ht=13,
sigtest=sigtest,ub=ub,numpts=numpts,
numsims=numsims,CI=CI,include_indep=include_indep)
saveRDS(CorlmCoru_hays_spaceavg,paste(resloc,file="CorlmCoru_hays_spaceavg_nbin_",nbin_hays,".RDS",sep=''))
```
```{r binom_sigtest_hays, echo=F}
# only run this chunk if sigtest=TRUE in previous chunks
#source("./binomial_sigtest.R")
# set.seed(seed=101) # not needed as binom test uses two-sided binom.test function
# also it does not matter here binom_sig="LT" or binom_sig="UT"
#sigtest_hays<-binomial_sigtest(ylist=CorlmCoru_hays_spaceavg,binom_sig="LT")
```
<!--get appropriate surrogates for hays with common+pseudo sp.-->
```{r make_surrogs_CP_hays, echo=F, results="hide", warning=F, cache=T, cache.extra=list(ts_mat_CP_hays,mtime("PPSurrogObjFun.R"),mtime("pwlin.R"),mtime("getmap.R"),mtime("alignranks.R"),mtime("SurrogsForHays.R"))}
source("SurrogsForHays.R")
#after this script runs the surrogates will be in the variable surrogs_CP_hays
# and saved as ./Results/hays_results/skewness_results/pp_surrogs_hays_CP/HaysSurrogates.RDS
```
<!-- genarating stability based results and plots for hays-->
```{r skewness_hays_spaceavg_PP, echo=F, results="hide", warning=F, cache=T, cache.extra=list(seed,ts_mat_CP_hays,surrogs_CP_hays,mtime("make_tab_stability_assessment.R"),mtime("mycvsq.R"),mtime("SkewnessAnd3CentMom.R"))}
set.seed(seed)
source("make_tab_stability_assessment.R")
# randomly sample numsurrog surrogate matrices from Pearson preserving array
numsurrog<-10000
id_surrogs<-sample(c(1:dim(surrogs_CP_hays)[3]),numsurrog,replace=F)
surrogs_CP_hays_sampled<-surrogs_CP_hays[,,id_surrogs]
stability_CP_hays<-make_tab_stability(m=ts_mat_CP_hays,surrogs = surrogs_CP_hays_sampled, surrogs_given = T)
saveRDS(stability_CP_hays,"./Results/hays_results/skewness_results/stability_CP_hays.RDS")
ans<-(stability_CP_hays$df_stability)
rownames(ans)<-"C+P"
class(ans)
write.csv(ans,"./Results/hays_results/skewness_results/hays_stability_CP.csv")
#--------------generate plots with hays stability results : CVsq and skewness-------------------------------
pdf("./Results/hays_results/skewness_results/hays_pearson_preserving_results_cvsq_skw_plots.pdf",height=2.5,width=10)
op<-par(mfrow=c(1,2),mar=c(6,5,0.2,2),mgp=c(3,1,0))
#--------------CVsq histogrm-------------------------------------
xlm<-range(ans$cvsq_real,ans$cvsq_indep,stability_CP_hays$cvsq_surrogs)
hist(stability_CP_hays$cvsq_surrogs,col="grey",border=F,breaks=100,xaxt="n",xlim=xlm,
xlab=expression(paste(CV^2," of surrogates: Hays")),main="",cex.lab=1.5)
axis(side=1, at=round(c(xlm[1],xlm[2]),3))
points(x=ans$cvsq_real,y=0,col="black",pch=20,cex=1) # actual CVsq from real data
#abline(v=ans$cvsq_real,col="black") # actual CVsq from real data
#95% quantiles
abline(v=ans$cvsq_ntd_0.025CI,col="black",lty="dotted")
abline(v=ans$cvsq_ntd_0.975CI,col="black",lty="dotted")
#50% quantiles
#CI_cvsq_50<-quantile(stability_CP_hays$cvsq_surrogs,probs=c(.25,.75))
#abline(v=CI_cvsq_50[1],col="green")
#abline(v=CI_cvsq_50[2],col="green")
# Cvsq with no tail dep.
points(x=ans$cvsq_ntd_median,y=0,col="black",pch=2,cex=1.5)
# Cvsq if indep.
abline(v=ans$cvsq_indep,col="black",lty="dashed")
#--------------skw histogrm-------------------------------------
xlm<-range(ans$skw_real,ans$skw_indep,stability_CP_hays$skw_surrogs)
hist(stability_CP_hays$skw_surrogs,col="grey",border=F,breaks=100,xaxt="n",xlim=xlm,
xlab="Skewness of surrogates: Hays",main="",cex.lab=1.5)
axis(side=1, at=round(c(xlm[1],0,xlm[2]),3))
points(x=ans$skw_real,y=0,col="black",pch=20,cex=1) # actual skw from real data
#95% quantiles
abline(v=ans$skw_ntd_0.025CI,col="black",lty="dotted")
abline(v=ans$skw_ntd_0.975CI,col="black",lty="dotted")
#50% quantiles
#CI_skw_50<-quantile(stability_CP_hays$skw_surrogs,probs=c(.25,.75))
#abline(v=CI_skw_50[1],col="green")
#abline(v=CI_skw_50[2],col="green")
# Skewness with no tail dep.
points(x=ans$skw_ntd_median,y=0,col="black",pch=2,cex=1.5)
# Skewness if indep.
abline(v=ans$skw_indep,col="black",lty="dashed")
# add legend
#legend("topright",lty=c(1,NA,2,3),pch=c(NA,1,NA,NA),
# horiz = F, bty="n",
# legend=c("real value","no Tail-dep. (median)","95%CI","Indep."))
par(op)
dev.off()
pdf("./Results/hays_results/skewness_results/legend_plot.pdf",height=0.5,width=12.5)
op<-par(mar=c(0.1,0.1,0.1,0.1),mgp=c(1,1,0))
plot.new()
legend_order <- matrix(1:4,ncol=4,byrow =F)
legend("topright",lty=c(NA,NA,3,2)[legend_order],pch=c(20,2,NA,NA)[legend_order],
bty="n", pt.cex=1.2, cex=1.2,
legend=c("actual community value (com),",expression(paste("median (nta surrogates),")),"95% CI (nta surrogates),","no interaction (ind)")[legend_order],x.intersp=0, ncol=4)
#par(op)
dev.off()
```
```{r few_checks_on_surrogs_hays, echo=F, results="hide", cache=T, cache.extra=list(seed,ts_mat_CP_hays,surrogs_CP_hays,mtime("PPsurrogs_tests.R"),mtime("get_var_ratio.R"))}
set.seed(seed)
source("./PPsurrogs_tests.R")
# randomly sample numsurrog surrogate matrices from Pearson preserving array
numsurrog<-10000
id_surrogs<-sample(c(1:dim(surrogs_CP_hays)[3]),numsurrog,replace=F)
surrogs_CP_hays_sampled<-surrogs_CP_hays[,,id_surrogs]
ans<-PPsurrogs_tests(m=ts_mat_CP_hays, surrogs=surrogs_CP_hays_sampled)
#ans<-PPsurrogs_tests(m=ts_mat_CP_hays, surrogs=surrogs_CP_hays)
saveRDS(ans,"./Results/hays_results/skewness_results/pp_surrogs_hays_CP/PPsurrogs_tests_with_HaysSurrogates.RDS")
```
```{r plotter_PPsurrogs_check_hays, echo=F, results="hide", cache=T, cache.extra=list(seed,ts_mat_CP_hays,mtime("./Results/hays_results/skewness_results/pp_surrogs_hays_CP/PPsurrogs_tests_with_HaysSurrogates.RDS"),mtime("Plotter_PPsurrogs_tests.R"))}
set.seed(seed)
source("./Plotter_PPsurrogs_tests.R")
m<-ts_mat_CP_hays
ans<-readRDS("./Results/hays_results/skewness_results/pp_surrogs_hays_CP/PPsurrogs_tests_with_HaysSurrogates.RDS")
resloc<-"./Results/hays_results/skewness_results/pp_surrogs_hays_CP/"
Plotter_PPsurrogs_tests(m=m,ans=ans,resloc=resloc,tag_legend = c("(A)","(C)","(E)"))
```
<!-- preparing spatial avg data in usual format with common+pseudo sp. for knz data-->
```{r read_and_prepare_knz_data,echo=F,results="hide",cache=T, cache.extra=list(seed,mtime("./Data/KnzData/KNZ_Data_downloaded/knb-lter-knz.69.15/PVC021.csv"),mtime("./Data/KnzData/KNZ_Data_downloaded/KFH011.csv"))}
set.seed(seed)
source("./data_cleaning_for_KNZ.R")
```
```{r screen_sp_for_knz_data,echo=F,results="hide",cache=T,cache.extra=list(seed,mtime("data_cleaning_for_KNZ.R"))}
set.seed(seed)
# knz_soiltype<-"t" # given variable for soil type in ./data_cleaning_for_KNZ.R
# the data cleaning file saves ts_all_sp_knz matrix as "./Results/knz_results/ts_all_sp_knz_soiltype_t.RDS"
#================ screening for common-intermediate-rare species category ================
ts_all_sp_knz<-readRDS(paste(resloc_knz,"ts_all_sp_knz_soiltype_",knz_soiltype,".RDS",sep=""))
# count on zero values for cover for each species
nyr_0_eachsp<-apply(ts_all_sp_knz,MARGIN = 2,FUN = function(x){sum(x==0)})
nyr_0_eachsp<-as.data.frame(nyr_0_eachsp)
# common sp. for KNZ : these sp present for atleast 35 years, i.e., absent for max 1 years
id_common_sp_knz<-which(nyr_0_eachsp$nyr_0_eachsp<=1)
ts_common_knz<-ts_all_sp_knz[,id_common_sp_knz]
# rare sp. for KNZ : absent for atleast 34 years, i.e. present max only for 2 years
id_rare_sp_knz<-which(nyr_0_eachsp$nyr_0_eachsp>=34)
ts_rare_knz<-ts_all_sp_knz[,id_rare_sp_knz]
# normal or intermediate sp. for KNZ
id_interm_sp_knz<-which(nyr_0_eachsp$nyr_0_eachsp>1 & nyr_0_eachsp$nyr_0_eachsp<34)
ts_normal_knz<-ts_all_sp_knz[,id_interm_sp_knz]
# sp. category for KNZ
sp_category_knz<-data.frame(sp=rownames(nyr_0_eachsp),category=NA)
sp_category_knz$category[id_common_sp_knz]<-"C"
sp_category_knz$category[id_interm_sp_knz]<-"I"
sp_category_knz$category[id_rare_sp_knz]<-"R"
#---------saving a 125sp by 2 matrix indicating C/I/R category for each knz-sp---------
saveRDS(sp_category_knz,paste(resloc_knz,"all_sp_category_spatialavg_knz_soiltype_",knz_soiltype,".RDS",sep=""))
#===========================Formatting data for tail-asymmetry analysis========================
# Now make the usual format for KNZ data (with common sp and all other merged into a pseudo species) to
# be used in tail-asymmetry analysis later
knz_spaceavg<-vector("list",1)
names(knz_spaceavg)<-"avg.percent.cover"
sp.screened.data<-vector("list",length(id_common_sp_knz))
names(sp.screened.data)<-rownames(nyr_0_eachsp)[id_common_sp_knz]
for(isp in 1:length(id_common_sp_knz)){
sp.screened.data[[isp]]<-data.frame(Year=c(1983:2018),Dat=ts_common_knz[,isp])
}
knz_spaceavg$avg.percent.cover<-sp.screened.data
# Append the pseudo species = merged sp. of I & R category
pseudo_knz_IR<-apply(X=ts_all_sp_knz[,which(sp_category_knz$category%in%c("I","R"))],MARGIN = 1,FUN = sum)
pseudo_knz<-data.frame(Year=c(1983:2018),Dat=pseudo_knz_IR)
pseudo_knz<-list(pseudo_knz)
knz_spaceavg$avg.percent.cover<-append(knz_spaceavg$avg.percent.cover,pseudo_knz)
names(knz_spaceavg$avg.percent.cover)[[length(id_common_sp_knz)+1]]<-"pseudo_knz"
#---------saving the spatial avg. data for knz with whigh we will do taildep. analysis later----------------
saveRDS(knz_spaceavg,paste(resloc_knz,"knz_spaceavg_data_CP_soiltype_",knz_soiltype,".RDS",sep=""))
#-----------saving a dataframe with timeseries of common + 1 pseudo (all other merged into 1) sp. for knz------
ts_CP_knz<-cbind(ts_common_knz,pseudo_knz_IR)
saveRDS(ts_CP_knz,paste(resloc_knz_skw,"ts_CP_knz_soiltype_",knz_soiltype,".RDS",sep=""))
#-------- time series plot for knz Common sp, Common + Normal(or Intermediate) sp., Common+Normal+Rare sp.----------
pdf(paste(resloc_knz_skw,"total_timeseries_soiltype_",knz_soiltype,".pdf",sep=""),height=6,width=6)
op<-par(mar=c(5.1, 5.1, 1.1, 2.1))
total_ts_C<-apply(X=ts_all_sp_knz[,id_common_sp_knz],MARGIN = 1,FUN = sum)
total_ts_CI<-apply(X=ts_all_sp_knz[,sort(c(id_common_sp_knz,id_interm_sp_knz))],MARGIN = 1,FUN = sum)
total_ts_CIR<-apply(X=ts_all_sp_knz[,sort(c(id_common_sp_knz,id_interm_sp_knz,id_rare_sp_knz))],MARGIN = 1,FUN = sum)
total_ts<-cbind(total_ts_C,total_ts_CI,total_ts_CIR)
plot(c(1983:2018),total_ts[,1],ylim=range(total_ts),col=rgb(1,0,0,0.5),type="b",pch=16,xlab="Years",ylab="Total percent cover",xlim=c(1983,2018),cex.lab=2,cex.axis=2)
lines(c(1983:2018),total_ts[,2],type="b",pch=16,col=rgb(0,1,0,0.5))
lines(c(1983:2018),total_ts[,3],type="b",col="black",pch=1)
legend("topright",c("common sp.","common + intermediate sp.","all sp. including rare"),lty=c(1,1,1),
col=c(rgb(1,0,0,0.5),rgb(0,1,0,0.5),"black"),pch=c(16,16,1),bty="n",cex=1.2)
par(op)
dev.off()
#------plot knz_spaceavg data for all common sp for all yearspan-------------------------------
good_sp<-c(1:length(knz_spaceavg[[1]]))
lensp<-length(good_sp)
summary_knz_commonsp<-data.frame(sp=names(knz_spaceavg$avg.percent.cover),n0=NA,nTies=NA)
pdf(paste(resloc_knz,"rawplot_knz_spaceavg_commonsp_with_pseudosp_avgcover_soiltype_",knz_soiltype,".pdf",sep=""),height = 0.5*lensp,width=0.5*lensp)
op<-par(mfrow=c(6,5),mar=c(5,5,3,3))
for (i in good_sp){
n0<-sum(knz_spaceavg$avg.percent.cover[[i]]$Dat==0)
nTies<-sum(duplicated(knz_spaceavg$avg.percent.cover[[i]]$Dat)==T)
summary_knz_commonsp$n0[i]<-n0
summary_knz_commonsp$nTies[i]<-nTies
if(n0==0){
col1<-rgb(1,0,0,0.3) # these are the sp. present for all years
}else{
col1<-rgb(0,0,1,0.3)
}
plot(knz_spaceavg$avg.percent.cover[[i]]$Year,knz_spaceavg$avg.percent.cover[[i]]$Dat,col=col1,pch=19,
ylim=c(0,max(knz_spaceavg$avg.percent.cover[[i]]$Dat)),xlab="Year (1983-2018)",type="b",ylab="avg. % cover")
abline(h=0)
mtext(paste0("sp = ",i," : ",names(knz_spaceavg$avg.percent.cover)[i]," ,nT=",nTies,sep=""))
}
par(op)
dev.off()
# ---------------------generate copula plots for all common sp for knz_spaceavg--------------------
source("./vivj_matrix.R")
include_indep<-FALSE
pdf(paste(resloc_knz,"copulaplot_knz_spaceavg_commonsp_with_pseudosp_avgcover_soiltype_",knz_soiltype,".pdf",sep=""),height=2*lensp,width = 2*lensp)
op<-par(mfrow=c(lensp,lensp),mar=c(3,3,3,3), mgp=c(1.5,0.5,0))
for(i in c(1:lensp)){
for(j in c(1:lensp)){
vivj_matrix(d_allsp=knz_spaceavg,loc=1,
i=good_sp[i],j=good_sp[j],level=0.05,
ploton=T,onbounds=T,lb=0,ub=0.5,include_indep=include_indep)
}
}
par(op)
dev.off()
```
<!-- non-parametric analysis for cor stat with common + pseudo sp. in knz-->
```{r npa_knz_spaceavg, echo=F, cache=T, cache.extra=list(seed,knz_spaceavg,mtime("NonParamStat.R"),mtime("vivj_matrix.R"),mtime("CopulaFunctions.R"), mtime("CopulaFunctions_flexible.R"))}
set.seed(seed)
source("./NonParamStat.R")
resloc_knz_npa<-paste(resloc_knz,"corstat_knz_spaceavg_results/",sep="")
if(!dir.exists(resloc_knz_npa)){
dir.create(resloc_knz_npa)
}
resloc2<-paste(resloc_knz_npa,"soiltype_",knz_soiltype,"/",sep="")
if(!dir.exists(resloc2)){
dir.create(resloc2)
}
resloc<-resloc2
nbin_knz<-2
include_indep<-FALSE
corstat_knz_spaceavg<-multcall(d_allsp=knz_spaceavg,
loc=1,
resloc=resloc,
good_sp=c(1:length(knz_spaceavg[[1]])),
nbin=nbin_knz,include_indep=include_indep)
saveRDS(corstat_knz_spaceavg,paste(resloc,file="corstat_knz_spaceavg_nbin_",nbin_knz,".RDS",sep=''))
```
<!-- genarating Corl - Coru plots from non-parametric analysis with common + pseudo sp. in knz-->
```{r plot_res_knz_npa_spaceavg, echo=F, results="hide",cache=T,warning=F, cache.extra=list(seed,knz_spaceavg,resloc2,corstat_knz_spaceavg,nbin_knz,mtime("NonParamStat_matrixplot.R"),mtime("mycorrplot_with_sig.R"),mtime("tailsignif.R"),mtime("CopulaFunctions_flexible.R"))}
set.seed(seed)
source("./NonParamStat_matrixplot.R")
resloc<-resloc2
ub<-1/nbin_knz
numpts<-length(knz_spaceavg$avg.percent.cover[[1]]$Year) #for knz data 33years
numsims<-10000
CI<-c(0.025,0.975)
sigtest<-FALSE
include_indep<-FALSE
CorlmCoru_knz_spaceavg<-NonParamStat_matrixplot(data=corstat_knz_spaceavg,
resloc=resloc,tagon=T,
type="lower",wd=15,ht=15,
sigtest=sigtest,ub=ub,numpts=numpts,numsims=numsims,CI=CI,
include_indep=include_indep)
saveRDS(CorlmCoru_knz_spaceavg,paste(resloc,file="CorlmCoru_knz_spaceavg_nbin_",nbin_knz,".RDS",sep=''))
```
```{r binom_sigtest_knz, echo=F}
# only run this chunk if sigtest=TRUE in previous chunks
#source("./binomial_sigtest.R")
# set.seed(seed=101) # not needed as binom test uses two-sided binom.test function
# also it does not matter here binom_sig="LT" or binom_sig="UT"
#sigtest_knz<-binomial_sigtest(ylist=CorlmCoru_knz_spaceavg,binom_sig="LT")
```
```{r read knz_data_soiltype_t, echo=F}
#do not cache
ts_mat_CP_knz<-readRDS("./Results/knz_results/skewness_results/ts_CP_knz_soiltype_t.RDS")
```
<!--get appropriate surrogates for knz with common+pseudo sp.-->
```{r make_surrogs_CP_knz_t, echo=F, results="hide", warning=F, cache=T,cache.extra=list(ts_mat_CP_knz,mtime("PPSurrogObjFun.R"),mtime("pwlin.R"),mtime("getmap.R"),mtime("alignranks.R"),mtime("SurrogsForKonza_t.R"))}
source("./SurrogsForKonza_t.R")
#after this script runs the surrogates will be in the variable surrogs_CP_KNZ_t
```
<!-- genarating stability based results and plots for knz-->
```{r skewness_knz_spaceavg_PP, echo=F, results="hide", warning=F, cache=T, cache.extra=list(seed,surrogs_CP_KNZ_t,ts_mat_CP_knz,mtime("make_tab_stability_assessment.R"),mtime("mycvsq.R"),mtime("SkewnessAnd3CentMom.R"))}
set.seed(seed)
source("make_tab_stability_assessment.R")
surrogs_CP_knz<-surrogs_CP_KNZ_t # available from SurrogsForKonza_t.R file
# randomly sample numsurrog surrogate matrices from Pearson preserving array
numsurrog<-10000
id_surrogs<-sample(c(1:dim(surrogs_CP_knz)[3]),numsurrog,replace=F)
surrogs_CP_knz_sampled<-surrogs_CP_knz[,,id_surrogs]
stability_CP_knz<-make_tab_stability(m=ts_mat_CP_knz,surrogs = surrogs_CP_knz_sampled, surrogs_given = T)
saveRDS(stability_CP_knz,"./Results/knz_results/skewness_results/stability_CP_knz.RDS")
ans<-(stability_CP_knz$df_stability)
rownames(ans)<-"C+P"
class(ans)
write.csv(ans,"./Results/knz_results/skewness_results/knz_stability_CP.csv")
#--------------generate plots with knz stability results : CVsq and skewness-------------------------------
pdf("./Results/knz_results/skewness_results/knz_pearson_preserving_results_cvsq_skw_plots.pdf",height=2.5,width=10)
op<-par(mfrow=c(1,2),mar=c(6,5,0.2,2),mgp=c(3,1,0))
#--------------CVsq histogrm-------------------------------------
xlm<-range(ans$cvsq_real,ans$cvsq_indep,stability_CP_knz$cvsq_surrogs)
hist(stability_CP_knz$cvsq_surrogs,col="grey",border=F,breaks=100,xaxt="n",xlim=xlm,
xlab=expression(paste(CV^2," of surrogates: Konza")),main="",cex.lab=1.5)
axis(side=1, at=round(c(xlm[1],xlm[2]),3))
points(x=ans$cvsq_real,y=0,col="black",pch=20,cex=1) # actual CVsq from real data
#abline(v=ans$cvsq_real,col="black") # actual CVsq from real data
#95% quantiles
abline(v=ans$cvsq_ntd_0.025CI,col="black",lty="dotted")
abline(v=ans$cvsq_ntd_0.975CI,col="black",lty="dotted")
#50% quantiles
#CI_cvsq_50<-quantile(stability_CP_knz$cvsq_surrogs,probs=c(.25,.75))
#abline(v=CI_cvsq_50[1],col="green")
#abline(v=CI_cvsq_50[2],col="green")
# Cvsq with no tail dep.
points(x=ans$cvsq_ntd_median,y=0,col="black",pch=2,cex=1.5)
# Cvsq if indep.
abline(v=ans$cvsq_indep,col="black",lty="dashed")
#--------------skw histogrm-------------------------------------
xlm<-range(ans$skw_real,ans$skw_indep,stability_CP_knz$skw_surrogs)
hist(stability_CP_knz$skw_surrogs,col="grey",border=F,breaks=100,xaxt="n",xlim=xlm,
xlab="Skewness of surrogates: Konza",main="",cex.lab=1.5)
axis(side=1, at=round(c(xlm[1],0,xlm[2]),3))
points(x=ans$skw_real,y=0,col="black",pch=20,cex=1) # actual skw from real data
#abline(v=ans$skw_real,col="black") # actual skw from real data
#95% quantiles
abline(v=ans$skw_ntd_0.025CI,col="black",lty="dotted")
abline(v=ans$skw_ntd_0.975CI,col="black",lty="dotted")
#50% quantiles
#CI_skw_50<-quantile(stability_CP_knz$skw_surrogs,probs=c(.25,.75))
#abline(v=CI_skw_50[1],col="green")
#abline(v=CI_skw_50[2],col="green")
# Skewness with no tail dep.
points(x=ans$skw_ntd_median,y=0,col="black",pch=2,cex=1.5)
# Skewness if indep.
abline(v=ans$skw_indep,col="black",lty="dashed")
# add legend
#legend("topright",lty=c(1,NA,2,3),pch=c(NA,1,NA,NA),
# horiz = F, bty="n",
# legend=c("real value","no Tail-dep. (median)","95%CI","Indep."))
par(op)
dev.off()
pdf("./Results/knz_results/skewness_results/legend_plot.pdf",height=0.5,width=12.5)
op<-par(mar=c(0.1,0.1,0.1,0.1),mgp=c(1,1,0))
plot.new()
legend_order <- matrix(1:4,ncol=4,byrow =F)
legend("topright",lty=c(NA,NA,3,2)[legend_order],pch=c(20,2,NA,NA)[legend_order],
bty="n", pt.cex=1.2, cex=1.2,
legend=c("actual community value (com),",expression(paste("median (nta surrogates),")),"95% CI (nta surrogates),","no interaction (ind)")[legend_order],x.intersp=0, ncol=4)
#par(op)
dev.off()
```
```{r few_checks_on_surrogs_knz, echo=F, results="hide", cache=T, cache.extra=list(seed,ts_mat_CP_knz,surrogs_CP_KNZ_t,mtime("PPsurrogs_tests.R"),mtime("get_var_ratio.R"))}
set.seed(seed)
source("./PPsurrogs_tests.R")
# randomly sample numsurrog surrogate matrices from Pearson preserving array
numsurrog<-10000
id_surrogs<-sample(c(1:dim(surrogs_CP_KNZ_t)[3]),numsurrog,replace=F)
surrogs_CP_KNZ_t_sampled<-surrogs_CP_KNZ_t[,,id_surrogs]
ans<-PPsurrogs_tests(m=ts_mat_CP_knz, surrogs=surrogs_CP_KNZ_t_sampled)
#ans<-PPsurrogs_tests(m=ts_mat_CP_knz, surrogs=surrogs_CP_KNZ_t)
saveRDS(ans,"./Results/knz_results/skewness_results/pp_surrogs_knz_t_CP/PPsurrogs_tests_with_KNZtSurrogates.RDS")
```
```{r plotter_PPsurrogs_check_knz, echo=F, results="hide", cache=T, cache.extra=list(seed,ts_mat_CP_knz,mtime("./Results/knz_results/skewness_results/pp_surrogs_knz_t_CP/PPsurrogs_tests_with_KNZtSurrogates.RDS"),mtime("Plotter_PPsurrogs_tests.R"))}
set.seed(seed)
source("./Plotter_PPsurrogs_tests.R")
m<-ts_mat_CP_knz
ans<-readRDS("./Results/knz_results/skewness_results/pp_surrogs_knz_t_CP/PPsurrogs_tests_with_KNZtSurrogates.RDS")
resloc<-"./Results/knz_results/skewness_results/pp_surrogs_knz_t_CP/"
Plotter_PPsurrogs_tests(m=m,ans=ans,resloc=resloc,tag_legend = c("(B)","(D)","(F)"))
```
```{r for_Kathy, echo=F, results="hide"}
# Writing csv file without rownames is needed, so we place the first column with the year as in csv
# NOTE: ts_mat_cp_hays in RDS format only has species time series along column as it has rownames as years
# but in csv file I am creating an extra first column as "Year" as rownames for reading/writing in csv file
# often creates column without any name
#------------ for Hays --------------------
ts_mat_CP_hays<-readRDS("./Results/hays_results/skewness_results/ts_mat_CP_hays.RDS")
Year_hays<-rownames(ts_mat_CP_hays)
ts_mat_CP_hays_for_Kathy<-cbind(Year=Year_hays,ts_mat_CP_hays)
row.names(ts_mat_CP_hays_for_Kathy)<-NULL
write.csv(ts_mat_CP_hays_for_Kathy,"./Results/hays_results/skewness_results/ts_mat_CP_hays_for_Kathy.csv",row.names = F)
# Now getting total species timeseries for Kathy
xtot_hays<-apply(ts_mat_CP_hays,MARGIN=1,FUN=sum)
xtot_hays<-cbind(Year=Year_hays,x_tot=xtot_hays)
write.csv(xtot_hays,"./Results/hays_results/skewness_results/xtotal_hays_for_Kathy.csv",row.names = F)
#-------- for KNZ ---------------
ts_mat_CP_knz<-readRDS("./Results/knz_results/skewness_results/ts_CP_knz_soiltype_t.RDS")
Year_knz<-rownames(ts_mat_CP_knz)
Year_knz<-substr(Year_knz,6,9)
ts_mat_CP_knz_for_Kathy<-cbind(Year=Year_knz,ts_mat_CP_knz)
row.names(ts_mat_CP_knz_for_Kathy)<-NULL
write.csv(ts_mat_CP_knz_for_Kathy,"./Results/knz_results/skewness_results/ts_mat_CP_knz_for_Kathy.csv",row.names = F)
# Now getting total species timeseries for Kathy
xtot_knz<-apply(ts_mat_CP_knz,MARGIN=1,FUN=sum)
xtot_knz<-cbind(Year=Year_knz,x_tot=xtot_knz)
write.csv(xtot_knz,"./Results/knz_results/skewness_results/xtotal_knz_for_Kathy.csv",row.names = F)
```
```{r for_skew_fig, echo=F, results="hide", cache=T, cache.extra=list(mtime("./Results/hays_results/skewness_results/ts_mat_CP_hays.RDS"),mtime("./Results/knz_results/skewness_results/ts_CP_knz_soiltype_t.RDS"),mtime("./Results/hays_results/skewness_results/pp_surrogs_hays_CP/HaysSurrogates.RDS"),mtime("./Results/knz_results/skewness_results/pp_surrogs_knz_t_CP/KNZtSurrogates.RDS"))}
#Here I generate a figure that shows the following:
#1. The histogram for the total-abundance time series for Hays
#2. The histogram for the total-abundance time series for a “typical” no-tail-association surrogate for Hays
#(one single surrogate, but a typical one – I’ll have to find one that has a skewness about equal to the median
#value and use that one)
#3. The same two histograms for Konza
#Variables (created above) that will be used:
#ts_mat_CP_hays: this is the matrix for Hays, each column is a species, aggregated pseudo-species in the last
#column, and row names equal to year. See the chunk "for_Kathy".
#ts_mat_CP_knz: Same for Konza. See the chunk "for_Kathy".
#surrogs_CP_hays: Pearson preserving surrogates for Hays, created in the r chunk named "make_surrogs_CP_hays"
#surrogs_CP_KNZ_t: same for Konza, created in the r chunk named "make_surrogs_CP_knz_t"
#In fact, the above variables are read in from where they were previously saved - makes these codes runnable
#separately from the chunk structure of this doc, to be commented after debugging
ts_mat_CP_hays<- readRDS("./Results/hays_results/skewness_results/ts_mat_CP_hays.RDS")
ts_mat_CP_knz<-readRDS("./Results/knz_results/skewness_results/ts_CP_knz_soiltype_t.RDS")
surrogs_CP_hays<-readRDS("./Results/hays_results/skewness_results/pp_surrogs_hays_CP/HaysSurrogates.RDS")
surrogs_CP_KNZ_t<-readRDS( "./Results/knz_results/skewness_results/pp_surrogs_knz_t_CP/KNZtSurrogates.RDS" )
#***plot dimensions, units inches
xmarht<-.5
ymarnumwd<-.25
ymarlabwd<-.25
ymarwd<-ymarnumwd+ymarlabwd
totwd<-6
gap<-0.2 #general purpose gap, aside from the below purposes
panwd<-(totwd-ymarwd-ymarnumwd-gap)/2
panht<-panwd/2
totht<-2*xmarht+3*panht+2*gap
pdf(file="./Results/EmpiricalParallelOfFig1.pdf",width=totwd,height=totht)
#make historgram of total abundance of Hays
tot_hays<-unname(apply(FUN=sum,MARGIN=1,X=as.matrix(ts_mat_CP_hays)))
par(fig=c((ymarwd)/totwd,
(ymarwd+panwd)/totwd,
(xmarht+panht+gap)/totht,
(xmarht+2*panht+gap)/totht),
mai=c(0,0,0,0),mgp=c(3,.15,0),tcl=-.25)
haysbreaks<-seq(from=2000,to=9000,by=1000)
h<-hist(tot_hays,main="",breaks=haysbreaks)
rug(tot_hays) #does not currently work in R markdown, but I hope it'll work when results are exported to a pdf instead
mtext("Frequency",2,1.2)
text(min(haysbreaks),max(h$counts),"B",cex=1.2,adj=c(0,1))
text(max(haysbreaks),.7*max(h$counts),paste0("sk=",round(myskns(tot_hays),3)),cex=.8,adj=c(1,1))
#calculate skewnesses of the totals of first 1000 surrogates, find the index of a close-to-median value
tot_hays_surrs<-apply(FUN=sum,MARGIN=c(1,3),X=surrogs_CP_hays[,,1:1000])
tot_hays_surrs_skns<-apply(FUN=myskns,MARGIN=2,X=tot_hays_surrs)
h<-abs(tot_hays_surrs_skns-median(tot_hays_surrs_skns))
ind_hays<-which(h==min(h))
ind_hays<-ind_hays[1]
#tot_hays_surrs_skns[ind_hays]
#make histogram of total abundance of the selected Hays surrogate
tot_hays_surr<-tot_hays_surrs[,ind_hays]
par(fig=c((ymarwd)/totwd,
(ymarwd+panwd)/totwd,
(xmarht)/totht,
(xmarht+panht)/totht),
mai=c(0,0,0,0),mgp=c(3,.15,0),tcl=-.25,new=TRUE)
h<-hist(tot_hays_surr,main="",breaks=haysbreaks)
mtext("Abundance",1,1.2)
mtext("Frequency",2,1.2)
text(min(haysbreaks),max(h$counts),"C",cex=1.2,adj=c(0,1))
rug(tot_hays_surr)
text(max(haysbreaks),.7*max(h$counts),paste0("sk=",round(myskns(tot_hays_surr),3)),cex=.8,adj=c(1,1))
#plot time series for hays
yr_hays<-as.numeric(rownames(ts_mat_CP_hays))
par(fig=c((ymarwd)/totwd,
(ymarwd+panwd)/totwd,
(2*xmarht+2*panht+gap)/totht,
(2*xmarht+3*panht+gap)/totht),
mai=c(0,0,0,0),mgp=c(3,.15,0),tcl=-.25,new=TRUE)
ylimits<-range(tot_hays,tot_hays_surr)
ylimits[2]<-ylimits[2]+.25*diff(ylimits)
plot(yr_hays,tot_hays,type="l",xlab="Year",ylab="Total abundance",ylim=ylimits)
lines(yr_hays,tot_hays_surr,type="l",lty="dashed")
mtext("Year",1,1.2)
mtext("Abundance",2,1.2)
text(min(yr_hays),max(ylimits),"A",cex=1.2,adj=c(0,1))
lines(range(yr_hays),rep(7800,2),type="l",lty="dotted")
#make historgram of total abundance of Konza
tot_knz<-unname(apply(FUN=sum,MARGIN=1,X=as.matrix(ts_mat_CP_knz)))
par(fig=c((ymarwd+panwd+ymarnumwd)/totwd,
(ymarwd+2*panwd+ymarnumwd)/totwd,
(xmarht+panht+gap)/totht,
(xmarht+2*panht+gap)/totht),
mai=c(0,0,0,0),mgp=c(3,.15,0),tcl=-.25,new=TRUE)
knzbreaks<-seq(from=100,to=240,by=20)
h<-hist(tot_knz,main="",breaks=knzbreaks)
rug(tot_knz)
text(min(knzbreaks),max(h$counts),"E",cex=1.2,adj=c(0,1))
text(max(knzbreaks),.7*max(h$counts),paste0("sk=",round(myskns(tot_knz),3)),cex=.8,adj=c(1,1))
#calculate skewnesses of the totals of first 1000 surrogates, find the index of a close-to-median value
tot_knz_surrs<-apply(FUN=sum,MARGIN=c(1,3),X=surrogs_CP_KNZ_t[,,1:1000])
tot_knz_surrs_skns<-apply(FUN=myskns,MARGIN=2,X=tot_knz_surrs)
h<-abs(tot_knz_surrs_skns-median(tot_knz_surrs_skns))
h<-order(h)
#ind_knz<-which(h==min(h))
ind_knz<-h[5]
tot_knz_surrs_skns[ind_knz]
#make histogram of total abundance of the selected Konza surrogate
tot_knz_surr<-tot_knz_surrs[,ind_knz]
par(fig=c((ymarwd+panwd+ymarnumwd)/totwd,
(ymarwd+2*panwd+ymarnumwd)/totwd,
(xmarht)/totht,
(xmarht+panht)/totht),
mai=c(0,0,0,0),mgp=c(3,.15,0),tcl=-.25,new=TRUE)
h<-hist(tot_knz_surr,main="",breaks=knzbreaks)
rug(tot_knz_surr)
mtext("Abundance",1,1.2)
text(min(knzbreaks),max(h$counts),"F",cex=1.2,adj=c(0,1))
text(max(knzbreaks),.7*max(h$counts),paste0("sk=",round(myskns(tot_knz_surr),3)),cex=.8,adj=c(1,1))
#plot time series for Konza
yr_knz<-rownames(ts_mat_CP_knz)
yr_knz<-as.numeric(substr(yr_knz,6,9))
par(fig=c((ymarwd+panwd+ymarnumwd)/totwd,
(ymarwd+2*panwd+ymarnumwd)/totwd,
(2*xmarht+2*panht+gap)/totht,
(2*xmarht+3*panht+gap)/totht),
mai=c(0,0,0,0),mgp=c(3,.15,0),tcl=-.25,new=TRUE)
ylimits<-range(tot_knz,tot_knz_surr)
ylimits[2]<-ylimits[2]+.25*diff(ylimits)
plot(yr_knz,tot_knz,type="l",xlab="Year",ylab="Total abundance",ylim=ylimits)
mtext("Year",1,1.2)
lines(yr_knz,tot_knz_surr,type="l",lty="dashed")
lines(range(yr_knz),rep(125,2),type="l",lty="dotted")
text(min(yr_knz),max(ylimits),"D",cex=1.2,adj=c(0,1))
dev.off()
```
```{r pedagog_fig, echo=F, results="hide"}
set.seed(seed)
#source("./pedagog_ts.R")
#------------------------------------------------------------------
# another pedagog fig. showing LT, UT with same correlation
library(copula)
library(VineCopula)
par_rho_0.8<-copula::iRho(claytonCopula(5),rho=0.8)
ccop<-BiCopSim(200,3,par=par_rho_0.8)
sccop<-BiCopSim(200,13,par=par_rho_0.8)
#pdf("./Results/pedagog_figs/LTUT_rho_0.8.pdf",height=3,width=6)
#op<-par(mfrow=c(1,2),mar=c(3.5, 3.5, 0.1, 1.1),mgp=c(1.8,0.5,0))
#plot(ccop[,1],ccop[,2],col=rgb(0,0,0,0.1),pch=20,xlab=expression("u"[i]),ylab=expression("u"[j]),cex.lab=1.5,cex.axis=0.8,xaxs="i",yaxs="i")
#lines(c(0,0.3),c(0.3,0),type='l')
#lines(c(0,0.6),c(0.6,0),type='l')
#ind1<-which(ccop[,1]+ccop[,2]>0.3 & ccop[,1]+ccop[,2]<0.6)
#points(ccop[ind1,1],ccop[ind1,2],col=rgb(1,0,0,0.1),pch=20)
#lines(c(0,1),c(1,0),type='l',lty=2)
#lines(c(0,1.4),c(1.4,0),type='l')
#lines(c(0,1.7),c(1.7,0),type='l')
#ind1<-which(ccop[,1]+ccop[,2]>1.4 & ccop[,1]+ccop[,2]<1.7)
#points(ccop[ind1,1],ccop[ind1,2],col=rgb(0,0,1,0.1),pch=20)
#text(x=0.1,y=0.9,"(A)",cex=1.3, family="serif")
#plot(sccop[,1],sccop[,2],col=rgb(0,0,0,0.1),pch=20,xlab=expression("u"[i]),ylab=expression("u"[j]),cex.lab=1.5,cex.axis=0.8,xaxs="i",yaxs="i")
#lines(c(0,0.3),c(0.3,0),type='l')
#lines(c(0,0.6),c(0.6,0),type='l')
#ind1<-which(sccop[,1]+sccop[,2]>0.3 & sccop[,1]+sccop[,2]<0.6)
#points(sccop[ind1,1],sccop[ind1,2],col=rgb(1,0,0,0.1),pch=20)