-
Notifications
You must be signed in to change notification settings - Fork 1
/
functions.r
1471 lines (1108 loc) · 55.5 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
# To do:
#
# - Color by batch, treatment, replicate, ....
# - Plotly lasso to select images
# - Summarize multiple measurements simultaneously
#
# Generic functions
#
loadpackage <- function(pckg){
if(!(pckg %in% installed.packages())){
install.packages(pckg)
}
library(pckg, character.only=TRUE)
}
# Print a string to the R console and to the webpage
echo <- function(...){
temp <- do.call("paste0", list(...))
print(temp)
message(temp)
}
# Reads a data.frame from csv, tsv, and xlsx files. Does not read the older xls format.
# The file format can be explicitly mentioned or auto-detected.
read.HTMtable <- function(filepath, filetype = c("Auto", "csv", "tsv", "xlsx"), decimalseparator = c("Auto", ".", ",")){
# filepath : full path to file. includes the filename. In Windows this is a temporary folder where the file is named '0'
# filename : original filename
loadpackage("openxlsx")
if(filetype == "Auto" | missing(filetype)){
tryCatch({
temp <- read.delim(filepath, header = T, as.is = T, stringsAsFactors = FALSE)
temp <- read.table(filepath, sep = "\t", nrows = 10, stringsAsFactors = FALSE)
fileheader <- readLines(filepath, n = 1)
if(grepl("\t", fileheader)){
filetype <- "tsv"
} else{
filetype <- "csv"
}
},
warning = function(e){
filetype <<- "xlsx"
})
}
if(filetype == "csv"){
tryCatch(
return( read.table(filepath, header = TRUE, sep = ",", dec = ".", fill = TRUE, as.is = TRUE, stringsAsFactors = FALSE) ),
error = function(e) filetype == "invalid"
)
}
if(filetype == "tsv"){
tryCatch(
{
# Auto detect decimal separator
if(decimalseparator == "Auto" | missing(decimalseparator)){
sampledata_df <- read.table(filepath, header = TRUE, sep = "\t", nrows = 100, colClasses = "character", fill = TRUE, as.is = TRUE, stringsAsFactors = FALSE)
sampledata_char <- as.character(as.matrix(sampledata_df))
sampledata_with_dots <- grep("\\.", sampledata_char, value = TRUE)
sampledata_with_1dot <- sampledata_with_dots[!grepl("\\..*\\.", sampledata_with_dots)]
sampledata_with_commas <- grep(",", sampledata_char, value = TRUE)
sampledata_with_1comma <- sampledata_with_commas[!grepl(",.,", sampledata_with_commas)]
# Let us imagine the true decimal separator is "."
sampledata_dotseparated <- sampledata_with_1dot[!is.na(as.numeric(sampledata_with_1dot))]
n_dotseparated <- length(sampledata_dotseparated)
# Let us imagine the true decimal separator is ","
sampledata_commaseparated <- gsub(",", "\\.", sampledata_with_1comma)
sampledata_commaseparated <- sampledata_commaseparated[!is.na(as.numeric(sampledata_commaseparated))]
n_commaseparated <- length(sampledata_commaseparated)
# Decide based on the most abundant
if(n_commaseparated > n_dotseparated){
decimalseparator <- ","
} else{
decimalseparator <- "."
}
}
return( read.table(filepath, header = TRUE, sep = "\t", dec = decimalseparator, fill = TRUE, as.is = TRUE, stringsAsFactors = FALSE) )
},
error = function(e) filetype == "invalid"
)
}
if(filetype == "xlsx"){
tryCatch(
return( read.xlsx(filepath) ),
error = function(e) filetype == "invalid"
)
}
if(filetype == "invalid"){
return( NULL )
}
}
filterDataFrame <- function( df, x_col, y_col, batch_col, batch, highlightQCfailed, filterByColumn, whichValues, col_QC, subsampledata = FALSE, XAxisType = "continuous", subsampleN = 10, extremevalues = 10){
# Subset batches
if( ! is.null( batch_col ) & ! is.null( batch ) ) {
if ( batch != "All batches" ) {
df <- df[ df[[batch_col]] == batch, ]
}
}
# Subset by columns
if( !is.null( whichValues) & !is.null(filterByColumn) )
{
if( filterByColumn != "None" ) {
if( !("All" %in% whichValues) ) {
OKrows <- sapply( df[[ filterByColumn ]], function(x)
{
x %in% whichValues
})
df <- df[OKrows,]
}
}
}
# Hide rejected data points if requested
if( !is.null( highlightQCfailed) & !is.null(col_QC) )
{
if( highlightQCfailed == "Don't show" )
{
df <- df[df[[col_QC]],]
}
}
# Subsample data frame
if(subsampledata){
# Decide how to do the subsampling
switch(XAxisType,
"continuous" = {
# The X axis is treated as a continuous numerical variable (i.e. there is only 1 category with continuous values)
# This is the algorithm followed further below:
# 1. Select the M highest and M lowest *of all y values* (These are the 'extreme values')
# 2. Take all non-extreme values and show only 1 in each N (These are the 'subsampled values')
# 3. Color the extreme values as green/red and subsampled values as black
categories <- factor(rep(1, nrow(df)))
},
"categorical" = {
# The X axis is treated as a categorical variable (each X value defines a category)
# This is the algorithm followed further below:
# 1. Split the data according according to their X values
# 2. Select the M highest and M lowest values *of each X category* (These are the 'extreme values')
# 3. Take all non-extreme values from each category and show only 1 in each N (These are the 'subsampled values')
# 4. Color the extreme values as green/red and subsampled values as black
categories <- factor(df[[x_col]])
}
)
df_final <- by(df, categories, function(df_byCat){
allvalues <- data.frame(x = 1:nrow(df_byCat),
values = df_byCat[[y_col]],
stringsAsFactors = FALSE)
allvalues_numeric <- allvalues[!is.na(allvalues$values),]
allvalues_numeric <- allvalues_numeric[order(allvalues_numeric$values, decreasing = TRUE),]
# Row numbers of top and bottom M values
rows_top <- head(allvalues_numeric, n = extremevalues)[["x"]]
rows_bottom <- tail(allvalues_numeric, n = extremevalues)[["x"]]
# Row numbers of values which are not the top or bottom ones
rows_others <- setdiff(allvalues$x, c(rows_top, rows_bottom))
# Row numbers of each Nth row
rows_sampled <- rows_others[seq(from = 1, to = length(rows_others), by = subsampleN)]
# Assemble final data frame (extreme_low, extreme_high and subsampled values only)
df_final0 <- df_byCat[c(rows_top, rows_bottom, rows_sampled),]
df_final0$HTM_color <- c(rep("green3", extremevalues),
rep("red", extremevalues),
rep("black", length(rows_sampled)))
df_final0
})
df_final <- do.call(rbind, df_final)
} else{
df_final <- df
}
return(df_final)
}
################################################################
# PLOTTING #
################################################################
# Plotting UI
############################################################
# Plot-generating functions
############################################################
# Generate Plotly scatter/jitter plot
pointPlot <- function( df, x, y, plottype, col_QC, highlightQCfailed, beeswarm = FALSE, splitBy = "None", colTreatment, colBatch, colColors ){
# Initialize variables
df$lineIndex <- 1:nrow(df)
plotSymbols <- c( approved = 20, rejected = 4 )
# Assign symbol to be used at each data point
symbols <- if( highlightQCfailed == "Show with cross" ){
sapply( df[[col_QC]], function(x) ifelse( x, plotSymbols["approved"], plotSymbols["rejected"] ) )
} else{
plotSymbols["approved"]
}
# Initialize colors
if(is.null(colColors)){
plotColors <- rep("black", nrow(df))
} else{
plotColors <- df[[colColors]]
}
names(plotColors) <- plotColors
# # Decide what kind of plot to do: scatter, jitter or beeswarm;
# plottype <- if(is.numeric( df[[x]] ) & is.numeric( df[[y]] )){
# "scatter"
# } else{
# if(beeswarm){
# "beeswarm"
# } else{
# "jitter"
# }
# }
g <- ggplot(df, aes_string( paste0( "`", x,"`" ), paste0( "`", y,"`" ))) + ggtitle( colBatch ) + scale_colour_gradient2()
# Generate plot object
# SCATTER PLOT
if(plottype == "scatter"){
g <- g + geom_point(shape = symbols,
aes(text = sprintf(
"<br>Treatment: %s<br>Batch: %s<br>Line Index: %s", df[[colTreatment]], df[[colBatch]], df$lineIndex), color = plotColors)) +
scale_color_manual(values=plotColors) +
theme(legend.position="none")
}
# BEESWARM
if(plottype == "beeswarm"){
g <- g + geom_quasirandom(shape = symbols, aes(text = sprintf("<br>Treatment: %s<br>Batch: %s<br>Line Index: %s", df[[colTreatment]], df[[colBatch]], df$lineIndex), color = plotColors)) +
scale_color_manual(values=plotColors) +
theme(legend.position="none")
}
# JITTER
if(plottype == "jitter"){
jitteramount = 0.2
# Jitter non-numerical axis
if(class(df[[x]]) %in% c("integer", "numeric")){
jitterX <- 0
} else{
jitterX <- jitteramount
}
if(class(df[[y]]) %in% c("integer", "numeric")){
jitterY <- 0
} else{
jitterY <- jitteramount
}
g <- g + geom_jitter(shape = symbols, aes(text = sprintf("<br>Treatment: %s<br>Batch: %s<br>Line Index: %s", df[[colTreatment]], df[[colBatch]], df$lineIndex), color = plotColors ), position = position_jitter(w = jitterX, h = jitterY)) +
scale_color_manual(values=plotColors) +
theme(legend.position="none")
}
# Customize plot
if(splitBy != "None"){
g <- g +
facet_grid( as.formula(paste("~", splitBy)), scales = "free_x" ) +
theme( strip.text.x = element_text( angle = 90 ) )
}
# Output finished plot
ggplotly( g )
}
# Generate Plotly boxplot
boxPlot <- function(df, batch, x, y, col_QC, highlightCenter = "No", splitBy = "None", colTreatment, colBatch ){
# Make plot
g <- ggplot( df, aes_string( paste0( "`", x,"`" ), paste0( "`", y,"`" ) ) )
g <- g + geom_boxplot() + ggtitle( batch )
# Customize plot
if(highlightCenter != "No"){
g <- switch(highlightCenter,
"Mean" = g + stat_summary(fun.y = "mean", colour = "red", size = 4, geom = "point", alpha = 0.5),
"Median" = g + stat_summary(fun.y = "median", colour = "red", size = 4, geom = "point", alpha = 0.5)
)
}
if(splitBy != "None"){
g <- g +
facet_grid(as.formula(paste("~", splitBy)), scales = "free_x") +
theme(strip.text.x = element_text(angle = 90))
}
# Output finished plot
ggplotly(g)
}
# Generate Plotly heatmap
heatmapPlot <- function( df, measurement, batch, nrows, ncolumns, symbolsize=1, col_QC, highlightQCfailed, colorMin = -Inf, colorMax = +Inf, lutColors = "Blue-White-Red", colTreatment, colBatch ){
# Initialize variables
df$lineIndex <- 1:nrow(df)
plotSymbols <- c(approved = 15, rejected = 4)
print( paste("Selected lutColors:", lutColors) )
if ( is.null( lutColors ))
{
colorGrad <- c("blue", "white", "red")
}
else
{
if ( lutColors == "Blue-White-Red" )
{
colorGrad <- c("blue", "white", "red")
}
else if ( lutColors == "Red-White-Green" )
{
colorGrad <- c("red2", "white", "green4")
}
else
{
colorGrad <- c("blue", "white", "red")
}
}
print( paste0( "colorMin ", colorMin ) )
print( paste0( "colorMax ", colorMax ) )
# Column 'LUT' has numeric values which are solely used for the color lookup table
df$LUT <- sapply(df[[measurement]], function(f){
if(is.na(f)) return(f)
if(f <= colorMin) return(colorMin)
if(f >= colorMax) return(colorMax)
f
})
# Define the data to be plotted
g <- ggplot( df,
aes( heatX, heatY, color = LUT,
text = sprintf("%s: %s<br>Treatment: %s<br>Batch: %s<br>Line Index: %s", measurement, df[[measurement]], df[[colTreatment]], df[[colBatch]], df$lineIndex)
)
)
# Calculate the symbol to be used at each data point
symbols <- if( highlightQCfailed == "Show with cross")
{
sapply( df[[col_QC]], function(x) ifelse(x, plotSymbols["approved"], plotSymbols["rejected"]))
}
else
{
plotSymbols["approved"]
}
# Other plot settings
g <- g + geom_point(size=symbolsize, shape=symbols) +
scale_colour_gradientn(colors = colorGrad) +
ggtitle(batch) +
theme(panel.grid = element_blank()) +
scale_x_continuous(breaks = 1:ncolumns) +
scale_y_continuous(breaks = 1:nrows, labels = LETTERS[nrows:1]) +
theme(axis.title.x=element_blank(), axis.title.y=element_blank())
# Output finished plot
ggplotly( g )
}
# Can open multiple files at once
# filePath is an array of character strings
OpenInFiji <- function( directories, filenames, fijiBinaryPath = "C:\\Fiji.app\\ImageJ-win64.exe", x, y, z, stackName = "composite" )
{
num_images = length( directories );
import_image_sequence_reg_exp_template = "IJ.run(\"Image Sequence...\", \"open=[DIRECTORY] file=(REGEXP) sort\");";
open_image_template = "IJ.open(\"DIRECTORY/FILENAME\");";
# init
commands <- "import ij.IJ;\n"
commands <- paste0( commands, "import ij.ImagePlus;", "\n" );
commands <- paste0( commands, "import ij.gui.OvalRoi;", "\n" );
# Generate the expression opening each image
for ( i in seq(1, num_images) )
{
if( grepl("\\?", filenames[ i ] ) )
{
# directory
import_image_sequence_reg_exp <- sub( "DIRECTORY", directories[ i ], import_image_sequence_reg_exp_template, fixed = TRUE )
# filename / regexp
reg_exp = gsub( "\\", "\\\\", filenames[ i ], fixed = TRUE )
import_image_sequence_reg_exp <- sub( "REGEXP", reg_exp, import_image_sequence_reg_exp, fixed = TRUE )
commands <- paste0( commands, import_image_sequence_reg_exp, "\n" );
}
else
{
open_image = sub( "DIRECTORY", directories[ i ], open_image_template, fixed = TRUE )
open_image = sub( "FILENAME", filenames[ i ], open_image, fixed = TRUE )
commands <- paste0( commands, open_image, "\n" )
}
if ( grepl( "LabelMask", filenames[ i ], ignore.case = TRUE ) )
{
set_label_mask_lut = "IJ.run(\"glasbey inverted\", \"\");";
commands <- paste0( commands, set_label_mask_lut, "\n" )
# IJ.run("16-bit", "");
}
get_imp = paste0( "ImagePlus imp", i, " = IJ.getImage(); ");
commands <- paste0( commands, get_imp, "\n" )
}
# When opening more than 1 image: additional post-processing required
if ( num_images > 1 & num_images <= 7 )
{
# Create composite image. ImageJ supports up to 7 channels.
# merge_channels = "IJ.run(imp1, \"Merge Channels...\", \"c1=\"+imp1.getTitle()+\" c2=\"+imp2.getTitle()+\" create\");"
merge_channels = paste0("IJ.run(imp1, \"Merge Channels...\", ",
paste0(
sapply(1:num_images, function(x) paste0("\"c", x, "=\"+imp", x, ".getTitle()")), collapse = "+\" \"+"
),
"+\" create\");")
get_imp2 <- paste0( "ImagePlus imp = IJ.getImage(); ")
rename_stack <- paste0("imp.setTitle(\"", stackName, "\");")
commands <- paste0( commands, merge_channels, "\n" )
commands <- paste0( commands, get_imp2, "\n" )
commands <- paste0( commands, rename_stack, "\n" )
commands <- paste0( commands, "IJ.wait( 100 );", "\n" ) # needs time to build the composite image
}
if ( num_images > 7 )
{
# Create stack
make_stack = "IJ.run(imp1, \"Images to Stack\", \"name=Stack title=[] use\");"
commands <- paste0( commands, make_stack, "\n" )
}
#
# highlight object
#
# set slice
if ( ! is.null( z ) && z != "NA" )
{
setSlice = paste0( "IJ.getImage().setPosition( 1 ,", ceiling( z ) ,", 1);" )
commands <- paste0( commands, setSlice, "\n" );
}
# put ROI at object location
if (! is.null( x ) && ! is.null( y ) && ( x != "NA" ) && ( y != "NA" ) )
{
diameter = 50;
x <- x - 25;
y <- y - 25;
setRoi = paste0( "IJ.getImage().setRoi( new OvalRoi(", x, "," , y, ",",diameter,",",diameter,") )");
commands <- paste0( commands, setRoi, "\n" );
addAsOverlay = paste0( "IJ.run (IJ.getImage(), \"Add Selection...\", \"\")" );
commands <- paste0( commands, addAsOverlay, "\n" );
}
#
# write commands to groovy script
#
tmp_directory = paste0( getwd(), "/tmp" )
dir.create( tmp_directory, showWarnings = FALSE )
tmp_groovy_script = paste0( tmp_directory, "/openImages.groovy" );
write( commands, file = tmp_groovy_script) ;
system_cmd = paste( fijiBinaryPath, '--run', paste0( '\"', tmp_groovy_script, '\"') );
# print groovy commands for user info and debugging
print( commands )
# print command for user info and debugging
print( system_cmd )
# Evoke Fiji with the expression compiled above
system( system_cmd, wait = FALSE )
}
# Generate coordinates for heatmap
generateHeatmapCoordinates <- function(WellX, WellY, PosX, PosY, subposjitter = 0.2){
numWells <- WellX * WellY
numSubpos <- PosX * PosY
# Map well numbers to a plate layout
wellLayout <- matrix(1:numWells, WellY, WellX, byrow = TRUE, dimnames = list(LETTERS[1:WellY], 1:WellX))
# (x,y) coordinates for all well centers
WellCenters <- data.frame(wellnum = integer(), X = integer(), Y = integer())
for (i in 1:WellY){
for (j in 1:WellX){
temp <- which(wellLayout == wellLayout[i,j], arr.ind=TRUE)
WellCenters <- rbind(WellCenters,
data.frame(wellnum = wellLayout[i,j], X = temp[1,"col"], Y = -temp[1,"row"]+WellY+1)
)
}
}
# Map subposition array
posLayout <- matrix(1:numSubpos, PosY, PosX, byrow = TRUE, dimnames = list(LETTERS[1:PosY], 1:PosX))
# (x,y) coordinates for each subposition cluster.
PosCenters <- data.frame(posnum = integer(), X = numeric(), Y = numeric())
for (u in 1:PosY){
for (v in 1:PosX){
temp <- which(posLayout == posLayout[u,v], arr.ind=TRUE)
PosCenters <- rbind(PosCenters,
data.frame(posnum = posLayout[u,v], X = temp[1,"col"]-0.5-PosX/2, Y = -temp[1,"row"]+PosY/2+0.5)
)
}
}
PosCenters[, c("X", "Y")] <- PosCenters[, c("X", "Y")] * subposjitter
# (x,y) coordinates for all images in a plate
temp <- data.frame(wellnum = integer(), posnum = integer(), X = numeric(), Y = numeric())
for(w in 1:numWells){
localcenter <- do.call("rbind", replicate(numSubpos, WellCenters[w,], simplify = FALSE))
localcenter$posnum <- PosCenters$posnum
localcenter$X <- localcenter$X + PosCenters$X
localcenter$Y <- localcenter$Y + PosCenters$Y
temp <- rbind(temp, localcenter)
}
temp <- temp[, c("wellnum", "posnum", "X", "Y")]
row.names(temp) <- NULL
temp
}
# Creates a 1-batch data.frame with all additional data required for a
makeHeatmapDataFrame <- function(df, WellX, WellY, PosX, PosY, subposjitter = 0.2, batch_col, batch, col_Well, col_Pos, col_QC = "HTM_QC"){
if(batch == "All batches") return(NULL)
# Subset data frame
df <- df[df[[batch_col]] == batch,]
# Calculate coordinates for heatmap
dfCoords <- generateHeatmapCoordinates(WellX, WellY, PosX, PosY, subposjitter)
# Add heatmap coordinates
for(i in 1:nrow(df)){
w <- df[i,col_Well]
p <- df[i,col_Pos]
xy <- dfCoords[dfCoords$wellnum == w & dfCoords$posnum == p, c("X", "Y")]
df[i, "heatX"] <- xy[1,"X"]
df[i, "heatY"] <- xy[1,"Y"]
}
df
}
# Apply QC
applyQC <- function(df, dfQC){
# This an example of how the 'dfQC' data.frame needs to look like
# 'measurement' is the name of one of the columns in 'df'
# All values in 'df' are text
# dfQC <- data.frame(type = c("Numeric QC", "Numeric QC", "Text QC", "Failed experiment"), measurement = c("Count_cell_all", "Count_cell_final", "FileName_PM", "Metadata_platePath"), minimum = c("50", "20", "image1.tif", "myplate_01"), maximum = c("500", "100", "image1.tif", "myplate_01"), stringsAsFactors = FALSE)
# Make sure the data frame only contains character variables (no factors wanted!)
dfQC[] <- lapply(dfQC, as.character)
apply(df, 1, function(x){
QCoverall <- NULL
for(i in 1:nrow(dfQC)){
testvalue <- x[dfQC[i, "measurement"]]
if(is.na(testvalue)){ # Make sure "NA" is correctly interpreted
testvalue <- "NA"}
if(is.nan(testvalue)){ # Make sure "NaN" is correctly interpreted
testvalue <- "NaN"}
temp <- switch (as.character(dfQC[i,"type"]),
"Numeric QC" = if(is.na(testvalue)){
FALSE
} else{
as.numeric(testvalue) >= as.numeric(dfQC[i, "minimum"]) & as.numeric(testvalue) <= as.numeric(dfQC[i, "maximum"])
},
"Text QC" = testvalue != dfQC[i, "minimum"],
"Failed experiment" = testvalue != dfQC[i, "minimum"]
)
QCoverall <- c(QCoverall, temp)
}
all(QCoverall)
})
}
#####################################################
################ From HTM-Explorer (below) ##########
#####################################################
#
# Normalization
#
htmNormalization <- function(
data, measurements, col_Experiment, transformation, gradient_correction, normalisation,
negcontrol, col_QC, col_Well, col_Treatment, num_WellX = 0, num_WellY = 0) {
echo("*")
echo("* Data normalization")
echo("*")
echo("")
# remove previously computed columns
drops = names(data)[which(grepl("HTM_norm", names(data)))]
data <- data[ ,!(names(data) %in% drops)]
# get all necessary information
measurements <- sort(measurements)
experiments <- sort(unique(data[[col_Experiment]]))
gradient_correction <- gsub("-", "_", gradient_correction) # The dash character '-' is mishandled by the selectInput widgets of shiny
normalisation <- gsub("-", "_", normalisation) # The dash character '-' is mishandled by the selectInput widgets of shiny
# transformation <- transformation
# negcontrol <- negcontrol
# compute
for (measurement in measurements) {
echo("Measurement:")
echo(" ", measurement)
echo("Negative Control:")
echo(" ", negcontrol)
#
# Check
#
if( ! (measurement %in% names(data)) ) {
cat(names(data))
cat("\nError: selected measurement does exist in data columns!\n")
return(data)
}
#
# Analyze
#
manipulation <- "__"
input <- measurement
# Log2
if(transformation == "log2") {
echo("")
echo("Log2:")
echo(" Input: ", input)
# compute log transformation
# create new column name
manipulation <- paste0(manipulation,"log2__")
output = paste0("HTM_norm",manipulation,measurement)
idsGtZero <- which(data[[input]]>0)
idsSmEqZero <- which(data[[input]]<=0)
data[idsGtZero,output] <- log2(data[idsGtZero,input])
data[idsSmEqZero,output] <- NaN
echo(" Output: ", output)
echo(" Number of data points: ", length(data[[input]]))
echo(" NaN's due to <=0: ", length(idsSmEqZero))
# todo: this should be at a more prominent position
#print("Replacing -Inf in log scores ******************************")
#logScores = data[[output]]
#finiteLogScores = subset(logScores,is.finite(logScores))
#minimum = min(finiteLogScores)
#idsInf = which(is.infinite(logScores))
#logScores[idsInf] <- minimum
#data[[output]] <- logScores
#htmAddLog("Replacing Infinities in Log2 Score by")
#htmAddLog(minimum)
#htmAddLog("Affected Wells:")
#for(id in idsInf) {
# htmAddLog(htm@wellSummary$treatment[id])
# htmAddLog(htm@wellSummary$wellQC[id])
# htmAddLog(htm@wellSummary[id,logScoreName])
# htmAddLog("")
#}
input <- output
} # if log transformation
if(gradient_correction == "median polish") {
echo(" median polish of ", input)
# also store the background
gradient = paste0("HTM_norm",paste0(manipulation,"__medpolish_gradient__"),measurement)
manipulation <- paste0(manipulation,"__medpolish_residuals__")
output = paste0("HTM_norm",manipulation,measurement)
data[[output]] = rep(NA,nrow(data))
for(experiment in experiments) {
echo("")
echo(" Experiment: ",experiment)
indices_all <- which((data[[col_Experiment]] == experiment))
#indices_ok <- which((data[[col_Experiment]] == experiment) & (data[[col_QC]]) & !is.na(data[[input]]))
# extract values
xy = htm_convert_wellNum_to_xy(data[indices_all, col_Well], num_WellX, num_WellY)
mp = htmMedpolish(xx=xy$x, yy=xy$y, val=data[indices_all, input], num_WellX, num_WellY)
data[indices_all, output] = mp$residuals
data[indices_all, gradient] = mp$gradient
} # experiment loop
input <- output
} #medpolish
if( gradient_correction %in% c("median 7x7","median 5x5","median 3x3")) {
echo(" median filter of ", input)
gradient = paste0("HTM_norm",paste0(manipulation,"__",gradient_correction,"__gradient__"),measurement)
manipulation <- paste0(manipulation,"__",gradient_correction,"__residuals__")
output = paste0("HTM_norm",manipulation,measurement)
data[[output]] = rep(NA,nrow(data))
for(experiment in experiments) {
echo(" Experiment: ", experiment)
indices_all <- which((data[[col_Experiment]] == experiment))
indices_ok <- which((data[[col_Experiment]] == experiment) & (data[[col_QC]]) & !is.na(data[[input]]))
xy = htm_convert_wellNum_to_xy(data[indices_ok, col_Well], num_WellX, num_WellY)
if(gradient_correction == "median 7x7") {
mp = htmLocalMedian(xx=xy$x, yy=xy$y, val=data[indices_ok, input], size=7, num_WellX, num_WellY)
}
if(gradient_correction == "median 5x5") {
mp = htmLocalMedian(xx=xy$x, yy=xy$y, val=data[indices_ok, input], size=5, num_WellX, num_WellY)
}
if(gradient_correction == "median 3x3") {
mp = htmLocalMedian(xx=xy$x, yy=xy$y, val=data[indices_ok, input], size=3, num_WellX, num_WellY)
}
data[indices_ok, output] = mp$residuals
data[indices_ok, gradient] = mp$gradient
} # experiment loop
input <- output
} #median filter
if( gradient_correction %in% c("z_score 5x5")) {
# Mean = E(X)
# Variance = E(X^2)-E(X)^2
# Z-Score = (Xi - E(X)) / Sqrt(E(X^2)-E(X)^2)
echo(" 5x5 z-score filter of ", input)
# also store the background
standard_deviation = paste0("HTM_norm",paste0(manipulation,"__5x5_standard_deviation__"),measurement)
mean_value = paste0("HTM_norm",paste0(manipulation,"__5x5_mean__"),measurement)
manipulation <- paste0(manipulation,"__5x5_z_score__")
output = paste0("HTM_norm",manipulation,measurement)
data[[output]] = rep(NA,nrow(data))
data[[standard_deviation]] = rep(NA,nrow(data))
data[[mean_value]] = rep(NA,nrow(data))
for(experiment in experiments) {
echo(" Experiment: ", experiment)
indices_all <- which((data[[col_Experiment]] == experiment))
xy = htm_convert_wellNum_to_xy(data[indices_all, col_Well], num_WellX, num_WellY)
mp = htmLocalZScore(xx=xy$x, yy=xy$y, val=data[indices_all, input], size=5, num_WellX, num_WellY)
data[indices_all, mean_value] = mp$avg
data[indices_all, standard_deviation] = mp$sd
data[indices_all, output] = mp$z
} # experiment loop
input <- output
} #median filter
if(normalisation != "None selected") {
echo("")
echo("Per batch normalisation:")
echo(" Method: ", normalisation)
echo(" Input: ", input)
# init columns
manipulation <- paste0(manipulation,normalisation,"__")
output = paste0("HTM_norm",manipulation,measurement)
output <- gsub(" ", "_", output)
data[[output]] = NA
echo(" Output: ",output)
# computation
#cat("\nComputing normalisations...\n")
for(experiment in experiments) {
#print("")
#print(paste(" Experiment:",experiment))
indices_all <- which((data[[col_Experiment]] == experiment))
indices_ok <- which((data[[col_Experiment]] == experiment) & (data[[col_QC]]) & !is.na(data[[input]]))
if("All treatments" %in% negcontrol) {
indices_controls_ok <- indices_ok
} else {
indices_controls_ok <- which((data[[col_Experiment]] == experiment)
& !is.na(data[[input]])
& (data[[col_QC]])
& (data[[col_Treatment]] %in% negcontrol))
}
#print(paste(" Total", length(indices_all)))
#print(paste(" Valid", length(indices_ok)))
#print(paste(" Valid Control", length(indices_controls_ok)))
# extract control values
valuescontrol <- data[indices_controls_ok, input]
#print(valuescontrol)
nr_of_controls <- length(valuescontrol)
meancontrol <- mean(valuescontrol)
sigmacontrol <- sd(valuescontrol)
mediancontrol <- median(valuescontrol)
madcontrol <- mad(valuescontrol)
semcontrol <- sigmacontrol/sqrt(nr_of_controls)
#print(paste(" Control Mean:", meancontrol))
#print(paste(" Control SD:", sigmacontrol))
#print(paste(" Control Median:", mediancontrol))
#print(paste(" Control MAD:", madcontrol))
if(normalisation == "z_score") {
data[indices_all, output] <- ( data[indices_all, input] - meancontrol ) / sigmacontrol
}
else if(normalisation == "z_score (median subtraction)") {
data[indices_all, output] <- ( data[indices_all, input] - mediancontrol ) / sigmacontrol
}
else if(normalisation == "robust z_score") {
data[indices_all, output] <- ( data[indices_all, input] - mediancontrol ) / madcontrol
}
else if(normalisation == "subtract mean ctrl") {
data[indices_all, output] <- data[indices_all, input] - meancontrol
}
else if(normalisation == "divide by mean ctrl") {
data[indices_all, output] <- data[indices_all, input] / meancontrol
}
else if(normalisation == "subtract median ctrl") {
data[indices_all, output] <- data[indices_all, input] - mediancontrol
}
else if(normalisation == "divide by median ctrl") {
data[indices_all, output] <- data[indices_all, input] / mediancontrol
}
} # experiment loop
input <- output
} # if normalisation
} # measurement loop
return(data)
}
#
# Spatial position related
#
htm_convert_wellNum_to_xy <- function(wellNum, plate.ncol, plate.nrow) {
### GET PLATE INFO
plate.nwells = plate.nrow * plate.ncol
### intialise
xx = vector(length=length(wellNum))
yy = xx
### WELLS
plate.wellNumToRow = vector(length=plate.nwells);
plate.wellNumToCol = vector(length=plate.nwells);
iw = 1;
for(ir in 1:plate.nrow) {
for(ic in 1:plate.ncol) {
plate.wellNumToRow[iw] = ir;
plate.wellNumToCol[iw] = ic;
iw=iw+1;
}
}
## return
list(y = plate.wellNumToRow[wellNum],
x = plate.wellNumToCol[wellNum])
}
#
# Local data normalisation
#
htmMedpolish <- function(xx, yy, val, num_PosX, num_PosY) {
# averaging for multi-sub-positions?
m = matrix(nrow=num_PosX,ncol=num_PosY) # from Hugo to Tischi: aren't the xy coordinates flipped?
mi = m