-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLDmergeFM.R
More file actions
194 lines (181 loc) · 5.6 KB
/
Copy pathLDmergeFM.R
File metadata and controls
194 lines (181 loc) · 5.6 KB
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
# Load arguments
script.flags <- commandArgs(trailingOnly = TRUE)
script.flags.n <- length(script.flags)
LOCUS <- script.flags[1]
cor.format <-
if (script.flags.n < 2) {
"LDSTORE"
} else {
script.flags[2]
}
neff.formula <-
if (script.flags.n < 3) {
"METAL"
} else {
script.flags[3]
}
# Load required libraries (CRAN versions after 01/09/18 will do)
suppressMessages(library("methods"))
suppressMessages(library("readr"))
suppressMessages(library("dplyr"))
suppressMessages(library("purrr"))
suppressMessages(library("reshape2"))
suppressMessages(library("Matrix"))
# Assertions
if (script.flags.n > 3) {
stop("Too many arguments for script to understand.")
}
if (!file.exists(paste0(LOCUS, ".ref"))) {
stop("Effect allele reference file not found, check locus name.")
}
if (!(neff.formula %in% c("METAL", "NCP"))) {
stop("Invalid option for sample size formula.")
}
if (!(cor.format %in% c("LDSTORE", "PLINK"))) {
stop("Invalid option for correlation matrix format.")
}
# Load list of SNPs in locus
SNP <-
unlist(read.table(
paste0(LOCUS, ".ref"),
header = F,
colClasses = c("character", "NULL")
))
# Load correlation files into a list
if (cor.format=="LDSTORE"){
corfile <- Sys.glob(paste0("*", LOCUS, ".cor.gz"))
if (length(corfile) < 2) {
stop("Fewer than two correlation matrices found, check locus name.")
}
samplevec <-
unlist(strsplit(corfile, paste0("_", LOCUS, ".cor.gz")))
LDlist <-
lapply(corfile,
read_table2,
col_types = cols_only(
RSID1 = "c",
RSID2 = "c",
correlation = "d"
))}
if (cor.format=="PLINK") {
corfile <- Sys.glob(paste0("*", LOCUS, ".ld.gz"))
if (length(corfile) < 2) {
stop("Fewer than two correlation matrices found, check locus name.")
}
samplevec <-
unlist(strsplit(corfile, paste0("_", LOCUS, ".ld.gz")))
LDlist <-
suppressWarnings(lapply(
corfile,
read_table2,
col_types = cols_only(
SNP_A = "c",
SNP_B = "c",
R = "d"
)
))
LDlist <-
LDlist %>% map( ~ rename(
.x,
RSID1 = SNP_A,
RSID2 = SNP_B,
correlation = R
))
}
names(LDlist) <- samplevec
# Expand correlation items to cover all pairwise SNP combinations
expand.cor <- function(cortable, snplist) {
snpvalid <- unique(c(cortable$RSID1, cortable$RSID2))
corlist.element <-
data.frame(RSID1 = SNP,
RSID2 = SNP,
stringsAsFactors = F)
corlist.element <-
full_join(corlist.element, cortable, by = c("RSID1", "RSID2"))
corlist.element$correlation[is.na(corlist.element$correlation) &
(corlist.element$RSID1 %in% snpvalid &
corlist.element$RSID2 %in% snpvalid)] <-
0
return(corlist.element)
}
LDlist <- lapply(LDlist, expand.cor, snplist = SNP)
# Load fam files into a list
famfile <- Sys.glob(paste0("*", LOCUS, ".fam"))
if (length(famfile) < 2) {
stop("Fewer than two .fam files found, check locus name.")
}
famlist <-
lapply(
famfile,
read.table,
header = F,
na.strings = c("NA", "-9"),
colClasses = c("NULL", "NULL", "NULL", "NULL", "NULL", "integer")
)
names(famlist) <- samplevec
famlist.pheno <-
lapply(famlist, function(x)
x[!is.na(x)]) # This transforms each element into a phenotype vector
# Calculate effective sample sizes
neffvec <- samplevec
for (sample in samplevec) {
ntot <- dim(famlist[[sample]])[1] # Takes into account missing phenotypes if used to calculate R2
ncas <- sum(famlist.pheno[[sample]] == 2)
if(ncas==0){ncas<-round(ntot/2)}
if(neff.formula=="METAL") {neff <- 4 / (1 / ncas + 1 / (ntot - ncas))}
if(neff.formula=="NCP") {neff <- ntot*(ncas/ntot)*(1-(ncas/ntot))}
neffvec[neffvec == sample] <- neff
}
# Create LD data frame with missing diagonal
LDframe <- data.frame(RSID1 = SNP,
RSID2 = SNP,
stringsAsFactors = F)
LDframe <-
full_join(LDframe,
reduce(LDlist, full_join, by = c("RSID1", "RSID2")),
by = c("RSID1", "RSID2"))
rm(LDlist) # Cleanup large object
gc() # Reallocate memory
# Calculate weighted correlation average
LDframe$wcor <-
apply(LDframe[, c(-1, -2)],
1,
weighted.mean,
w = as.numeric(neffvec),
na.rm = T)
LDframe$wcor[LDframe$RSID1 == LDframe$RSID2] <- 1
LDframe <- subset(LDframe, select = c("RSID1", "RSID2", "wcor"))
# Transform into LD correlation format
LDmatrix <-
acast(LDframe, RSID1 ~ RSID2, value.var = "wcor", drop = F, fill = 0) # Fill might not be necessary but is a safeguard for a FINEMAP error caused if NAs are present
rm(LDframe) # Cleanup large object
gc() # Reallocate memory
LDmatrix <- LDmatrix[SNP, SNP] # Keep SNP order, creating the upper triangle
LDmatrix <- forceSymmetric(LDmatrix, "U")
LDmatrix <-
as.matrix(LDmatrix) # Return actual correlation values in writable format
# Export matrix with LD format
write.table(
LDmatrix,
file = paste0(LOCUS, ".ld"),
col.names = F,
row.names = F
)
# Generate heatmap
if (capabilities()["png"]==T) {
heat.pal <- colorRampPalette(c("#d73027", "#fc8d59", "#fee090","#ffffbf","#e0f3f8","#91bfdb","#4575b4"))(256)
png(filename=paste0(LOCUS, ".heatmap.png"),type="cairo",width=4800,height=4800,pointsize=16,res=300)
heatmap(LDmatrix, Colv = NA, Rowv = NA, col = col, scale = "none",symm=T,labRow = F,labCol = F)
dev.off()}
# Log files used in computing correlations
options(max.print = 1000000)
sink(paste0(LOCUS, ".samples.log"))
for (obj in ls(pattern = "corfile")) {
cat(unname(get(obj)), sep = "\n")
}
sink()
sink(paste0(LOCUS, ".snp.log"))
for (obj in ls(pattern = "SNP")) {
cat(unname(get(obj)), sep = "\n")
}
sink()