-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbacteria_processing_3.Rmd
4240 lines (3542 loc) · 164 KB
/
bacteria_processing_3.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "bacteria_processing_3"
author: "Ilya"
date: "6/24/2019"
output: github_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
####install and load required packages
```{r packages, echo=FALSE}
source("packages_bacteria1.R")
# devtools::install_github("guiastrennec/ggplus")
# library(ggplus)
#https://github.com/guiastrennec/ggplus
```
###read in BacDive data
###find out fields with at least threshold % coverage
```{r get_proportion}
# load("DATA/PROCESSED/Data from Backdive-2.RData")
load("Data from Backdive-2.RData")
# load("bacteria_species_out.Rdata")
dim(merge)
merge_test = unique(merge)
dim(merge_test)
#11752 taxonomy_name strains_tax_PNU species_epithet actinomycetemcomitans
test = subset(merge, bacdive_id == 11752 &
section == "taxonomy_name" &
subsection == "strains_tax_PNU" &
field == "species_epithet")
threshold = 0.01
D = merge
dim(D)
D = unique(D)
dim(D)
#rm(merge)
#remove NA values
inds.na = which(!is.na(D$value))
D = D[inds.na,]
id_len=length(unique(D$bacdive_id))
D$new_field = paste(D$section, D$subsection, D$field)
save(D, file = "DATA/PROCESSED/D.Rdata")
count=as.data.frame(table(D$new_field))#combination of subsection and field
var1=count$Var1
freq=count$Freq
var<-list()
freqs<-list()
for (i in 1:length(freq)) {
if (freq[i]>=threshold*id_len) {#this will get fields greater than 1%
var[[i]]=var1[i]
freqs[[i]]=freq[i]
}
}
df=do.call(rbind, Map(data.frame, Feature_name=var, Frequency=freqs))
df$Fraction = df$Frequency/id_len
###get those seen at least 1% of time
df01 = subset(df, Fraction >= 0.01)
save(df01, file = "DATA/PROCESSED/df01.Rdata")
```
#use df01 to subset all data for those variables
```{r subset_01}
load("DATA/PROCESSED/D.RData")
merge01 = subset(D, new_field %in% df01$Feature_name)
save(merge01, file = "DATA/PROCESSED/merge01.Rdata")
```
```{r data_processing}
##this part is from data_processing.R
load("DATA/PROCESSED/merge01.Rdata")
df <- merge01
df <- unique(df)
df$feature_name <- paste(df$section, df$subsection, df$field)
a <- df[is.element(df$feature_name, df01$Feature_name),]#df01 for 1% threshold
q_all <- dcast(a, bacdive_id~feature_name)
dim(q_all)
q = q_all
q <- q[order(q$bacdive_id),]
dim(q)
##test with merge10
# df10 <- merge10
#
# df10 <- unique(df10)
#
# df10$feature_name <- paste(df10$section, df10$subsection, df10$field)
#
# a10 <- df10[is.element(df10$feature_name, df20$Feature_name),]
# q <- dcast(a, bacdive_id~feature_name)
# q <- q[order(q$bacdive_id),]
write.csv(q, file = "df.csv", row.names = F)
temp = read.csv("df.csv")
col_names_list = names(temp)
write.csv(col_names_list, file = "bacteria_fields.csv",
row.names=FALSE)
dim(temp)
# # remove columns with near zero variance Global
# nzv <- nearZeroVar(q,saveMetrics=TRUE,freqCut = 95/5)
# nzv <- row.names(nzv[which(nzv$nzv==TRUE),])
# dropnzv<-names(q[ , which(names(q) %in% nzv)])
# q <- q[ , -which(names(q) %in% nzv)]
# write.csv(q, file = "dropnzvdata.csv", row.names = F)
```
```{r rm_fix_fields}
##this part corresponds to Zach's one_hot_encoding.R
#one-hot encode categorical variables
q_all <- read.csv(file = "df.csv")
q = q_all
dim(q)
str(q)
str(q, list.len=ncol(q))
q$molecular_biology.GC_content.GC_content=as.character(q$molecular_biology.GC_content.GC_content)
q$culture_growth_condition.culture_temp.temp1=as.character(q$culture_growth_condition.culture_temp.temp1)
q$culture_growth_condition.culture_temp.temp2=as.character(q$culture_growth_condition.culture_temp.temp2)
q$culture_growth_condition.culture_temp.temp = as.character(q$culture_growth_condition.culture_temp.temp)
#remove some fields we checked out
rm = c("culture_growth_condition.culture_medium.medium_name",
"culture_growth_condition.culture_medium.medium_name1",
"culture_growth_condition.culture_medium.medium_name2",
"culture_growth_condition.culture_temp.temp2","culture_growth_condition.culture_temp.test_type2",
"environment_sampling_isolation_source.origin.geo_loc_name",
"environment_sampling_isolation_source.origin.sample_type",
"molecular_biology.sequence.DB_sequence",
"molecular_biology.sequence.DB_sequence2",
"molecular_biology.sequence.seq_acc_num",
"molecular_biology.sequence.seq_acc_num1",
"molecular_biology.sequence.seq_acc_num2",
"references.reference1.NA",
"references.reference2.NA",
"references.reference3.NA",
"references.reference4.NA",
"strain_availability.strain_history.history",
"strain_availability.straininfo_link.URL",
"strain_availability.straininfo_link.URL1",
"strain_availability.straininfo_link.URL2",
"strain_availability.strains.strain_number",
"taxonomy_name.strains.designation",
"taxonomy_name.strains.full_scientific_name",
"taxonomy_name.strains.genus",
"taxonomy_name.strains.species",
"taxonomy_name.strains.species_epithet",
"taxonomy_name.strains_synonyms_PNU.pnu_synonym",
"taxonomy_name.strains_tax_PNU.status_gen",
"taxonomy_name.strains_tax_PNU.status_spec",
"environment_sampling_isolation_source.origin.country",
# "taxonomy_name.strains_tax_PNU.phylum",
"molecular_biology.sequence.DB_sequence1",
"taxonomy_name.strains.class",
"taxonomy_name.strains.family",
"taxonomy_name.strains.ordo",
"taxonomy_name.strains.phylum",
"taxonomy_name.strains_tax_PNU.class",
"taxonomy_name.strains_tax_PNU.family",
"taxonomy_name.strains_tax_PNU.genus",
"taxonomy_name.strains_tax_PNU.full_scientific_name",
#"taxonomy_name.strains_tax_PNU.species",#use species as identifier
"taxonomy_name.strains_tax_PNU.species_epithet")#30
keep = setdiff(names(q), rm)
q = q[,keep]
na_temp_range = which(is.na(q$`culture_growth_condition culture_temp temperature_range`))
q$`culture_growth_condition culture_temp temperature_range`[na_temp_range]=
q$`culture_growth_condition culture_temp temperature_range1`[na_temp_range]
q$molecular_biology.GC_content.GC_content= as.character(q$molecular_biology.GC_content.GC_content)
a = 904
#fix GC content
for (a in 1:dim(q)[1]){
if(!is.na(q$molecular_biology.GC_content.GC_content[a])){
if (grepl("±", q$molecular_biology.GC_content.GC_content[a])==TRUE){
split = strsplit(q$molecular_biology.GC_content.GC_content[a], "±")
q$molecular_biology.GC_content.GC_content[a] =as.numeric(split[[1]][1])
}
length_char = str_length(q$molecular_biology.GC_content.GC_content[a])
if (length_char > 4){
split = strsplit(q$molecular_biology.GC_content.GC_content[a], "-")
q$molecular_biology.GC_content.GC_content[a] =(as.numeric(split[[1]][2])+as.numeric(split[[1]][1]))/2
}
}
}
#fix morphology_physiology.colony_morphology.colony_len
q$morphology_physiology.colony_morphology.colony_len=as.character(q$morphology_physiology.colony_morphology.colony_len)
for (a in 1:dim(q)[1]){
if(!is.na(q$morphology_physiology.colony_morphology.colony_len[a])){
q$morphology_physiology.colony_morphology.colony_len[a]=str_replace(q$morphology_physiology.colony_morphology.colony_len[a],
pattern = ">",
replacement = "")
q$morphology_physiology.colony_morphology.colony_len[a]=str_replace(q$morphology_physiology.colony_morphology.colony_len[a],
pattern = "<",
replacement = "")
grep_test = grepl("-", q$morphology_physiology.colony_morphology.colony_len[a])
if (grep_test == TRUE){
split = strsplit(q$morphology_physiology.colony_morphology.colony_len[a], "-")
q$morphology_physiology.colony_morphology.colony_len[a] =(as.numeric(split[[1]][2])+as.numeric(split[[1]][1]))/2
}
}
}
q$morphology_physiology.colony_morphology.colony_len=as.numeric(q$morphology_physiology.colony_morphology.colony_len)
#fix morphology_physiology.cell_morphology.cell_len
q$morphology_physiology.cell_morphology.cell_len=as.character(q$morphology_physiology.cell_morphology.cell_len)
for (a in 1:dim(q)[1]){
if(!is.na(q$morphology_physiology.cell_morphology.cell_len[a])){
q$morphology_physiology.cell_morphology.cell_len[a]=str_replace(q$morphology_physiology.cell_morphology.cell_len[a],
pattern = ">",
replacement = "")
q$morphology_physiology.cell_morphology.cell_len[a]=str_replace(q$morphology_physiology.cell_morphology.cell_len[a],
pattern = "<",
replacement = "")
grep_test = grepl("-", q$morphology_physiology.cell_morphology.cell_len[a])
if (grep_test == TRUE){
split = strsplit(q$morphology_physiology.cell_morphology.cell_len[a], "-")
q$morphology_physiology.cell_morphology.cell_len[a] =(as.numeric(split[[1]][2])+as.numeric(split[[1]][1]))/2
}
}
}
q$morphology_physiology.cell_morphology.cell_len=as.numeric(q$morphology_physiology.cell_morphology.cell_len)
#fix morphology_physiology.cell_morphology.cell_width
q$morphology_physiology.cell_morphology.cell_width=as.character(q$morphology_physiology.cell_morphology.cell_width)
for (a in 1:dim(q)[1]){
if(!is.na(q$morphology_physiology.cell_morphology.cell_width[a])){
q$morphology_physiology.cell_morphology.cell_width[a]=str_replace(q$morphology_physiology.cell_morphology.cell_width[a],
pattern = ">",
replacement = "")
q$morphology_physiology.cell_morphology.cell_width[a]=str_replace(q$morphology_physiology.cell_morphology.cell_width[a],
pattern = "<",
replacement = "")
grep_test = grepl("-", q$morphology_physiology.cell_morphology.cell_width[a])
if (grep_test == TRUE){
split = strsplit(q$morphology_physiology.cell_morphology.cell_width[a], "-")
q$morphology_physiology.cell_morphology.cell_width[a] =(as.numeric(split[[1]][2])+as.numeric(split[[1]][1]))/2
}
}
}
q$morphology_physiology.cell_morphology.cell_width=as.numeric(q$morphology_physiology.cell_morphology.cell_width)
q$molecular_biology.GC_content.GC_content= as.numeric(q$molecular_biology.GC_content.GC_content)
keep = c(#"application_interaction.risk_assessment.biosafety_level",
"molecular_biology.GC_content.GC_content",
"taxonomy_name.strains_tax_PNU.species",
"culture_growth_condition.culture_temp.temperature_range",
# "culture_growth_condition culture_temp temperature_range1",
"environment_sampling_isolation_source.origin.continent",
# "taxonomy_name.strains_tax_PNU.phylum",
"taxonomy_name.strains_tax_PNU.species",
"environment_sampling_isolation_source.origin.latitude",
"environment_sampling_isolation_source.origin.longitude",
"morphology_physiology.spore_formation.type",
"morphology_physiology.oxygen_tolerance.oxygen_tol",
#"morphology_physiology.met_test.metabolite_test",#don't know what this means
#"morphology_physiology.met_production.metabolite_prod",#don't know what this means
#"morphology_physiology.met_antibiotica.metabolite_antib",#don't know what this means
#"morphology_physiology.halophily.salt_concentration",#FIXED to make numeric. Includes >, <. This is relative to multiple possible measures -- growth, optimum. discard.
#"morphology_physiology.met_antibiotica.ab_resistance_conc",#don't know what this means. Seems to refer to concentration of antibiotic in test. Exclude.
"morphology_physiology.colony_morphology.colony_len",#FIXED to make numeric. Includes >, <
"morphology_physiology.colony_morphology.hemolysis_type",#don't know what this means
"morphology_physiology.cell_morphology.motility",#factor
"morphology_physiology.cell_morphology.gram_stain",#factor
"morphology_physiology.cell_morphology.flagellum_arrangement",#factor
"morphology_physiology.cell_morphology.cell_len",#FIXED to make numeric. assumning all in same units
"morphology_physiology.cell_morphology.cell_shape",#factor
"morphology_physiology.cell_morphology.cell_width",#need to FIX to make numeric
# "culture_growth_condition.culture_temp.temp",#need to FIX to make numeric; refers to growth vs. optimum; exclude
# "culture_growth_condition.culture_pH.pH",
"bacdive_id")#need to FIX to make numeric; refers to growth vs. optimum; exclude
q = q[,keep]
save(q, file = "q.Rdata")
load("q.Rdata")
bacteria_traits_fields_subset = q
write.csv(bacteria_traits_fields_subset, file = "bacteria_traits_fields_subset.csv",
row.names = FALSE)
```
###one hot encode
```{r hot_one}
# load("q.Rdata")
# names(q)
# dmy <- dummyVars(" ~ .", data = q,fullRank = T, sep=".")
# df_transformed <- data.frame(predict(dmy, newdata = q))
#
# write.csv(df_transformed, file = "onehotdata.csv", row.names = F)
```
###visualize features
```{r graphs}
load("q.Rdata")
#biosafety
# plot <- ggplot(data = q, aes(x = application_interaction.risk_assessment.biosafety_level))+
# geom_histogram(stat = "count")
# plot
#
# ggsave(filename = "biosafety.jpeg", plot = plot)
#temperature range
plot <- ggplot(data = q, aes(x = culture_growth_condition.culture_temp.temperature_range))+
geom_histogram(stat = "count")
plot
ggsave(filename = "temp.jpeg", plot = plot)
#continent
plot <- ggplot(data = q, aes(x = environment_sampling_isolation_source.origin.continent))+
geom_histogram(stat = "count")+
theme(axis.text.x = element_text(angle = 90, hjust = 1))
plot
ggsave(filename = "continent.jpeg", plot = plot)
#phylum
# plot <- ggplot(data = q, aes(x = taxonomy_name.strains_tax_PNU.phylum))+
# geom_histogram(stat = "count")+
# theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
# plot
#
# ggsave(filename = "phylum.jpeg", plot = plot)
#GC content
plot <- ggplot(data = q, aes(x = molecular_biology.GC_content.GC_content))+
geom_histogram()+
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
plot
ggsave(filename = "GC.jpeg", plot = plot)
#morphology_physiology.spore_formation.type
plot <- ggplot(data = q, aes(x = morphology_physiology.spore_formation.type))+
geom_histogram(stat = "count")+
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))+
scale_y_log10()
plot
ggsave(filename = "formation-type.jpeg", plot = plot)
length(which(!is.na(q$morphology_physiology.spore_formation.type)))/dim(q)[1]#1%
#morphology_physiology.oxygen_tolerance.oxygen_tol
# plot <- ggplot(data = q, aes(x = morphology_physiology.oxygen_tolerance.oxygen_tol))+
# geom_histogram(stat = "count")+
# theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
# scale_y_log10()
#
# plot
ggsave(filename = "morphology_physiology.oxygen_tolerance.oxygen_tol.jpeg", plot = plot)
#morphology_physiology.cell_morphology.motility
plot <- ggplot(data = q, aes(x = morphology_physiology.cell_morphology.motility))+
geom_histogram(stat = "count")+
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
scale_y_log10()
plot
ggsave(filename = "morphology_physiology.cell_morphology.motility.jpeg", plot = plot)
#morphology_physiology.cell_morphology.gram_stain
plot <- ggplot(data = q, aes(x = morphology_physiology.cell_morphology.gram_stain))+
geom_histogram(stat = "count")+
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
scale_y_log10()
plot
ggsave(filename = "morphology_physiology.cell_morphology.gram_stain.jpeg", plot = plot)
#morphology_physiology.cell_morphology.flagellum_arrangement
# plot <- ggplot(data = q, aes(x = morphology_physiology.cell_morphology.flagellum_arrangement))+
# geom_histogram(stat = "count")+
# theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
# scale_y_log10()
#
# plot
ggsave(filename = "morphology_physiology.cell_morphology.flagellum_arrangement.jpeg", plot = plot)
#morphology_physiology.cell_morphology.cell_shape
plot <- ggplot(data = q, aes(x = morphology_physiology.cell_morphology.cell_shape))+
geom_histogram(stat = "count")+
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
scale_y_log10()
plot
ggsave(filename = "morphology_physiology.cell_morphology.cell_shape.jpeg", plot = plot)
#morphology_physiology.colony_morphology.hemolysis_type
# plot <- ggplot(data = q, aes(x = morphology_physiology.colony_morphology.hemolysis_type))+
# geom_histogram(stat = "count")+
# theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
# scale_y_log10()
#
# plot
ggsave(filename = "morphology_physiology.colony_morphology.hemolysis_type.jpeg", plot = plot)
#morphology_physiology.colony_morphology.colony_len
plot <- ggplot(data = q, aes(x = morphology_physiology.colony_morphology.colony_len))+
geom_histogram()+
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
plot
ggsave(filename = "morphology_physiology.colony_morphology.colony_len.jpeg", plot = plot)
#morphology_physiology.cell_morphology.cell_len
plot <- ggplot(data = q, aes(x = morphology_physiology.cell_morphology.cell_len))+
geom_histogram()+
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))+
scale_y_log10()+
scale_x_log10()
plot
ggsave(filename = "morphology_physiology.cell_morphology.cell_len.jpeg", plot = plot)
#morphology_physiology.cell_morphology.cell_width
plot <- ggplot(data = q, aes(x = morphology_physiology.cell_morphology.cell_width))+
geom_histogram()+
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))+
scale_y_log10()
plot
ggsave(filename = "morphology_physiology.cell_morphology.cell_width.jpeg", plot = plot)
#morphology_physiology.cell_morphology.cell_width log
plot <- ggplot(data = q, aes(x = morphology_physiology.cell_morphology.cell_width))+
geom_histogram()+
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))+
scale_y_log10()+
scale_x_log10()
plot
ggsave(filename = "morphology_physiology.cell_morphology.cell_width_log10.jpeg", plot = plot)
#legnth_to_width
q$length_to_width = q$morphology_physiology.cell_morphology.cell_len/q$morphology_physiology.cell_morphology.cell_width
plot <- ggplot(data = q, aes(x = length_to_width))+
geom_histogram()+
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))+
scale_y_log10()+
scale_x_log10()
plot
ggsave(filename = "length_to_width.jpeg", plot = plot)
```
##find coverage by phylum for interesting field -- pathogenicity to humans
```{r}
load("DATA/PROCESSED/D.Rdata")
phylum_all = subset(D, field == "phylum")
P_all = data.frame(table(phylum_all$value))
names(P_all)=c("phylum", "count_total")
path_hum = subset(D, field == "pathogenicity_human")
#get the species for which we have pathogenicity info
path_spp = path_hum$species
path_hum_spp = subset(D, species %in% path_spp)
phylum = subset(path_hum_spp, field == "phylum")
P_path_hum = data.frame(table(phylum$value))
names(P_path_hum)=c("phylum", "count_pathogenicity_human")
P_comb = merge(P_all, P_path_hum, by = "phylum")
P_comb$fraction_pathogenic = P_comb$count_pathogenicity_human/P_comb$count_total
plot <- ggplot(data = P_comb, aes(x = phylum, y = fraction_pathogenic))+
geom_bar(stat = "identity")+
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
plot
ggsave(plot=plot, filename = "fraction_pathogenic.jpeg")
path_anim = subset(D, field == "pathogenicity_animal")
#get the species for which we have pathogenicity info
path_spp_anim = path_anim$species
path_anim_spp = subset(D, species %in% path_spp_anim)
phylum_anim = subset(path_anim_spp, field == "phylum")
table(phylum_anim$value)
risk = subset(D, subsection == "risk_assessment")
risk_check = subset(risk, field == "pathogenicity_human1")
origin = subset(D, subsection == "origin")
unique(origin$field)
origin_human_abscess = subset(origin, value == "human abscess")
origin_human_abscess$field
origin_human_abscess$value
sample_type = subset(origin, field == "sample_type")
str_detect(sample_type$value, "human")
```
###get data for well-covered fields for one phylum, Firmicutes
```{r}
load("Data from Backdive-2.RData")
threshold = 0.01
D = merge
D = unique(D)
#rm(merge)
#remove NA values
inds.na = which(!is.na(D$value))
D = D[inds.na,]
D_phylum = subset(D, field == "phylum")
D_sub = subset(D_phylum, value == "Firmicutes")
id_len=length(unique(D_sub$bacdive_id))
bacdive_tmp = D_sub$bacdive_id
D_sub_all = subset(D, bacdive_id %in% bacdive_tmp)#get all in this phylum based on bacdive_ids
D = D_sub_all
D$new_field = paste(D$section, D$subsection, D$field)
save(D, file = "DATA/PROCESSED/D_Firmicutes.Rdata")
count=as.data.frame(table(D$new_field))#combination of subsection and field
var1=count$Var1
freq=count$Freq
var<-list()
freqs<-list()
for (i in 1:length(freq)) {
if (freq[i]>=threshold*id_len) {#this will get fields greater than 1%
var[[i]]=var1[i]
freqs[[i]]=freq[i]
}
}
df=do.call(rbind, Map(data.frame, Feature_name=var, Frequency=freqs))
df$Fraction = df$Frequency/id_len
###get those seen at least 1% of time
df01 = subset(df, Fraction >= 0.01)
save(df01, file = "DATA/PROCESSED/df01_Firmicutes.Rdata")
merge01 = subset(D, new_field %in% df01$Feature_name)
save(merge01, file = "DATA/PROCESSED/merge01_Firmicutes.Rdata")
load("DATA/PROCESSED/merge01_Firmicutes.Rdata")
# df_freq =
##this part is data_processing.R @
df <- merge01
df <- unique(df)
df$feature_name <- paste(df$section, df$subsection, df$field)
a <- df[is.element(df$feature_name, df01$Feature_name),]#df01 for 1% threshold
q <- dcast(a, bacdive_id~feature_name)
q <- q[order(q$bacdive_id),]
write.csv(q, file = "df_Firmicutes.csv", row.names = F)
temp = read.csv("df_Firmicutes.csv")
dim(temp)
# remove columns with near zero variance Global. Not doing this because it removes interesting variables like pathogenicity.animal
# nzv <- nearZeroVar(q,saveMetrics=TRUE,freqCut = 99/1)
# nzv <- row.names(nzv[which(nzv$nzv==TRUE),])
# dropnzv<-names(q[ , which(names(q) %in% nzv)])
# q <- q[ , -which(names(q) %in% nzv)]
# write.csv(q, file = "dropnzvdata_Firmicutes.csv", row.names = F)
#
# #######
# q <- read.csv(file = "dropnzvdata_Firmicutes.csv")
dim(q)
#str(q)
#str(q, list.len=ncol(q))
q$`molecular_biology GC_content GC_content`=as.character(q$`molecular_biology GC_content GC_content`)
na_temp_range = which(is.na(q$`culture_growth_condition culture_temp temperature_range`))
q$`culture_growth_condition culture_temp temperature_range`[na_temp_range]=
q$`culture_growth_condition culture_temp temperature_range1`[na_temp_range]
q$`molecular_biology GC_content GC_content`= as.character(q$`molecular_biology GC_content GC_content`)
#fix GC content
for (a in 1:dim(q)[1]){
if(!is.na(q$`molecular_biology GC_content GC_content`[a])){
if (grepl("±", q$`molecular_biology GC_content GC_content`[a])==TRUE){
split = strsplit(q$`molecular_biology GC_content GC_content`[a], "±")
q$`molecular_biology GC_content GC_content`[a] =as.numeric(split[[1]][1])
}
length_char = str_length(q$`molecular_biology GC_content GC_content`[a])
if (length_char > 4){
split = strsplit(q$`molecular_biology GC_content GC_content`[a], "-")
q$`molecular_biology GC_content GC_content`[a] =(as.numeric(split[[1]][2])+as.numeric(split[[1]][1]))/2
}
}
}
#fix morphology_physiology cell_morphology cell_len
q$`morphology_physiology cell_morphology cell_len`=as.character(q$`morphology_physiology cell_morphology cell_len`)
for (a in 1:dim(q)[1]){
if(!is.na(q$`morphology_physiology cell_morphology cell_len`[a])){
q$`morphology_physiology cell_morphology cell_len`[a]=str_replace(q$`morphology_physiology cell_morphology cell_len`[a],
pattern = ">",
replacement = "")
q$`morphology_physiology cell_morphology cell_len`[a]=str_replace(q$`morphology_physiology cell_morphology cell_len`[a],
pattern = "<",
replacement = "")
grep_test = grepl("-", q$`morphology_physiology cell_morphology cell_len`[a])
if (grep_test == TRUE){
split = strsplit(q$`morphology_physiology cell_morphology cell_len`[a], "-")
q$`morphology_physiology cell_morphology cell_len`[a] =(as.numeric(split[[1]][2])+as.numeric(split[[1]][1]))/2
}
}
}
q$`morphology_physiology cell_morphology cell_len`=as.numeric(q$`morphology_physiology cell_morphology cell_len`)
inds = which(q$`morphology_physiology cell_morphology cell_len_unit` == "mm")
q$`morphology_physiology cell_morphology cell_len`[inds]=q$`morphology_physiology cell_morphology cell_len`[inds]*1000
##now change into log
q$`morphology_physiology cell_morphology cell_len log`=log(q$`morphology_physiology cell_morphology cell_len`)
rm = c("morphology_physiology cell_morphology cell_len")
keep = setdiff(names(q), rm)
q = q[,keep]
#fix morphology_physiology cell_morphology cell_width
q$`morphology_physiology cell_morphology cell_width`=as.character(q$`morphology_physiology cell_morphology cell_width`)
for (a in 1:dim(q)[1]){
if(!is.na(q$`morphology_physiology cell_morphology cell_width`[a])){
q$`morphology_physiology cell_morphology cell_width`[a]=str_replace(q$`morphology_physiology cell_morphology cell_width`[a],
pattern = ">",
replacement = "")
q$`morphology_physiology cell_morphology cell_width`[a]=str_replace(q$`morphology_physiology cell_morphology cell_width`[a],
pattern = "<",
replacement = "")
grep_test = grepl("-", q$`morphology_physiology cell_morphology cell_width`[a])
if (grep_test == TRUE){
split = strsplit(q$`morphology_physiology cell_morphology cell_width`[a], "-")
q$`morphology_physiology cell_morphology cell_width`[a] =(as.numeric(split[[1]][2])+as.numeric(split[[1]][1]))/2
}
}
}
q$`morphology_physiology cell_morphology cell_width`=as.numeric(q$`morphology_physiology cell_morphology cell_width`)
inds = which(q$`morphology_physiology cell_morphology cell_width_unit` == "mm")
q$`morphology_physiology cell_morphology cell_width`[inds] = 1000*q$`morphology_physiology cell_morphology cell_width`[inds]
##now change into log
q$`morphology_physiology cell_morphology cell_width log`=log(q$`morphology_physiology cell_morphology cell_width`)
rm = c("morphology_physiology cell_morphology cell_width")
keep = setdiff(names(q), rm)
q = q[,keep]
#unique(q$morphology_physiology colony_morphology incubation_period)
q$`morphology_physiology colony_morphology incubation_period`=as.character(q$`morphology_physiology colony_morphology incubation_period`)
for (a in 1:dim(q)[1]){
if(!is.na(q$`morphology_physiology colony_morphology incubation_period`[a])){
q$`morphology_physiology colony_morphology incubation_period`[a]=str_replace(q$`morphology_physiology colony_morphology incubation_period`[a],
pattern = ">",
replacement = "")
q$`morphology_physiology colony_morphology incubation_period`[a]=str_replace(q$`morphology_physiology colony_morphology incubation_period`[a],
pattern = "<",
replacement = "")
q$`morphology_physiology colony_morphology incubation_period`[a]=str_replace(q$`morphology_physiology colony_morphology incubation_period`[a],
pattern = "days",
replacement = "")
grep_test = grepl("-", q$`morphology_physiology colony_morphology incubation_period`[a])
if (grep_test == TRUE){
split = strsplit(q$`morphology_physiology colony_morphology incubation_period`[a], "-")
q$`morphology_physiology colony_morphology incubation_period`[a] =(as.numeric(split[[1]][2])+as.numeric(split[[1]][1]))/2
}
}
}
q$`morphology_physiology colony_morphology incubation_period`=as.numeric(q$`morphology_physiology colony_morphology incubation_period`)
q$`molecular_biology GC_content GC_content`= as.numeric(q$`molecular_biology GC_content GC_content`)
keep = c(
#"application_interaction risk_assessment biosafety_level",
"molecular_biology GC_content GC_content",
"taxonomy_name strains_tax_PNU species",
"culture_growth_condition culture_temp temperature_range",
# "environment_sampling_isolation_source origin continent",#hard to interpret biologically
# "taxonomy_name strains_tax_PNU phylum",
"environment_sampling_isolation_source origin latitude",
"environment_sampling_isolation_source origin longitude",
"morphology_physiology spore_formation type",
# "morphology_physiology oxygen_tolerance oxygen_tol",#this has multiple entries, tol1, tol2.
#"morphology_physiology met_test metabolite_test",#don't know what this means
#"morphology_physiology met_production metabolite_prod",#don't know what this means
#"morphology_physiology met_antibiotica metabolite_antib",#don't know what this means
#"morphology_physiology halophily salt_concentration",#FIXED to make numeric Includes >, < This is relative to multiple possible measures -- growth, optimum discard
#"morphology_physiology met_antibiotica ab_resistance_conc",#don't know what this means Seems to refer to concentration of antibiotic in test Exclude
"morphology_physiology colony_morphology colony_len",#FIXED to make numeric Includes >, <
# "morphology_physiology colony_morphology hemolysis_type",#don't know what this means. doesn't seem to exist for Firmicutes
"morphology_physiology cell_morphology motility",#factor
"morphology_physiology cell_morphology gram_stain",#factor
"morphology_physiology cell_morphology flagellum_arrangement",#factor; does not seem to be present for Firmicutes
"morphology_physiology cell_morphology cell_len log",#FIXED to make numeric assumning all in same units
"morphology_physiology cell_morphology cell_shape",#factor
"morphology_physiology cell_morphology cell_width log",#need to FIX to make numeric
# "culture_growth_condition culture_temp temp",#need to FIX to make numeric; refers to growth vs optimum; exclude
# "culture_growth_condition culture_pH pH",
"morphology_physiology spore_formation ability",
#"taxonomy_name strains ordo",
"application_interaction risk_assessment pathogenicity_animal",
"application_interaction risk_assessment pathogenicity_human",
"bacdive_id",
"environment_sampling_isolation_source origin sample_type",
"morphology_physiology cell_morphology gram_stain",
"taxonomy_name strains_tax_PNU class",
"morphology_physiology spore_formation type",
"morphology_physiology colony_morphology colony_shape")
keep = intersect(names(q), keep)
q = q[,keep]
q$`environment_sampling_isolation_source origin longitude`=as.numeric(as.character(q$`environment_sampling_isolation_source origin longitude`))
q$`environment_sampling_isolation_source origin latitude`=as.numeric(as.character(q$`environment_sampling_isolation_source origin latitude`))
q$`morphology_physiology colony_morphology colony_len`=as.numeric(as.character(q$`morphology_physiology colony_morphology colony_len`))
save(q, file = "q_Firmicutes Rdata")
load("q_Firmicutes Rdata")
bacteria_traits_fields_subset = q
write.csv(bacteria_traits_fields_subset, file = "bacteria_traits_fields_subset_Firmicutes.csv",
row.names = FALSE)
#fix animal pathogenic
inds = which(!is.na(q$`application_interaction risk_assessment pathogenicity_animal`))
q$`application_interaction risk_assessment pathogenicity_animal`[inds]="1"
inds.na = which(is.na(q$`application_interaction risk_assessment pathogenicity_animal`))
q$`application_interaction risk_assessment pathogenicity_animal`[inds.na]="0"
q$`application_interaction risk_assessment pathogenicity_animal`=as.numeric(q$`application_interaction risk_assessment pathogenicity_animal`)
# q$`application_interaction risk_assessment pathogenicity_animal`[is.na(q$`application_interaction risk_assessment pathogenicity_animal`)]=0
# q$`application_interaction risk_assessment pathogenicity_animal`[!is.na(q$`application_interaction risk_assessment pathogenicity_animal`)]=1
#fix human pathogenic
inds = which(!is.na(q$`application_interaction risk_assessment pathogenicity_human`))
q$`application_interaction risk_assessment pathogenicity_human`[inds]="1"
inds.na = which(is.na(q$`application_interaction risk_assessment pathogenicity_human`))
q$`application_interaction risk_assessment pathogenicity_human`[inds.na]="0"
q$`application_interaction risk_assessment pathogenicity_human`=as.numeric(q$`application_interaction risk_assessment pathogenicity_human`)
# q$`application_interaction risk_assessment pathogenicity_human`[is.na(q$`application_interaction risk_assessment pathogenicity_human`)]=0
# q$`application_interaction risk_assessment pathogenicity_human`[!is.na(q$`application_interaction risk_assessment pathogenicity_human`)]=1
summary(q$`application_interaction risk_assessment pathogenicity_human`)
q$human_origin = grepl("human", q$`environment_sampling_isolation_source origin sample_type`)
q$human_origin[q$human_origin==FALSE]=0
q$human_origin[q$human_origin==TRUE]=1
rm = c("bacdive_id",
"taxonomy_name strains_tax_PNU species",
"environment_sampling_isolation_source origin sample_type")
keep = setdiff(names(q), rm)
q = q[,keep]
# q$`application_interaction risk_assessment biosafety_level`=factor(q$`application_interaction risk_assessment biosafety_level`)
q$`application_interaction risk_assessment pathogenicity_animal`=as.numeric(q$`application_interaction risk_assessment pathogenicity_animal`)
q$`culture_growth_condition culture_temp temp`=as.numeric(q$`culture_growth_condition culture_temp temp`)
# q$`environment_sampling_isolation_source origin continent`=factor(q$`environment_sampling_isolation_source origin continent`)
q$`morphology_physiology cell_morphology cell_shape`=factor(q$`morphology_physiology cell_morphology cell_shape`)
q$`morphology_physiology cell_morphology gram_stain`=factor(q$`morphology_physiology cell_morphology gram_stain`)
q$`morphology_physiology cell_morphology motility`=factor(q$`morphology_physiology cell_morphology motility`)
# q$`morphology_physiology oxygen_tolerance oxygen_tol`=factor(q$`morphology_physiology oxygen_tolerance oxygen_tol`)
q$`morphology_physiology spore_formation ability`=factor(q$`morphology_physiology spore_formation ability`)
#q$`taxonomy_name strains ordo`=factor(q$`taxonomy_name strains ordo`)
# # remove columns with near zero variance Global
# nzv <- nearZeroVar(q,saveMetrics=TRUE,freqCut = 99/1)
# nzv <- row.names(nzv[which(nzv$nzv==TRUE),])
# dropnzv<-names(q[ , which(names(q) %in% nzv)])
# q <- q[ , -which(names(q) %in% nzv)]
# write.csv(q, file = "dropnzvdata_Firmicutes.csv", row.names = F)
q_Firmicutes = q
save(q_Firmicutes, file = "q_Firmicutes.Rdata")
dmy <- dummyVars(" ~ .", data = q,fullRank = F, sep=".")
df_transformed <- data.frame(predict(dmy, newdata = q))
save(df_transformed, file = "df_transformed.Rdata")
write.csv(df_transformed, file = "onehotdata_Firmicutes.csv", row.names = F)
```
##make model
```{r}
load("df_transformed.Rdata")
rm = "X.culture_growth_condition.culture_temp.temp."
keep = setdiff(names(df_transformed), rm)
df_transformed = df_transformed[,keep]
y_col = 2
x_col = c(1, 3:dim(df_transformed)[2])
model<-as.formula(paste(colnames(df_transformed)[y_col], "~",
paste(colnames(df_transformed)[x_col],collapse = "+"),
sep = ""))
```
##get train and test
```{r}
load("df_transformed.Rdata")
df = df_transformed
DP =createDataPartition(y = df$X.application_interaction.risk_assessment.pathogenicity_human.,
p = 0.8,
list = FALSE)
Train = df[DP,]
Test = df[-DP,]
save(Train, file = "Train.Rdata")
save(Test, file = "Test.Rdata")
```
##fit gbm -- Firmicutes
```{r gbm firmicutes}
load("Train.Rdata")
load("Test.Rdata")
attach(Train)
#Start the clock
ptm<-proc.time()
n.trees = 50000
shrinkage = 0.001#final version should be 0.001
cv.folds = 10#final version should be 10
gbmtest<- gbm(model,
data=Train,
distribution="bernoulli",
n.trees=n.trees,
shrinkage=shrinkage,
interaction.depth=3,
bag.fraction=0.50,
train.fraction=1,
n.minobsinnode=5,
cv.folds=cv.folds,
keep.data=TRUE,
verbose=TRUE,
n.cores=NULL)
save(gbmtest, file = "gbmtest.Rdata")
#check performance using 5-fold cross-validation
best.iter <- gbm.perf(gbmtest,method="cv",plot.it=FALSE) #this gives you the optimal number of trees based on cv performance, other methods will over or under predict
print(best.iter)
gbm_error = data.frame(train.error = gbmtest$train.error,
trees = seq(1,n.trees))
plot <- ggplot(gbm_error, aes(x = trees, y = train.error))+
geom_line()
plot
ggsave(filename = "deviance_human_pathogenic_Firmicutes.jpg",
plot = plot)
#Stop the clock
(proc.time()-ptm)/60
load("gbmtest.Rdata")
best.iter <- gbm.perf(gbmtest,method="cv",plot.it=FALSE) #this gives you the optimal number of trees based on cv performance, other methods
# output predictions on the TRAINING SET
output<-predict(gbmtest,
newdata=Train,
n.trees=best.iter,
type="response")
output<-cbind(output,Train$X.application_interaction.risk_assessment.pathogenicity_human.)
colnames(output)<-c("output","data")
rownames(output)<-rownames(Train)
output<-output[order(-output[,1]),]
# # AUC for Bernoulli distributed responses
par(mar = c(1,1,1,1))
auc=colAUC(output[,1],output[,2],
plotROC = TRUE)
print(auc)
pred<-prediction(output[,1],output[,2])
perf<-performance(pred,"tpr","fpr")
par(mar = c(1,1,1,1))
plot(perf,colorize=TRUE,main="ROC full model")
abline(a=0, b= 1)
# output predictions on the Test SET
output<-predict(gbmtest,
newdata=Test,
n.trees=best.iter,
type="response")
output<-cbind(output,Test$X.application_interaction.risk_assessment.pathogenicity_human.)
colnames(output)<-c("output","data")
rownames(output)<-rownames(Test)
output<-output[order(-output[,1]),]
# # AUC for Bernoulli distributed responses
par(mar = c(1,1,1,1))
auc=colAUC(output[,1],output[,2],
plotROC = TRUE)
print(auc)
pred<-prediction(output[,1],output[,2])
perf<-performance(pred,"tpr","fpr")
par(mar = c(1,1,1,1))
plot(perf,colorize=TRUE,main="ROC full model test data")
abline(a=0, b= 1)
```
###plot relative influence -- Firmicutes
```{r}
#format relative influence for figure
load("gbmtest.Rdata")
x = summary(gbmtest)
#
x.df= data.frame(variable = x$var,
relative.influence = x$rel.inf)
load("DATA/PROCESSED/df01_Firmicutes.Rdata")
# df01$Feature_name = str_replace(df01$Feature_name, " " , ".")
# df01$Feature_name = paste0("X.", df01$Feature_name)
# names(df01)[names(df01)=="Feature_name"]="variable"
# x.df = merge(x.df, df01)
# keep = c("variable",
# "relative.influence",
# "Fraction")
# x.df = x.df[,keep]
# write.csv(x.df, file = "x.df.csv")
#
# mod = lm(relative.influence ~ Fraction, data = x.df)
subset(df01, Feature_name == "application_interaction risk_assessment pathogenicity_animal")
subset(df01, Feature_name == "molecular_biology GC_content GC_content")
subset(df01, Feature_name == "taxonomy_name strains ordo")
subset(df01, Feature_name == "environment_sampling_isolation_source origin sample_type")
subset(df01, Feature_name == "morphology_physiology cell_morphology gram_stain")
subset(df01, Feature_name == "culture_growth_condition culture_temp temperature_range")
subset(df01, Feature_name == "morphology_physiology cell_morphology cell_shape")