-
Notifications
You must be signed in to change notification settings - Fork 0
/
Methylation_kaja_final_2023.Rmd
4949 lines (3159 loc) · 149 KB
/
Methylation_kaja_final_2023.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: "Methylation/survival analysis for UHRF1 mediator of KRASin lung adenocarcinoma "
author: "Kostyrko et al"
date: "`r format(Sys.time(), '%d %B, %Y')`"
output:
html_document:
toc: TRUE
toc_float: FALSE
editor_options:
chunk_output_type: console
chunk_output_type: console
---
<style type="text/css">
.main-container {
max-width: 2500px;
margin-left: 5px;
margin-right: auto;
}
.toc-content {
max-width: 2500px;
margin-left: 50px;
margin-right: auto;
}
div {
margin-left: 5px;
}
hr.new1 {
border-top: 1px solid #84a8e0;
}
</style>
version: 1.0 <br />
Run at "`r format(Sys.time())`"
# Overview/Method:
* Data analysis performed in Kostyrko et al., 2023.
* The dataset used for the Kostyrko et al study can be accessed from the GEO SuperSeries under the accession number GSE198289.
+ This SuperSeries is composed of the following SubSeries:
+ GSE198289 UHRF1 is a mediator of KRAS driven oncogenesis in lung adenocarcinoma [RNA-seq]
+ GSE198446 UHRF1 is a mediator of KRAS driven oncogenesis in lung adenocarcinoma [epic_methyl]
+ GSE209923 UHRF1 is a mediator of KRAS driven oncogenesis in lung adenocarcinoma [shRNA]
* Additional detailed information and datasets can be downloaded from: https://github.com/ahdee/Kostyrko_2023.
* Please keep in mind that it would take a minimum of > 60GB to successfully run this markdown.
```{r setup, include=FALSE, echo=FALSE, message=FALSE, warning=FALSE}
knitr::opts_chunk$set(include=F, echo=FALSE, message=FALSE, warning=FALSE, fig.show="asis", fig.keep="all",tidy.opts=list(width.cutoff=100),tidy=TRUE, cache=F)
options(knitr.table.format = "latex")
options(width = 1600)
### global options
options(scipen=999)
update = 0
savexls = 0
## load libraries
# Genomic Data Annotation #
library(biomaRt) # Tools for BioMart databases (like Ensembl).
library(BSgenome) # Infrastructure for Bioconductor packages using large-scale genomic or other data.
library(org.Hs.eg.db) # Mapping information for human genes.
library(GenomicFeatures) # Tools for making and manipulating transcript centric annotations.
library(IlluminaHumanMethylation450kanno.ilmn12.hg19) # Annotation data for the Illumina Human Methylation 450k array.
library(IlluminaHumanMethylationEPICanno.ilm10b4.hg19) # Annotation data for the Illumina Human Methylation EPIC array.
library(IlluminaHumanMethylationEPICmanifest) # Manifest file for Illumina's EPIC methylation arrays.
library(Homo.sapiens) # Annotation data for the human genome.
# Genomic Data Analysis (Omics) #
library(limma) # Linear models for microarray data.
library(DESeq2) # Differential gene expression analysis based on the negative binomial distribution.
library(edgeR) # Empirical analysis of digital gene expression data in R.
library(GenomicRanges) # Representations and manipulations of genomic intervals and variables defined along a genome.
library(GSVA) # Gene set variation analysis for microarray and RNA-seq data.
library(Gviz) # Plotting data and annotation information along genomic coordinates.
library(minfi) # Tools to analyze Illumina's methylation arrays.
library(missMethyl) # Analyzes differential methylation in the context of GC content.
library(methylGSA) # Gene set testing for Illumina's methylation arrays.
library(pathview) # Plots pathway maps and overlays experimental data.
library(sva) # Surrogate Variable Analysis # identification and adjustment for hidden confounding factors.
library(biovizBase) # Basic graphic utilities for visualization of genomic data.
library(ggbio) # Visualization tools for genomic data.
#Statistical Genomics #
library(clusterProfiler) # Analysis and visualization of functional profiles for genes and gene clusters.
library(DGCA) # Differential gene correlation analysis.
library(DMRcate) # Detects differentially methylated regions in genomic data.
library(EpiDISH) # Decomposes cell mixture distribution in DNA methylation data.
library(rtracklayer) # Tools to interact with genome browsers, manipulate genomic tracks, and visualize genomic data.
library(fgsea) # Fast implementation of preranked gene set enrichment analysis (GSEA).
library(pathfindR) # Pathway enrichment analysis utilizing active subnetworks.
library (DGCA) #Differential Gene Correlation Analysis
# Data Manipulation #
library(data.table) # Extension of R's data.frame.
library(dplyr) # A grammar of data manipulation.
library(forcats) # Tools for working with categorical variables (factors).
library(tidyr) # Tools to tidy messy datasets.
library(plyr) # Tools for splitting, applying and combining data.
library(reshape) # Flexibly reshape data.
library(stringr) # Simple, consistent wrappers for common string operations.
# Data Transformation
library(scales) # Scale functions for visualization.
#Heatmaps and Clustering #
library(ComplexHeatmap) # Making complex heatmaps.
library(d3heatmap) # Interactive heatmaps.
library(dendextend) # Extending R's dendrogram functionality.
library(dendroextras) # Extra functions to cut, label and colour dendrogram clusters
library(heatmap3) # Enhanced heatmap representation.
library(heatmaply) # Interactive heatmaps.
library(pheatmap) # Pretty heatmaps.
# Visualization #
library(corrplot) # Visualization of a correlation matrix.
library(cowplot) # functions to align plots and arrange them into complex compound figures
library(factoextra) # Extract and visualize the results of multivariate data analyses.
library ( ggbeeswarm ) # Beeswarm plots helper
library(ggdendro) # Create dendrograms using ggplot.
library(ggplot2) # An implementation of the Grammar of Graphics.
library(ggplotify) # Convert plot function call to 'ggplot' objects.
library(ggpubr) # 'ggplot2' based publication ready plots.
library(ggpval) # Annotate statistical significance onto 'ggplot' objects.
library(ggrepel) # Automatically position non-overlapping text labels with 'ggplot2'.
library(gplots) # Various R programming tools for plotting data.
library(gridExtra) # Miscellaneous functions for "grid" graphics.
library(forestplot) # forest plot helper, mostly use in meta-analysis
library(patchwork) # The composer of ggplots.
library(RColorBrewer) # ColorBrewer palettes.
library ( ggridges) # Ridgeline plots
library(VennDiagram) # Generate high-resolution Venn and Euler plots.
library(Vennerable) # Venn and Euler area-proportional diagrams.
library(wesanderson) # Wes Anderson color palettes.
library(stargazer) # LATEX, HTML and ASCII tables from R statistical output
#Statistical Analysis #
library(FactoMineR) # An R package for multivariate analysis.
library(fgsea) # Fast gene set enrichment analysis.
library(MASS) # Functions and datasets to support Venables and Ripley's MASS.
library(matrixStats) # Functions that apply to rows and columns of matrices (and to vectors).
library(PerformanceAnalytics) # Econometric tools for performance and risk analysis.
library(psych) # Procedures for psychological, psychometric, and personality research.
library(survival) # Survival analysis.
library(survminer) # Drawing survival curves using 'ggplot2'.
library(vegan) # Community Ecology Package.
#High-Dimensional Data Analysis #
library(Rtsne) # T-Distributed Stochastic Neighbor Embedding using a Barnes-Hut implementation.
library(umap) # Uniform Manifold Approximation and Projection.
library(parallelDist) # Parallel distance matrix computation.
#Table/Spreadsheet Handling #
library(DT) # A wrapper of the JavaScript library 'DataTables'.
library(openxlsx) # Read, write and edit XLSX files.
# Report Generation #
library(knitr) # A general-purpose literate programming engine.
library(pander) # An R Pandoc writer.
library(kableExtra) # Build complex HTML or 'LaTeX' tables using 'kable()' and pipe syntax.
#Network Analysis #
library(igraph) # Network analysis and visualization.
data(centDHSbloodDMC.m)
getPalette = colorRampPalette(brewer.pal(9, "Set1")) # expand color pallete
```
```{r}
# original study
## read in resources
##
main.data = "/data/"
resource = "/ehome/resource/"
resource.ext = "/ehome/"
input_dir = "./input/"
dir.create(input_dir)
epic = paste0(resource, "EPIC")
final_fig = "./paper_fig/revision/"
dir.create(final_fig)
source ( "./aux1.1.R" )
## pathways
pathways = readRDS( paste0( resource, "/gsea/limma/go_path.rds"))
# change column to make it work with profiler
pathway.p = pathways
colnames ( pathway.p)[1] = c("geneID")
annt = readRDS( paste0( resource, "/gsea/limma/go_path_withWeneName.rds"))
annt$GeneID = NULL
colnames ( annt ) = c ( "gene" , "term")
annt = annt [ , c ( "term" , "gene") ]
pathgsea = readRDS( paste0( resource, "/gsea/limma/go_path_fgsea_genename.rds"))
wb <- createWorkbook()
out.dir = "./out/"
dir.create(out.dir)
cosmic = read.csv("https://www.dropbox.com/s/ceo0ol2h9vt01c3/cosmic-cancer_gene_census.v85.csv?dl=1")
tsg = cosmic[ grepl("TSG", cosmic$Role.in.Cancer, ignore.case = T), ]
oncogene = cosmic[ grepl("oncog", cosmic$Role.in.Cancer, ignore.case = T), ]
cosmic$Gene.Symbol = as.character(cosmic$Gene.Symbol)
ens = readRDS( paste0( resource, "annotation/gene.detail.rds"))
goanadb = readRDS( paste0( resource, "/gsea/limma/go_path.rds"))
ss = 123
set.seed(ss)
# load the key which also defines where the idat files will be
## this is for the 850 K
### this will include annotations to genes, cpg island, snp etc..
ann850k = getAnnotation(IlluminaHumanMethylationEPICanno.ilm10b4.hg19)
# set up a path for your project
dataDirectory <- "./raw/"
update = 1
kaja = read.table ("LUAD_TSGene.txt", header = T, sep="\t" )
kaja_og = nrow ( kaja )
```
```{r}
if ( update == 1){
# read in the experimental design and key
#targets <- read.metharray.sheet(dataDirectory, pattern = "epic_raw.csv")
targets <- read.csv("./raw/20210603_GenomeStudioSampleSheet_EPIC63_KostyrkoLab_Only.csv", header=T)
targets$ID = paste0( targets$Sentrix_ID, "_", targets$Sentrix_Position)
key = openxlsx::read.xlsx("https://www.dropbox.com/s/6oe2aepjfmj5lac/20210503_72h_EPIC_key.xlsx?dl=1")
setdiff ( key$tube, targets$Subject.ID)
key = merge ( key, targets, by.x="tube", "Subject.ID")
key$Basename = key$ID
key = key [ order ( key$siRNA, key$Cells), ]
key$Replicate.x = NULL
key$Replicate.y = NULL
key$Sample.External.ID= NULL
key$Subject.External.Key= NULL
key$smp_type= NULL
key$Sample_Group= NULL
key$Pool_ID= NULL
key$Number= NULL
key$ID= NULL
key$Gender = NULL
# read in the raw data from the IDAT files
rgSet <- read.metharray.exp(base= dataDirectory, key )
order = colnames ( rgSet)
all.equal(order, key$Basename)
setdiff ( key$ID, order)
setdiff ( order, key$ID )
################### QC
# The method used by minfi to calculate detection p-values compares the total signal
# (M + U) for each probe to the background signal level, which is estimated from the negative control probes.
### Very small p-values are indicative of a reliable signal whilst large p-values, for example >0.01, generally
# indicate a poor quality signal.
# calculate the detection p-values
# A detection p-value is returned for every genomic position in every sample. Small p-values indicate a good position. Positions with non-significant p-values (typically >0.01) should not be trusted.
detP <- detectionP(rgSet)
failed <- detP > 0.01
colMeans(failed) # Fraction of failed positions per sample
sum(rowMeans(failed)>0.5) # How many positions failed in >50% of samples?
# this is how many probes will be eliminated
failed.probes <- rownames(detP[rowMeans(failed)>0.5,])
length (failed.probes)
pal <- brewer.pal(8,"Dark2")
par(mar=c(10,6,2,0))
# check if we have all the samples
all.equal ( key$Basename, colnames ( detP))
# reorder key
# mean of p-value: all samples look good, basically any p > .05 is not good, lower the p.value the better it is.
# here I set the limit to .01 so anything below that is good.
qc = data.frame(
name=key$tube ,
value=colMeans(detP),
group=key$siRNA
)
ccc = getPalette(3)
names ( ccc) = unique ( key$siRNA)
qc$group = factor ( qc$group, levels=unique ( qc$group))
qc$name = factor ( qc$name, levels=unique ( qc$name))
pdetect = ggplot(qc, aes( fill=group, y=value, x=name)) +
geom_bar(position="dodge", stat="identity") +
theme_bw() +
ylab( "p.value") +
xlab("") +
theme(legend.position="bottom", legend.title=element_blank(), legend.key = element_blank(),
#axis.text.x = element_blank(),
#axis.text.y = element_blank(), # comment this out to display cancer.subtype
axis.text.y = element_text(size=12),
axis.text.x = element_text(size=15),
axis.title.x = element_text(size=22),
axis.title.y = element_text(size=22),
legend.text =element_text(size=12)
) + scale_fill_manual(values = ccc )
# clean up
gc()
# filter out bad samples (note nothing is removed here) since all the probe seem to be working
keep <- colMeans(detP) < 0.05
rgSet <- rgSet[,keep]
# normalize cpg
mSetSq <- preprocessQuantile(rgSet)
# visualise what the data looks like before and after normalization
#### filter data
# ensure probes are in the same order in the mSetSq and detP objects
detP <- detP[match(featureNames(mSetSq),rownames(detP)),]
# remove any probes that have failed in one or more samples
keep <- rowSums(detP < 0.01) == ncol(mSetSq)
# this is how many probes will be removed
table(keep)
mSetSqFlt <- mSetSq[keep,]
# before
dim (mSetSq)
# after
dim (mSetSqFlt)
# remove SNP using minfi
nosnp <- dropLociWithSnps(mSetSqFlt)
# after removing snps
dim (nosnp)
# remove unspecific probes
# we get the 450 and then the EPIC
## cross reactive
non.spec.450K <- paste0(epic,'/illumina450k_filtering-master/48639-non-specific-probes-Illumina450k.csv')
xReactiveProbes <- read.csv(file=non.spec.450K, stringsAsFactors=FALSE)
## multi-mapped
multi.map <- read.csv(paste0(epic,'/illumina450k_filtering-master/HumanMethylation450_15017482_v.1.1_hg19_bowtie_multimap.txt'), head = F, as.is = T)
multi.map.probes <- as.character(multi.map$V1)
filter.probes <- unique ( c( xReactiveProbes$TargetID, multi.map.probes) )
# https://github.com/sirselim/illumina450k_filtering
# get epic probes now > 100 K from the same github
## this file was generate with epic.filter.R in the same dir that combined mulitple epic files
epic.filter.probe <-read.table(paste0(epic,"/illumina450k_filtering-master/EPIC/EPIC.badprobes.tsv"), header=TRUE,sep="\t",stringsAsFactors = FALSE,na.strings=".", quote = "", fill = TRUE)
filter.probes <- unique ( c( filter.probes, epic.filter.probe$x ) )
# this is how many will be remove
length ( filter.probes)
keep <- !(featureNames(nosnp) %in% filter.probes)
nosnp <- nosnp[keep,]
# final cpg
dim (nosnp)
#The Beta-value has a more intuitive biological interpretation, but the M-value is more statistically valid for the differential analysis of methylation levels. Du et al, 2010
# http://bmcbioinformatics.biomedcentral.com/articles/10.1186/1471-2105-11-587
qc = data.frame(
name=key$tube ,
value=colMeans(detP),
group=key$siRNA
)
ccc = getPalette(3)
names ( ccc) = unique ( key$siRNA)
qc$group = factor ( qc$group, levels=unique ( qc$group))
qc$name = factor ( qc$name, levels=unique ( qc$name))
pdetect = ggplot(qc, aes( fill=group, y=value, x=name)) +
geom_bar(position="dodge", stat="identity") +
theme_bw() +
ylab( "p.value") +
xlab("") +
theme(legend.position="bottom", legend.title=element_blank(), legend.key = element_blank(),
#axis.text.x = element_blank(),
#axis.text.y = element_blank(), # comment this out to display cancer.subtype
axis.text.y = element_text(size=12),
axis.text.x = element_text(size=15),
axis.title.x = element_text(size=22),
axis.title.y = element_text(size=22),
legend.text =element_text(size=12)
) + scale_fill_manual(values = ccc )
cpg.m.after <- getM(nosnp)
cpgBeta.after <- getBeta(nosnp)
# prepare for geo
# last to use rgset is here.
# mSetSq <- preprocessQuantile(rgSet)
MSet.raw <- preprocessRaw(rgSet)
head(getMeth(MSet.raw)[,1:3])
head(getUnmeth (MSet.raw)[,1:3])
detP[1:3, 1:3 ]
saveRDS( list (
cpg.m.after = cpg.m.after,
cpgBeta.after = cpgBeta.after,
qc = qc ,
key = key,
detP=detP,
MSet.raw = MSet.raw,
meta = "updated, 3-8-2022, includes pvalue and MSet.raw, use getMeth or getUnmeth to extract values"
),
"DATA2.rds")
options(scipen=0)
# reorder key by sample name
key2 = key [gtools::mixedorder(key$tube) , ]
g = cpgBeta.after[ , key2$Basename]
p = detP[ , key2$Basename]
all.equal(key2$Basename, colnames ( g))
all.equal(key2$Basename, colnames ( p))
# replacing ugly names with tube numbers
# wanted to be sure so use sapply instead just setting colnames to key$tube
colnames ( g ) = as.character ( sapply( colnames ( g), function(x) key[key$Basename == x, ]$tube ) )
colnames ( p ) = as.character ( sapply( colnames ( p), function(x) key[key$Basename == x, ]$tube ) )
# the format is sample_id and p.value , sample_id p.value
# so the issue is the that the name are repeated, thus would need to convert to matrix first
geo = merge ( g, p, by="row.names")
row.names ( geo ) = geo$Row.names
geo$Row.names= NULL
colnames ( geo ) = gsub ( ".x", "", colnames ( geo ))
colnames ( geo ) = gsub ( ".y", ".pval", colnames ( geo ))
geo = geo [ , gtools::mixedsort (colnames ( geo ) )]
geo$ID_REF = row.names ( geo )
geo = geo[ , unique ( c( "ID_REF", colnames ( geo )))]
#test = head ( as.matrix ( geo ))
#colnames ( test) = gsub ( ".*.pval", "Detection Pval", colnames ( test ))
test = as.matrix ( geo )
colnames ( test) = gsub ( ".*.pval", "Detection Pval", colnames ( test ))
write.table(test,paste0(out.dir,"geosubmit.tsv"), sep = "\t", row.names = FALSE ,quote=FALSE)
mdt = system ( paste0("md5sum ", out.dir,"geosubmit.tsv") , intern = T )
# get name of idat files
idat = list.files("./raw", pattern=".idat")
idat = data.frame ( file=idat[grepl ( "Grn", idat)],
file2=idat[grepl ( "Red", idat)])
idat$Basename = gsub ( "_Grn.idat", "", idat$file )
key2 = merge ( key2, idat, by="Basename")
key2 = key2[!duplicated ( key2$Basename) , ]
key2 = key2[!duplicated ( key2$file), ]
# get checksum
# system ( "md5sum ./raw/* > ./raw/checklist.chk")
# don't worry about warning
df2 = read.table ( "./raw/checklist.chk", sep=" ", header=F)
df2$V2 = NULL
df2 = df2[ grepl ( "_R", df2$V3), ]
df2$V3 = gsub ( ".*\\/", "", df2$V3)
colnames ( df2 ) = c("md5sum","filename")
df2 = rbind ( df2, c( unlist ( str_split(mdt, " ") ) [1] , "geosubmit.tsv" ) )
write.table(df2,paste0(out.dir,"md5sum.tsv"), sep = "\t", row.names = FALSE ,quote=FALSE)
key2$title = paste0( key2$siRNA, "_", key2$Cells, "_", key2$tube)
wb_geo <- createWorkbook()
addWorksheet(wb_geo, 'key')
writeData(wb_geo, 'key' , key2 , rowNames=F )
saveWorkbook(wb_geo, file = paste0(out.dir,"geosubmit.xlsx"), overwrite = TRUE)
} else {
data = readRDS("DATA2.rds" )
cpg.m.after = data$cpg.m.after
cpgBeta.after = data$cpgBeta.after
qc = data$qc
}
```
```{r}
# make sure that the order of target and cpg samples are the same.
all.equal( colnames(cpg.m.after), key$Basename )
all.equal( colnames(cpgBeta.after),key$Basename )
# remove NA / incomplete rows
nrow ( cpg.m.after)
cpg.m.after <- cpg.m.after[complete.cases(cpg.m.after), ]
cpgBeta.after <- cpgBeta.after[complete.cases(cpgBeta.after), ]
# calculate cell poportions
ref.m <- centDHSbloodDMC.m
cell.porportion <- epidish( cpgBeta.after , ref.m, method = "RPC")
boxplot(cell.porportion$estF)
cp <- cell.porportion$estF
# rename the id to make it look better
#cp = merge ( cp, key, by.x="row.names", "Basename")
cp.table <- cp
cp <- melt (cp)
colsingl <- getPalette ( length ( unique ( cp$X2 ) ))
cell_portion = ggplot(cp, aes(x = X2, y = value, fill = X2)) +
geom_bar(stat = "identity") +
theme(legend.position="bottom", legend.title=element_blank(), legend.key = element_blank(),
axis.text.x = element_text(angle = 90, size=10),
axis.text.y = element_text(size=15.5), panel.background = element_blank()
) + ggtitle( " cell porportion ") +
scale_fill_manual(values = colsingl )
cp.table <- round( cp.table , digits = 4)
cp2 = merge ( key, cp, by.x="Basename", by.y="X1")
cell_type_group = ggplot(cp2, aes(y=value, x=X2)) +
geom_violin()+
geom_jitter(shape=19, position=position_jitter(0.07), aes( colour=siRNA), size=4 ) +
theme_bw() +
ylab(" ") +
xlab("") +
theme(legend.position="none", legend.title=element_blank(), legend.key = element_blank(),
axis.text.y = element_text(size=12),
axis.text.x = element_text(angle = 90, size=11.5),
axis.title.x = element_text(size=22),
axis.title.y = element_text(size=22),
legend.text =element_text(size=12)
) + stat_summary(fun.y = mean, fun.ymin = mean, fun.ymax = mean,
geom = "crossbar", width = .5) + scale_colour_manual(values=ccc) +
facet_grid(~siRNA)
targets = key
```
# Data {.tabset}
## Key
```{r, message=FALSE, warning=FALSE,fig=TRUE,fig.width=10, fig.height=10, echo=FALSE, include=TRUE}
kable( key , format = "html" , row.names = F, caption = "All samples" ) %>% kable_classic(full_width = F, position = "center")
```
## Cell Type Proportion {.tabset}
* checking cell type compositions.
__SINCE this is cell lines this portion is not useful__
### Plot
```{r, include=TRUE, echo=FALSE, message=FALSE, warning=FALSE, fig.width=10, fig.height=6}
cell_portion
```
### compare
```{r, include=TRUE, echo=FALSE, message=FALSE, warning=FALSE, fig.width=10, fig.height=6}
cell_type_group
```
```{r}
# subset the correct values
#The Beta-value has a more intuitive biological interpretation, but the M-value is more statistically valid for the differential analysis of methylation levels. Du et al, 2010
# http://bmcbioinformatics.biomedcentral.com/articles/10.1186/1471-2105-11-587
c_key = key
c_key$sample = key$Basename
c_key$Group = key$siRNA
mv = cpg.m.after[ , c_key$sample]
bv = cpgBeta.after [ , c_key$sample]
## this is for the 850 K
### this will include annotations to genes, cpg island, snp etc..
ann850k = getAnnotation(IlluminaHumanMethylationEPICanno.ilm10b4.hg19)
ann850kSub <- ann850k[match(rownames(mv),ann850k$Name),
c(1:4,12:19,24:ncol(ann850k))]
```
```{r}
if ( update == 1){
modcombat2 <- model.matrix (~1, data= key )
mvc = ComBat(dat=as.matrix(mv ), batch=key$Cells, mod=modcombat2, par.prior=TRUE, prior.plots=FALSE)
mvc = data.frame ( mvc)
colnames ( mvc ) = gsub ( "^X", "",colnames ( mvc))
bvc = ComBat(dat=as.matrix(bv ), batch=key$Cells, mod=modcombat2, par.prior=TRUE, prior.plots=FALSE)
bvc = data.frame ( bvc)
colnames ( bvc ) = gsub ( "^X", "",colnames ( bvc))
saveRDS( list ( mvc=mvc, bvc=bvc
), "mod.rds")
}else {
temp = readRDS("mod.rds")
mvc = temp$mvc
bvc = temp$bvc
}
# unsupervised pca
dir.create(input_dir)
if ( update == 1){
mad <- apply (mvc, 1, mad )
mad <- sort ( mad, decreasing = T)
saveRDS( mad, paste0(input_dir, "mad.rds") )
}else {
mad = readRDS( paste0(input_dir, "mad.rds") )
}
top1 = ceiling ( length ( mad ) * .01 )
m.cpm = mvc [ row.names ( mvc) %in% names(mad)[1:10000] , c_key$sample ]
###
###
set.seed(123)
umap_r = umap(t( m.cpm ))
df2 <- data.frame(x = umap_r$layout[,1],
y = umap_r$layout[,2],
group =c_key$Group ,
cell = c_key$Cells
)
labelT = data.frame ( x=c(-1), y=c(5), group = c("siUHRF1"), label=c("siUHRF1"), cell="A549")
um1 = ggplot(df2, aes(x, y, colour = group, shape=cell )) +
geom_point(size=12, alpha=.8) +
theme_minimal() + xlab("UMAP 1") + ylab ( "UMAP 2 ") +
theme(legend.position="bottom", legend.key = element_blank(),
axis.text.y = element_text(size= 15 ),
#axis.text.x = element_blank(),
axis.title.x = element_text(size=20),
axis.title.y = element_text(size=20),
legend.text =element_text(size=12)
) + scale_colour_manual(values=ccc) + geom_text_repel(data = labelT, aes(label = label), size=15 , show.legend=FALSE )
### tsne
set.seed(123)
tsne_out <- Rtsne( t(m.cpm) , perplexity = 5 ) # Run TSNE
df1 <- data.frame(x = tsne_out$Y[,1],
y = tsne_out$Y[,2],
group =c_key$Group
)
labelT = data.frame ( x=c(-15, 15), y=c(0,-5), group = c("M","C"), label=c("moyamoya", "control"))
tsne1 = ggplot(df1, aes(x, y, shape = group )) +
geom_point(size=12, alpha=.8, stroke=3) +
theme_minimal() + xlab("tSNE 1") + ylab ( "tSNE 2 ") +
theme(legend.position="bottom", legend.key = element_blank(),
axis.text.y = element_text(size= 15 ),
#axis.text.x = element_blank(),
axis.title.x = element_text(size=20),
axis.title.y = element_text(size=20),
legend.text =element_text(size=12)
) + scale_colour_manual(values=ccc)
```
```{r}
scpm = scale ( data.matrix(m.cpm) )
kaja_colors = c()
kaja_colors[[ 'siKRAS' ]] = '#F8766D'
kaja_colors[[ 'siUHRF1' ]] = '#619CFF'
kaja_colors[[ 'siNeg' ]] = '#999999'
annt.color = list()
annt.color[['group']] = kaja_colors
# sanity check
all.equal( names ( m.cpm ), c_key$sample )
topannt = HeatmapAnnotation(
group = c_key$Group
,col = annt.color
, show_legend = T, simple_anno_size = unit(1.5, "cm")
)
km2=2
temp = m.cpm
colnames ( temp ) = make.unique( paste ( c_key$siRNA) )
dend2 = makehr ( t( temp ), km=1
, dist.this = "euclidean", aggreg= "ward.D2", meta1 = c_key$Group )
dend2$dend = dend2$dend %>% set("labels_cex", 0) %>% set("labels_col", "white")
plot ( sort ( dend2$dend) )
heat1 = ComplexHeatmap::Heatmap( data.matrix(m.cpm)
, name = "Methylation"
, show_row_dend = T
, show_column_names = F
, show_row_names = F
#, name= heat.title
,column_split = 2
,top_annotation = topannt
#, col = pals::brewer.rdylbu(25)
, col = colorRampPalette(rev(brewer.pal(n = 7, name ="RdYlBu")))(25)
#, cluster_columns = sort ( dend2$dend , decreasing = T)
#, column_split = 2
, cluster_columns = sort ( dend2$dend)
#, row_split = 7
,row_title = NULL
,column_title = NULL
,show_heatmap_legend = T
, row_names_gp = grid::gpar(fontsize = 14)
,heatmap_legend_param = list(legend_height =unit(6, "cm") , labels_gp = gpar(col = "black", fontsize = 14) )
#, clustering_distance_columns = "spearman"
)
```
## Unsupervised Clustering {.tabset}
* CpG profiling shown in a two-dimensional tSNE plot. Each dot represents a sample.
* The top 10000 of most variable cpgs (on the basis of median absolute deviation) were selected and processed by the UMAP algorithm
### UMAP
```{r, message=FALSE, warning=FALSE,fig=TRUE,fig.width=10, fig.height=7, echo=FALSE, include=TRUE}
um1
```
### Heatmap
```{r, message=FALSE, warning=FALSE,fig=TRUE,fig.width=10, fig.height=7, echo=FALSE, include=TRUE}
draw ( heat1 )
paper_fig = "/projects/lab.mis/kaja/epic/paper_fig"
dir.create(paper_fig)
pdf(paste0(paper_fig, "/unsup_heat.pdf"), width=12.5, height=12.3)
draw ( heat1 )
dev.off()
```
```{r}
# differential expression
#
group <- factor(c_key$Group)
cell <- factor ( c_key$Cells)
design <- model.matrix(~0+group + cell , data=c_key)
colnames ( design) = gsub ( 'group',"",colnames(design))
colnames ( design) = make.names ( colnames ( design) )
# fit the linear model
fit <- lmFit(mvc, design)
# create a contrast matrix for specific comparisons
contMatrix <- makeContrasts(
siKRAS=siKRAS - siNeg
,siUHRF1=siUHRF1-siNeg
,siUHRF1k = siUHRF1 - siKRAS
, levels=design)
# fit the contrasts
fit2 <- contrasts.fit(fit, contMatrix)
fit2 <- eBayes(fit2)
summary(decideTests(fit2))
result_uhrf1 <- topTable(fit2, num=Inf, coef="siUHRF1", genelist=ann850kSub)
result_kras <- topTable(fit2, num=Inf, coef="siKRAS", genelist=ann850kSub)
hist ( result_uhrf1$adj.P.Val, breaks= seq(0,1,.05) )
hist ( result_kras$adj.P.Val, breaks= seq(0,1,.05) )
dim (result_kras[result_kras$adj.P.Val < .7 & result_kras$P.Value < .001 & abs ( result_kras$logFC) > .5 , ] )
dim (result_uhrf1[result_uhrf1$adj.P.Val < .05 & abs ( result_uhrf1$logFC) > 1.5 & result_uhrf1$P.Value < .001 , ] )
key_uhrf1 = c_key[ c_key$siRNA %in% c("siUHRF1","siNeg" ), ]
result_uhrf1 <- merge( result_uhrf1 , bvc [ , key_uhrf1$sample ] , by="row.names" )
colnames( result_uhrf1 )[1] <- "gene"
key_kras = c_key[ c_key$siRNA %in% c("siKRAS","siNeg" ), ]
result_kras <- merge( result_kras , bvc [ , key_kras$sample ] , by="row.names" )
colnames( result_kras )[1] <- "gene"
rsub <- colnames(result_uhrf1 )[1:which ( colnames ( result_uhrf1) == "B")]
result = list ()
result$uhrf1$result = result_uhrf1
result$uhrf1$fdr = .05
result$uhrf1$pv = .001
result$uhrf1$logfc = 1.5
result$uhrf1$key = key_uhrf1
result$uhrf1$exp = c ( exp="siUHRF1", control="siNeg" )
result$uhrf1$title = " siUHRF1_vs_siNeg"
result$kras$result = result_kras
result$kras$fdr = .7
result$kras$pv = .001
result$kras$logfc = .5
result$kras$key = key_kras
result$kras$exp = c ( exp="siKRAS", control="siNeg" )
result$kras$title = " siKRAS_vs_siNeg"
for ( res in names ( result )){
post = plot.post ( result.gene= result[[res]]$result , g1="Group", g2="Group"
, new.key=result[[res]]$key, r.sub=rsub, exp.group='Group'
, exp.this=as.character ( result[[res]]$exp['exp'] )
, normal.this= as.character ( result[[res]]$exp['control'] )
, sample.id="sample"
, GENE_SYMBOL = "gene"
, fdr= result[[res]]$fdr
, p.val =result[[res]]$pv
, fold_thres = result[[res]]$logfc