forked from Al-Murphy/MungeSumstats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathieugwasr.R
331 lines (302 loc) · 10.1 KB
/
ieugwasr.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
################################################################
## Functions extracted from ieugwasr because Bioconductor doesn't
## allow any remotes.
## All code in this file was written by the ieugwasr team
## and is available on GitHub:
## https://github.com/MRCIEU/ieugwasr
################################################################
#' Get list of studies with available GWAS summary statistics through API
#'
#' @param id List of MR-Base IDs to retrieve. If NULL (default)
#' retrieves all available datasets
#' @param access_token Google OAuth2 access token.
#' Used to authenticate level of access to data
#'
#' @importFrom magrittr %>%
#' @keywords internal
#' @return Dataframe of details for all available studies
gwasinfo <- function(id = NULL, access_token = check_access_token()) {
id <- legacy_ids(id)
if (!is.null(id)) {
stopifnot(is.vector(id))
out <- api_query("gwasinfo",
query = list(id = id),
access_token = access_token) %>% get_query_content()
} else {
out <- api_query("gwasinfo", access_token = access_token) %>%
get_query_content()
}
if (length(out) == 0) {
return(dplyr::tibble())
}
out <- dplyr::bind_rows(out) %>%
dplyr::select("id", "trait", dplyr::everything())
class(out) <- c("GwasInfo", class(out))
return(out)
}
#' Get access token for OAuth2 access to MR Base
#'
#'
#' @keywords internal
#' @return access token string
#' @importFrom googleAuthR gar_auth
get_access_token <- function() {
msg <- "Using access token. For info on how this is used see logging_info()"
message(msg)
tf <- basename(tempfile())
check <- file.create(tf, showWarnings = FALSE)
if (!check) {
stop(
"You are currently in a directory",
" which doesn't have write access.\n",
" In order to authenticate we need to store",
" the credentials in a file called '.httr-oauth'.\n",
" Please setwd() to a different directory",
" where you have write access."
)
} else {
unlink(tf)
}
a <- googleAuthR::gar_auth(email = TRUE)
if (!a$validate()) {
a$refresh()
}
return(a$credentials$access_token)
}
#' Check if authentication has been made
#'
#' If a call to get_access_token() has been made then it will
#' have generated mrbase.oauth. Pass the token if it is present,
#' if not, return NULL and do not authenticate.
#'
#' @keywords internal
#' @return NULL or access_token depending on current authentication state
check_access_token <- function() {
if (file.exists("ieugwasr_oauth")) {
return(get_access_token())
} else {
return(NULL)
}
}
#' Convert current IDs to legacy IDs
#'
#' @param x Vector of ids
#'
#' @keywords internal
#' @return vector of back compatible ids
#' @importFrom dplyr tibble
legacy_ids <- function(x) {
if (is.null(x)) {
return(NULL)
}
changes <- dplyr::tibble(
old = c("UKB-a:", "UKB-b:", "UKB-c:", "IEU-a:", "\\D"),
new = c("ukb-a-", "ukb-b-", "ukb-c-", "ieu-a-", "ieu-a-")
)
y <- x
for (i in seq(1, nrow(changes)))
{
index <- grepl(changes$old[i], x)
if (changes$old[i] == "\\D") {
index <- !grepl(changes$old[i], x)
}
if (any(index)) {
if (changes$old[i] == "\\D") {
x[index] <- paste0(changes$new[i], x[index])
} else {
x[index] <- gsub(changes$old[i], changes$new[i], x[index])
}
}
}
# met datasets
index <- x %in% paste0("ieu-a-", 303:754)
x[index] <- gsub("ieu-a-", "met-a-", x[index])
index <- x %in% paste0("ieu-a-", 119:269)
x[index] <- gsub("ieu-a-", "met-b-", x[index])
index <- x %in% paste0("ieu-a-", 838:960)
x[index] <- gsub("ieu-a-", "met-c-", x[index])
overallindex <- y != x
if (any(overallindex)) {
msg <- paste(
"Deprecated IDs being used? Detected numeric IDs.",
"Trying to fix, but please note the changes below for future."
)
message(msg)
message(paste(y[overallindex], " -> ", x[overallindex],
collapse = "\n"))
}
return(x)
}
#' Wrapper for sending queries and payloads to API
#'
#' There are a number of different GET and POST endpoints
#' in the GWAS database API. This is a generic way to access them
#'
#' @param path Either a full query path (e.g. for get) or
#' an endpoint (e.g. for post) queries
#' @param query If post query, provide a list of arguments as the payload.
#' NULL by default
#' @param access_token Google OAuth2 access token. Used to authenticate
#' level of access to data. By default, checks if already authenticated
#' through \code{get_access_token} and if not then does
#' not perform authentication.
#' @param method GET (default) or POST, DELETE etc
#' @param silent TRUE/FALSE to be passed to httr call. TRUE by default
#' @param encode Default = json, see httr::POST for options
#' @param timeout Default = 300, avoid increasing this,
#' preferentially simplify the query first.
#'
#' @keywords internal
#' @return httr response object
#' @importFrom httr add_headers timeout DELETE GET POST
api_query <- function(path,
query = NULL,
access_token = check_access_token(),
method = "GET",
silent = TRUE,
encode = "json",
timeout = 300) {
ntry <- 0
ntries <- 5
headers <- httr::add_headers(
# 'Content-Type'='application/json; charset=UTF-8',
"X-Api-Token" = access_token,
"X-Api-Source" = ifelse(is.null(options()$mrbase.environment),
"R/TwoSampleMR", "mr-base-shiny")
)
retry_flag <- FALSE
while (ntry <= ntries) {
if (method == "DELETE") {
r <- try(
httr::DELETE(
paste0(options()$ieugwasr_api, path),
headers,
httr::timeout(timeout)
),
silent = TRUE
)
} else if (!is.null(query)) {
r <- try(
httr::POST(
paste0(options()$ieugwasr_api, path),
body = query,
headers,
encode = encode,
httr::timeout(timeout)
),
silent = TRUE
)
} else {
r <- try(
httr::GET(
paste0(options()$ieugwasr_api, path),
headers,
httr::timeout(timeout)
),
silent = TRUE
)
}
if ("try-error" %in% class(r)) {
if (grepl("Timeout", as.character(attributes(r)$condition))) {
stop(
"The query to MR-Base exceeded ", timeout,
" seconds and timed out. Please simplify the query"
)
}
}
if (!"try-error" %in% class(r)) {
if (r$status_code >= 500 & r$status_code < 600) {
message("Server code: ",
r$status_code,
"; Server is possibly experiencing traffic,",
" trying again...")
retry_flag <- TRUE
Sys.sleep(1)
} else {
if (retry_flag) {
message("Retry succeeded!")
}
break
}
}
ntry <- ntry + 1
}
if (r$status_code >= 500 & r$status_code < 600) {
message("Server issue: ", r$status_code)
message(
"Unable to retrieve results from server. See status in",
" the returned object and contact the developers if the ",
"problem persists."
)
return(r)
}
if ("try-error" %in% class(r)) {
if (grepl(
"Could not resolve host",
as.character(attributes(r)$condition)
)) {
stop(
"The MR-Base server appears to be down, the following issue",
" was received:\n", as.character(attributes(r)$condition)
)
} else {
stop(
"The following issue was encountered in trying to query the ",
"MR-Base server:\n", as.character(attributes(r)$condition)
)
}
}
return(r)
}
#' Parse out json response from httr object
#'
#' @param response Output from httr
#'
#' @keywords internal
#' @return Parsed json output from query, often in form of data frame.
#' If status code is not successful then return the actual response.
#' @importFrom jsonlite fromJSON
#' @importFrom httr content status_code
get_query_content <- function(response) {
if (httr::status_code(response) >= 200 &
httr::status_code(response) < 300) {
o <- jsonlite::fromJSON(
httr::content(response, "text", encoding = "UTF-8"))
if ("eaf" %in% names(o)) {
o[["eaf"]] <- as.numeric(o[["eaf"]])
}
return(o)
} else {
return(response)
# stop("error code: ", httr::status_code(response),
#"\n message: ",
#jsonlite::fromJSON(httr::content(response, "text", encoding='UTF-8')))
}
}
#' Toggle API address between development and release
#'
#' From \code{ieugwasr}.
#'
#' @return No return
#'
#' @param where Which API to use.
#' Choice between "local", "release", "test". Default = "local"
#'
#' @keywords internal
select_api <- function(where = "public",
verbose = TRUE) {
url <- switch(where,
public = "http://gwas-api.mrcieu.ac.uk/",
private = "http://ieu-db-interface.epi.bris.ac.uk:8082/",
dev1 = "http://localhost:8019/",
dev2 = "http://127.0.0.1:5000/"
)
if (is.null(url)) {
url <- options()$ieugwasr_api
warning("A valid API was not selected. No change")
}
options(ieugwasr_api = url)
if(verbose){
message("API: ", where, ": ", url)
}
}