-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.R
More file actions
341 lines (274 loc) · 11 KB
/
app.R
File metadata and controls
341 lines (274 loc) · 11 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
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
# Load R packages
library(shiny)
library(shinythemes)
library(httr)
library(jsonlite)
library(base64enc)
library(digest)
library(shinycssloaders)
library(dplyr)
library(htmlwidgets)
# Source utility functions
source("utils.R")
################################################################################
# AUTHENTICATION CONFIGURATION - Set your method here
################################################################################
USE_OAUTH2 <- FALSE # Set to FALSE for JWT (default), TRUE for OAuth2
# OAuth2 credentials (only used if USE_OAUTH2 = TRUE)
if (USE_OAUTH2) {
client_id <- Sys.getenv("BENCHLING_CLIENT_ID")
client_secret <- Sys.getenv("BENCHLING_CLIENT_SECRET")
domain_fixed <- Sys.getenv("BENCHLING_DOMAIN")
if (client_id == "" || client_secret == "" || domain_fixed == "") {
stop("OAuth2 enabled but credentials missing! Set BENCHLING_CLIENT_ID, BENCHLING_CLIENT_SECRET, and BENCHLING_DOMAIN in .Renviron")
}
}
################################################################################
# Define UI
ui <- fluidPage(theme = shinytheme("cerulean"),
navbarPage(
"R Shiny - IC50 Calc",
tabPanel("Import Dataset",
sidebarPanel(
tags$h3("Input:"),
textInput("DatasetKey", "Analysis Key:", ""),
actionButton("submitbutton", "Get Dataset", class = "btn btn-primary"),
actionButton("sendresultAnalysis", "Send Analysis", class = "btn btn-primary")
),
mainPanel(
tags$label(h4("Tenant Subdomain")),
verbatimTextOutput("subdomain"),
verbatimTextOutput("analysis") %>% withSpinner(color="#0dc5c1"),
tableOutput('tabledata')
)
),
tabPanel("Regression Algorithm",
mainPanel(
tags$h2("4-Parameter Log-Logistic Model (LL.4)"),
tags$p("IC50 calculations use dose-response curve fitting with the drc package.")
)
)
)
)
# Define server function
server <- function(input, output) {
# Extract base domain (full domain including suffix)
base_domain <- reactive({
if (USE_OAUTH2) {
# OAuth2: use domain from credentials
domain_fixed
} else {
# JWT: extract from analysis key
split_key <- strsplit(input$DatasetKey, ".", fixed = TRUE)
payload <- jsonlite::fromJSON(rawToChar(base64decode(split_key[[1]][2])))
domain_raw <- payload$aud
# Determine if this is a full domain or just a subdomain
if (grepl("\\.", domain_raw)) {
# Contains a dot - it's a full domain, use as-is
domain_raw
} else {
# No dot - it's just a subdomain, append .benchling.com
paste0(domain_raw, ".benchling.com")
}
}
})
# Extract subdomain (first part only, for display)
subdomain <- reactive({
sub("\\..*", "", base_domain())
})
# Get dataset from Benchling
datasetInput <- reactive({
# Extract analysis ID from key
key_parts <- strsplit(input$DatasetKey, ":", fixed = TRUE)[[1]]
analysis_id <- key_parts[1]
# Get access token based on auth method
if (USE_OAUTH2) {
# OAuth2: Generate token from app credentials
token_url <- paste0("https://", domain_fixed, "/api/v2/token")
token_request <- httr::POST(
url = token_url,
body = paste0("client_id=", client_id,
"&client_secret=", client_secret,
"&grant_type=client_credentials"),
httr::accept('application/json'),
httr::content_type('application/x-www-form-urlencoded')
)
if (token_request$status_code != 200) {
stop("OAuth2 authentication failed!")
}
request_body <- jsonlite::fromJSON(rawToChar(token_request$content))
access_token <- request_body$access_token
} else {
# JWT: Use token from analysis key
access_token <- key_parts[2]
}
# Get analysis
endpoint <- "/api/v2-beta/analyses/"
URL <- paste("https://", isolate(base_domain()), endpoint, analysis_id, sep = "")
analysis_req <- GET(URL, add_headers(
Accept = 'application/json',
Authorization = paste("Bearer", access_token)
))
dat <- jsonlite::fromJSON(rawToChar(analysis_req$content))
datasetId <- c(dat$dataFrameIds)[1]
folder_id <- c(dat$folderId)
# Store for later use
assign("access_token", access_token, envir = .GlobalEnv)
assign("folder_id", folder_id, envir = .GlobalEnv)
assign("analysis_id", analysis_id, envir = .GlobalEnv)
# Get dataset
endpoint <- "/api/v2-beta/data-frames/"
URL <- paste("https://", isolate(base_domain()), endpoint, datasetId, sep = "")
Dataset_req <- GET(URL, add_headers(
Accept = 'application/json',
Authorization = paste("Bearer", access_token)
))
dat <- jsonlite::fromJSON(rawToChar(Dataset_req$content))
DatasetUrl <- c(dat$manifest$url)
df <- read.csv(DatasetUrl)
df
})
# Process analysis and upload results
analysis <- reactive({
df <- datasetInput()
# Find concentration column
conc_col <- grep("^Concentration$|Cell\\.Mortality\\.Concentration",
names(df), ignore.case = TRUE, value = TRUE)[1]
# Find mortality columns (matches "Mortality.24h" or "Cell.Mortality.Mortality.24h")
mort_24h_col <- grep("Mortality\\.24h",
names(df), ignore.case = TRUE, value = TRUE)[1]
mort_48h_col <- grep("Mortality\\.48h",
names(df), ignore.case = TRUE, value = TRUE)[1]
# Calculate IC50 for 24h using utility function
result_24 <- calculate_ic50(df, conc_col, mort_24h_col)
IC50_24 <- result_24$ic50
slope_24 <- result_24$slope
# Calculate IC50 for 48h using utility function
result_48 <- calculate_ic50(df, conc_col, mort_48h_col)
IC50_48 <- result_48$ic50
slope_48 <- result_48$slope
# Create plotly graphs using utility function
imageName_24 <- "mortality_24h.html"
File_24 <- tempfile(fileext = ".html")
plot_24 <- create_ic50_plot(df, conc_col, mort_24h_col, IC50_24, slope_24,
title = "IC50 24h Dose-Response")
saveWidget(widget = plot_24, file = File_24, selfcontained = TRUE)
imageName_48 <- "mortality_48h.html"
File_48 <- tempfile(fileext = ".html")
plot_48 <- create_ic50_plot(df, conc_col, mort_48h_col, IC50_48, slope_48,
title = "IC50 48h Dose-Response")
saveWidget(widget = plot_48, file = File_48, selfcontained = TRUE)
# Upload files to Benchling
upload_file <- function(filepath, filename, folder_id, access_token, base_domain) {
endpoint <- "/api/v2-beta/files"
URL <- paste("https://", base_domain, endpoint, sep = "")
my_data <- readBin(filepath, "raw", 10e6)
filePostBody <- list(name = filename, folderId = folder_id, filename = filename)
filePostResponse <- httr::POST(
url = URL,
body = toJSON(filePostBody, pretty = TRUE, auto_unbox = TRUE),
httr::accept('application/json'),
httr::add_headers('Authorization' = paste("Bearer", access_token)),
httr::content_type('application/json')
)
dat <- jsonlite::fromJSON(rawToChar(filePostResponse$content))
fileID <- dat$id
s3_Put_Url <- filePostResponse$headers$`content-location`
s3FileUpload <- httr::PUT(
url = s3_Put_Url,
body = my_data,
httr::add_headers('x-amz-server-side-encryption' = 'AES256')
)
if (s3FileUpload$status_code == 200) {
endpoint <- "/api/v2-beta/files/"
URL <- paste("https://", base_domain, endpoint, fileID, sep = "")
s3FileUploadStatus <- list(uploadStatus = 'SUCCEEDED')
PatchFile <- httr::PATCH(
url = URL,
body = toJSON(s3FileUploadStatus, pretty = TRUE, auto_unbox = TRUE),
httr::accept('application/json'),
httr::add_headers('Authorization' = paste("Bearer", access_token)),
httr::content_type('application/json')
)
}
fileID
}
fileID_24 <- upload_file(File_24, imageName_24, folder_id, access_token, isolate(base_domain()))
fileID_48 <- upload_file(File_48, imageName_48, folder_id, access_token, isolate(base_domain()))
# Create and upload CSV results
cell_name <- unique(df$Cell.Name)[1]
Cell <- rep(cell_name, 2)
Hours <- c(24, 48)
Function <- c('LL.4', 'LL.4')
IC50 <- c(IC50_24, IC50_48)
Csv_df <- data.frame(Cell, Hours, Function, IC50)
Csv_file <- tempfile(fileext = ".csv")
write.csv(Csv_df, Csv_file, row.names = FALSE)
# Upload CSV as dataframe
endpoint <- "/api/v2-beta/data-frames"
URL <- paste("https://", isolate(base_domain()), endpoint, sep = "")
my_data <- readBin(Csv_file, "raw", 10e6)
DatasetBody <- list(manifest = list(list(fileName = "mortality.csv")), name = 'MortalityIC50')
DatasetPostResponse <- httr::POST(
url = URL,
body = toJSON(DatasetBody, pretty = TRUE, auto_unbox = TRUE),
httr::accept('application/json'),
httr::add_headers('Authorization' = paste("Bearer", access_token)),
httr::content_type('application/json')
)
dat <- jsonlite::fromJSON(rawToChar(DatasetPostResponse$content))
DatasetID_Result <- dat$id
s3_Put_Url <- dat$manifest$url
s3FileUpload <- httr::PUT(
url = s3_Put_Url,
body = my_data,
httr::add_headers('x-amz-server-side-encryption' = 'AES256')
)
if (s3FileUpload$status_code == 200) {
endpoint <- "/api/v2-beta/data-frames/"
URL <- paste("https://", isolate(base_domain()), endpoint, DatasetID_Result, sep = "")
DatasetStatusBody <- list(uploadStatus = "IN_PROGRESS")
PatchFile <- httr::PATCH(
url = URL,
body = toJSON(DatasetStatusBody, pretty = TRUE, auto_unbox = TRUE),
httr::accept('application/json'),
httr::add_headers('Authorization' = paste("Bearer", access_token)),
httr::content_type('application/json')
)
}
# Patch analysis with outputs
endpoint <- "/api/v2-beta/analyses/"
URL <- paste("https://", isolate(base_domain()), endpoint, analysis_id, sep = "")
Analysisfiles <- list(fileIds = list(fileID_24, fileID_48), dataFrameIds = list(DatasetID_Result))
PatchAnalysis <- httr::PATCH(
url = URL,
body = toJSON(Analysisfiles, pretty = TRUE, auto_unbox = TRUE),
httr::accept('application/json'),
httr::add_headers('Authorization' = paste("Bearer", access_token)),
httr::content_type('application/json')
)
dat <- jsonlite::fromJSON(rawToChar(PatchAnalysis$content))
paste("Analysis complete! Status:", dat$status)
})
# Outputs
output$subdomain <- renderText({
if (input$submitbutton > 0) {
isolate(subdomain())
} else {
"Enter Analysis Key"
}
})
output$tabledata <- renderTable({
if (input$submitbutton > 0) {
datasetInput()
}
})
output$analysis <- renderText({
if (input$sendresultAnalysis > 0) {
isolate(analysis())
} else {
"Click 'Send Analysis' to process"
}
})
}
shinyApp(ui = ui, server = server)