comparison Normalisation_QCpool.r @ 0:b74d1d533dea draft default tip

planemo upload for repository https://github.com/workflow4metabolomics/batchcorrection.git commit 241fb99a843e13195c5054cd9731e1561f039bde
author ethevenot
date Thu, 04 Aug 2016 11:40:35 -0400
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:b74d1d533dea
1 # Author: jfmartin
2 # Modified by : mpetera
3 ###############################################################################
4 # Correction of analytical effects inter and intra batch on intensities using quality control pooled samples (QC-pools)
5 # according to the algorithm mentioned by Van der Kloet (J Prot Res 2009).
6 # Parameters : a dataframe of Ions intensities and an other of samples? metadata which must contains at least the three following columns :
7 # "batch" to identify the batches of analyses ; need at least 3 QC-pools for linear adjustment and 8 for lo(w)ess adjustment
8 # "injectionOrder" integer defining the injection order of all samples : QC-pools and analysed samples
9 # "sampleType" indicates if defining a sample with "sample" or a QC-pool with "pool"
10 # NO MISSING DATA are allowed
11 # Version 0.91 insertion of ok_norm function to assess correction feasibility
12 # Version 0.92 insertion of slope test in ok_norm
13 # Version 0.93 name of log file define as a parameter of the correction function
14 # Version 0.94 Within a batch, test if all QCpools or samples values = 0. Definition of an error code in ok_norm function (see function for details)
15 # Version 0.99 include non linear lowess correction.
16 # Version 1.00 the corrected result matrix is return transposed in Galaxy
17 # Version 1.01 standard deviation=0 instead of sum of value=0 is used to assess constant data in ok_norm function. Negative values in corrected matrix are converted to 0.
18 # Version 1.02 plotsituation create a result file with the error code of non execution of correction set by function ok_norm
19 # Version 1.03 fix bug in plot with "reg" option. suppression of ok_norm=4 condition if ok_norm function
20 # Version 2.00 Addition of loess function, correction indicator, plots ; modification of returned objects' format, some plots' displays and ok_norm ifelse format
21 # Version 2.01 Correction for pools negative values earlier in norm_QCpool
22 # Version 2.10 Script refreshing ; vocabulary adjustment ; span in parameters for lo(w)ess regression ; conditionning for third line ACP display ; order in loess display
23 # Version 2.11 ok1 and ok2 permutation (ok_norm) ; conditional display of regression (plotsituation) ; grouping of linked lignes + conditioning (normX) ; conditioning for CVplot
24 # Version 2.20 acplight function added from previous toolBox.R [# Version 1.01 "NA"-coding possibility added in acplight function]
25 # Version 2.30 addition of suppressWarnings() for known and controlled warnings ; suppression of one useless "cat" message ; change in Rdata names ; 'batch(es)' in cat
26
27 ok_norm=function(qcp,qci,spl,spi,method) {
28 # Function used for one ion within one batch to determine whether or not batch correction is possible
29 # ok_norm values :
30 # 0 : no preliminary-condition problem
31 # 1 : standard deviation of QC-pools or samples = 0
32 # 2 : insufficient number of QC-pools within a batch (n=3 for linear, n=8 for lowess or loess)
33 # 3 : significant difference between QC-pools' and samples' means
34 # 4 : denominator =0 when on 1 pool per batch <> 0
35 # 5 : (linear regression only) the slopes ratio ?QC-pools/samples? is lower than -0.2
36
37 ok=0
38 if (method=="linear") {minQC=3} else {minQC=8}
39 if (length(qcp)<minQC) { ok=2
40 } else {
41 if (sd(qcp)==0 | sd(spl)==0) { ok=1
42 } else {
43 cvp= sd(qcp)/mean(qcp); cvs=sd(spl)/mean(spl)
44 rttest=t.test(qcp,y=spl)
45 reslsfit=lsfit(qci, qcp)
46 reslsfitSample=lsfit(spl, spi)
47 ordori=reslsfit$coefficients[1]
48 penteB=reslsfit$coefficients[2]
49 penteS=reslsfitSample$coefficients[2]
50 # Significant difference between samples and pools
51 if (rttest$p.value < 0.01) { ok=3
52 } else {
53 # to avoid denominator =0 when on 1 pool per batch <> 0
54 if (method=="linear" & length(which(((penteB*qci)+ordori)==0))>0 ){ ok=6
55 } else {
56 # different sloop between samples and pools
57 if (method=="linear" & penteB/penteS < -0.20) { ok=5 }
58 }}}}
59 ok_norm=ok
60 }
61
62 plotsituation <- function (x, nbid,outfic="plot_regression.pdf", outres="PreNormSummary.txt",fact="batch",span="none") {
63 # Check for all ions in every batch if linear or lo(w)ess correction is possible.
64 # Use ok_norm function and create a file (PreNormSummary.txt) with the error code.
65 # Also create a pdf file with plots of linear and lo(w)ess regression lines.
66 # x: dataframe with ions in columns and samples in rows ; x is the result of concatenation of sample metadata file and ions file
67 # nbid: number of samples description columns (id and factors) with at least : "batch","injectionOrder","sampleType"
68 # outfic: name of regression plots pdf file
69 # fact: factor to be used as categorical variable for plots and PCA.
70 indfact =which(dimnames(x)[[2]]==fact)
71 indtypsamp =which(dimnames(x)[[2]]=="sampleType")
72 indbatch =which(dimnames(x)[[2]]=="batch")
73 indinject =which(dimnames(x)[[2]]=="injectionOrder")
74 lastIon=dim(x)[2]
75 nbi=lastIon-nbid # Number of ions = total number of columns - number of identifying columns
76 nbb=length(levels(x$batch)) # Number of batch = number of levels of "batch" comlumn (factor)
77 nbs=length(x$sampleType[x$sampleType=="sample"])# Number of samples = number of rows with "sample" value in sampleType
78 pdf(outfic,width=27,height=20)
79 cat(nbi," ions ",nbb," batch(es) \n")
80 cv=data.frame(matrix(0,nrow=nbi,ncol=2))# initialisation de la dataset qui contiendra les CV avant et apres correction
81 pre_bilan=matrix(0,nrow=nbi,ncol=3*nbb) # dataset of ok_norm function results
82 for (p in 1:nbi) {# for each ion
83 par (mfrow=c(3,nbb),ask=F,cex=1.2)
84 labion=dimnames(x)[[2]][p+nbid]
85 indpool=which(x$sampleType=="pool") # QCpools subscripts in x
86 pools1=x[indpool,p+nbid];
87 for (b in 1:nbb) {# for each batch...
88 xb=data.frame(x[(x$batch==levels(x$batch)[b]),c(indtypsamp,indinject,p+nbid)])
89 indpb = which(xb$sampleType=="pool")# QCpools subscripts in the current batch
90 indsp = which(xb$sampleType=="sample")# samples subscripts in the current batch
91 indbt = which(xb$sampleType=="sample" | xb$sampleType=="pool")# indices de tous les samples d'un batch pools+samples
92 normLinearTest=ok_norm(xb[indpb,3],xb[indpb,2], xb[indsp,3],xb[indsp,2],method="linear")
93 normLoessTest=ok_norm(xb[indpb,3],xb[indpb,2], xb[indsp,3],xb[indsp,2],method="loess")
94 normLowessTest=ok_norm(xb[indpb,3],xb[indpb,2], xb[indsp,3],xb[indsp,2],method="lowess")
95 #cat(dimnames(x)[[2]][p+nbid]," batch ",b," loess ",normLoessTest," linear ",normLinearTest,"\n")
96 pre_bilan[ p,3*b-2]=normLinearTest
97 pre_bilan[ p,3*b-1]=normLoessTest
98 pre_bilan[ p,3*b]=normLowessTest
99 if(length(indpb)>1){
100 if(span=="none"){span1<-1 ; span2<-2*length(indpool)/nbs}else{span1<-span ; span2<-span}
101 resloess=loess(xb[indpb,3]~xb[indpb,2],span=span1,degree=2,family="gaussian",iterations=4,surface="direct")
102 resloessSample=loess(xb[indsp,3]~xb[indsp,2],span=2*length(indpool)/nbs,degree=2,family="gaussian",iterations=4,surface="direct")
103 reslowess=lowess(xb[indpb,2],xb[indpb,3],f=span2)
104 reslowessSample=lowess(xb[indsp,2],xb[indsp,3])
105 liminf=min(xb[indbt,3]);limsup=max(xb[indbt,3])
106 plot(xb[indsp,2],xb[indsp,3],pch=16, main=paste(labion,"batch ",b),ylab="intensity",xlab="injection order",ylim=c(liminf,limsup))
107 points(xb[indpb,2], xb[indpb,3],pch=5)
108 points(cbind(resloess$x,resloess$fitted)[order(resloess$x),],type="l",col="orange")
109 points(cbind(resloessSample$x,resloessSample$fitted)[order(resloessSample$x),],type="l",col="green",lty=2)
110 points(reslowess,type="l",col="red"); points(reslowessSample,type="l",col="cyan",lty=2)
111 abline(lsfit(xb[indpb,2],xb[indpb,3]),col="blue")
112 abline(lsfit(xb[indsp,2],xb[indsp,3]),lty=2)
113 legend("topright",c("pools","samples"),lty=c(1,2),bty="n")
114 }
115 }
116 # series de plot avant et apres correction
117 minval=min(x[p+nbid]);maxval=max(x[p+nbid])
118 plot( x$injectionOrder, x[,p+nbid],col=x$batch,ylim=c(minval,maxval),ylab=labion,main=paste("avant correction CV pools=",round(cv[p,1],2)))
119 suppressWarnings(plot.design( x[c(indtypsamp,indbatch,indfact,p+nbid)],main="effet sur facteurs avant"))
120 }
121 dev.off()
122 pre_bilan=data.frame(pre_bilan)
123 labion=dimnames(x)[[2]][nbid+1:nbi]
124 for (i in 1:nbb) {
125 dimnames(pre_bilan)[[2]][3*i-2]=paste("batch",i,"linear")
126 dimnames(pre_bilan)[[2]][3*i-1]=paste("batch",i,"loess")
127 dimnames(pre_bilan)[[2]][3*i]=paste("batch",i,"lowess")
128 }
129 bilan=data.frame(labion,pre_bilan)
130 write.table(bilan,file=outres,sep="\t",row.names=F,quote=F)
131 }
132
133
134 normlowess=function (xb,detail="no",vref=1,b,span=NULL) {
135 # Correction function applied to 1 ion in 1 batch. Use a lowess regression computed on QC-pools in order to correct samples intensity values
136 # xb : dataframe for 1 ion in columns and samples in rows.
137 # vref : reference value (average of ion)
138 # b : batch subscript
139 # nbid: number of samples description columns (id and factors) with at least : "batch","injectionOrder","sampleType"
140 indpb = which(xb$sampleType=="pool") # pools subscripts of current batch
141 indsp = which(xb$sampleType=="sample") # samples of current batch subscripts
142 indbt = which(xb$sampleType=="sample" | xb$sampleType=="pool");# batch subscripts of all samples and QC-pools
143 labion=dimnames(xb)[[2]][3]
144 newval=xb[[3]] # initialisation of corrected values = intial values
145 ind <- 0 # initialisation of correction indicator
146 normTodo=ok_norm(xb[indpb,3],xb[indpb,2], xb[indsp,3],xb[indsp,2],method="lowess")
147 #cat("batch:",b," dim xb=",dim(xb)," ok=",normTodo,"\n")
148 if (normTodo==0) {
149 if(length(span)==0){span2<-2*length(indpb)/length(indsp)}else{span2<-span}
150 reslowess=lowess(xb[indpb,2],xb[indpb,3],f=span2) # lowess regression with QC-pools
151 px=xb[indsp,2]; # vector of injectionOrder values only for samples
152 for(j in 1:length(indbt)) {
153 if (xb$sampleType[j]=="pool") {
154 if (reslowess$y[which(indpb==j)]==0) reslowess$y[which(indpb==j)] <- 1
155 newval[j]=(vref*xb[j,3]) / (reslowess$y[which(indpb==j)])}
156 else { # for samples, the correction value cor correspond to the nearest QCpools
157 cor= reslowess$y[which(abs(reslowess$x-px[which(indsp==j)])==min(abs(reslowess$x - px[which(indsp==j)])))]
158 if (length(cor)>1) {cor=cor[1]}
159 if (cor <= 0) {cor=vref} # no modification of initial value
160 newval[j]=(vref*xb[j,3]) / cor
161 }
162 }
163 if (detail=="reg") {
164 liminf=min(xb[indbt,3]);limsup=max(xb[indbt,3])
165 plot(xb[indsp,2],xb[indsp,3],pch=16,main=paste(labion,"batch ",b),ylab="intensity",xlab="injection order",ylim=c(liminf,limsup))
166 points(xb[indpb,2], xb[indpb,3],pch=5)
167 points(reslowess,type="l",col="red")
168 }
169 ind <- 1
170 } else {# if ok_norm <> 0 , we perform a correction based on batch samples average
171 moySample=mean(xb[indsp,3]);if (moySample==0) moySample=1
172 newval[indsp] = (vref*xb[indsp,3])/moySample
173 if(length(indpb)>0){
174 moypool=mean(xb[indpb,3]) ; if (moypool==0) moypool=1
175 newval[indpb] = (vref*xb[indpb,3])/moypool
176 }
177 }
178 newval <- list(norm.ion=newval,norm.ind=ind)
179 return(newval)
180 }
181
182 normlinear <-function (xb,detail="no",vref=1,b) {
183 # Correction function applied to 1 ion in 1 batch. Use a linear regression computed on QC-pools in order to correct samples intensity values
184 # xb : dataframe with ions in columns and samples in rows ; x is a result of concatenation of samples metadata file and ions file
185 # nbid : number of samples description columns (id and factors) with at least : "batch","injectionOrder","sampleType"
186 indpb = which(xb$sampleType=="pool")# pools subscripts of current batch
187 indsp = which(xb$sampleType=="sample")# samples of current batch subscripts
188 indbt = which(xb$sampleType=="sample" | xb$sampleType=="pool") # QCpools and samples of current batch subscripts
189 labion=dimnames(xb)[[2]][3]
190 newval=xb[[3]] # initialisation of corrected values = intial values
191 ind <- 0 # initialisation of correction indicator
192 normTodo=ok_norm(xb[indpb,3],xb[indpb,2], xb[indsp,3],xb[indsp,2],method="linear")
193 #cat("batch:",b," ok=",normTodo,"\n")
194 if (normTodo==0) {
195 reslsfit=lsfit(xb[indpb,2],xb[indpb,3]) # linear regression for QCpools
196 reslsfitSample=lsfit(xb[indsp,2],xb[indsp,3]) # linear regression for samples
197 ordori=reslsfit$coefficients[1]
198 pente=reslsfit$coefficients[2]
199 if (detail=="reg") {
200 liminf=min(xb[indbt,3]);limsup=max(xb[indbt,3])
201 plot(xb[indsp,2],xb[indsp,3],pch=16,
202 main=paste(labion,"batch ",b),ylab="intensity",xlab="injection order",ylim=c(liminf,limsup))
203 points(xb[indpb,2], xb[indpb,3],pch=5)
204 abline(reslsfit)
205 abline(reslsfitSample,lty=2)
206 }
207 # correction avec remise a l'echelle de la valeur de l'ion (valref)
208 newval = (vref*xb[indbt,3]) / ((pente * xb[indbt,2]) + ordori)
209 ind <- 1
210 } else {# if ok_norm<>0 , we perform a correction based on batch samples average.
211 moySample=mean(xb[indsp,3]); if (moySample==0) moySample=1
212 newval[indsp] = (vref*xb[indsp,3])/moySample
213 if(length(indpb)>0){
214 moypool=mean(xb[indpb,3]) ; if (moypool==0) moypool=1
215 newval[indpb] = (vref*xb[indpb,3])/moypool
216 }
217 }
218 newval <- list(norm.ion=newval,norm.ind=ind)
219 return(newval)
220 }
221
222
223 normloess <- function (xb,detail="no",vref=1,b,span=NULL) {
224 # Correction function applied to 1 ion in 1 batch.
225 # Use a loess regression computed on QC-pools in order to correct samples intensity values.
226 # xb : dataframe for 1 ion in columns and samples in rows.
227 # detail : level of detail in the outlog file.
228 # vref : reference value (average of ion)
229 # b : batch subscript
230 indpb = which(xb$sampleType=="pool") # pools subscripts of current batch
231 indsp = which(xb$sampleType=="sample") # samples of current batch subscripts
232 indbt = which(xb$sampleType=="sample" | xb$sampleType=="pool");# batch subscripts of all samples and QCpools
233 labion=dimnames(xb)[[2]][3]
234 newval=xb[[3]] # initialisation of corrected values = intial values
235 ind <- 0 # initialisation of correction indicator
236 normTodo=ok_norm(xb[indpb,3],xb[indpb,2], xb[indsp,3],xb[indsp,2],method="loess")
237 #cat("batch:",b," dim xb=",dim(xb)," ok=",normTodo,"\n")
238 if (normTodo==0) {
239 if(length(span)==0){span1<-1}else{span1<-span}
240 resloess=loess(xb[indpb,3]~xb[indpb,2],span=span1,degree=2,family="gaussian",iterations=4,surface="direct") # loess regression with QCpools
241 cor=predict(resloess,newdata=xb[,2])
242 cor[cor<=1] <- 1
243 newval=(vref*xb[,3]) / cor
244 if(length(which(newval>3*(quantile(newval)[4])))>0){newval <- xb[,3]} # no modification of initial value
245 else {ind <- 1} # confirmation of correction
246 if (detail=="reg") { # plot
247 liminf=min(xb[indbt,3]);limsup=max(xb[indbt,3])
248 plot(xb[indsp,2],xb[indsp,3],pch=16,main=paste(labion,"batch ",b),ylab="intensity",xlab="injection order",ylim=c(liminf,limsup))
249 points(xb[indpb,2], xb[indpb,3],pch=5)
250 points(cbind(resloess$x,resloess$fitted)[order(resloess$x),],type="l",col="red")
251 }
252 }
253 if (ind==0) {# if ok_norm != 0 or if correction creates outliers, we perform a correction based on batch samples average
254 moySample=mean(xb[indsp,3]);if (moySample==0) moySample=1
255 newval[indsp] = (vref*xb[indsp,3])/moySample
256 if(length(indpb)>0){
257 moypool=mean(xb[indpb,3]) ; if (moypool==0) moypool=1
258 newval[indpb] = (vref*xb[indpb,3])/moypool
259 }
260 }
261 newval <- list(norm.ion=newval,norm.ind=ind)
262 return(newval)
263 }
264
265
266
267 norm_QCpool <- function (x, nbid, outfic, outlog, fact, metaion, detail="no", NormMoyPool=F, NormInt=F, method="linear",span="none")
268 {
269 # Correction applying linear or lowess correction function on all ions for every batch of a dataframe.
270 # x : dataframe with ions in column and samples' metadata
271 # nbid: number of samples description columns (id and factors) with at least : "batch","injectionOrder","sampleType"
272 # outfic: result corrected intensity file
273 # outlog: name of regression plots and PCA pdf file
274 # fact : factor to be used as categorical variable for plots and PCA.
275 # metaion : dataframe of ions' metadata
276 # detail : level of detail in the outlog file. detail="no" ACP+histogram of CV before and after correction.
277 # detail="plot" with plot for all batch before and after correction. detail="reg" with added plots with regression lines for all batches.
278 # NormMoyPool : not used
279 # NormInt : not used
280 # method : regression method to be used to correct : "linear" oo "lowess" oo "loess"
281 indfact =which(dimnames(x)[[2]]==fact)
282 indtypsamp=which(dimnames(x)[[2]]=="sampleType")
283 indbatch =which(dimnames(x)[[2]]=="batch")
284 indinject =which(dimnames(x)[[2]]=="injectionOrder")
285 lastIon=dim(x)[2]
286 valref=apply(as.matrix(x[,(nbid+1):(lastIon)]),2,mean) # reference value for each ion used to still have the same rought size of values
287 nbi=lastIon-nbid # number of ions
288 nbb=length(levels(x$batch)) # Number of batch(es) = number of levels of factor "batch" (can be =1)
289 nbs=length(x$sampleType[x$sampleType=="sample"])# Number of samples
290 nbp=length(x$sampleType[x$sampleType=="pool"])# Number of QCpools
291 Xn=data.frame(x[,c(1:nbid)],matrix(0,nrow=nbp+nbs,ncol=nbi))# initialisation of the corrected dataframe (=initial dataframe)
292 dimnames(Xn)=dimnames(x)
293 cv=data.frame(matrix(0,nrow=nbi,ncol=2))# initialisation of dataframe containing CV before and after correction
294 dimnames(cv)[[2]]=c("avant","apres")
295 if (detail!="reg" && detail!="plot" && detail!="no") {detail="no"}
296 pdf(outlog,width=27,height=20)
297 cat(nbi," ions ",nbb," batch(es) \n")
298 if (detail=="plot") {par (mfrow=c(4,4),ask=F,cex=1.5)}
299 res.ind <- matrix(NA,ncol=nbb,nrow=nbi,dimnames=list(dimnames(x)[[2]][-c(1:nbid)],paste("norm.b",1:nbb,sep="")))
300 for (p in 1:nbi) {# for each ion
301 labion=dimnames(x)[[2]][p+nbid]
302 if (detail == "reg") {par (mfrow=c(4,4),ask=F,cex=1.5)}
303 indpool=which(x$sampleType=="pool")# QCpools subscripts in all batches
304 pools1=x[indpool,p+nbid]; cv[p,1]=sd(pools1)/mean(pools1)# CV before correction
305 for (b in 1:nbb) {# for every batch
306 indpb = which(x$batch==levels(x$batch)[b] & x$sampleType=="pool")# QCpools subscripts of the current batch
307 indsp = which(x$batch==levels(x$batch)[b] & x$sampleType=="sample")# samples subscripts of the current batch
308 indbt = which(x$batch==levels(x$batch)[b] & (x$sampleType=="pool" | x$sampleType=="sample")) # subscripts of all samples
309 # cat(dimnames(x)[[2]][p+nbid]," indsp:",length(indsp)," indpb=",length(indpb)," indbt=",length(indbt)," ")
310 sub=data.frame(x[(x$batch==levels(x$batch)[b]),c(indtypsamp,indinject,p+nbid)])
311 if (method=="linear") { res.norm = normlinear(sub,detail,valref[p],b)
312 } else { if (method=="loess"){ res.norm <- normloess(sub,detail,valref[p],b,span)
313 } else { if (method=="lowess"){ res.norm <- normlowess(sub,detail,valref[p],b,span)
314 } else {stop("\n--\nNo valid 'method' argument supplied.\nMust be 'linear','loess' or 'lowess'.\n--\n")}
315 }}
316 Xn[indbt,p+nbid] = res.norm[[1]]
317 res.ind[p,b] <- res.norm[[2]]
318 # CV batch test : if after normaliszation, CV before < CV after initial values are kept
319 # moypoolRaw=mean(x[indpb,p+nbid]) ; if (moypoolRaw==0) moypoolRaw=1
320 # moySampleRaw=mean(x[indsp,p+nbid]); if (moySampleRaw==0) moySampleRaw=1
321 # moypool=mean(Xn[indpb,p+nbid]) ; if (moypool==0) moypool=1
322 # #moySample=mean(Xn[indsp,p+nbid]); if (moySample==0) moySample=1
323 # if (sd( Xn[indpb,p+nbid])/moypool>sd(x[indpb,p+nbid])/moypoolRaw) {
324 # Xn[indpb,p+nbid] = (valref[p]*x[indpb,p+nbid])/moypoolRaw
325 # Xn[indsp,p+nbid] = (valref[p]*x[indsp,p+nbid])/moySampleRaw
326 # }
327 }
328 Xn[indpool,p+nbid][Xn[indpool,p+nbid]<0] <- 0
329 pools2=Xn[indpool,p+nbid]; cv[p,2]=sd(pools2)/mean(pools2)# CV apres correction
330 if (detail=="reg" || detail=="plot" ) {
331 # plot before and after correction
332 minval=min(cbind(x[p+nbid],Xn[p+nbid]));maxval=max(cbind(x[p+nbid],Xn[p+nbid]))
333 plot( x$injectionOrder, x[,p+nbid],col=x$batch,ylab=labion,ylim=c(minval,maxval),main=paste("avant correction CV pools=",round(cv[p,1],2)))
334 points(x$injectionOrder[indpool],x[indpool,p+nbid],col="maroon",pch=".",cex=2)
335 plot(Xn$injectionOrder,Xn[,p+nbid],col=x$batch,ylab="",ylim=c(minval,maxval),main=paste("apres correction CV pools=",round(cv[p,2],2)))
336 points(Xn$injectionOrder[indpool],Xn[indpool,p+nbid],col="maroon",pch=".",cex=2)
337 suppressWarnings(plot.design( x[c(indtypsamp,indbatch,indfact,p+nbid)],main="effet sur facteurs avant"))
338 suppressWarnings(plot.design(Xn[c(indtypsamp,indbatch,indfact,p+nbid)],main="effet sur facteurs apres"))
339 }
340 }
341 ### Replacement of post correction negative values by 0
342 Xnn=Xn
343 valNulle=0
344 for (i in c((nbid+1):dim(Xn)[2])) {
345 cneg=which(Xn[[i]]<0)
346 Xnn[[i]]=replace(Xn[[i]],cneg,valNulle)
347 }
348 Xn=Xnn
349 write.table(Xn,file=outfic,sep="\t",row.names=F,quote=F)
350
351 if (detail=="reg" || detail=="plot" || detail=="no") {
352 if (nbi > 3) {
353 par(mfrow=c(3,4),ask=F,cex=1.2) # PCA Plot before/after, normed only and ions plot
354 acplight(x[,c(indtypsamp,indbatch,indtypsamp,indfact,(nbid+1):lastIon)],"uv",TRUE)
355 norm.ion <- which(colnames(Xn)%in%(rownames(res.ind)[which(rowSums(res.ind)>=1)]))
356 acplight(Xn[,c(indtypsamp,indbatch,indtypsamp,indfact,(nbid+1):lastIon)],"uv",TRUE,norm.ion)
357 if(length(norm.ion)>0){acplight(Xn[,c(indtypsamp,indbatch,indtypsamp,indfact,norm.ion)],"uv",TRUE)}
358 par(mfrow=c(1,2),ask=F,cex=1.2) # Before/after boxplot
359 cvplot=cv[!is.na(cv[[1]])&!is.na(cv[[2]]),]
360 if(nrow(cvplot)>0){
361 boxplot(cvplot[[1]],ylim=c(min(cvplot),max(cvplot)),main="CV avant")
362 boxplot(cvplot[[2]],ylim=c(min(cvplot),max(cvplot)),main="CV apres")
363 }
364 dev.off()
365 }
366 }
367 if (nbi<=3) {dev.off()}
368 # transposed matrix is return (format of the initial matrix with ions in rows)
369 Xr=Xn[,-c(1:nbid)]; dimnames(Xr)[[1]]=Xn[[1]]
370 Xr=t(Xr) ; Xr <- data.frame(ions=rownames(Xr),Xr)
371
372 res.norm[[1]] <- Xr ; res.norm[[2]] <- data.frame(metaion,res.ind) ; res.norm[[3]] <- x[,c(1:nbid)]
373 names(res.norm) <- c("dataMatrix","variableMetadata","sampleMetadata")
374 return(res.norm)
375 }
376
377
378
379
380
381 acplight <- function(ids, scaling="uv", indiv=FALSE,indcol=NULL) {
382 suppressPackageStartupMessages(library(ade4))
383 suppressPackageStartupMessages(library(pcaMethods))
384 # fait une ACP sur ids sachant que la colonne 1 contient l'identificateur d'individu
385 # la colonne 2:nf contient les facteurs definissant la couleur des individus
386 for (i in 1:3) {
387 idss=ids[which(ids[,i+1]!="NA"),]
388 idss=data.frame(idss[idss[,i+1]!="",])
389 classe=as.factor(idss[[i+1]])
390 idsample=as.character(idss[[1]])
391 colour=1:length(levels(classe))
392 ions=as.matrix(idss[,5:dim(idss)[2]])
393 # choix du scaling : "uv","none","pareto"
394 object=suppressWarnings(prep(ions, scale=scaling, center=TRUE))
395 if(i==1){if(length(which(apply(ions,2,var)==0))>0){cat("Warning : there are",length(which(apply(ions,2,var)==0)),"constant ions.\n")}}
396 # ALGO: nipals,svdImpute, Bayesian, svd, probalistic=F
397 result <- pca(object, center=F, method="svd", nPcs=2)
398 # ADE4 : representation des ellipsoides des individus de chaque classe
399 s.class(result@scores, classe, cpoint = 1,xax=1,yax=2,col=colour,sub=sprintf("Scores - PCs %sx%s",1,2), possub="bottomright")
400 #s.label(result@loadings,label = ions, cpoint = 0, clabel=0.4, xax=1,yax=2,sub="Loadings",possub="bottomright")
401 if(i==1){resulti <- result}
402 }
403 if(indiv) {
404 colour <- rep("darkblue",length(resulti@loadings)) ; if(!is.null(indcol)) {colour[-c(indcol)] <- "red"}
405 plot(resulti@loadings,col=colour,main="Loadings",xaxt="n",yaxt="n",pch=20)
406 abline(h=0,v=0)}
407 }
408
409