-
Notifications
You must be signed in to change notification settings - Fork 1
/
gene_ratio_functions.R
476 lines (365 loc) · 16.6 KB
/
gene_ratio_functions.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
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
# HEADER --------------------------------------------------
# Author: Matthew Muller
#
# Date: 2023-01-22
#
# Script Name: Gene Ratio Functions
#
# Notes:
# So this is all the gene ratio stuff I've been working with.
# Now I'm trying to just bring them all to one spot
# LOAD LIBRARIES ------------------------------------------
library(tidyverse, quietly = T)
library(ggplot2, quietly = T)
library(skimr, quietly = T)
library(DESeq2, quietly = T)
library(scales, quietly = T)
# LOAD FUNCTIONS ------------------------------------------
# space reserved for sourcing in functions
# CODE BLOCK ----------------------------------------------
# Add code here
#
###############################################################
#
# Create some things to use first
#
###############################################################
# ## Load in DGE data from duke and pace datasets
# pace_dge <- read.csv('data/hyper_v_hypo_deseqoutput.csv')
# duke_dge <- read.csv('data/duke_validation_run3/dge_analysis/comp_group1__hyper_v_nothyper_AGCONTROL_deseqout.csv')
# press_genes <- t(read.csv('data/clean/genes.csv'))
# # Select press genes present in both
# pace_dge <- pace_dge[pace_dge$X %in% press_genes,]
# pace_dge <- pace_dge[order(pace_dge$X),]
# duke_dge <- duke_dge[duke_dge$X %in% press_genes,]
# duke_dge <- duke_dge[order(duke_dge$X),]
# dge_data <- subset(pace_dge, select=c("X", "log2FoldChange"))
# colnames(dge_data) <- c("Genes", "Pace")
# dge_data$"Duke" <- duke_dge$log2FoldChange
# # Filter with p value
# dge_filtered_sign <- dge_data[duke_dge$pvalue < 0.05,]
# # Take only genes that align and write them to csvs
# gene_list_up_sign <- dge_filtered_sign[dge_filtered_sign$Pace > 0 & dge_filtered_sign$Duke > 0,]
# gene_list_down_sign <- dge_filtered_sign[dge_filtered_sign$Pace < 0 & dge_filtered_sign$Duke < 0,]
# ## Load in the correlated gene list data (data is median of ratios)
# subset_up <- gene_list_up_sign$Genes
# subset_down <- gene_list_down_sign$Genes
# pace_genes <- read.csv('data/clean/pace/features.csv')
# pace_labels <- read.csv('data/clean/pace/labels.csv')$X0
# duke_genes <- read.csv('data/clean/duke/features_group1.csv')
# duke_labels <- read.csv('data/clean/duke/labels_group1.csv')$compouttable...2.
# subset_up <- subset_up[subset_up %in% colnames(pace_genes)]
# subset_down <- subset_down[subset_down %in% colnames(pace_genes)]
###############################################################
#
# First Set of Functions for making gene ratios
#
###############################################################
gene_ratio_iterator <- function(
up_samples_df, down_samples_df){
# This function brute forces the ratio of every gene in up_df (up-regulated genes)
# with those in down_df (down-regulated genes). It is assumed the dataframes are
# built identically and have the same number of rows (ie. samples).
# Initialize things...
up_genes <- colnames(up_samples_df)
down_genes <- colnames(down_samples_df)
gene_ratio_df <- data.frame(matrix(ncol = length(down_genes)*length(up_genes),
nrow = dim(up_samples_df)[1]
)
)
# Fill in ratios
ratio_names <- c()
for (sample in 1:dim(up_samples_df)[1]) {
for (down_idx in 1:length(down_genes)) {
for (up_idx in 1:length(up_genes)) {
# Get values we need
up_gene <- up_genes[up_idx]
down_gene <- down_genes[down_idx]
if (sample == 1) {
ratio_names <- append(ratio_names, paste0(up_gene,"/",down_gene))
}
# Add in the ratio value
idx <- up_idx+(down_idx-1)*length(up_genes)
gene_ratio_df[sample,idx] <- up_samples_df[sample,up_idx] / down_samples_df[sample,down_idx]
}
}
}
colnames(gene_ratio_df) <- ratio_names
return(gene_ratio_df)
}
gene_to_ratio_table_converter <- function(
genes, labels){
# Subset the gene data and summarize it with skim
pace_up_genes_hyper <- genes[!!labels,] %>%
select(subset_up)
pace_down_genes_hyper <- genes[!!labels,] %>%
select(subset_down)
# Call the gene ratio iterator function
pace_hyper_ratios <- gene_ratio_iterator(pace_up_genes_hyper, pace_down_genes_hyper)
is.na(pace_hyper_ratios)<-sapply(pace_hyper_ratios, is.infinite)
pace_hyper_ratios[is.na(pace_hyper_ratios)]<-0
# Subset the gene data and summarize it with skim
pace_up_genes_normal <- genes[!!!labels,] %>%
select(subset_up)
pace_down_genes_normal <- genes[!!!labels,] %>%
select(subset_down)
# Call the gene ratio iterator function
pace_normal_ratios <- gene_ratio_iterator(pace_up_genes_normal, pace_down_genes_normal)
is.na(pace_normal_ratios)<-sapply(pace_normal_ratios, is.infinite)
pace_normal_ratios[is.na(pace_normal_ratios)] <- 0
ret <- list(pace_hyper_ratios, pace_normal_ratios)
return(ret)
}
ratio_significance_finder <- function(genes, labels){
# Subset the gene data and summarize it with skim
pace_up_genes_hyper <- genes[!!labels,] %>%
select(subset_up)
pace_down_genes_hyper <- genes[!!labels,] %>%
select(subset_down)
# Call the gene ratio iterator function
pace_hyper_ratios <- gene_ratio_iterator(pace_up_genes_hyper, pace_down_genes_hyper)
is.na(pace_hyper_ratios)<-sapply(pace_hyper_ratios, is.infinite)
pace_hyper_ratios[is.na(pace_hyper_ratios)]<-0
# Subset the gene data and summarize it with skim
pace_up_genes_normal <- genes[!!!labels,] %>%
select(subset_up)
pace_down_genes_normal <- genes[!!!labels,] %>%
select(subset_down)
# Call the gene ratio iterator function
pace_normal_ratios <- gene_ratio_iterator(pace_up_genes_normal, pace_down_genes_normal)
is.na(pace_normal_ratios)<-sapply(pace_normal_ratios, is.infinite)
pace_normal_ratios[is.na(pace_normal_ratios)] <- 0
pace_hyper_ratios_skim <- pace_hyper_ratios %>%skim()
pace_normal_ratios_skim <- pace_normal_ratios %>%skim()
# hist(pace_hyper_ratios_skim$numeric.mean - pace_normal_ratios_skim$numeric.mean, breaks="fd")
pace_ratios = data.frame(pace_hyper_ratios_skim$skim_variable,
pace_hyper_ratios_skim$numeric.mean,
pace_hyper_ratios_skim$numeric.sd,
pace_normal_ratios_skim$numeric.mean,
pace_hyper_ratios_skim$numeric.sd)
colnames(pace_ratios) <- c("Gene Ratio", "Hyper Mean", "Hyper SD", "Normal Mean", "Normal SD")
pace_ratios$Difference <- pace_hyper_ratios_skim$numeric.mean - pace_normal_ratios_skim$numeric.mean
# pace_ratios <- pace_ratios[pace_ratios$Difference > 500,]
significance_testing <- list()
for (gene in colnames(pace_hyper_ratios)) {
tmp <- t.test(pace_hyper_ratios[gene],pace_normal_ratios[gene])
significance_testing <- append(significance_testing, tmp$p.value)
}
pace_ratios$pvalue <- significance_testing
return(pace_ratios)
}
###############################################################
#
# Now some prediction and metric tools
#
###############################################################
gene_ratio_predictor <- function(
# Input dataframes need to have more than one column right now!!!
gene_ratio_df_condition,
gene_ratio_df_normal,
thresholds = NULL, # should be a vector
method = median # a function to calculate the thresholds
# algorithm will compute midpoint of the method on the two conditions
){
if (is.null(thresholds)) {
print("Setting Thresholds")
median_condition <- sapply(gene_ratio_df_condition, method)
median_normal <- sapply(gene_ratio_df_normal, method)
thresholds <- (median_condition + median_normal)/2
}
thresholds_cond <- matrix(nrow=dim(gene_ratio_df_condition)[1],
ncol=dim(gene_ratio_df_condition)[2] )
thresholds_norm <- matrix(nrow=dim(gene_ratio_df_normal)[1],
ncol=dim(gene_ratio_df_normal)[2] )
for (idx in 1:length(thresholds)) {
thresholds_cond[,idx] <- thresholds[idx]
thresholds_norm[,idx] <- thresholds[idx]
}
true_condition <- colSums(gene_ratio_df_condition >= thresholds_cond)
total_condition <- dim(gene_ratio_df_condition)[1]
sensitivity <- true_condition / total_condition
true_normal <- colSums(gene_ratio_df_normal <= thresholds_norm)
total_normal <- dim(gene_ratio_df_normal)[1]
specificity <- true_normal / total_normal
true_total <- true_normal + true_condition
total <- total_normal + total_condition
accuracy <- true_total / total
results <- t(data.frame(thresholds, sensitivity, specificity, accuracy))
return(results)
}
gene_ratio_sample_scorer <- function(
# Input dataframes need to have more than one column right now!!!
gene_ratio_df_condition,
gene_ratio_df_normal,
thresholds = NULL, # should be a vector
method = median # a function to calculate the thresholds
# algorithm will compute midpoint of the method on the two conditions
){
if (is.null(thresholds)) {
print("Setting Thresholds")
median_condition <- sapply(gene_ratio_df_condition, method)
median_normal <- sapply(gene_ratio_df_normal, method)
thresholds <- (median_condition + median_normal)/2
}
thresholds_cond <- matrix(nrow=dim(gene_ratio_df_condition)[1],
ncol=dim(gene_ratio_df_condition)[2] )
thresholds_norm <- matrix(nrow=dim(gene_ratio_df_normal)[1],
ncol=dim(gene_ratio_df_normal)[2] )
for (idx in 1:length(thresholds)) {
thresholds_cond[,idx] <- thresholds[idx]
thresholds_norm[,idx] <- thresholds[idx]
}
sample_scores_cond <- data.frame(scores = rowSums(gene_ratio_df_condition >= thresholds_cond))
sample_scores_cond$label <- "positive"
sample_scores_norm <- data.frame(scores = rowSums(gene_ratio_df_normal >= thresholds_norm))
sample_scores_norm$label <- "normal"
results <- rbind(sample_scores_cond, sample_scores_norm)
return(results)
}
gene_ratio_majority_voting <- function(
# Input dataframes need to have more than one column right now!!!
gene_ratio_df,
labels, # labels should be binary vector
weights = NULL, # use if weighing the gene ratios
thresholds = NULL, # should be a vector
margin = NULL, # error of thresholds used to determine prediction confidence
C = 1,
method = median, # a function to calculate the thresholds
probability = F
# algorithm will compute midpoint of the method on the two conditions
){
# Subset the data into the condition and normal groups
label_ <- unique(labels)
gene_ratio_df_condition <- gene_ratio_df[labels == label_[1],]
gene_ratio_df_normal <- gene_ratio_df[labels == label_[2],]
if (is.null(weights)) {
if (!probability) {
if (is.null(thresholds)) {
print("Setting Thresholds")
median_condition <- sapply(gene_ratio_df_condition, method)
median_normal <- sapply(gene_ratio_df_normal, method)
thresholds <- (median_condition + median_normal) / 2
}
thresholds_ <- matrix(nrow=dim(gene_ratio_df)[1],
ncol=dim(gene_ratio_df)[2] )
for (idx in 1:length(thresholds)) {thresholds_[,idx] <- thresholds[idx]}
sample_scores <- data.frame(scores = rowSums(gene_ratio_df >= thresholds_))
sample_scores <- sample_scores >= dim(gene_ratio_df)[2]/2
sample_scores <- data.frame(
scores = mapvalues(sample_scores, from=c(T, F), to=c(label_[1], label_[2]))
)
return(sample_scores)
}
if (probability) {
print("Using probability function. Must have margins.")
if (is.null(thresholds)) {
print("Setting thresholds and margins")
median_condition <- sapply(gene_ratio_df_condition, method)
sd_condition <- sapply(gene_ratio_df_condition, function(x){sd(x)/sqrt(length(x))})
median_normal <- sapply(gene_ratio_df_normal, method)
sd_normal <- sapply(gene_ratio_df_normal, function(x){sd(x)/sqrt(length(x))})
thresholds <- (median_condition + median_normal)
margin <- (sd_condition + sd_normal) * C # following error propagation logic
}
thresholds_ <- matrix(nrow=dim(gene_ratio_df)[1],
ncol=dim(gene_ratio_df)[2] )
for (idx in 1:length(thresholds)) {thresholds_[,idx] = thresholds[idx]}
sample_scores <- (gene_ratio_df - thresholds) / margin
sample_scores[ sample_scores > 1 ] <- 1
sample_scores[ sample_scores < -1] <- -1
sample_scores <- rowSums(sample_scores) > dim(gene_ratio_df)[2]/2
sample_scores <- data.frame(
scores = mapvalues( sample_scores, from = c(T, F), to = c(label_[1], label_[2]) )
)
return(sample_scores)
}
}
if (!is.null(weights)) {
if (!probability) {
if (is.null(thresholds)) {
print("Setting Thresholds")
median_condition <- sapply(gene_ratio_df_condition, method)
median_normal <- sapply(gene_ratio_df_normal, method)
thresholds <- (median_condition + median_normal) / 2
}
thresholds_ <- matrix(nrow=dim(gene_ratio_df)[1],
ncol=dim(gene_ratio_df)[2] )
weights_ <- matrix(nrow=dim(gene_ratio_df)[1],
ncol=dim(gene_ratio_df)[2] )
for (idx in 1:length(thresholds)) {thresholds_[,idx] <- thresholds[idx]}
for (idx in 1:length(weights)) {weights_[,idx] = weights[idx]}
sample_scores <- as.numeric(gene_ratio_df >= thresholds_) * weights_
sample_scores <- data.frame(scores = rowSums(sample_scores))
sample_scores <- sample_scores >= dim(gene_ratio_df)[2]/2
sample_scores <- data.frame(
scores = mapvalues(sample_scores, from=c(T, F), to=c(label_[1], label_[2]))
)
return(sample_scores)
}
if (probability) {
print("Using probability function. Must have margins.")
if (is.null(thresholds)) {
print("Setting thresholds and margins")
median_condition <- sapply(gene_ratio_df_condition, method)
sd_condition <- sapply(gene_ratio_df_condition, function(x){sd(x)/length(x)})
median_normal <- sapply(gene_ratio_df_normal, method)
sd_normal <- sapply(gene_ratio_df_normal, function(x){sd(x)/length(x)})
thresholds <- (median_condition + median_normal)
margin <- (sd_condition + sd_normal) * C # following error propagation logic
}
thresholds_ <- matrix(nrow=dim(gene_ratio_df)[1],
ncol=dim(gene_ratio_df)[2] )
weights_ <- matrix(nrow=dim(gene_ratio_df)[1],
ncol=dim(gene_ratio_df)[2] )
for (idx in 1:length(thresholds)) {thresholds_[,idx] = thresholds[idx]}
for (idx in 1:length(weights)) {weights_[,idx] = weights[idx]}
sample_scores <- (gene_ratio_df - thresholds) / margin
sample_scores[ sample_scores > 1 ] <- 1
sample_scores[ sample_scores < -1] <- -1
sample_scores <- sample_scores * weights_
sample_scores <- rowSums(sample_scores) > dim(gene_ratio_df)[2]/2
sample_scores <- data.frame(
scores = mapvalues( sample_scores, from = c(T, F), to = c(label_[1], label_[2]) )
)
return(sample_scores)
}
}
}
gene_ratio_threshold <- function(gene_ratio_df, labels, method = median) {
label_ <- unique(labels)
gene_ratio_df_condition <- gene_ratio_df[labels == label_[1],]
gene_ratio_df_normal <- gene_ratio_df[labels == label_[2],]
print("Setting thresholds")
median_condition <- sapply(gene_ratio_df_condition, method)
sd_condition <- sapply(gene_ratio_df_condition, sd)
median_normal <- sapply(gene_ratio_df_normal, method)
sd_normal <- sapply(gene_ratio_df_normal, sd)
thresholds <- (median_condition + median_normal) / 2
margin <- (sd_condition + sd_normal) # following error propagation logic
return(thresholds)
}
gene_ratio_margin <- function(gene_ratio_df, labels, method = median) {
label_ <- unique(labels)
gene_ratio_df_condition <- gene_ratio_df[labels == label_[1],]
gene_ratio_df_normal <- gene_ratio_df[labels == label_[2],]
print("Setting margins")
median_condition <- sapply(gene_ratio_df_condition, method)
sd_condition <- sapply(gene_ratio_df_condition, sd)
median_normal <- sapply(gene_ratio_df_normal, method)
sd_normal <- sapply(gene_ratio_df_normal, sd)
thresholds <- (median_condition + median_normal) / 2
margin <- (sd_condition + sd_normal) / 2# following error propagation logic
return(margin)
}
plot_umap <- function(x, labels, main="A UMAP Visualization") {
layout <- x
if (is(x, "umap")) {
layout <- x$layout
}
umap_df <- data.frame(
"UMAP.1" = layout[,1],
"UMAP.2" = layout[,2],
"cohort" = labels )
ggplot(umap_df, aes(x=UMAP.1, y=UMAP.2, col = cohort)) +
geom_point() + theme_minimal() + labs(title=main)
}