-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathfunctions.R
1544 lines (1465 loc) · 52.9 KB
/
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
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
# # @@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@ @@@@@@@ @@@@@@ @@@@@@
# # @@@@@@@@ @@@@@@@ @@@@@@@@ @@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@
# # @@! @@@ @@! !@@ @@! @@! !@@ @@! @@@
# # !@! @!@ !@! !@! !@! !@! !@! !@! @!@
# # @!@!!@! @!! @!@!@!@!@ !@! @!!!:! @!! !!@@!! @!@!@!@!
# # !!@!@! !!! !!!@!@!!! !!! !!!!!: !!! !!@!!! !!!@!!!!
# # !!: :!! !!: :!! !!: !!: !:! !!: !!!
# # :!: !:! :!: :!: :!: :!: !:! :!: !:!
# # :: ::: :: ::: ::: :: :::: :: :::: :: :: :::
# # Isothermal Analysis of CETSA/RT-CETSA Experimental Sets
# #
# # Plate assignment, data cleanup, and functions
# # Patents: PCT/US21/45184, HHS E-022-2022-0-US-01
library(tidyverse)
library(readxl)
library(stringr)
library(drc)
library(ggthemes)
library(cowplot)
library(hrbrthemes)
library(ggpubr)
library(MESS)
library(devtools);
load_all(".");
#' construct_grid
#' Construct a grid with compatable headers for MoltenProt file prep
#'
#' @param row_num Number of rows in microplate
#' @param col_num Number of columns in microplate
#' @param pad_num Add padding 0 to well address?
#'
#' @return df containing the grid
#' @export
#'
#' @examples
#' construct_grid(16,24)
#' construct_grid(32,48,TRUE)
construct_grid <-
function(row_num = 16,
col_num = 24,
pad_num = FALSE) {
if (pad_num == FALSE) {
grid <-
expand.grid(row = LETTERS[1:(row_num)], col = c(1:(col_num))) %>%
arrange(row) %>%
mutate(address = paste(row, col, sep = '')) %>%
dplyr::select(-c('row', 'col'))
} else {
letter <- LETTERS[1:(row_num)]
number <- c(1:(col_num))
number <- str_pad(number, 2, pad = '0')
col_by_row <-
expand.grid(row = sprintf('%.2d', 1:16),
col = sprintf('%.2d', 1:24)) %>%
arrange(., row)
}
return(grid)
}
#' prepMatLabforMolt
#'
#' Need to provide location of file, usually in ./data/, and sheet location
#'
#' @param file_loc Location of raw Matlab data file
#' @param sheet What sheet in the .xlsx is the data located
#' @param col_names Are there column names in the data sheet
#' @param start_temp Start temp for the experiment
#' @param end_temp End temp for the experiment
#'
#' @return df containing the raw values for the RT-CETSA experiment
#' @export
#'
#' @examples
#' prepMatLabforMolt(file_loc = './data/210318_plate3.xlsx',
#' start_temp = startTemp,
#' end_temp = endTemp)
prepMatLabforMolt <- function(file_loc = './data/rtcetsa_raw.xlsx',
sheet = 'Sheet1',
col_names = FALSE,
start_temp = 37,
end_temp = 90) {
if (file.exists(file_loc) == FALSE) {
stop('File does not exist at path supplied.')
}
df <-
read_excel(
path = file_loc,
sheet = sheet,
col_names = col_names,
.name_repair = 'unique'
)
if (nrow(df) == 0 || ncol(df) == 0) {
stop('Imported file is empty. Please navigate to correct RT-CETSA file')
}
df <- df %>%
dplyr::select(-c('...1', '...2')) %>%
rownames_to_column() %>%
rename('well' = 'rowname')
# Construct temperature index (t_n) and pivot around the data to tidy
tracker <- 1
for (val in 2:ncol(df) - 1) {
names(df)[val + 1] <- paste('t_', val, sep = '')
tracker <- tracker + 1
}
df <- df %>%
pivot_longer(., cols = 2:ncol(df)) %>%
pivot_wider(names_from = well) %>%
rename(., 'Temperature' = 'name') %>%
mutate(., Temperature = as.integer(gsub("[^0-9.]", "", Temperature)))
#Create temperature index in line with experimental parameters supplied in main script
temperature_df <-
seq(start_temp, end_temp, by = ((end_temp - start_temp) / (nrow(df) -
1))) %>%
round(., digits = 1)
for (i in 1:length(temperature_df))
df$Temperature[i] <- temperature_df[i]
# Assemble data for moltenprot analysis by splitting 384-well plate to 96-well plate with appropriate index
grid_96w <- construct_grid(row_num = 8, col_num = 12)
q1 <- df %>%
dplyr::select(., 1, 2:97)
tracker <- 1
for (val in 1:nrow(grid_96w)) {
colnames(q1)[val + 1] <- grid_96w$address[val]
tracker <- tracker + 1
}
q2 <- df %>%
dplyr::select(., 1, 98:193)
tracker <- 1
for (val in 1:nrow(grid_96w)) {
colnames(q2)[val + 1] <- grid_96w$address[val]
tracker <- tracker + 1
}
q3 <- df %>%
dplyr::select(., 1, 194:289)
tracker <- 1
for (val in 1:nrow(grid_96w)) {
colnames(q3)[val + 1] <- grid_96w$address[val]
tracker <- tracker + 1
}
q4 <- df %>%
dplyr::select(., 1, 290:385)
tracker <- 1
for (val in 1:nrow(grid_96w)) {
colnames(q4)[val + 1] <- grid_96w$address[val]
tracker <- tracker + 1
}
write.csv(q1, './data/cleaned_expt1.csv', row.names = FALSE)
write.csv(q2, './data/cleaned_expt2.csv', row.names = FALSE)
write.csv(q3, './data/cleaned_expt3.csv', row.names = FALSE)
write.csv(q4, './data/cleaned_expt4.csv', row.names = FALSE)
return(df)
}
# Read in MoltenProt readout, with different column identities for different models
retrieveMoltenData <-
function(model = 'standard',
plate_format = 384) {
# Retrieve experimental data from processed file folders
col_by_row <-
expand.grid(row = sprintf('%.2d', 1:16), col = sprintf('%.2d', 1:24)) %>%
arrange(., row)
if (model == 'standard') {
exp1_param <-
read_excel('./data/cleaned_expt1/Signal_resources/Signal_results.xlsx',
sheet = 'Fit parameters') %>%
dplyr::select(-c('Condition'))
exp2_param <-
read_excel('./data/cleaned_expt2/Signal_resources/Signal_results.xlsx',
sheet = 'Fit parameters') %>%
dplyr::select(-c('Condition'))
exp3_param <-
read_excel('./data/cleaned_expt3/Signal_resources/Signal_results.xlsx',
sheet = 'Fit parameters') %>%
dplyr::select(-c('Condition'))
exp4_param <-
read_excel('./data/cleaned_expt4/Signal_resources/Signal_results.xlsx',
sheet = 'Fit parameters') %>%
dplyr::select(-c('Condition'))
# Reformat ID column in each exp from MoltenProt format (A1, not A01) to arrange
exp1_param$ID <-
gsub('([A-Z])(\\d)(?!\\d)', '\\10\\2\\3', exp1_param$ID, perl = TRUE)
exp1_param <- exp1_param %>% arrange(ID)
exp2_param$ID <-
gsub('([A-Z])(\\d)(?!\\d)', '\\10\\2\\3', exp2_param$ID, perl = TRUE)
exp2_param <- exp2_param %>% arrange(ID)
exp3_param$ID <-
gsub('([A-Z])(\\d)(?!\\d)', '\\10\\2\\3', exp3_param$ID, perl = TRUE)
exp3_param <- exp3_param %>% arrange(ID)
exp4_param$ID <-
gsub('([A-Z])(\\d)(?!\\d)', '\\10\\2\\3', exp4_param$ID, perl = TRUE)
exp4_param <- exp4_param %>% arrange(ID)
# Combine all experiments and add identifiers
exp_param_full <-
exp1_param %>% rbind(., exp2_param, exp3_param, exp4_param) %>%
rownames_to_column() %>% rename('well' = 'rowname') %>%
dplyr::select(
-c(
'ID',
'kN_init',
'bN_init',
'kU_init',
'bU_init',
'dHm_init',
'Tm_init',
'kN_fit',
'bN_fit',
'kU_fit',
'bU_fit',
'S',
'dCp_component'
)
) %>%
bind_cols(col_by_row) %>%
relocate(c('row', 'col'), .after = well) %>%
dplyr::select(-'well')
exp_param_full <- well_assignment(exp_param_full, 384)
return(exp_param_full)
}
if (model == 'irrev') {
exp1_param <-
read_excel('./data/cleaned_expt1/Signal_resources/Signal_results.xlsx',
sheet = 'Fit parameters') %>%
dplyr::select(-c('Condition'))
exp2_param <-
read_excel('./data/cleaned_expt2/Signal_resources/Signal_results.xlsx',
sheet = 'Fit parameters') %>%
dplyr::select(-c('Condition'))
exp3_param <-
read_excel('./data/cleaned_expt3/Signal_resources/Signal_results.xlsx',
sheet = 'Fit parameters') %>%
dplyr::select(-c('Condition'))
exp4_param <-
read_excel('./data/cleaned_expt4/Signal_resources/Signal_results.xlsx',
sheet = 'Fit parameters') %>%
dplyr::select(-c('Condition'))
# Reformat ID column in each exp from MoltenProt format (A1, not A01) to arrange
exp1_param$ID <-
gsub('([A-Z])(\\d)(?!\\d)', '\\10\\2\\3', exp1_param$ID, perl = TRUE)
exp1_param <- exp1_param %>% arrange(ID)
exp2_param$ID <-
gsub('([A-Z])(\\d)(?!\\d)', '\\10\\2\\3', exp2_param$ID, perl = TRUE)
exp2_param <- exp2_param %>% arrange(ID)
exp3_param$ID <-
gsub('([A-Z])(\\d)(?!\\d)', '\\10\\2\\3', exp3_param$ID, perl = TRUE)
exp3_param <- exp3_param %>% arrange(ID)
exp4_param$ID <-
gsub('([A-Z])(\\d)(?!\\d)', '\\10\\2\\3', exp4_param$ID, perl = TRUE)
exp4_param <- exp4_param %>% arrange(ID)
# Combine all experiments and add identifiers
exp_param_full <-
exp1_param %>% rbind(., exp2_param, exp3_param, exp4_param) %>%
rownames_to_column() %>% rename('well' = 'rowname') %>%
dplyr::select(c(
'well',
'Ea_fit',
'Tf_fit',
'kN_fit',
'bN_fit',
'kU_fit',
'bU_fit',
'S'
)) %>%
bind_cols(col_by_row) %>%
relocate(c('row', 'col'), .after = well) %>%
dplyr::select(-'well')
exp_param_full <- well_assignment(exp_param_full, 384)
return(exp_param_full)
}
}
# Gather base-line corrected fit curves for the 384-well plate and pivot plate
retrieve_FittedCurves <-
function(model = 'baseline-fit',
start_temp = 37,
end_temp = 90) {
col_by_row <-
expand.grid(row = sprintf('%.2d', 1:16), col = sprintf('%.2d', 1:24)) %>%
arrange(., row)
if (model == 'baseline-fit') {
exp1_curve <-
read_excel('./data/cleaned_expt1/Signal_resources/Signal_results.xlsx',
sheet = 'Baseline-corrected')
exp2_curve <-
read_excel('./data/cleaned_expt2/Signal_resources/Signal_results.xlsx',
sheet = 'Baseline-corrected') %>%
dplyr::select(-c('Temperature'))
exp3_curve <-
read_excel('./data/cleaned_expt3/Signal_resources/Signal_results.xlsx',
sheet = 'Baseline-corrected') %>%
dplyr::select(-c('Temperature'))
exp4_curve <-
read_excel('./data/cleaned_expt4/Signal_resources/Signal_results.xlsx',
sheet = 'Baseline-corrected') %>%
dplyr::select(-c('Temperature'))
exp_curve_all <-
cbind(
xp1 = exp1_curve,
xp2 = exp2_curve,
xp3 = exp3_curve,
xp4 = exp4_curve
) %>%
rename(., Temperature = xp1.Temperature) %>%
mutate(., Temperature = paste('val_t_', Temperature, sep = ''))
exp_curve_all <- exp_curve_all %>%
pivot_longer(cols = 2:ncol(exp_curve_all)) %>%
pivot_wider(names_from = Temperature) %>%
rownames_to_column() %>% rename('well' = 'rowname') %>%
bind_cols(col_by_row) %>%
dplyr::select(-c('name', 'well', 'row', 'col')) %>%
add_tempheaders(., start_temp, end_temp)
message('Fit curves retrieved.')
return(exp_curve_all)
}
if (model == 'fit_curves') {
exp1_curve <-
read_excel('./data/cleaned_expt1/Signal_resources/Signal_results.xlsx',
sheet = 'Fit curves')
exp2_curve <-
read_excel('./data/cleaned_expt2/Signal_resources/Signal_results.xlsx',
sheet = 'Fit curves') %>%
dplyr::select(-c('Temperature'))
exp3_curve <-
read_excel('./data/cleaned_expt3/Signal_resources/Signal_results.xlsx',
sheet = 'Fit curves') %>%
dplyr::select(-c('Temperature'))
exp4_curve <-
read_excel('./data/cleaned_expt4/Signal_resources/Signal_results.xlsx',
sheet = 'Fit curves') %>%
dplyr::select(-c('Temperature'))
exp_curve_all <-
cbind(
xp1 = exp1_curve,
xp2 = exp2_curve,
xp3 = exp3_curve,
xp4 = exp4_curve
) %>%
rename(., Temperature = xp1.Temperature) %>%
mutate(., Temperature = paste('val_t_', Temperature, sep = ''))
exp_curve_all <- exp_curve_all %>%
pivot_longer(cols = 2:ncol(exp_curve_all)) %>%
pivot_wider(names_from = Temperature) %>%
rownames_to_column() %>% rename('well' = 'rowname') %>%
bind_cols(col_by_row) %>%
dplyr::select(-c('name', 'well', 'row', 'col')) %>%
add_tempheaders(., start_temp, end_temp)
message('Fit curves retrieved.')
return(exp_curve_all)
}
}
# Construct full data frame with curve fit and parameters for analysis
bind_fulldf <- function(param_df, curve_df) {
df <- cbind(param_df, curve_df)
return(df)
}
#Convert any columns containing Kelvin values from MoltenProt to Celsius
kelToCel <- function(df) {
df <- df %>%
mutate(Tm_fit = Tm_fit - 273.15) %>%
mutate(T_onset = T_onset - 273.15)
}
# #
# ISO-CETSA Functions (new)
# #
# Add temperature headers to df
add_tempheaders <- function(df,
start_temp = 37,
end_temp = 90) {
temperature_df <-
seq(start_temp, end_temp, by = ((end_temp - start_temp) / (ncol(df) - 1))) %>%
round(., digits = 1)
for (i in 1:ncol(df)) {
colnames(df)[i] <- paste('t_', temperature_df[i], sep = '')
}
message('Temperature assignments changed for ',
ncol(df),
' points.')
return(df)
}
# Add row and column to a tidy dataframe (columns are each temperatures, rows are wells/conditions)
add_rowcol <- function(df, well_num) {
if (well_num == 96) {
col_by_row <-
expand.grid(row = sprintf('%.2d', 1:8), col = sprintf('%.2d', 1:12)) %>%
arrange(., row)
}
else if (well_num == 384) {
col_by_row <-
expand.grid(row = sprintf('%.2d', 1:16),
col = sprintf('%.2d', 1:24)) %>%
arrange(., row)
}
message('Row + Column assignments created for ',
well_num,
'-well plate')
df <- cbind(col_by_row, df)
return(df)
}
# Add well assignmnets for each plate
well_assignment <- function(df, well_num) {
if (well_num == 96) {
letter <- LETTERS[1:8]
number <- c(1:12)
number <- str_pad(number, 2, pad = '0')
tracker <- 1
temp_df <- tibble(well = c(1:384))
for (val in letter) {
for (num in number) {
temp_df$well[tracker] <- paste(val, num, sep = '')
tracker <- tracker + 1
}
}
}
else if (well_num == 384) {
letter <- LETTERS[1:16]
number <- c(1:24)
number <- str_pad(number, 2, pad = '0')
tracker <- 1
temp_df <- tibble(well = c(1:384))
for (val in letter) {
for (num in number) {
temp_df$well[tracker] <- paste(val, num, sep = '')
tracker <- tracker + 1
}
}
}
message('Well assignments created for ', well_num, '-well plate.')
df <- cbind(temp_df, df)
return(df)
}
# Assign compound ids and concentration from platemap
plate_assignment <- function(df, platemap_file) {
id_df <- read_excel(platemap_file, sheet = 'sample') %>%
dplyr::select(-1) %>%
pivot_longer(., cols = 1:ncol(.)) %>%
rename(ncgc_id = value) %>%
dplyr::select(-c('name'))
id_df$ncgc_id <- gsub('empty', 'vehicle', id_df$ncgc_id)
conc_df <- read_excel(platemap_file, sheet = 'conc') %>%
dplyr::select(-1) %>%
pivot_longer(., cols = 1:ncol(.)) %>%
rename(conc = value) %>%
dplyr::select(-c('name'))
df <- cbind(id_df, conc_df, df)
message('Plate assignment attached to dataframe.')
df$row <- as.numeric(df$row)
df$col <- as.numeric(df$col)
return(df)
}
# Calculate AUC for each well
calculate_auc <- function(df) {
#Retrieve temperatures to be used for AUC determination.
auc.df <- df %>%
dplyr::select(matches('t_\\d'))
#Initialize the AUC column
df$auc <- NA
# Pivot and clean each row for AUC model
for (i in 1:nrow(auc.df)) {
curveVals <- as.vector(auc.df[i,]) %>%
pivot_longer(cols = everything(),
names_to = 'temp',
values_to = 'response')
curveVals$temp <- curveVals$temp %>%
sub('t_', '', .)
curveVals$temp <- as.numeric(curveVals$temp)
df$auc[i] <- auc(x = curveVals$temp, y = curveVals$response)
}
message('AUC Values calculated for ', nrow(auc.df), ' wells.')
return(df)
}
control_grouping <- function(df, control = 'DMSO', pc = 'control') {
control_df <- filter(df, ncgc_id == control | ncgc_id == pc)
if (nrow(control_df) == 0) {
message('No control wells found. Review control input to function.')
} else
if (nrow(control_df) > 0) {
control_df <- control_df %>%
dplyr::select(-'conc')
return(control_df)
}
}
control_variability <-
function(df, nc = 'vehicle', pc = 'control') {
#Filter out positive and negative controls into their own df
nc.controls.df <- df %>%
filter(ncgc_id == nc) %>%
dplyr::select(-c('ncgc_id', 'well', 'row', 'col'))
pc.controls.df <- df %>%
filter(ncgc_id == pc) %>%
dplyr::select(-c('ncgc_id', 'well', 'row', 'col'))
#Calculate means, sd, and %CV
nc.mean.df <-
apply(nc.controls.df[1:ncol(nc.controls.df)], 2, mean)
nc.sd.df <- apply(nc.controls.df[1:ncol(nc.controls.df)], 2, sd)
pc.mean.df <-
apply(pc.controls.df[1:ncol(pc.controls.df)], 2, mean)
pc.sd.df <- apply(pc.controls.df[1:ncol(pc.controls.df)], 2, sd)
#Calculate %CV
nc.var.df <- tibble(nc.mean = nc.mean.df, nc.sd = nc.sd.df) %>%
mutate(nc.cv = (nc.sd / nc.mean) * 100)
pc.var.df <- tibble(pc.mean = pc.mean.df, pc.sd = pc.sd.df) %>%
mutate(pc.cv = (pc.sd / pc.mean) * 100)
analysis_method <- colnames(nc.controls.df)
var_df <- cbind(analysis_method, nc.var.df, pc.var.df)
message('Control group variability analyzed.')
return(var_df)
}
# Returns thermogram with mean/sd of DMSO curve across temps
control_thermogram <- function(df, pcTm, ncTm) {
subset_df <- subset(df, grepl('t_', analysis_method)) %>%
mutate(temp = as.numeric(gsub('t_', '', analysis_method))) %>%
dplyr::select(-'analysis_method')
therm_plot <- ggplot(subset_df, aes(x = temp)) +
geom_line(aes(y = nc.mean),
size = 1.5,
alpha = 0.75,
color = '#88CCEE') +
geom_errorbar(aes(ymin = nc.mean - nc.sd, ymax = nc.mean + nc.sd),
size = 0.5,
width = 1) +
geom_point(
aes(y = nc.mean),
size = 3.25,
shape = 21,
color = 'black',
fill = '#88CCEE'
) +
geom_line(aes(y = pc.mean),
size = 1.5,
alpha = 0.75,
color = '#882255') +
geom_errorbar(aes(ymin = pc.mean - pc.sd, ymax = pc.mean + pc.sd),
size = 0.5,
width = 1) +
geom_point(
aes(y = pc.mean),
size = 3.25,
shape = 21,
color = 'black',
fill = '#EE3377'
) +
theme_minimal() +
labs(title = 'Control Thermograms',
x = 'Temperature [C]',
y = 'Fraction Unfolded')
print(therm_plot)
return(therm_plot)
}
# Controls analysis and z' output for groups
# Possible outputs:
# output = 'plot': Cowplot of controls
# output = 'df': Control dataframe
control_analysis <-
function(df,
nc = 'vehicle',
pc = 'control',
output = '',
controlDF) {
controls.df <- df %>%
filter(ncgc_id == nc | ncgc_id == pc)
#Calculate Z' from controls for each parameter
test_params <-
c('Tm_fit',
'auc')
Tm.nc.mean <-
mean(controls.df$Tm_fit[controls.df$ncgc_id == nc])
Tm.nc.sd <- sd(controls.df$Tm_fit[controls.df$ncgc_id == nc])
Tm.pc.mean <-
mean(controls.df$Tm_fit[controls.df$ncgc_id == pc])
Tm.pc.sd <- sd(controls.df$Tm_fit[controls.df$ncgc_id == pc])
Tm.z <-
1 - (((3 * Tm.pc.sd) + (3 * Tm.nc.sd)) / abs(Tm.pc.mean - Tm.nc.mean))
message('Z\' for Tm: ', signif(Tm.z))
auc.nc.mean <- mean(controls.df$auc[controls.df$ncgc_id == nc])
auc.nc.sd <- sd(controls.df$auc[controls.df$ncgc_id == nc])
auc.pc.mean <- mean(controls.df$auc[controls.df$ncgc_id == pc])
auc.pc.sd <- sd(controls.df$auc[controls.df$ncgc_id == pc])
auc.z <-
1 - (((3 * auc.pc.sd) + (3 * auc.nc.sd)) / abs(auc.pc.mean - auc.nc.mean))
message('Z\' for AUC: ', signif(auc.z))
if (output == 'plot') {
Tm.plot <-
ggplot(controls.df, aes(x = ncgc_id, y = Tm_fit, fill = ncgc_id)) +
geom_boxplot(outlier.alpha = 0, size = 0.75) +
geom_jitter(shape = 21, size = 3) +
theme_minimal() +
scale_fill_hue() +
labs(title = 'Controls | Tagg',
subtitle = paste('Z\': ', signif(Tm.z), sep = '')) +
theme(
legend.position = 'none',
axis.title.x = element_blank(),
axis.text.x = element_text(size = 12, face = 'bold'),
axis.text.y = element_text(size = 10),
axis.title.y = element_text(size = 12, face = 'bold'),
plot.title = element_text(size = 12, face = 'bold')
)
auc.plot <-
ggplot(controls.df, aes(x = ncgc_id, y = auc, fill = ncgc_id)) +
geom_boxplot(outlier.alpha = 0, size = 0.75) +
geom_jitter(shape = 21, size = 3) +
theme_minimal() +
scale_fill_hue() +
labs(title = 'Controls | AUC',
subtitle = paste('Z\': ', signif(auc.z), sep = '')) +
theme(
legend.position = 'none',
axis.title.x = element_blank(),
axis.text.x = element_text(size = 12, face = 'bold'),
axis.text.y = element_text(size = 10),
axis.title.y = element_text(size = 12, face = 'bold'),
plot.title = element_text(size = 12, face = 'bold')
)
right.grid <-
plot_grid(Tm.plot, auc.plot, ncol = 1)
control.grid <-
plot_grid(
control_thermogram(controlDF, ncTm = Tm.nc.mean, pcTm = Tm.pc.mean),
right.grid,
ncol = 2,
nrow = 1
)
ggsave('./data/controls.png', dpi = 'retina', scale = 1.5)
return(control.grid)
}
if (output == 'df') {
means <-
c(Tm.nc.mean,
auc.nc.mean)
parameters <- c('Tm_fit', 'auc')
output.df <- tibble(parameters, means)
return(output.df)
}
}
# Dose-response curve fit with LL.4 log-logistic fit
# otrace = TRUE; output from optim method is displayed. Good for diagnostic
# trace = TRUE; trace from optim displayed
# robust fitting
# robust = 'lms': doesn't handle outlier/noisy data well
dr_fit <- function(df) {
try(expr = {
drm(
resp ~ conc,
data = df,
type = 'continuous',
fct = LL.4(),
control = drmc(
errorm = FALSE,
maxIt = 10000,
noMessage = TRUE,
)
)
})
}
# Deprecated for now...
# Perform drm on each compound at each temperature
dr_analysis <-
function(df,
control = 'DMSO',
export_label = '',
plot = TRUE) {
# Construct df from the unique compound ids (less control) with empty analysis parameters
model_df <-
tibble(compound = (unique(filter(
df, ncgc_id != control
)$ncgc_id))) %>%
filter(compound != 'control')
for (i in 6:ncol(df)) {
col.nm <- colnames(df)[i]
model_df[, col.nm] <- NA
}
# Make a long df with the parameters (colnames above)
modelfit_df <- tibble(colnames(model_df)[2:ncol(model_df)])
names(modelfit_df)[1] <- 'analysis'
# Loop through each column in every row of modelfit_df and create a drm model for each and
# add statistics and readouts to a temp df that is bound to modelfit_df
for (i in 1:nrow(model_df)) {
# Create a working df with the raw data from compound[i]
temp_df <-
filter(df, df$ncgc_id == model_df$compound[(i)]) %>%
dplyr::select(-c('well', 'row', 'col'))
print(paste('Analyzing: ', model_df$compound[i]), sep = '')
# This temp df will hold the statistics that we read out from each model, and is reset every time.
# Parameters to include:
# ec50: EC50 reading of the curve fit
# pval: curve fit pvalue
# noEffect: p-value of the noEffect test of the dose-response
# hill: LL4 parameter B
# ec50: LL4 parameter A
# lowerlim: LL4 parameter C
# upperlim: LL4 parameter D
temp_modelfit_df <- modelfit_df[1] %>%
mutate(
ec50 = 0,
noEffect = 0,
hill = 0,
lowerlim = 0,
upperlim = 0,
ec50 = 0
)
# Iterate through columns
for (n in 3:ncol(temp_df)) {
#Make df for drm model by selecting concentration and appropriate column
dr_df <- temp_df %>% dplyr::select(c(2, n))
colnames(dr_df)[1] <- 'conc'
colnames(dr_df)[2] <- 'resp'
temp.model <-
drm(
resp ~ conc,
data = dr_df,
fct = LL.4(),
control = drmc(
errorm = FALSE,
maxIt = 500,
noMessage = TRUE
)
)
# Construct fitted curve for plotting
pred.fit <-
expand.grid(pr.x = exp(seq(log(min(
dr_df[1]
)), log(max(
dr_df[1]
)), length = 1000)))
# Seems necessary to make loop continue through curves that can't be fit... NEED TO STUDY
if ("convergence" %in% names(temp.model) == FALSE) {
pm <-
predict(object = temp.model,
newdata = pred.fit,
interval = 'confidence')
pred.fit$p <- pm[, 1]
pred.fit$pmin <- pm[, 2]
pred.fit$pmax <- pm[, 3]
# Plot out dose response curve if conditional met in function
if (plot == TRUE) {
dr_plot <- ggplot(dr_df, aes(x = conc, y = resp)) +
geom_line(
data = pred.fit,
aes(x = pr.x, y = p),
size = 1.5,
color = 'black'
) +
geom_point(
size = 4,
shape = 21,
fill = 'orange',
color = 'black'
) +
scale_x_log10() +
theme_cowplot() +
labs(
title = paste(
'Analysis of ',
model_df$compound[i],
' by ',
colnames(temp_df)[n],
sep = ''
),
subtitle = paste(
'EC50: ',
signif(temp.model$coefficients[4], 3),
' nM',
'\n',
'Significance of noEffect Test: ',
signif(noEffect(temp.model)[3], 3),
sep = ''
),
x = 'Concentration'
)
print(dr_plot)
png(
filename = paste(
'./data/dr_curves/',
export_label,
'_',
model_df$compound[i],
colnames(temp_df)[n],
'.png',
sep = ''
),
width = 3200,
height = 1800,
res = 300
)
print(dr_plot)
dev.off()
}
print(n)
# Extract fit parameters for the dr model
temp_modelfit_df$ec50[(n - 2)] <-
signif(temp.model$coefficients[4], 3)
temp_modelfit_df$noEffect[(n - 2)] <-
signif(noEffect(temp.model)[3], 3)
temp_modelfit_df$hill[(n - 2)] <-
signif(temp.model$coefficients[1], 3)
temp_modelfit_df$lowerlim[(n - 2)] <-
signif(temp.model$coefficients[2], 3)
temp_modelfit_df$upperlim[(n - 2)] <-
signif(temp.model$coefficients[3], 3)
}
}
modelfit_df <- modelfit_df %>% cbind(., temp_modelfit_df[2:6])
names(modelfit_df)[names(modelfit_df) == 'ec50'] <-
paste('ec50_', model_df$compound[i], sep = '')
names(modelfit_df)[names(modelfit_df) == 'noEffect'] <-
paste('noEffect_', model_df$compound[i], sep = '')
names(modelfit_df)[names(modelfit_df) == 'hill'] <-
paste('hill_', model_df$compound[i], sep = '')
names(modelfit_df)[names(modelfit_df) == 'lowerlim'] <-
paste('lowerlim_', model_df$compound[i], sep = '')
names(modelfit_df)[names(modelfit_df) == 'upperlim'] <-
paste('upperlim_', model_df$compound[i], sep = '')
}
return(modelfit_df)
}
# Extract residual sum of squares for dmso columns
# Returns df with all dmso values ready for model fit
dmso_rss <- function(df, control = 'DMSO') {
df_rss <- df %>%
dplyr::select(starts_with("t_")) %>%
pivot_longer(cols = everything())
colnames(df_rss)[1] <- 'conc'
colnames(df_rss)[2] <- 'resp'
df_rss$conc <- as.integer(gsub('t_', '', df_rss$conc))
message('Fitting DMSO thermogram...')
rss_model <- dr_fit(df_rss)
rss_dmso <- sum(residuals(rss_model) ^ 2)
message('DMSO RSS: ', signif(rss_dmso, 6))
plot(
rss_model,
type = 'all',
cex = 0.5,
main = paste('DMSO Thermogram Fit\n', 'RSS: ', signif(rss_dmso, 5), sep =
''),
sub = paste('DMSO RSS: ', signif(rss_dmso, 5), sep = ''),
xlab = 'Temperature',
ylab = 'Fraction Unfolded',
ylim = c(-0.25, 1.25)
)
return(df_rss)
}
compare_models <- function(df, dmso.rss.df, plot = FALSE) {
temp_df <- df %>% dplyr::select(-one_of(
'Ea_fit',
'Tf_fit',
'kN_fit',
'bN_fit',
'kU_fit',
'bU_fit',
'S'
)) %>%
filter(ncgc_id != 'DMSO' & ncgc_id != 'ignore')
rss_df <- temp_df %>%
dplyr::select(-starts_with('t_'))
rss_df$null.rss <- NA
rss_df$alt.rss <- NA
rss_df$rss.diff <- NA
dmso.model <- dr_fit(dmso.rss.df)
dmso.rss <- sum(residuals(dmso.model) ^ 2)
for (i in 1:nrow(temp_df)) {
cmpnd.df <- temp_df[i, ] %>%
dplyr::select(starts_with('t_')) %>%
pivot_longer(cols = everything())
colnames(cmpnd.df)[1] <- 'conc'
colnames(cmpnd.df)[2] <- 'resp'
cmpnd.df$conc <- as.integer(gsub('t_', '', cmpnd.df$conc))
# Fitting the null model
null.model <- bind_rows(dmso.rss.df, cmpnd.df)
null.drm <- dr_fit(null.model)
null.rss <- sum(residuals(null.drm) ^ 2)
rss_df$null.rss[i] <- null.rss
message(
'Null model for ',
temp_df$ncgc_id[i],
' at concentration \' ',
temp_df$conc[i],
'\': ',
signif(null.rss, 6)
)
if (plot == TRUE) {
plot(null.drm,
type = 'all',
cex = 0.5,
main = 'Null model fit')
}
# Fitting the alternate model
cmpnd.drm <- dr_fit(cmpnd.df)
cmpnd.rss <- sum(residuals(cmpnd.drm) ^ 2)
alt.rss <- sum(cmpnd.rss, dmso.rss)
rss_df$alt.rss[i] <- alt.rss
message (
'Alternate Model for ',
temp_df$ncgc_id[i],
' at concentration \' ',
temp_df$conc[i],
' \': ',
signif(alt.rss, 6)
)
rss.diff <- null.rss - alt.rss
message('RSS.0 - RSS.1: ', signif(rss.diff, 6))
rss_df$rss.diff[i] <- rss.diff
}
return(rss_df)
}
# Calculate the traditional melting parameters from the full + rss model and output df
# of the parameters for each compound
calculate_meltingparams <- function (df, control = 'vehicle') {
#Standard parameters to test:
test_params <- c('dHm_fit', 'Tm_fit', 'dG_std', 'T_onset')
#Set up to loop through entire dataframe for each of the above params
for (i in 1:length(test_params)) {
#Initialize the column name
current_param <- test_params[i]
df[, paste(current_param, '_diff', sep = '')] <- NA
#First, calculate the mean of control columns
mean_control <- mean(df[[current_param]][df$ncgc_id == control])
#Then, subtract this mean value from each well in the plate in a new column.
#Can't figure out how to mutate with a pasted column name...
for (i in 1:nrow(df)) {
df[i, paste(current_param, '_diff', sep = '')] <-
df[i, current_param] - mean_control
}
#Print out mean and stdev of vehicle for each condition
std_control <- sd(df[[current_param]][df$ncgc_id == control])
message('Vehicle mean for ',
current_param,
': ',
mean_control,
' (SD: ',
std_control,
')')
}
return(df)
}
# Print out the volcano plots for each parameter and RSS vs. p-val
plot_volcanos <- function(df, save = TRUE) {
test_params <-
c('Tm_fit.maxDiff',
'auc.maxDiff')
test_pval <-
c('Tm_fit.maxDiff',
'auc.maxDiff')
# Plot out RSS Difference(x) vs. Parameter Difference(y)
# Conditional fill: grey/alpha if not significant in either
# grey/alpha if not significant in either #DDDDDD
# teal if by parameter only #009988
# orange if by NPARC only #EE7733
# wine if by both #882255
# NEED TO CODE THIS BETTER WTF
for (i in 1:length(test_params)) {
current_param <- test_params[i]
current_pval <- test_pval[i]
plot.df <- df %>%
dplyr::select(compound,
rss.diff,
mannwhit.pval,
one_of(current_param),
one_of(current_pval))
# Assign significance testing outcomes
plot.df$sigVal <-
case_when((plot.df$mannwhit.pval < 0.05 &
plot.df[, current_pval] < 0.05) ~ 'Both',