-
Notifications
You must be signed in to change notification settings - Fork 0
/
lipidomicLib.r
2547 lines (2369 loc) · 77.9 KB
/
lipidomicLib.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
#a library of regularly used functions in the babraham project.
library(RMySQL)
library(MASS)
library(caret)
library(gplots)
library(RColorBrewer)
library(igraph)
library(stringr)
#con <- dbConnect(MySQL(), user="admin", password="johnny5", dbname= "crc", host = "mysql-jfoster.ebi.ac.uk", port = 4226)
con <- dbConnect(MySQL(), user="root", password="root", dbname= "lnet", host = "127.0.0.1", port = 3306)
getPatientData <-function(){
patientQuery = "select p.number, s.name, p.date_of_analysis, p.tumor_sample_amount_microgram, p.normal_sample_amount_microgram from patient as p, stage as s where p.l_stage_id = s.stage_id order by 1"
patData = dbGetQuery(con, patientQuery)
rownames(patData) = patData[,1]
patData = patData[,-1]
patData
}
# This function is to select more fields in patient table for PCA analysis
getAllPatientData <- function(){
patientQuery = "select p.number, p.genre, p.age, s.name, p.date_of_analysis, p.tumor_sample_amount_microgram, p.normal_sample_amount_microgram from patient as p, stage as s where p.l_stage_id = s.stage_id and p.age IS NOT NULL order by 1"
patData = dbGetQuery(con, patientQuery)
rownames(patData) = patData[,1]
patData = patData[,-1]
patData
}
getLipidClass <- function(){
patientQuery = "select name from lipid_class order by name"
patData = dbGetQuery(con, patientQuery)
#rownames(patData) = patData[,1]
patData = patData[,1]
patData
}
getPatientStageData <- function(){
patientQuery = "select s.name, count(p.number) from patient as p, stage as s where p.l_stage_id = s.stage_id group by s.name"
patData = dbGetQuery(con, patientQuery)
rownames(patData) = patData[,1]
patData
}
getPatientFattyAcidData <- function(){
patientQuery = "select DISTINCT(p.number), s.name from patient_has_fatty_acid_species pt, stage s, patient p where pt.f_patient_id = p.patient_id and p.l_stage_id = s.stage_id order by 1"
patData = dbGetQuery(con, patientQuery)
rownames(patData) = patData[,1]
patData
}
# tumour is dataset type
# true : tumour dataset ( TRG, DRG, MRG) -> (TG, DG, MG)
# false : other dataset ( TG, DG, MG)
getMassSpecies <- function(speciesL, tumour){
mass = rep(1,length(speciesL))
names(mass) = speciesL
id1 = which(speciesL == "SG" | speciesL == "C18-SG" | speciesL == "C18 Sphingosine")
if(length(id1) > 0){
mass[id1] = 299.2824
}
id2 = which(speciesL == "C18-S1P")
if(length(id2) > 0){
mass[id2] = 379.472
}
id3 = which(speciesL == "CH")
if(length(id3) > 0){
mass[id3] = 1
}
id4 = which(speciesL == "C18-SPC")
if(length(id4) > 0){
mass[id4] = 465.3457
}
id = c(id1,id2,id3,id4)
if(length(id) > 0)
speciesL = speciesL[-id]
df = read.csv("D:/project/lipidomics/data/lipidHomeDataExport.csv", header = F)
l = unlist(strsplit(speciesL, split ="-"))
if(tumour){
l[which(l=="TRG")] = "TG"
l[which(l=="DRG")] = "DG"
l[which(l=="MRG")] = "MG"
l[which(l=="DHCer")] = "dhCer"
}
speciesL = paste(l[seq(2,length(l),2)],l[seq(1,length(l),2)])
df = df[which(df$V2 %in% speciesL),]
if(nrow(df)>0){
for(i in 1:nrow(df)){
name = unlist(strsplit(as.character(df[i,'V2']), split =" "))
if(tumour){
if(name[1]=="TG")
name[1]="TRG"
if(name[1]=="DG")
name[1]="DRG"
if(name[1]=="MG")
name[1]="MRG"
if(name[1]=="dhCer")
name[1]="DHCer"
}
newN = paste(name[2],name[1],sep="-")
mass[newN] = as.numeric(as.character(df[i,'V9']))
}
}
mass
}
# Convert mass concentration to molar concentration
getMolarData <- function(data, tumour){
l = colnames(data)
mass = getMassSpecies(l, tumour)
data = t(t(data) / mass)
data
}
getPatientFattyAcidMatrix <- function(tumor){
patientData = getPatientFattyAcidData()
patients = rownames(patientData)
specieData = getFattyAcidData()
species = rownames(specieData)[which(!grepl('17_0-FA',specieData[,1]))]
patientFattyAcidMatrix = matrix(ncol = length(patients), nrow = length(species))
rownames(patientFattyAcidMatrix) = species
#if(tumor){
# ts = "t"
#}else{
# ts = "n"
#}
#colnames(patientFattyAcidMatrix) = paste(ts,patients, sep = "")
colnames(patientFattyAcidMatrix) = patients
for(i in 1:length(patients)){
quantityDataQ= paste("select h.quantity, CONCAT(s.carbons, '_', s.double_bonds, '-FA') as name from patient_has_fatty_acid_species as h, patient as p, fatty_acid_species as s where h.f_patient_id = p.patient_id and h.tumour = ",tumor," and h.f_fatty_acid_species_id = s.fatty_acid_species_id and p.number = ",patients[i]," and h.quantity != 400 order by s.carbons", sep = "")
quantitydata = dbGetQuery(con, quantityDataQ)
patientFattyAcidMatrix[,i] = quantitydata[,1]
#print(nrow(quantitydata))
}
t(patientFattyAcidMatrix)
}
# this function is a new version of filterClassPSM function, which deals with all lipid including PIPx
filterClassPSM_1 <- function(data, lipidClass){
lipidSpecies = vector()
tmp = colnames(data)
if(toupper(lipidClass) == "S1P" | toupper(lipidClass) == "SPC" | toupper(lipidClass) == "CH" | toupper(lipidClass) =="SG"){
data1 = matrix(data[,which(grepl(lipidClass, tmp))])
colnames(data1) = lipidClass
rownames(data1) = rownames(data)
data = data1
}else if(toupper(lipidClass) == "PIP" | toupper(lipidClass) == "PIP2" | toupper(lipidClass) == "PIP3"){
k = 1
for(i in 1:length(tmp)){
# only take species which are formatted as carbon:bond
if(grepl(":",tmp[i])){
lipidSpecies[k] = tmp[i]
k = k + 1
}
}
tSpeciesVec = unlist(strsplit(lipidSpecies, split ="-"))
l = length(tSpeciesVec)
data = data[,lipidSpecies]
data = data[,which(toupper(tSpeciesVec[seq(2,l,2)]) == toupper(lipidClass))]
}else{
lpClass = unlist(strsplit(tmp,"-"))
data = data[, which(toupper(lpClass[seq(2,length(lpClass),by=2)]) == toupper(lipidClass))]
}
data
}
# this is for cell data
convertToMatrix <- function(data){
row = nrow(data[[1]])
speciesClassNum = length(data)
colNames = vector()
quantity = vector()
k = 1
for(i in 1:speciesClassNum){
colN = colnames(data[[i]])
for(j in 1:length(colN)){
colNames[k] = colN[j]
quantity[k] = data[[i]][1,j]
k = k + 1
}
}
# in case of one row data only
m = matrix(nrow = 1, ncol = length(colNames))
m[1,] = quantity
colnames(m) = colNames
m
}
# get data for PCA analysis
getPatientDataMatrix <-function(tumor){
patientData = getAllPatientData()
patients = rownames(patientData)
patients = rownames(patientData)
specieData = getSpecieData()
species = rownames(specieData)[which(specieData[,2] == 0)]
#lipidClass = getLipidClass()
#lipidName = rownames(lipidClass)
patientSpecieMatrix = matrix(ncol = length(patients), nrow = length(species)+3)
if(tumor){
ts = "t"
}else{
ts = "n"
}
colnames(patientSpecieMatrix) = paste(ts,patients, sep = "")
#colnames(patientSpecieMatrix) = patients
for(i in 1:length(patients)){
quantityDataQ= paste("select h.quantity, s.name, c.name from patient_has_lipid_species as h, patient as p, lipid_species as s, lipid_class as c where h.l_patient_id = p.patient_id and h.tumour = ",tumor," and h.l_lipid_species_id = s.lipid_species_id and p.number = ",patients[i]," and s.standard = false and s.l_lipid_class_id = c.lipid_class_id order by c.name", sep = "")
quantitydata = dbGetQuery(con, quantityDataQ)
# measure lipid concentrations on log10 scale
age = as.numeric(patientData[i,2])
if(age >= 31 && age <= 40){
ageStr = "31-40"
}else if(age >= 41 && age <= 49){
ageStr = "41-49"
}else if(age >= 50 && age <= 59){
ageStr = "50-59"
}else if(age >= 60 && age <= 72){
ageStr = "60-72"
}else if(age >= 73 && age <= 98){
ageStr = "73-98"
}
dataVec = c(quantitydata[,1],ageStr,patientData[i,1],patientData[i,3])
patientSpecieMatrix[,i] = dataVec
#print(nrow(quantitydata))
}
rownames(patientSpecieMatrix) = c(species,'age','genre','stage')
t(patientSpecieMatrix)
}
plotPCAAnalysis <- function(){
pr = getPatientDataMatrix(TRUE)
pr1 = data.frame(pr)
# get quantitative varibles
x1 = pr[,1:547]
# convert to numeric
class(x1) = "numeric"
# get categorical variables (age, genre, stage)
x2 = pr1[,548:550]
scale(x2, center = TRUE, scale = TRUE)
# do PCA for mixed data types
library(PCAmixdata)
obj = PCAmix(X.quanti = x1, X.quali = x2, ndim = 3)
# factor scores for quantitative variables
A1 = obj$quanti.cor
# factor scores for categorical variables
A2 = obj$categ.coord
# factor scores for rows in the data
head(F)
# Component map with factor scores of the data (rows)
setwd("D:/project/lipidomics/data/lipid analysis")
#par(mfrow=c(2,2))
pdf(file = "pca_component_factor_score.pdf")
plot(obj, choice = "ind", ces = 0.6, habillage = "ind")
dev.off()
# Component map with factor scores of the numerical columns
pdf(file = "pca_numerical_col_factor_score.pdf")
plot(obj, choice = "cor", ces = 0.6, habillage = "cor")
dev.off()
pdf(file = "pca_categorical_col_factor_score.pdf")
# Component map with factor scores of the categorical columns
plot(obj, choice = "levels", ces = 0.6, habillage = "levels")
dev.off()
# contributions of the variables
pdf(file = "pca_variables_contribution.pdf")
plot(obj, choice = "sqload", ces = 0.6, habillage = "sqload")
dev.off()
# clustering
# Construction of the hierarchy
library(ClustOfVar)
pdf(file = "pca_hierarchical_cluster.pdf")
tree = hclustvar(X.quanti = x1, X.quali = x2)
# Graphical representation
plot(tree, cex = 0.5)
# Partition in 6 clusters
part = cutreevar(tree, 6)
dev.off()
plotData = obj$levels$coord
# get variables names
vars = rownames(plotData)
# extract age group
ageVars = vars[which(!is.na(as.numeric(vars)))]
ageCoord = plotData[ageVars,1:2]
genreVars = vars[which(vars == "female" | vars == "male")]
genreCoord = plotData[genreVars,1:2]
for(i in 1:length(genreVars)){
if(genreVars[i] == "female")
{
genreVars[i] = "F"
}
else{
genreVars[i] = "M"
}
}
stageVars = vars[which(vars %in% c("adenoma","dukes a","dukes b","dukes c","dukes d") )]
stageCoord = plotData[stageVars,1:2]
for(i in 1:length(stageVars)){
if(stageVars[i] == "adenoma"){
stageVars[i] = "Ade"
}
else if(stageVars[i] == "dukes a"){
stageVars[i] = "A"
}else if(stageVars[i] == "dukes b"){
stageVars[i] = "B"
}
else if(stageVars[i] == "dukes c"){
stageVars[i] = "C"
}else {
stageVars[i] = "D"
}
}
# Do PCA with using non-numeric variables as suppplementary variables
# extract numeric columns
# take first 65 rows for PCA analysis
# install.packages("devtools")
devtools::install_github("kassambara/factoextra")
# load
library("factoextra")
my.active = matrix(0, nrow = nrow(pr1[1:70,1:547]), ncol = ncol(pr1[1:70,1:547]))
my.active = pr1[1:70,1:547]
matrix = as.numeric(as.matrix(my.active))
dim(matrix) = dim(my.active)
rownames(matrix) = rownames(my.active)
res.pca = prcomp(matrix, center = TRUE, scale = TRUE)
#the matrix of variable loadings (columns are eigenvectors)
head(unclass(res.pca$rotation)[, 1:4])
# Eigenvalues
eig = (res.pca$sdev)^2
# Variances in percentage
variance = eig*100/sum(eig)
# Cumulative variances
cumvar = cumsum(variance)
eig.matrix = data.frame(eig = eig, variance = variance,
cumvariance = cumvar)
head(eig.matrix)
eig.val = get_eigenvalue(res.pca)
head(eig.val)
barplot(eig.matrix[, 2], names.arg=1:nrow(eig.matrix),
main = "Variances",
xlab = "Principal Components",
ylab = "Percentage of variances",
col ="steelblue")
# Add connected line segments to the plot
lines(x = 1:nrow(eig.matrix),
eig.matrix[, 2],
type="b", pch=19, col = "red")
# plot variance
fviz_screeplot(res.pca, ncp=10)
#plot eigenvalues
fviz_screeplot(res.pca, ncp=10, choice="eigenvalue")
# Variable correlation/coordinates
# this is to see how each component is strongly correlated with variables
loadings = res.pca$rotation
sdev = res.pca$sdev
var <- get_pca_var(res.pca)
var.coord = var.cor <- t(apply(loadings, 1, var_cor_func, sdev))
head(var.coord[, 1:4])
# Plot the correlation circle
a <- seq(0, 2*pi, length = 100)
plot( cos(a), sin(a), type = 'l', col="gray",
xlab = "PC1 - 13.6%", ylab = "PC2 - 9.1%")
abline(h = 0, v = 0, lty = 2)
# Add active variables
arrows(0, 0, var.coord[, 1], var.coord[, 2],
length = 0.1, angle = 15, code = 2)
# Add labels
text(var.coord, labels=colnames(my.active), cex = 1, adj=1)
# add supplmentary variables
# plot for age
pdf(file = "pca_suppl_age1.pdf")
quali.sup <- as.factor(as.matrix(pr1[1:70, 548]))
fviz_pca_ind(res.pca, data = matrix, axes = c(1,2),
habillage = quali.sup, addEllipses = TRUE, ellipse.level = 0.68) +
theme_minimal()
dev.off()
# plot for genre
pdf(file = "pca_suppl_genre1.pdf")
quali.sup <- as.factor(as.matrix(pr1[1:70, 549]))
fviz_pca_ind(res.pca, data = matrix, axes = c(1,2),
habillage = quali.sup, addEllipses = TRUE, ellipse.level = 0.68) +
theme_minimal()
dev.off()
# plot for stage
pdf(file = "pca_suppl_stage1.pdf")
quali.sup <- as.factor(as.matrix(pr1[1:70, 550]))
fviz_pca_ind(res.pca, data = matrix, axes = c(1,3),
habillage = quali.sup, addEllipses = TRUE, ellipse.level = 0.68) +
theme_minimal()
# plot individual factor map
ind.coord <- res.pca$x
plot(ind.coord[,1], ind.coord[,2], pch = 19,
xlab="PC1 - 13.6%",ylab="PC2 - 9.1%")
abline(h=0, v=0, lty = 2)
text(ind.coord[,1], ind.coord[,2], labels=rownames(ind.coord),
cex=0.7, pos = 3)
# plot individual factor map using sum of squared cosines
# The sum of squared cosines over all axes is 1
# the closer the observation to 1, the better interpreabilty of representation
fviz_pca_ind(res.pca, data = matrix, col.ind="cos2") +
scale_color_gradient2(low="white", mid="blue",
high="red", midpoint=0.50) + theme_minimal()
####################################################
par(new=TRUE)
plot(ageCoord,
, xlab = "Dim 1 (9.061 %)"
, ylab = "Dim 2 (6.726 %)"
, type = "p"
, cex = 0.8
, pch = 17
, col = "red"
)
text(ageCoord, labels=ageVars, cex= 0.7, pos=3)
par(new=TRUE)
plot(genreCoord,
, xlab = ""
, ylab = ""
, type = "p"
, cex = 0.8
, pch = 19
, col = "blue"
)
text(genreCoord, labels=genreVars, cex= 0.7, pos=3)
par(new=TRUE)
plot(stageCoord,
, xlab = ""
, ylab = ""
, axes = FALSE
, type = "p"
, cex = 0.8
, pch = 15
, col = "green"
)
text(stageCoord, labels=stageVars, cex= 0.7, pos=3)
}
# Correlation between variables and principal components
var_cor_func <- function(var.loadings, comp.sdev){
var.loadings*comp.sdev
}
getPatientSpecieMatrix <-function(tumor){
patientData = getPatientData()
patients = rownames(patientData)
specieData = getSpecieData()
species = rownames(specieData)[which(specieData[,2] == 0)]
patientSpecieMatrix = matrix(ncol = length(patients), nrow = length(species))
rownames(patientSpecieMatrix) = species
#if(tumor){
# ts = "t"
#}else{
# ts = "n"
#}
#colnames(patientSpecieMatrix) = paste(ts,patients, sep = "")
colnames(patientSpecieMatrix) = patients
for(i in 1:length(patients)){
quantityDataQ= paste("select h.quantity, s.name, c.name from patient_has_lipid_species as h, patient as p, lipid_species as s, lipid_class as c where h.l_patient_id = p.patient_id and h.tumour = ",tumor," and h.l_lipid_species_id = s.lipid_species_id and p.number = ",patients[i]," and s.standard = false and s.l_lipid_class_id = c.lipid_class_id order by 2", sep = "")
quantitydata = dbGetQuery(con, quantityDataQ)
patientSpecieMatrix[,i] = quantitydata[,1]
#print(nrow(quantitydata))
}
t(patientSpecieMatrix)
}
normalisePatientSpecieMatrix <- function(patientSpecieMatrix){
for(i in 1:nrow(patientSpecieMatrix)){
patientSpecieMatrix[i,] = patientSpecieMatrix[i,]/sum(patientSpecieMatrix[i,])
}
patientSpecieMatrix
}
normaliseSpecieMatrix <- function(mt){
for(i in 1:nrow(mt)){
mt[i,] = mt[i,]/sum(mt[i,])
}
mt
}
filterClassPSM <- function(PSM, lclass){
specieData = getSpecieData()
cespecies = rownames(specieData)[which(specieData[,1] == lclass)]
coi = which(colnames(PSM) %in% cespecies)
PSM[,coi,drop=FALSE]
}
getSpecieData <- function(){
specieInformationQ = "select s.name,c.name,s.standard,s.carbons, s.double_bonds from lipid_species as s, lipid_class as c where s.l_lipid_class_id = c.lipid_class_id and s.standard=false order by 1"
specieData = dbGetQuery(con, specieInformationQ)
rownames(specieData) = specieData[,1]
specieData = specieData[,-1]
specieData
}
getFattyAcidData <- function(){
fattyAcidInformationQ = "select CONCAT(s.carbons, '_', s.double_bonds, '-FA') as name from fatty_acid_species as s order by 1"
specieData = dbGetQuery(con, fattyAcidInformationQ)
rownames(specieData) = specieData[,1]
specieData
}
applyDetectionLimit<- function(patientSpecieMatrix){
specieData = getSpecieData()
detectionLimits = read.table(file= "D:/project/lipidomics/data/detectionLimit.txt", header = F, sep = "\t")
for(i in 1:ncol(patientSpecieMatrix)){
specie = colnames(patientSpecieMatrix)[i]
class = specieData[which(rownames(specieData) == specie),1]
detectionLimit = detectionLimits[which(detectionLimits[,1] == class),2]
patientSpecieMatrix[which(patientSpecieMatrix[,i] < detectionLimit),i] = detectionLimit
}
patientSpecieMatrix
}
getRatioPSM<- function(tPSM, nPSM){
applyDetectionLimit(tPSM)/applyDetectionLimit(nPSM)
}
stageMeta <- function(patientData){
meta = 1
patientMeta = patientData[,meta]
result = list()
result$patientMeta = patientMeta
result$toRemove = vector()
result
}
metastasisMeta <- function(patientData){
meta = 13
patientMeta = patientData[,meta]
result = list()
a= is.na(patientMeta)
for(i in 1:length(a)){
if(a[i]){
if(patientData[i,1] == "dukes d"){
patientMeta[i] = "M"
}else{
patientMeta[i] = "N"
}
}else{
if(patientData[i,1] == "dukes d"){
patientMeta[i] = "M"
}else{
patientMeta[i] = "N"
}
}
}
result$patientMeta = patientMeta
result$toRemove = vector()
result
}
maleMeta <- function(patientData){
meta = 6
patientMeta = patientData[,meta]
a = which(is.na(patientMeta))
toRemove = a
patientMeta = as.character(patientMeta[-toRemove])
for(i in 1:length(patientMeta)){
if(patientMeta[i] == "0"){
patientMeta[i] = "F"
}else{
patientMeta[i] = "M"
}
}
result = list()
result$patientMeta = patientMeta
result$toRemove = toRemove
result
}
mortalityMeta <- function(patientData){
meta = 15
patientMeta = patientData[,meta]
a = which(is.na(patientMeta))
patientMeta[a] = "alive"
patientMeta[-a] = "dead"
result = list()
result$patientMeta = patientMeta
result$toRemove = vector()
result
}
siteMeta <- function(patientData){
meta = 7
patientMeta = patientData[,meta]
a = names(which(table(patientMeta)>5))
toKeep = which(patientMeta %in% a)
v = 1:length(patientMeta)
toRemove = v[-toKeep]
patientMeta = patientMeta[-toRemove]
result = list()
result$patientMeta = patientMeta
result$toRemove = toRemove
result
}
#this is probably regression even though we have distinct classes
sizeMeta<- function(patientData){
meta = 11
patientMeta = patientData[,meta]
a = which(is.na(patientMeta))
toRemove = a
patientMeta = patientMeta[-toRemove]
result = list()
result$patientMeta = patientMeta
result$toRemove = toRemove
result
}
spreadMeta = function(patientData){
meta = 12
patientMeta = patientData[,meta]
a = which(is.na(patientMeta))
toRemove = a
patientMeta = patientMeta[-toRemove]
result = list()
result$patientMeta = patientMeta
result$toRemove = toRemove
result
}
sampleMeta<- function(pNamesVec){
patientMeta = vector(length = length(pNamesVec))
for(i in 1:length(pNamesVec)){
patientMeta[i] = substr(pNamesVec[i],1,1)
}
toRemove = vector()
result = list()
result$patientMeta = patientMeta
result$toRemove = toRemove
result
}
tExpression <- function(tData, nData){
tVec = vector(length = ncol(tData))
for(i in 1:ncol(tData)){
t = t.test(tData[,i], nData[,i], paired = T)
tVec[i] = t$p.value
}
#bontVec = tVec * i
#bontVec
tVec
}
mdsPlot <- function(PSMO, nFeatures){
d <- dist(PSMO[,1:nFeatures]) # euclidean distances between the rows
mds <- isoMDS(d, k=2) # k is the number of dim
mds # view results
# plot solution
x <- mds$points[,1]
y <- mds$points[,2]
plot(x, y, xlab="Coordinate 1", ylab="Coordinate 2", main=paste("isoMDS of ", nFeatures," most important sample species",sep = ""), type="n")
text(x, y, labels = row.names(PSMO), cex=.7)
}
pcaPlot <- function(PSMO, nFeatures){
pcaa <- princomp(PSMO[,1:nFeatures], cor=TRUE)
#plot(pcaa,type="lines") # scree plot
biplot(pcaa, main = paste("isoMDS of ", nFeatures," most important sample species",sep = ""))
}
plotFeatureRatioDistribution<- function(logData, features){
ldata = logData[,features]
for(i in 1:ncol(ldata)){
feature = features[i]
pdf(width = 8 , height = 8 , file = paste("featureRatio_",feature,".pdf", sep = ""))
plot(density(logData[,i]))
dev.off()
}
}
getPatientColVec <- function(patientNumbers, meta){
a = list()
colVec = vector(length = length(patientNumbers))
pData = getPatientData()
mClasses = unique(pData[,meta])
colPal = rainbow(length(mClasses))
for(i in 1:length(patientNumbers)){
p = substr(patientNumbers[i], 2, nchar(patientNumbers[i]))
roi = which(rownames(pData) == p)
moi = which(mClasses == pData[roi,meta])
if(length(moi)==0){
colVec[i] = "black"
colPal[1] = "black"
if(length(which(mClasses=="unknown"))==0){
mClasses[which(is.na(mClasses))] = "unknown"
}
}else{
colVec[i] = colPal[moi]
}
}
a$classcols = colPal
a$colVec = colVec
a$classes = mClasses
a
}
removeSparseSpecies<-function(PSM,cutOff,threshold){
excluders = vector()
for(i in 1:ncol(PSM)){
toExclude = which(PSM[,i] <= threshold)
if(length(toExclude)>cutOff){
excluders = c(excluders, i)
}
}
PSM[,-excluders]
}
# get set of
#you are here
getReactionRatio <- function(PSM){
reactions = as.matrix(read.csv("D:/project/lipidomics/reactions.csv", header = T))
result = list()
reactionCount = list()
layerCount = list()
sReactions = matrix(ncol = 2)
firstRun = TRUE
for(i in 1:nrow(reactions)){
reactant = reactions[i,1]
product = reactions[i,2]
rSpecies = colnames(filterClassPSM(PSM,reactant))
pSpecies = colnames(filterClassPSM(PSM,product))
if(reactant == "DG"){
reactant = "DRG"
}
if(product == "DG"){
product = "DRG"
}
rFAs = getFAs(rSpecies)
pFAs = getFAs(pSpecies)
sharedFAs = which(rFAs %in% pFAs)
for(j in 1:length(sharedFAs)){
fai = sharedFAs[j]
fa = rFAs[fai]
if(is.null(layerCount[[fa]])) {
layerCount[[fa]] = 1
}else{
layerCount[[fa]] = layerCount[[fa]] + 1
}
if(is.null(reactionCount[[paste(reactions[i,], collapse = "->")]])){
reactionCount[[paste(reactions[i,], collapse = "->")]] = 1
}else{
reactionCount[[paste(reactions[i,], collapse = "->")]] = reactionCount[[paste(reactions[i,], collapse = "->")]] + 1
}
if(firstRun){
sReactions[1,] = c(paste(fa, reactant,sep = "-"),paste(pFAs[which(pFAs==fa)],product,sep = "-"))
firstRun = FALSE
}else{
sReactions = rbind(sReactions, c(paste(fa,reactant,sep = "-"),paste(pFAs[which(pFAs==fa)],product,sep = "-")))
}
}
}
#par(ask = TRUE)
prMat = matrix(ncol =nrow(sReactions), nrow = nrow(PSM))
colVec = vector(length = nrow(sReactions))
rownames(prMat) = rownames(PSM)
for(i in 1:nrow(sReactions)){
reactant = sReactions[i,1]
product = sReactions[i,2]
#colVec[i] = paste(reactant,"->", product, sep = "")
s = unlist(strsplit(reactant, split="-"))
layer = s[1]
rec = s[2]
s1 = unlist(strsplit(product, split="-"))
pro = s1[2]
colVec[i] = paste(paste(rec,"-", pro, sep = ""), "[", layer, "]", sep = "")
rVec = PSM[,which(colnames(PSM) == reactant)]
pVec = PSM[,which(colnames(PSM)== product)]
prVec = vector(length = length(pVec))
#for(j in 1:length(pVec)){
# if(rVec[j] != 0 && pVec[j] != 0){
# prVec[j] = log10(pVec[j]/rVec[j]);
# }else{
# prVec[j] = 4;
# }
#}
prVec = pVec/rVec
prMat[,i] =prVec
}
colnames(prMat) = colVec
result$prMat = prMat
result$sReactions = sReactions
result$reactionCount = reactionCount
result$layerCount = layerCount
result
}
getFAs <- function(species){
fas = vector(length = length(species))
for(i in 1:length(species)){
fas[i] = as.vector(unlist(strsplit(species[i], split ="-")))[length(as.vector(unlist(strsplit(species[i], split ="-"))))-1]
}
fas
}
closeDBConnection <- function(){
all_cons <- dbListConnections(MySQL())
for(con in all_cons)
dbDisconnect(con)
}
getFeatureSumCoefV <- function(PSMN,PSMT){
ncoefv = vector(length = ncol(PSMN))
tcoefv = vector(length = ncol(PSMT))
nans = vector()
for(i in 1:ncol(PSMN)){
ncoefv[i] = calculateCoefv(PSMN[,i])
tcoefv[i] = calculateCoefv(PSMT[,i])
}
coefvM = matrix(nrow =length(ncoefv), ncol = 3)
rownames(coefvM) = colnames(PSMN)
coefvM[,1] = ncoefv
coefvM[,2] = tcoefv
for(i in 1:nrow(coefvM)){
coefvM[i,3] = coefvM[i,1] + coefvM[i,2]
}
coefvM
}
calculateCoefv <- function(aVec){
asdev = sd(aVec)
amean = mean(aVec)
result = (asdev*100)/amean
result
}
# This function is to calculate z-score of subpathway when ignoring the layers
getSubPathwayZScore <- function(pathway, tData, nData,alt){
size = length(pathway)-1
z = vector()
z_score = 0
for(i in 1:size){
# get z-score for each edge
z[i] = getEdgeZScore(pathway[i],pathway[i+1], tData, nData,alt)
}
z_score = sum(z)/sqrt(size)
z_score
}
getFattyAcidEdgeZScore <- function(pathway, refData, controlData, alt){
size = length(pathway)-1
z = vector()
z_score = 0
for(i in 1:size){
# get z-score for each edge
z[i] = getFattyAcidZScore(pathway[i],pathway[i+1], refData, controlData, alt)
}
z_score = sum(z)/sqrt(size)
z_score
}
# calculate z-sore of subpathway for Hbec
getHbecSubPathwayZScore <- function(pathway, refData, controlData,alt){
size = length(pathway)-1
z = vector()
z_score = 0
for(i in 1:size){
# get z-score for each edge
z[i] = getHbecEdgeZScore(pathway[i],pathway[i+1], refData, controlData,alt)
}
z_score = sum(z)/sqrt(size)
z_score
}
getHbecSubPathwayZScore0 <- function(pathway, refData, controlData,alt,type){
size = length(pathway)-1
z = vector()
z_score = 0
for(i in 1:size){
# get z-score for each edge
z[i] = getHbecEdgeZScore0(pathway[i],pathway[i+1], refData, controlData,alt,type)
}
z_score = sum(z)/sqrt(size)
z_score
}
getHbecSubPathwayZScore1 <- function(pathway, refData, controlData,alt){
size = length(pathway)-1
z = vector()
z_score = 0
for(i in 1:size){
# get z-score for each edge
z[i] = getHbecEdgeZScore1(pathway[i],pathway[i+1], refData, controlData,alt)
}
z_score = sum(z)/sqrt(size)
z_score
}
getFattyAcidSubPathwayZScore <- function(pathway, refData, controlData,alt){
size = length(pathway)-1
z = vector()
z_score = 0
for(i in 1:size){
# get z-score for each edge
z[i] = getFattyAcidEdgeZScore(pathway[i],pathway[i+1], refData, controlData,alt)
}
z_score = sum(z)/sqrt(size)
z_score
}
getSubPathwayZScoreByStage <- function(pathway, tData, nData,alt,sigLevel){
# get data by stages
#patientData = getPatientData()
#pml = stageMeta(patientData)
#patientMeta = pml$patientMeta
#split into stages
#stages = unique(patientMeta)
stages = getPatientStageData()
# only consider stages which have sufficiently large amount of data
# Set the threshold to be 20 (ideally at least 30)
index = which(stages[,2] >= 20)
stages = stages[index,1]
stagePatients = list()
size = length(pathway)-1
z_score = 0
s = 0
z = vector()
p = vector()
n = length(stages)
for(i in 1:n){
poi = which(patientMeta == stages[i])
stagePatients = tData[poi,]
nnData = nData[poi,]
for(j in 1:size){
# get z-score for each edge
z[j] = getEdgeZScore(pathway[j],pathway[j+1], stagePatients, nnData,alt)
}
# convert to p-value
p[i] = 1 - pnorm(sum(z)/sqrt(size))
}
p = sort(p, decreasing = FALSE)
pp = vector()
zz = vector()
for(i in 1:n){
s = 0
for(j in i:n){
s = s + (factorial(n) / (factorial(j) * factorial(n-j))) * p[i]^j*(1-p[i])^(n-j)
}
pp[i] = s
zz[i] = qnorm(1 - pp[i])
}
z_score = max(zz)
z_score
}
# this function is to plot weighted pathway graph
plotPathwayGraph <- function(reactant, product, ZScore, pdfFileName){
edge = data.frame(from = reactant, to = product, thickness = ZScore)
qgraph(as.matrix(edge),edge.labels=T,label.prop = 0.6, mode="direct", edge.label.cex=0.6, asize=1.5, vsize=4,fade=F,filename=pdfFileName,filetype = "pdf", height = 5, width = 10)
#edge = data.frame(from = reactant, to = product)
#n = nrow(edge)
#edge = cbind(edge, seq(min(2*ZScore),max(2*ZScore),length=n))
#qgraph(as.matrix(edge),edge.labels=F,label.prop = 0.6, mode="direct", edge.label.cex=0.6, asize=1.5, vsize=4,fade=FALSE, filename=pdfFileName,filetype = "pdf", height = 5, width = 10)
}
getEdgeZScoreByStage <- function(reactant, product, tData, nData){
# get data by stages
patientData = getPatientData()
pml = stageMeta(patientData)
patientMeta = pml$patientMeta
#split into stages
stages = unique(patientMeta)
stagePatients = list()
z_score = 0
s = 0
p = vector()
n = length(stages)
for(i in 1:n){
poi = which(patientMeta == stages[i])
stagePatients = tData[poi,]
trData = filterClassPSM(stagePatients,reactant)
tpData = filterClassPSM(stagePatients,product)
nrData = filterClassPSM(nData,reactant)
npData = filterClassPSM(nData,product)
if(is.vector(nrData)){
nnrData = nrData[poi]
}else{
nnrData = nrData[poi,]
}
if(is.vector(npData)){
nnpData = npData[poi]
}else{
nnpData = npData[poi,]
}
tSumV = list()
nSumV = list()
p[i] = 0
if(is.vector(tpData)){
tSumV[[1]] = tpData
}else{
tSumV[[1]] = rowSums(tpData)