-
Notifications
You must be signed in to change notification settings - Fork 0
/
finalComparatore.R
1158 lines (987 loc) · 48.5 KB
/
finalComparatore.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
##### REQUIREMENTS ####
library(vegan)
library(pROC)
library(rLims)
#Put path were output should be written here
prefix <- ""
while (prefix == ""){
prefix <- readline("Where should the plots be stored? (e.g. /home/moi/put_images_here/)")
}
if (substr(prefix,nchar(prefix),nchar(prefix)) != "/"){
prefix <- paste(prefix, "/", sep="")
}
prefix <- paste(prefix,"Coffee_Origin_IRvNMR_Images897/", sep="")
dir.create(prefix)
ginv<-function(X, tol = sqrt(.Machine$double.eps))
{
## Generalized Inverse of a Matrix
dnx <- dimnames(X)
if(is.null(dnx)) dnx <- vector("list", 2)
s <- svd(X)
nz <- s$d > tol * s$d[1]
structure(
if(any(nz)) s$v[, nz] %*% (t(s$u[, nz])/s$d[nz]) else X,
dimnames = dnx[2:1])
}
Deriv1 <- function(x,y){
y.prime <- diff(y) / diff(x)
x.prime <- x[-length(x)] + diff(x)/2
list(shift = x.prime,
intensity = y.prime)
}
#function for computation of second derivative
Deriv2 <- function(x,y){
h <- x[2] - x[1]
Range <- 2:(length(x)-1) # Drop first and last points
list(shift = x[Range],
intensity = (y[Range+1] - 2*y[Range] + y[Range-1]) / h^2)
}
msc <- function(spectrum, ...){
UseMethod("msc", spectrum)
}
msc.numeric <- function(spectrum, reference){
Rm <- mean(reference)
Sc <- spectrum - mean(spectrum);
Rc <- reference - Rm;
m = ginv(crossprod(Rc)) %*% crossprod(Rc, Sc);
Sc / m + Rm
}
msc.matrix <- function(spectra, reference = apply(spectra, 2, median)){
t(apply(spectra, 1, function(x) msc.numeric(x, reference = reference)));
}
integral.normalization<- function(spectra, value = 100){
t(apply(spectra, 1, function(x) (x * value) / sum(abs(x))))
}
##Function for plotting Q2_average vs. Number of components with std. dev. error bars
plot.with.error.bars <- function(x, matrix, col = "black",
ylim = range(c(apply(matrix, 2, mean) - apply(matrix, 2, sd),
apply(matrix, 2, mean) + apply(matrix, 2, sd))), ...){
avg <- apply(matrix,2,mean)
sdev <- apply(matrix,2,sd)
plot(x, avg, col = col, ylim = ylim, ...)
arrows(x, avg - sdev, x, avg + sdev, length=0.05, angle=90, code=3, col = col)
}
#Returns the indices of the top values of x that encompass the upper fraction of its total magnitude according to the given norm
upper <- function(x, fraction = 1, norm = function(x) sum(abs(x))){
ordering <- order(x, decreasing = TRUE)
n <- length(x)
total <- norm(x)
res <- c()
partial <- 0
partial.fraction <- 0
for (index in ordering){
if (partial.fraction < fraction){
res <- c(res, index)
partial = partial + x[index]
partial.fraction <- partial / total
}
else{
break;
}
}
res
}
##Environment variables to determine how to compute certain things (normalization, centering and scaling, validation, number of components)
validating <- "kfold"
valsize <- 7
nComp <- 15
nModels <- 100
normalizing <- c(integral.normalization,msc,identity)
centering <- c(FALSE,FALSE,FALSE)
scaling <- c(TRUE,TRUE,TRUE) #c(FALSE,FALSE,FALSE)
centering1<-c(TRUE,TRUE,TRUE)
scaling1<- c(TRUE,TRUE,TRUE)
model <- c(lims.opls.model, lims.pls.model, lims.opls.model)
names <- c("IR", "NIR", "NMR")
color<-c("gray60","2","4")
nfigs <- 0
### READ DATA ###
##read metadata
metadata <- read.table("./data/metadata.csv",
header=TRUE,sep="\t")[1:317,]
#Change labels to -1 = Arabica, 1 = Robusta
metadata$species1<-metadata$species
levels(metadata$species1)[1]<-"Arabica"
levels(metadata$species1)<-c("1", "-1")
#set up 4 labels for scores plot: Robusta, Arabica Colombia, Arabica Brazil (neighbor), Arabica Peru (neighbor aussi),
#Other Arabicas
#groups<-factor(metadata$species1)
metadata$groups<-metadata$country
levels(metadata$groups)[levels(metadata$groups) %in% metadata$country[metadata$species == "Robusta"]] = "Robusta"
levels(metadata$groups)[!levels(metadata$groups) %in% c("Colombia", "Peru", "Brazil","Robusta")] = "Others"
## IR
#read data
irdata <- as.matrix(read.table("./data/mIRspectra.csv",
header=FALSE,sep=" ")[1:317,])
#nu scale for spectra
dx <- 0.964233
irscale <- seq(649.893311,3999.640625,dx)
###Data preprocessing
#filter samples with spectra in absorbance units
irdata <- irdata[!metadata$ID %in% c("AC1199", "AC1242", "AC1376", "AC1380", "AC1427"),]
metadata <- metadata[!metadata$ID %in% c("AC1199", "AC1242", "AC1376", "AC1380", "AC1427"),]
#remove duplicates
irdata <- irdata[!duplicated(metadata$ID),]
metadata <- metadata[!duplicated(metadata$ID),]
#sort
irdata <- irdata[order(metadata$ID),]
metadata <- metadata[order(metadata$ID),]
#spectra second derivatives
irdata.deriv2 <- t(apply(irdata,1,function(y) Deriv2(irscale,y)$intensity))
#irdata.deriv2<-irdata
#select nus and normalize
irdata.deriv2.wavelength.optimized1 <- irdata.deriv2[,(irscale > 800 & irscale < 1800)[2:3474]]#t(scale(t(irdata.deriv2[,(irscale>800 & irscale<1800)[2:3474]])))
irscale<- irscale[irscale>800 & irscale<1800]
irdata.deriv2.wavelength.optimized1 <- normalizing[[1]](irdata.deriv2.wavelength.optimized1)
#irdata.deriv2.wavelength.optimized1 <- t(lims.scaling(t(irdata.deriv2.wavelength.optimized1), center = FALSE,
# scale = function(x) max(abs(x))))
### NIR ###
#read data
id<-as.vector(as.matrix(read.csv("./data/NIRSamples.csv")))
dataNIR<-as.matrix(read.csv("./data/NIRspectra.csv", sep=""))
nirscale<-as.vector(as.matrix(read.csv("./data/NIRscale.csv", sep="", header=FALSE)))
#metadata <- read.table("~/CoffeeIR/FT-IR_ JCAMP-DX and .SPA files/sampleMetadata.csv",
# header=TRUE,sep="\t")[1:317,]
#remove duplicates
dataNIR <- dataNIR[!duplicated(id),]
id <- id[!duplicated(id)]
#filter common samples (with IR)
filter<-which(id %in% as.vector(metadata$ID),T)
dataNIR<-dataNIR[filter,]
id <- id[filter]
#nir.metadata<-metadata[which(id.selected%in%metadata$ID,T),]
#sort
dataNIR <- dataNIR[order(id),]
id <- id[order(id)]
#compute second derivative
nirdev2<-t(apply(dataNIR,1, function(y) Deriv2(nirscale,y)$intensity))
#select nus and normalize
nirdev2<-nirdev2[,1:900] ###scale
nirdev2 <- normalizing[[2]](nirdev2)
#nirdev2 <- t(lims.scaling(t(nirdev2),center = FALSE, scale = function(x) max(abs(x))))
#scale for second derivative
nirdev2scale<-as.numeric(nirscale[2:901])
##Read NMR
load("./data/dataNMR.rda")
nmr.spectra <- res$nmrData #vaya nombre...
nmr.id <- res$param$catalogID
#Select roasted samples
nmr.spectra <- nmr.spectra[res$param$presentation == "t",]
nmr.id <- nmr.id[res$param$presentation == "t"]
#Remove duplicates
nmr.spectra <- nmr.spectra[!duplicated(nmr.id),]
nmr.id <- nmr.id[!duplicated(nmr.id)]
#Select common data (should be all in IR)
filter <- which(nmr.id %in% as.vector(metadata$ID),T)
nmr.spectra <- nmr.spectra[filter,]
nmr.id <- nmr.id[filter]
#Back-filter: restrict metadata, IR, NIR to samples that were also in NMR
irdata.deriv2.wavelength.optimized1 <- irdata.deriv2.wavelength.optimized1[metadata$ID %in% nmr.id,]
nirdev2 <- nirdev2[metadata$ID %in% nmr.id,]
metadata <- metadata[metadata$ID %in% nmr.id,]
#Sort
nmr.spectra <- nmr.spectra[order(nmr.id),]
nmr.id <- nmr.id[order(nmr.id)]
#Normalize
nmr.spectra <- normalizing[[3]](nmr.spectra)
#nmr.spectra <- t(lims.scaling(t(nmr.spectra),center=FALSE,scale=function(x) max(abs(x))))
#Remove outliers that were detected on PCA
#AC1229 is outlier for IR, the rest were outliers for NMR
#1227 AC1290 "AC1339" nmr outliers
nmr.spectra <- nmr.spectra[!metadata$ID %in% c("AC1441", "AC1431", "AC1445", "AC1414", "AC1169", "AC1403",
"AC1207", "AC1420", "AC1337", "AC1229",
"AC1227", "AC1290", "AC1339"),]
nmr.id <- nmr.id[!metadata$ID %in% c("AC1441", "AC1431", "AC1445", "AC1414", "AC1169", "AC1403",
"AC1207", "AC1420", "AC1337", "AC1229",
"AC1227", "AC1290", "AC1339")]
# ### plot outliers #####
#
# matplot(res$ppm, t(nmr.spectra[1:10,]), type="l", xlim=c(3,1), ylim=c(0,3e9))
irdata.deriv2.wavelength.optimized1 <-
irdata.deriv2.wavelength.optimized1[!metadata$ID %in% c("AC1441", "AC1431", "AC1445", "AC1414", "AC1169", "AC1403",
"AC1207", "AC1420", "AC1337", "AC1229",
"AC1227", "AC1290", "AC1339"),]
nirdev2 <- nirdev2[!metadata$ID %in% c("AC1441", "AC1431", "AC1445", "AC1414", "AC1169", "AC1403",
"AC1207", "AC1420", "AC1337", "AC1229",
"AC1227", "AC1290", "AC1339"),]
metadata <- metadata[!metadata$ID %in% c("AC1441", "AC1431", "AC1445", "AC1414", "AC1169", "AC1403",
"AC1207", "AC1420", "AC1337", "AC1229",
"AC1227", "AC1290", "AC1339"),]
##ASSEMBLE DATA
#c<- which(metadata$species=="Arabica",T)[1:12]
#c1<-which(metadata$species=="100% ARABICA COLOMBIA",T)[1:12]
#d<-which(metadata$species=="Robusta",T)
#F<-c(c,c1,d)
#irFAR<-cbind(metadata$species[F],irdata.deriv2.wavelength.optimized1[F,])
#write.table(nmrFAR, file="nmrARF.csv")
#data <- c(list(irdata.deriv2.wavelength.optimized1), list(nirdev2), list(nmr.spectra)) #list(nirdev2)
osc <- osc.lims(as.matrix((nirdev2)), as.matrix(as.numeric(metadata$species1)), nComp=1, training=1:101,
xcenter = centering[[2]], xscale = scaling[[2]], ycenter = FALSE,
yscale = FALSE, accuracy = 1e-5, maxit = 100,
discriminant = FALSE)
data <- c(list(irdata.deriv2.wavelength.optimized1), list(osc$X), list(nmr.spectra))
scales <- c(irscale, nirdev2scale, res$ppm)
#y<-normalization(nmr.spectra, method = "pqn")
#data <- c(list(y$newXtrain))
#data <- c(list(osc$X))
#metadata<-metadata[F,]
#matplot(t(y$newXtrain), type="l")
### DATA PROCESSING ####
AR.Q2 <- c()
AR.ROC <- list(list("predicted" = c(), "observed" = c()),list("predicted" = c(), "observed" = c()),list("predicted" = c(), "observed" = c()))
CO.ROC <- list(list("predicted" = c(), "observed" = c()),list("predicted" = c(), "observed" = c()),list("predicted" = c(), "observed" = c()))
AR.Q2.densities <- c()
CO.Q2 <- c()
CO.Q2.densities <- c()
nComp <- 15
for (i in 1:3){
predictors <- data[[i]]
## ARABICA VS. ROBUSTA
#tiff(paste(path,names[i],"1"))
nfigs = nfigs + 1
postscript(paste(prefix,nfigs,".eps", sep=""), paper="special",height=10,width=8, horizontal=FALSE)
# png(file = paste(prefix,nfigs,".png"), bg = "white")
plot(c(), main = c(names[[i]], "Arabica vs. Robusta"), xlim=c(0,0), ylim=c(0,0))
dev.off()
# ## PCA to detect outliers
# pca <- prcomp(predictors,scale=scaling[[i]],center=centering[[i]])
# plot(pca$x[,1],pca$x[,2],
# col=c("grey66", "black", "black", "black", "black")[as.numeric(metadata$groups)],
# pch=c(15,1,15,7,22)[as.numeric(metadata$groups)], #pch=c(16,15)[metadata$groups],
# xlab= paste("1st PC (", round((pca$sdev^2 / sum(pca$sdev^2))[1] * 100,1), "%)"),
# ylab= paste("2nd PC (", round((pca$sdev^2 / sum(pca$sdev^2))[2] * 100,1), "%)"),
# cex=1.2, cex.axis=1.0,cex.lab=1.3) ##png and pdf
# text(pca$x[,1:2], label=metadata$ID,cex=0.7, pos=1, col="red")
# abline(h=0);abline(v=0)
# ordiellipse(cbind(pca$x[,1], pca$x[,2]),
# metadata$species1,
# conf=0.95, col="gray66", lwd=2)
#saveDevice("pca")
#}
##Model and validation
#Next two lines: select just as many arabicas as there are robustas. The scores plots are expected to go
##gaga but everything else should be fine
original.predictors <- predictors;
selection <- sort(c(which(metadata$species1 == -1), sample(which(metadata$species1 == 1),length(which(metadata$species1 == -1)))))
predictors <- predictors[selection,]
ir.validation <-lims.validate(model = model[[i]], predictors = predictors,
responses = as.matrix(as.numeric(as.character(metadata$species1)[selection])),
nModels = nModels, nComp=nComp, ycenter = FALSE, yscale = FALSE,
codomain = c(-1,1), xscale = scaling[[i]], xcenter = centering[[i]], valsize = valsize,
method=validating)
# y1<-ir.validation$training.set[[1]]
# y2<-as.matrix(as.numeric(as.character(metadata$species1)))[y1,]
# X<-osc$X[y1,]
# X1<-irdata.deriv2.wavelength.optimized1[y1,]
# X2<-nmr.spectra[y1,]
# Xtrain = list(X,X1,X2);#list(X,X2,X3);
# Xtest<-osc$X[-y1,]
# X1test<-irdata.deriv2.wavelength.optimized1[-y1,]
# X2test<-nmr.spectra[-y1,]
# XTest = list(Xtest,X1test, X2test);
# m=c(dim(X)[2],dim(X1)[2], dim(X2)[2])
# multi<-multiblock(Xtrain,y2,m,3)
#
# ypred=predict1(Xtrain,multi);
# print(cbind(y2,ypred))
# R2 <- cov(y2,ypred)^2/(var(y2)*var(ypred))
# print(cbind("R2",R2))
# x <- Xtest
# Ytest<-as.matrix(as.numeric(as.character(metadata$species1)))[-y1,]
# ypred = predict1(x,multi) #Abdi verion
# Q2 <- cov(Ytest,ypred)^2/(var(Ytest)*var(ypred))
# print(cbind("Q2: ",Q2))
# print("Confusion matrix test XWQ")
# print(rbind(cbind("R/P", "T", " F "),cbind("T ",colSums(ypred>0&response>0),colSums(ypred<0&response>0)),cbind("F ",colSums(ypred>0&response<0),colSums(ypred<0&response<0))))
# ## Compute and save ROC curve (for all accumulated predictions) and AUCs for individual ROC curves
# Pred1<-c(); W1<-c()
# for (i in c(1:length(ir.validation$full.results))){
# pred1<-(ir.validation$full.results[[i]]$predicted.values[,,nComp])
# # pred<-as.factor(as.numeric(ir.validation$full.results[[i]]$predicted.values[,,nComp]>0))
# #levels(pred)<-c("-1","1")
# #pred<-as.numeric(as.character(pred))
# w1<-as.numeric(as.character(metadata$species1[-ir.validation$training.set[[i]]]))
#
# Pred1<-c(Pred1,pred1)
# W1<-c(W1,w1)
# }
#
# roc1 <- roc(W1,
# Pred1, percent=TRUE,
# # arguments for auc
# partial.auc=c(100, 90), partial.auc.correct=TRUE,
# partial.auc.focus="sens",
# # arguments for ci
# ci=TRUE, boot.n=100, ci.alpha=0.9, stratified=FALSE,
# # arguments for plot
# plot=TRUE, auc.polygon=TRUE, max.auc.polygon=TRUE, grid=TRUE,
# print.auc=TRUE, show.thres=TRUE, legacy.axes = TRUE)
# AR.ROC <- c(AR.ROC,roc1)
##Select optimum number of components
#Plot Q2 vs. Nº of components to choose optimum
plot.with.error.bars(1:nComp,ir.validation$Q2, pch=19, xlab = "Number of components", ylab = "Q2")
# saveDevice(paste(names[i],"Q2" ))
#Choose best number of components from the previous plot
best.nComp <- 0
while (best.nComp < 1){
best.nComp <- readline("Choose number of components to proceed")
}
best.nComp <- as.numeric(best.nComp)
##Save data for ROC analysis
j <- 0
for (results in ir.validation$full.results){
j = j + 1
# AR.ROC[[i]]$predicted <- rbind(AR.ROC[[i]]$predicted, sign(results$predicted.values[,,best.nComp]))
AR.ROC[[i]]$predicted <- rbind(AR.ROC[[i]]$predicted, (results$predicted.values[,,best.nComp][1:4]))
AR.ROC[[i]]$observed <- rbind(AR.ROC[[i]]$observed,
as.numeric(as.character(metadata$species1[selection][-ir.validation$training.set[[j]]][1:4])))
}
# ARNIR<-c()
# W<-c(); Pred<-c()
# for (j in c(1:length(ir.validation$full.results))){
# pred<-(ir.validation$full.results[[j]]$predicted.values[,,best.nComp])
# # pred<-as.factor(as.numeric(ir.validation$full.results[[i]]$predicted.values[,,nComp]>0))
# #levels(pred)<-c("-1","1")
# #pred<-as.numeric(as.character(pred))
# w<-as.numeric(as.character(metadata$species1[-ir.validation$training.set[[j]]]))
# #print(w)
# #W<-c(W,w)
# #Pred<-c(Pred,pred)
# AR <- roc(w,
# pred, percent=TRUE,
# # arguments for auc
# # partial.auc=c(100, 90), partial.auc.correct=TRUE,
# # partial.auc.focus="sens",
# # arguments for ci
# ci=TRUE, boot.n=100, ci.alpha=0.9, stratified=FALSE,
# # arguments for plot
# plot=FALSE, auc.polygon=TRUE, max.auc.polygon=TRUE, grid=TRUE,
# print.auc=TRUE, show.thres=TRUE, legacy.axes = TRUE)
# ARNIR<-c(ARNIR,list(AR))
#
# }
##Save Q2 for latter comparative plotting
AR.Q2 <- c(AR.Q2, list(ir.validation$Q2))
##Compute Q2.density and select example model
Q2.density <- density(ir.validation$Q2[,best.nComp])
# plot(Q2.density, xlab = "Q2 for optimum number of components") #Just for checking, eventually all Q2 densities will be in a single plot
selected.model <- which.min(abs(ir.validation$Q2[,best.nComp] - Q2.density$x[which.max(Q2.density$y)])) #we draw
best.model <- which.max(ir.validation$Q2[,best.nComp])
##Save Q2.density for latter comparative plotting
AR.Q2.densities <- c(AR.Q2.densities, list(Q2.density))
##scores plot of model with Q2 in the maximum of the distribution
par(mar=c(5.1,4.5,4,5.1))
scoresX <- c()
scoresY <- c()
labelY <- ""
if (identical(model[[i]], lims.pls.model)){
scoresX <- ir.validation$full.results[[selected.model]]$xscores[,1]
scoresY <- ir.validation$full.results[[selected.model]]$xscores[,2]
labelY <- "Predictive Component"
}
else{
if (identical(model[[i]], lims.opls.model)){
scoresX <- ir.validation$full.results[[selected.model]]$xscores[,best.nComp]
scoresY <- ir.validation$full.results[[selected.model]]$orthoscores[,1]
labelY <- "Orthogonal Component"
}
}
nfigs = nfigs + 1
postscript(paste(prefix,nfigs,".eps", sep=""), paper="special",height=10,width=8, horizontal=FALSE)
# png(file = paste(prefix,nfigs,".png"), bg = "white")
plot(scoresX,scoresY,
xlab="Predictive Component",
ylab=labelY, cex.lab=1.2,
main = paste("Typical model: R2 = ",
substr(as.character(ir.validation$full.results[[selected.model]]$R2[best.nComp]),
start=1,stop=6),
" Q2 = ",
substr(as.character(ir.validation$full.results[[selected.model]]$Q2[best.nComp]),
start=1,stop=6)),
#squares = arabica, circles = robusta
#black squares = colombia
#grey squares = brazil
#clear squares = peru
#x squares = other arabicas
col=c("grey66", "black", "black", "black",
"black")[as.numeric(metadata$groups)[unlist(ir.validation$training.set[selected.model])]],
pch=c(15,1,15,7,22)[as.numeric(metadata$groups)[unlist(ir.validation$training.set[selected.model])]])
abline(h=0);abline(v=0)
ordiellipse(cbind(scoresX, scoresY),
metadata$species1[unlist(ir.validation$training.set[selected.model])],conf=0.95, col="gray66", lwd=2)
dev.off()
##scores plot of model with best Q2
# if (identical(model[[i]], lims.pls.model)){
# scoresX <- ir.validation$full.results[[best.model]]$xscores[,1]
# scoresY <- ir.validation$full.results[[best.model]]$xscores[,2]
# }
# else{
# if (identical(model[[i]], lims.opls.model)){
# scoresX <- ir.validation$full.results[[best.model]]$xscores[,best.nComp]
# scoresY <- ir.validation$full.results[[best.model]]$orthoscores[,1]
# }
# }
par(mar=c(5.1,4.5,4,5.1))
if (identical(model[[i]], lims.pls.model)){
scoresX <- ir.validation$full.results[[best.model]]$xscores[,1]
scoresY <- ir.validation$full.results[[best.model]]$xscores[,2]
}
else{
if (identical(model[[i]], lims.opls.model)){
scoresX <- ir.validation$full.results[[best.model]]$xscores[,best.nComp]
scoresY <- ir.validation$full.results[[best.model]]$orthoscores[,1]
}
}
nfigs = nfigs + 1
postscript(paste(prefix,nfigs,".eps", sep=""), paper="special",height=10,width=8, horizontal=FALSE)
# png(file = paste(prefix,nfigs,".png"), bg = "white")
plot(scoresX, scoresY,
xlab="Predictive Component",
ylab=labelY, cex.lab=1.2,
main = paste("Best model: R2 = ",
substr(as.character(ir.validation$full.results[[best.model]]$R2[best.nComp]),
start=1,stop=6),
" Q2 = ",
substr(as.character(ir.validation$full.results[[best.model]]$Q2[best.nComp]),
start=1,stop=6)),
#squares = arabica, circles = robusta
#black squares = colombia
#grey squares = brazil
#clear squares = peru
#x squares = other arabicas
col=c("grey66", "black", "black", "black",
"black")[as.numeric(metadata$groups)[unlist(ir.validation$training.set[best.model])]],
pch=c(15,1,15,7,22)[as.numeric(metadata$groups)[unlist(ir.validation$training.set[best.model])]])
abline(h=0);abline(v=0)
ordiellipse(cbind(scoresX, scoresY),
metadata$species1[unlist(ir.validation$training.set[best.model])],conf=0.95, col="gray66", lwd=2)
dev.off()
#saveDevice("irARopls")
# plot(ir.validation$full.results[[selected.model]]$xloadings[,1],
# ir.validation$full.results[[selected.model]]$xloadings[,2],
# type="p", main="")
# plot(ir.validation$full.results[[best.model]]$xloadings[,1]/max(ir.validation$full.results[[best.model]]$xloadings[,1]),
# ir.validation$full.results[[best.model]]$ortholoadings[,1]/(max(ir.validation$full.results[[best.model]]$ortholoadings[,1])),
# type="p", main="best")
#
# plot(ir.validation$full.results[[selected.model]]$xloadings[,1],
# ir.validation$full.results[[selected.model]]$xloadings[,2],
# type="p", main="")
#
# plot(ir.validation$full.results[[selected.model]]$ortholoadings[,2],
# ir.validation$full.results[[selected.model]]$xloadings[,1],
# type="p", main="")
# loadings.quartiles <- matrix(c(1:(dim(predictors)[[2]]*5)),ncol=5);
#
# current.loadings <- c(1:15);
# for (i in c(1:dim(predictors)[[2]])){
# for (j in c(1:length(ir.validation$full.results))){
# current.loadings[[j]] <- ir.validation$full.results[[j]]$xloadings[[i]];
# }
# current.loadings <- sort(current.loadings);
# loadings.quartiles[i,1] <- current.loadings[[1]];
# loadings.quartiles[i,2] <- current.loadings[[25]];
# loadings.quartiles[i,3] <- current.loadings[[50]];
# loadings.quartiles[i,4] <- current.loadings[75];
# loadings.quartiles[i,5] <- current.loadings[100];
# }
# matplot(matrix(c(1:dim(predictors)[[2]]),ncol=1), loadings.quartiles, type="l");
#
nirL<-t(do.call("cbind", lapply(ir.validation$full.results, function(x) x$xloadings[,1])))
nirL2<-t(do.call("cbind", lapply(ir.validation$full.results, function(x) x$xloadings[,2])))
nirL3<-t(do.call("cbind", lapply(ir.validation$full.results, function(x) x$xloadings[,3])))
#t(nirdev2)
#Checking loading stability: plot spectra, loadings, and relative error on loadings for first 2 loadings
#Doing it sorted for easier comparison of high loading value vs. high variability
#Filtering top 95% loadings
ordering <- upper(apply(abs(nirL),2,median))
# plot(apply(predictors,2,median)[ordering], type="l", main = "Spectrum ordered by loadings")
nfigs = nfigs + 1
postscript(paste(prefix,nfigs,".eps", sep=""), paper="special",height=10,width=8, horizontal=FALSE)
# png(file = paste(prefix,nfigs,".png"), bg = "white")
layout(matrix(c(1,1,2,2), 2, 2, byrow = TRUE), widths=c(2,1), heights=c(1,2))
plot(apply(predictors,2,median)[ordering], type="l", main = "",
frame.plot = FALSE, ylab="", axes=FALSE, col=1, xlab="") #Spectrum ordered by loadings
axis(2, cex=3.5, cex.lab=3.5, cex.axis=1.4)
#grid(50,NA ,lwd = 2)
#par(new=TRUE)
plot(apply(abs(nirL),2,median)[ordering], type = "l", main = "",
frame.plot = FALSE, axes=FALSE, ylab="", col=color[i], xlab="") #Median Loading 1 (Absolute value)
#axis(3, cex=0.5, col=2) # Draw the x-axis above the plot area
axis(4, cex=3.5,cex.lab=3.5, col=color[i], cex.axis=1.4 )
par(new=TRUE)
# grid(50,NA ,lwd = 2)
plot(apply(abs(nirL),2,function(x) sd(x) / mean(x))[ordering], type = "l",
main="", frame.plot = FALSE, ylab="", xlab="Order of decreasing loadings",
cex=3.5, cex.lab=3.5,cex.axis=1.4) #Loading 1 relative error (absolute values)
#saveDevice(paste(names[i],"LoagOrder3" ))
# grid(50,NA ,lwd = 2)
par(mfrow=c(1,1))
dev.off()
#plot(apply(abs(nirL),2,function(x) sd(x) / mean(x))[ordering], type = "l",
# main="Loading 1 relative error (absolute values)")
plot(apply(nirL,2,function(x) sd(x) / mean(x))[ordering], type = "l",
main="Loading 1 relative error")
plot(apply(nirL,2,function(x) sd(x) / mean(x))[ordering], type = "l", ylim = c(-10,10),
main="Loading 1 relative error (ZOOM)")
#Another check for loading stability: correlations between first loadings for the different models, histogramize
hist(apply(nirL, 1, function(x) cor(nirL[1,], x)), breaks = 20, xlab = "Correlation with model 1",
main = "Loading 1 stability")
ordering <- upper(apply(abs(nirL2),2,median))
# plot(apply(predictors,2,median)[ordering], type="l", main = "Spectrum ordered by loadings")
plot(apply(abs(nirL2),2,median)[ordering], type = "l", main = "Median Loading 2 (Absolute value)")
plot(apply(nirL2,2,function(x) sd(x) / mean(x))[ordering], type = "l",
main="Loading 2 relative error")
plot(apply(nirL2,2,function(x) sd(x) / mean(x))[ordering], type = "l", ylim = c(-10,10),
main="Loading 2 relative error (ZOOM)")
plot(apply(abs(nirL2),2,function(x) sd(x) / mean(x))[ordering], type = "l",
main="Loading 2 relative error (absolute values)")
#Another check for loading stability: correlations between first loadings for the different models, histogramize
hist(apply(nirL2, 1, function(x) cor(nirL2[1,], x)), breaks = 20, xlab = "Correlation with model 1",
main = "Loading 2 stability")
####COLOMBIA VS. OTHER ARABICAS
predictors <- original.predictors;
nfigs = nfigs + 1
postscript(paste(prefix,nfigs,".eps", sep=""), paper="special",height=10,width=8, horizontal=FALSE)
# png(file = paste(prefix,nfigs,".png"), bg = "white")
plot(c(), main = c(names[[i]], "Colombia vs. Other countries"), xlim=c(0,0), ylim=c(0,0))
dev.off()
##Select Arabica Samples and build the corresponding predictors and responses matrices
filter <- metadata$species1 == 1 & !metadata$ID %in% c("AC1436", "AC1437", "AC1432")
predictors <- predictors[filter,]
# X<-osc$X[filter,]
# X1<-irdata.deriv2.wavelength.optimized1[filter,]
# X2<-nmr.spectra[filter,]
#
responses <- metadata$groups[filter]
levels(responses)[!levels(responses) == "Colombia"] = -1
levels(responses)[levels(responses) == "Colombia"] = 1
#filtered.metadata <- metadata[filter,]
# ## PCA to detect outliers
# pca <- prcomp(predictors,scale=scaling[[i]],center=centering[[i]])
# plot(pca$x[,1],pca$x[,2],
# col=c("grey66", "black", "black", "black", "black")[as.numeric(metadata$groups[filter])],
# pch=c(15,1,15,7,22)[as.numeric(metadata$groups[filter])], #pch=c(16,15)[metadata$groups],
# xlab= paste("1st PC (", round((pca$sdev^2 / sum(pca$sdev^2))[1] * 100,1), "%)"),
# ylab= paste("2nd PC (", round((pca$sdev^2 / sum(pca$sdev^2))[2] * 100,1), "%)"),
# cex=1.2, cex.axis=1.0,cex.lab=1.3) ##png and pdf
# text(pca$x[,1:2], label=metadata$ID[filter],cex=0.7, pos=1, col="red")
# abline(h=0);abline(v=0)
# ordiellipse(cbind(pca$x[,1], pca$x[,2]),
# responses,
# conf=0.95, col="gray66", lwd=2)
#saveDevice("pca")
## remove outliers ###
#sub outliers detected visually in the PCA scores plot
#outliers<-which(ir.metadata$catalogID=="AC1427"|ir.metadata$catalogID=="AC1199"|ir.metadata$catalogID=="AC1380")
#irdata.deriv2.wavelength.optimized1<-irdata.deriv2.wavelength.optimized1[-outliers,]
#ir.metadata<-ir.metadata[-outliers,]
ir.validation <-lims.validate(model = model[[i]], predictors = predictors,
responses = as.matrix(as.numeric(as.character(responses))),
nModels = nModels, nComp=nComp,xscale = scaling1[[i]], ycenter = FALSE,
yscale = FALSE, xcenter = centering1[[i]], method=validating, valsize = valsize)
##Select optimum number of components
# y1<-ir.validation$training.set[[1]]
# y2<-as.matrix(as.numeric(as.character(responses)))[y1,]
# Xtest<-X[-y1,]
# X1test<-X1[-y1,]
# X2test<-X2[-y1,]
# XTest = list(Xtest,X1test, X2test);
#
# X<-X[y1,]
# X1<-X1[y1,]
# X2<-X2[y1,]
# Xtrain = list(X,X1,X2);#list(X,X2,X3);
# m=c(dim(X)[2],dim(X1)[2], dim(X2)[2])
# multi<-multiblock(Xtrain,y2,m,3)
# ypred=predict1(Xtrain,multi);
# print(cbind(y2,ypred))
# R2 <- cov(y2,ypred)^2/(var(y2)*var(ypred))
# print(cbind("R2",R2))
#
# x <- Xtest
# Ytest<-as.matrix(as.numeric(as.character(metadata$species1)))[-y1,]
# ypred = predict1(x,multi) #Abdi verion
# Q2 <- cov(Ytest,ypred)^2/(var(Ytest)*var(ypred))
# print(cbind("Q2: ",Q2))
# print("Confusion matrix test XWQ")
#
# W<-c(); Pred<-c()
# for (j in c(1:length(ir.validation$full.results))){
# pred<-(ir.validation$full.results[[j]]$predicted.values[,,best.nComp])
# # pred<-as.factor(as.numeric(ir.validation$full.results[[i]]$predicted.values[,,nComp]>0))
# #levels(pred)<-c("-1","1")
# #pred<-as.numeric(as.character(pred))
# w<-as.numeric(as.character(responses[-ir.validation$training.set[[j]]]))
# #print(w)
# #W<-c(W,w)
# #Pred<-c(Pred,pred)
# roc1 <- roc(w,
# pred, percent=TRUE,
# # arguments for auc
# # partial.auc=c(100, 90), partial.auc.correct=TRUE,
# # partial.auc.focus="sens",
# # arguments for ci
# ci=TRUE, boot.n=100, ci.alpha=0.9, stratified=FALSE,
# # arguments for plot
# plot=FALSE, auc.polygon=TRUE, max.auc.polygon=TRUE, grid=TRUE,
# print.auc=TRUE, show.thres=TRUE, legacy.axes = TRUE)
# }
# CO.ROC <- c(CO.ROC,roc1)
# # AUC<-c(AUC,ROC$auc)
# rm(Pred)
# rm(conf)
#Plot Q2 vs. Nº of components to choose optimum
plot.with.error.bars(1:nComp,ir.validation$Q2, pch=19, xlab = "Number of components",
ylab = "Q2")
#Choose best number of components from the previous plot
best.nComp <- 0
while (best.nComp < 1){
best.nComp <- readline("Choose number of components to proceed")
}
best.nComp <- as.numeric(best.nComp)
##Save data for ROC analysis
j <- 0
for (results in ir.validation$full.results){
j = j + 1
# CO.ROC[[i]]$predicted <- rbind(CO.ROC[[i]]$predicted, sign(results$predicted.values[,,best.nComp]))
CO.ROC[[i]]$predicted <- rbind(CO.ROC[[i]]$predicted, (results$predicted.values[,,best.nComp]))
CO.ROC[[i]]$observed <- rbind(CO.ROC[[i]]$observed,
as.numeric(as.character(responses[-ir.validation$training.set[[j]]])))
}
##Save Q2 for latter comparative plotting
CO.Q2 <- c(CO.Q2, list(ir.validation$Q2))
##Compute Q2.density and select example model
Q2.density <- density(ir.validation$Q2[,best.nComp])
# plot(Q2.density, xlab = "Q2 for optimum number of components") #Just for checking, eventually all Q2 densities will be in a single plot
selected.model <- which.min(abs(ir.validation$Q2[,best.nComp] - Q2.density$x[which.max(Q2.density$y)])) #we draw
best.model <- which.max(ir.validation$Q2[,best.nComp])
##Save Q2.density for latter comparative plotting
CO.Q2.densities <- c(CO.Q2.densities, list(Q2.density))
##scores plot of model with Q2 in the maximum of the distribution #(for 2 components?)
#Q2.density <- density(ir.validation$Q2[,2])
#selected.model <- which.min(abs(ir.validation$Q2[,2] - Q2.density$x[which.max(Q2.density$y)])) #we draw
par(mar=c(5.1,4.5,4,5.1))
if (identical(model[[i]], lims.pls.model)){
scoresX <- ir.validation$full.results[[selected.model]]$xscores[,1]
scoresY <- ir.validation$full.results[[selected.model]]$xscores[,2]
labelY <- "Predictive Component"
}
else{
if (identical(model[[i]], lims.opls.model)){
scoresX <- ir.validation$full.results[[selected.model]]$xscores[,best.nComp]
scoresY <- ir.validation$full.results[[selected.model]]$orthoscores[,1]
labelY <- "Orthogonal Component"
}
}
nfigs = nfigs + 1
postscript(paste(prefix,nfigs,".eps", sep=""), paper="special",height=10,width=8, horizontal=FALSE)
# png(file = paste(prefix,nfigs,".png"), bg = "white")
plot(scoresX, scoresY,
xlab="Predictive Component",
ylab=labelY, cex.lab=1.2,
main = paste("Typical model: R2 = ",
substr(as.character(ir.validation$full.results[[selected.model]]$R2[best.nComp]),
start=1,stop=6),
" Q2 = ",
substr(as.character(ir.validation$full.results[[selected.model]]$Q2[best.nComp]),
start=1,stop=6)),
#squares = arabica, circles = robusta
#black squares = colombia
#grey squares = brazil
#clear squares = peru
#x squares = other arabicas
col=c("grey66", "black", "black", "black",
"black")[as.numeric(metadata$groups)[filter][unlist(ir.validation$training.set[selected.model])]],
pch=c(15,1,15,7,22)[as.numeric(metadata$groups)[filter][unlist(ir.validation$training.set[selected.model])]])
abline(h=0);abline(v=0)
ordiellipse(cbind(scoresX, scoresY),
responses[unlist(ir.validation$training.set[selected.model])],conf=0.95, col="gray66", lwd=2)
dev.off()
# plot(ir.validation$full.results[[selected.model]]$xloadings[,1],
# ir.validation$full.results[[selected.model]]$xloadings[,2],
# type="p", main="CO")
#Scores plot of best model
par(mar=c(5.1,4.5,4,5.1))
# if (identical(model[[i]], lims.pls.model)){
# scoresX <- ir.validation$full.results[[best.model]]$xscores[,1]
# scoresY <- ir.validation$full.results[[selected.model]]$xscores[,2]
# }
# else{
# if (identical(model[[i]], lims.opls.model)){
# scoresX <- ir.validation$full.results[[selected.model]]$xscores[,best.nComp]
# scoresY <- ir.validation$full.results[[selected.model]]$orthoscores[,1]
# }
# }
if (identical(model[[i]], lims.pls.model)){
scoresX <- ir.validation$full.results[[best.model]]$xscores[,1]
scoresY <- ir.validation$full.results[[best.model]]$xscores[,2]
}
else{
if (identical(model[[i]], lims.opls.model)){
scoresX <- ir.validation$full.results[[best.model]]$xscores[,best.nComp]
scoresY <- ir.validation$full.results[[best.model]]$orthoscores[,1]
}
}
nfigs = nfigs + 1
postscript(paste(prefix,nfigs,".eps", sep=""), paper="special",height=10,width=8, horizontal=FALSE)
# png(file = paste(prefix,nfigs,".png"), bg = "white")
plot(scoresX, scoresY,
xlab="Predictive Component",
ylab=labelY, cex.lab=1.2,
main = paste("Best model: R2 = ",
substr(as.character(ir.validation$full.results[[best.model]]$R2[best.nComp]),
start=1,stop=6),
" Q2 = ",
substr(as.character(ir.validation$full.results[[best.model]]$Q2[best.nComp]),
start=1,stop=6)),
#squares = arabica, circles = robusta
#black squares = colombia
#grey squares = brazil
#clear squares = peru
#x squares = other arabicas
col=c("grey66", "black", "black", "black",
"black")[as.numeric(metadata$groups)[filter][unlist(ir.validation$training.set[best.model])]],
pch=c(15,1,15,7,22)[as.numeric(metadata$groups)[filter][unlist(ir.validation$training.set[best.model])]])
abline(h=0);abline(v=0)
ordiellipse(cbind(scoresX, scoresY),
responses[unlist(ir.validation$training.set[best.model])],conf=0.95, col="gray66", lwd=2)
dev.off()
#saveDevice("irARopls")
# loadings.quartiles <- matrix(c(1:(dim(predictors)[[2]]*5)),ncol=5);
# current.loadings <- c(1:15);
# for (i in c(1:dim(predictors)[[2]])){
# for (j in c(1:length(ir.validation$full.results))){
# current.loadings[[j]] <- ir.validation$full.results[[j]]$xloadings[[i]];
# }
# current.loadings <- sort(current.loadings);
# loadings.quartiles[i,1] <- current.loadings[[1]];
# loadings.quartiles[i,2] <- current.loadings[[25]];
# loadings.quartiles[i,3] <- current.loadings[[50]];
# loadings.quartiles[i,4] <- current.loadings[75];
# loadings.quartiles[i,5] <- current.loadings[100];
# }
#matplot(matrix(c(1:dim(predictors)[[2]]),ncol=1), loadings.quartiles, type="l");
nirL<-t(do.call("cbind", lapply(ir.validation$full.results, function(x) x$xloadings[,1])))
nirL2<-t(do.call("cbind", lapply(ir.validation$full.results, function(x) x$xloadings[,2])))
# nirL3<-t(do.call("cbind", lapply(ir.validation$full.results, function(x) x$xloadings[,3])))
#t(nirdev2)
#Checking loading stability: plot spectra, loadings, and relative error on loadings for first 2 loadings
#Doing it sorted for easier comparison of high loading value vs. high variability
ordering <- upper(apply(abs(nirL),2,median))
#par(mfrow=c(2,1))
nfigs = nfigs + 1
postscript(paste(prefix,nfigs,".eps", sep=""), paper="special",height=10,width=8, horizontal=FALSE)
# png(file = paste(prefix,nfigs,".png"), bg = "white")
layout(matrix(c(1,1,2,2), 2, 2, byrow = TRUE), widths=c(2,1), heights=c(1,2))
#par(mar = c(4,4,0,0), oma = c(0,0, 0,0))
plot(apply(predictors,2,median)[ordering], type="l", main = "",
frame.plot = FALSE, ylab="", axes=FALSE, col=1, xlab="") #Spectrum ordered by loadings
axis(2, cex=3.5, cex=3.5, cex.axis=1.4)
#grid(50,NA ,lwd = 2)
#par(new=TRUE)
# par(mar = c(4,4,0,0), oma = c(0,0, 0,0))
plot(apply(abs(nirL),2,median)[ordering], type = "l", main = "",
frame.plot = FALSE, axes=FALSE, ylab="", col=color[i], xlab="", cex=3.5, cex.lab=3.5) #Median Loading 1 (Absolute value)
#axis(3, cex=0.5, col=2) # Draw the x-axis above the plot area
axis(4, cex.lab=3.5,cex=3.5,col=color[i],cex.axis=1.4)
par(new=TRUE)
# par(mar = c(4,4,0,0), oma = c(0,0, 0,0))
# grid(50,NA ,lwd = 2)
plot(apply(abs(nirL),2,function(x) sd(x) / mean(x))[ordering], type = "l",
main="", frame.plot = FALSE, ylab="", xlab="Order of decreasing loadings",cex.axis=1.4, cex.lab=3.5, cex=3.5) #Loading 1 relative error (absolute values)
# grid(50,NA ,lwd = 2)
par(mfrow=c(1,1))
dev.off()
plot(apply(nirL,2,function(x) sd(x) / mean(x))[ordering], type = "l",
main="Loading 1 relative error", ylab="")
par(mfrow=c(1,1))
plot(apply(nirL,2,function(x) sd(x) / mean(x))[ordering], type = "l", ylim = c(-10,10),
main="Loading 1 relative error (ZOOM)")
#Another check for loading stability: correlations between first loadings for the different models, histogramize
hist(apply(nirL, 1, function(x) cor(nirL[1,], x)), breaks = 20, xlab = "Correlation with model 1",
main = "Loading 1 stability")
ordering <- upper(apply(abs(nirL2),2,median))
# plot(apply(predictors,2,median)[ordering], type="l", main = "Spectrum ordered by loadings")
plot(apply(abs(nirL2),2,median)[ordering], type = "l", main = "Median Loading 2 (Absolute value)")
plot(apply(nirL2,2,function(x) sd(x) / mean(x))[ordering], type = "l",
main="Loading 2 relative error")
plot(apply(nirL2,2,function(x) sd(x) / mean(x))[ordering], type = "l", ylim = c(-10,10),
main="Loading 2 relative error (ZOOM)")
plot(apply(abs(nirL2),2,function(x) sd(x) / mean(x))[ordering], type = "l",
main="Loading 2 relative error (absolute values)")
#Another check for loading stability: correlations between first loadings for the different models, histogramize
hist(apply(nirL2, 1, function(x) cor(nirL[1,], x)), breaks = 20, xlab = "Correlation with model 1",
main = "Loading 2 stability")
}
nfigs = nfigs + 1
postscript(paste(prefix,nfigs,".eps", sep=""), paper="special",height=6,width=8, horizontal=FALSE)
#png(file = paste(prefix,nfigs,".png"), bg = "white")
plot.with.error.bars(c(1:15), AR.Q2[[1]], pch = 15, col = "black", xlab = "Number of components", ylab = "Q2",
ylim = c(-1,1),main="Arabica / Robusta", cex.axis=1.5, cex.lab=1.5, cex = 1.5)
par(new = T)
plot.with.error.bars(c(1:15), AR.Q2[[2]], pch = 15, col = "red", xlab = "Number of components", ylab = "Q2",
ylim = c(-1,1), cex.axis=1.5, cex.lab=1.5, cex=1.5)
par(new = T)
plot.with.error.bars(c(1:15), AR.Q2[[3]], pch = 15, col = "blue", xlab = "Number of components", ylab = "Q2",
ylim = c(-1,1), cex.axis=1.5, cex.lab=1.5, cex=1.5)
dev.off()
ymax <- max(as.numeric(lapply(AR.Q2.densities, function(x) max(x$y))))
xmin <- min(as.numeric(lapply(AR.Q2.densities, function(x) min(x$x))))
xmax <- max(as.numeric(lapply(AR.Q2.densities, function(x) max(x$x))))
nfigs = nfigs + 1
postscript(paste(prefix,nfigs,".eps", sep=""), paper="special",height=6,width=8, horizontal=FALSE)
#png(file = paste(prefix,nfigs,".png"), bg = "white")
plot(AR.Q2.densities[[1]], xlab = "Q2", col="black", ylim = c(0,ymax), xlim = c(xmin,xmax), main="Arabica / Robusta")
lines(AR.Q2.densities[[2]], col="red")
lines(AR.Q2.densities[[3]], col="blue")
dev.off()
nfigs = nfigs + 1
postscript(paste(prefix,nfigs,".eps", sep=""), paper="special",height=6,width=8, horizontal=FALSE)
#png(file = paste(prefix,nfigs,".png"), bg = "white")
plot.with.error.bars(c(1:15), CO.Q2[[1]], pch = 15, col = "black", xlab = "Number of components", ylab = "Q2",
ylim = c(-1,1), main = "Colombia / Others", cex.axis=1.5, cex.lab=1.5, cex=1.5)
par(new = T)
plot.with.error.bars(c(1:15), CO.Q2[[2]], pch = 15, col = "red", xlab = "Number of components", ylab = "Q2",
ylim = c(-1,1), cex.axis=1.5, cex.lab=1.5, cex=1.5)
par(new = T)
plot.with.error.bars(c(1:15), CO.Q2[[3]], pch = 15, col = "blue", xlab = "Number of components", ylab = "Q2",
ylim = c(-1,1), cex.axis=1.5, cex.lab=1.5, cex=1.5)
dev.off()
ymax <- max(as.numeric(lapply(CO.Q2.densities, function(x) max(x$y))))
xmin <- min(as.numeric(lapply(CO.Q2.densities, function(x) min(x$x))))
xmax <- max(as.numeric(lapply(CO.Q2.densities, function(x) max(x$x))))