-
Notifications
You must be signed in to change notification settings - Fork 1
/
deprecated_code.R
2788 lines (2085 loc) · 109 KB
/
deprecated_code.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
htmImageNormalization <- function(htm) {
print("")
print("Image normalization")
print("*******************")
print("")
# get all necessary information
measurement <- htmGetListSetting(htm,"statistics","measurement")
experiments <- sort(unique(htm@data[[htm@settings@columns$experiment]]))
experiments_to_exclude <- htmGetVectorSettings("statistics$experiments_to_exclude")
negcontrols <- c(htmGetListSetting(htm,"statistics","negativeControl"))
transformation <- htmGetListSetting(htm,"statistics","transformation")
cat("\nMeasurement:\n")
print(measurement)
cat("\nNegative Control:\n")
print(negcontrols)
# check whether we know everything
if( is.null(experiments) || measurement=="None selected") {
print("")
print(" ERROR: cannot perform analysis due to lacking information (see above).")
gmessage("Error: see R console output.")
return(htm)
}
if( is.null(htm@data$HTM_qcImages) ) {
print(" WARNING: there was no Image QC column; all images with non NA values will be set tovalid!")
htm@data$HTM_qcImages = !is.na(htm@data[[measurement]])
}
if(transformation == "log2") {
# compute log transformation
# create new column name
logScoreName = paste(measurement,"log2",sep="__")
htm@data[[logScoreName]] <- log2(htm@data[[measurement]])
# todo: this should be at a more prominent position
print("Replacing -Inf in log scores ******************************")
logScores = htm@data[[logScoreName]]
finiteLogScores = subset(logScores,is.finite(logScores))
minimum = min(finiteLogScores)
idsInf = which(is.infinite(logScores))
logScores[idsInf] <- minimum
htm@data[[logScoreName]] <- 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("")
#}
} # if log transformation
# select log2 data in case data transformation is selected
if(transformation == "log2") {
measurement = logScoreName
} else {
measurement = measurement
}
measurement_minusMeanCtrl = paste(measurement,"minusMeanCtrl",sep="__")
# initialisation
htm@data[[measurement_minusMeanCtrl]] = NA
# computation
cat("\nComputing Image Normalisations...\n")
for(experiment in experiments) {
if(experiment %in% experiments_to_exclude) next
print("")
print(paste(" Experiment:",experiment))
indices_all <- which((htm@data[[htm@settings@columns$experiment]] == experiment))
indices_ok <- which((htm@data[[htm@settings@columns$experiment]] == experiment) & (htm@data$HTM_qcImages) & !is.nan(htm@data[[measurement]]))
if("all treatments" %in% negcontrols) {
indices_controls_ok <- indices_ok
} else {
indices_controls_ok <- which((htm@data[[htm@settings@columns$experiment]] == experiment) & (htm@data$HTM_qcImages) & !is.nan(htm@data[[measurement]]) & (htm@data[[htm@settings@columns$treatment]] %in% negcontrols))
}
print(paste(" Images Total", length(indices_all)))
print(paste(" Images Valid", length(indices_ok)))
print(paste(" Images Valid Control", length(indices_controls_ok)))
# here values are extracted
valuescontrol <- htm@data[indices_controls_ok, measurement]
#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))
htm@data[indices_all, measurement_minusMeanCtrl] <- ( htm@data[indices_all, measurement] - meancontrol )
# t_test, image based
} # experiment loop
return(htm@data)
}
htmObjectNormalization <- function(htm) {
print("")
print("Object normalization")
print("********************")
print("")
data <- htm@objectdata
# get all necessary information
measurement <- htmGetListSetting(htm,"statistics","measurement")
experiments <- sort(unique(data[[htm@settings@columns$experiment]]))
experiments_to_exclude <- htmGetVectorSettings("statistics$experiments_to_exclude")
negcontrols <- c(htmGetListSetting(htm,"statistics","negativeControl"))
transformation <- htmGetListSetting(htm,"statistics","transformation")
cat("\nMeasurement:\n")
print(measurement)
cat("\nNegative Control:\n")
print(negcontrols)
# check whether we know everything
if( is.null(experiments) || measurement=="None selected") {
print("")
print(" ERROR: cannot perform analysis due to lacking information (see above).")
gmessage("Error: see R console output.")
return(htm)
}
#if( is.null(data$HTM_qcObjects) ) {
# print(" WARNING: there was no QC column; all objects with non NA values will be set to valid!")
print("Performing quality control:")
htm <- htmApplyImageQCs(htm)
print("transferring image QC to the objects")
htm <- htmGenerateImageObjectLink(htm)
data$HTM_qcObjects = unlist(lapply(htm@objectdata$HTM_imageID,function(x) htm@data$HTM_qcImages[x]))
data$HTM_qcObjects = data$HTM_qcObjects & (!is.nan(data[[measurement]]))
print(paste("Total number of objects",length(data$HTM_qcObjects)))
print(paste("Valid number of objects",sum(data$HTM_qcObjects)))
#} else {
# data$HTM_qcObjects = (data$HTM_qcObjects) & (!is.nan(data[[measurement]]))
#}
#
htmNormName = "HTM_Norm"
# remove previously computed columns
idsRemove = which(grepl(htmNormName,colnames(data)))
data[,idsRemove] <- NULL
if(transformation == "log2") {
# compute log transformation
# create new column name
logScoreName = paste(htmNormName,measurement,"log2",sep="__")
data[[logScoreName]] <- log2(data[[measurement]])
# todo: this should be at a more prominent position
print("Replacing -Inf in log scores ******************************")
logScores = data[[logScoreName]]
finiteLogScores = subset(logScores,is.finite(logScores))
minimum = min(finiteLogScores)
idsInf = which(is.infinite(logScores))
logScores[idsInf] <- minimum
data[[logScoreName]] <- 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("")
#}
} # if log transformation
# select log2 data in case data transformation is selected
if(transformation == "log2") {
measurement = logScoreName
} else {
measurement = measurement
}
measurement_minusMeanCtrl = paste(htmNormName,measurement,"minusMeanCtrl",sep="__")
# initialisation
data[[measurement_minusMeanCtrl]] = NA
# computation
cat("\nComputing normalisations...\n")
for(experiment in experiments) {
if(experiment %in% experiments_to_exclude) next
print("")
print(paste(" Experiment:",experiment))
indices_all <- which((data[[htm@settings@columns$experiment]] == experiment))
indices_ok <- which((data[[htm@settings@columns$experiment]] == experiment) & (data$HTM_qcObjects))
if("all treatments" %in% negcontrols) {
indices_controls_ok <- indices_ok
} else {
indices_controls_ok <- which((data[[htm@settings@columns$experiment]] == experiment) & (data$HTM_qcObjects) & (data[[htm@settings@columns$treatment]] %in% negcontrols))
}
print(paste(" Objects Total", length(indices_all)))
print(paste(" Objects Valid", length(indices_ok)))
print(paste(" Objects Valid Control", length(indices_controls_ok)))
# here values are extracted
valuescontrol <- data[indices_controls_ok, measurement]
#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))
data[indices_all, measurement_minusMeanCtrl] <- ( data[indices_all, measurement] - meancontrol )
# t_test, image based
} # experiment loop
return(data)
}
htmApplyImageQCs <- function(htm) {
print("Performing Image QC:")
# get image QC dataframe from htm object
data = htm@data
qc = htm@settings@qcImages
if(qc[1,1]=="None selected") {
print(" No image QCs selected. Setting all images to valid.")
htm@data$HTM_qcImages <- rep(1,nrow(htm@data)) # at this point something happens to the memory of htm...
} else {
# compute QC and put results into htm
passedQC = dataframeQC(data,qc)
# return the modified htm
htm@data$HTM_qcImages <- passedQC # at this point something happens to the memory of htm...
}
print(" (The column HTM_qcImages has been updated or generated.)")
print("")
return(htm)
}
htmGenerateImageObjectLink <- function(htm, columns=NULL) {
print("Generating columns that link image and object table.")
if (is.null(columns)) {
# columns to match images and objects
c1 = htmGetListSetting(htm,"columns","treatment")
c2 = htmGetListSetting(htm,"columns","experiment")
c3 = htmGetListSetting(htm,"columns","wellnum")
c4 = htmGetListSetting(htm,"columns","posnum")
htm@objectdata$HTM_imageobjectlink = paste(htm@objectdata[[c1]],htm@objectdata[[c2]],htm@objectdata[[c3]],htm@objectdata[[c4]],sep="--")
htm@data$HTM_imageobjectlink = paste(htm@data[[c1]],htm@data[[c2]],htm@data[[c3]],htm@data[[c4]],sep="--")
htm@objectdata$HTM_imageID = unlist(lapply(htm@objectdata$HTM_imageobjectlink, function(x) which(htm@data$HTM_imageobjectlink==x)))
}
return(htm)
}
handler_showImageJitterPlot <- function(h, ...){
print("please select a point for viewing!")
ir = identify(x = jp.x, y = jp.y, n = 1, plot = FALSE)
#print(ir)
#showImagesFromRow(ir)
showImagesFromRow2(ir)
}
htmAddImageQC <- function(htm,.colname,.min,.max) {
qc = htm@settings@qcImages
if(qc[1,1]=="None selected") {
htm@settings@qcImages <- data.frame(colname=.colname, min=.min, max=.max)
} else {
htm@settings@qcImages <- rbind(htm@settings@qcImages,data.frame(colname=.colname, min=.min, max=.max))
}
#print(paste("added image QC: colname =",.colname,"; min =",.min,"; max =",.max))
return(htm)
}
htmGetImageQCs <- function(htm) {
nImageQCs = nrow(htm@settings@qcImages)
QCs = vector()
for(i in 1:nImageQCs) {
.colname = htm@settings@qcImages[i,1]
.min = htm@settings@qcImages[i,2]
.max = htm@settings@qcImages[i,3]
QCs[length(QCs)+1]=paste(.colname," min=",.min," max=",.max,sep="")
}
return(QCs)
}
htmRemoveImageQCs <- function(htm, indices) {
htm@settings@qcImages <- htm@settings@qcImages[-indices,]
if(nrow(htm@settings@qcImages)==0) {
htm@settings@qcImages <- data.frame(colname="None selected", min=NA, max=NA)
}
#print(htm@settings@qcImages)
return(htm)
}
#
# Select a subset of the data
#
# ids <- htmSelectData(htm, treatments=unique(htm@data$Metadata_Well), measurement="HTM__z_score__projection", r=c(1,100), method="random", n=3)
# htmShowDataFromRow(htm,htm@data,ids)
htmSelectData <- function(htm, treatments, measurement, r=c(2,100), method="random", n=5, save_to_disc=FALSE) {
print("*")
print("* Data selection")
print("*" )
print("")
data <- htm@data
cat("\nMeasurement:\n")
print(measurement)
cat("\nTreatments:\n")
print(treatments)
htm <- htmApplyQCs(htm)
print(paste("Total data points",length(data$HTM_qc)))
print(paste("Valid data points",sum(data$HTM_qc)))
ids_selected = vector()
for(treatment in treatments) {
ids <- which( (data[[htm@settings@columns$treatment]] == treatment) &
(data$HTM_qc==1) &
(data[[measurement]] > r[1]) &
(data[[measurement]] < r[2]) )
if(method == "random") {
ids <- sample(ids, min(n,length(ids)))
}
ids_selected = c(ids_selected, ids)
print(paste(treatment,"selected",length(ids)))
}
if(save_to_disc) {
data_subset <- data[ids_selected,]
saveTable(data_subset)
}
return(ids_selected)
}
htmWellSummary <- function(htm) {
print("")
print("Image score -> Well score:")
print("**************************")
print("")
# get all necessary information
measurement <- htmGetListSetting(htm,"statistics","measurement")
method <- htmGetListSetting(htm,"statistics","wellSummaryMethod")
minNumValidImages <- 1 #htmGetListSetting(htm,"statistics","WellQC_Minimum_Number_Valid_Images")
minNumObjects <- htmGetListSetting(htm,"statistics","WellQC_Minimum_Number_Objects")
weighting <- htmGetListSetting(htm,"statistics","objectCount")
colObjectCount <- htmGetListSetting(htm,"statistics","objectCount")
experiments <- sort(unique(htm@data[[htm@settings@columns$experiment]]))
experiments_to_exculde <- htmGetVectorSettings("statistics$experiments_to_exclude")
# output
#print("");print("Experiments:")
#print(experiments)
print("");print("Well Summary Method:")
print(method)
print("");print("Measurement:")
print(measurement)
print("");print("Weighting with:")
print(weighting)
print("");print("Column containing the object count:")
print(colObjectCount)
print("");
print(paste("Well QC: minimum number of valid images:",minNumValidImages))
print(paste("Well QC: minimum number of objects",minNumObjects))
if(htm@settings@columns$wellnum=="") {
gmessage("Cannot proceed: you need to specify a Well Column!")
return(htm)
}
# check whether we know everything
if( is.null(experiments) ||
(measurement=="None selected") ||
(method=="None selected")
) {
print("")
print(" ERROR: cannot perform analysis due to lacking information (see above).")
gmessage("Error: see R console output.")
return(htm)
}
if( is.null(htm@data$HTM_qcImages) ) {
print(" WARNING: there is no Image QC column; all images with non NA values will be considered valid!")
}
ids_wells = split(1:nrow(htm@data), paste(htm@data[[htm@settings@columns$experiment]], htm@data[[htm@settings@columns$wellnum]]) )
# removing "bad experiments" => why should this be here?
#print(""); print("removing bad wells")
#ids_to_exclude = vector()
#for(i in 1:length(ids_wells)) {
#
# experiment = htm@data[ids_wells[[i]][1],htm@settings@columns$experiment]
#
# if( experiment %in% experiments_to_exculde ) {
# ids_to_exclude = append(ids_to_exclude,i)
# }
#
#}
#print(ids_to_exclude)
#print(length(ids_wells))
#if(length(ids_to_exclude)) {
# ids_wells = ids_wells[-ids_to_exclude]
#}
#print(length(ids_wells))
numEntries = length(ids_wells)
results <- data.frame(wellNum=rep(NA,numEntries),
numObjectsOK=rep(NA,numEntries),
wellQC=rep(NA,numEntries),
numImages=rep(NA,numEntries),
numImagesOK=rep(NA,numEntries),
objectsPerImage=rep(NA,numEntries),
experiment=rep(NA,numEntries),
treatment=rep(NA,numEntries),
stringsAsFactors = FALSE)
# init columns for the scores that are obtained by averaging the images in the well
# average
scorename <- paste("wellscore",measurement,method,sep="__")
results[[scorename]] <- rep(NA,numEntries)
# average deviation
if( method == "mean_of_images" ) {
wellscoredevmethod <- "sd"
} else if (method == "median_of_images") {
wellscoredevmethod <- "MAD"
} else if (method== "weighted_mean_of_images") {
wellscoredevmethod <- "NotSureYet"
}
print(method)
#print(wellscoredevmethod)
scoredevname <- paste("wellscore_deviation",measurement,method,wellscoredevmethod,sep="__")
#print(scoredevname)
results[[scoredevname]] <- rep(NA,numEntries)
#print(colnames(results))
# start computing the well average from the images
i = 0
print("Analyzing.....")
for(ids in ids_wells) {
if( is.null(htm@data$HTM_qcImages) ) {
idsOK = ids[which(!is.na(htm@data[ids,measurement]))]
} else {
idsOK = ids[ which( (htm@data$HTM_qcImages[ids]==1) & (!is.na(htm@data[ids,measurement])) ) ]
}
## QC
wellQC <- 1
if( length(idsOK) < minNumValidImages ) wellQC <- 0
if(colObjectCount != "None selected") {
numObjectsOK <- sum(htm@data[idsOK,colObjectCount])
if( is.na(numObjectsOK) || (numObjectsOK < minNumObjects) ) wellQC <- 0
} else {
numObjectsOK <- NA
}
i=i+1
results$experiment[i] <- htm@data[ids[1],htm@settings@columns$experiment]
results$treatment[i] <- htm@data[ids[1],htm@settings@columns$treatment]
results$wellNum[i] <- htm@data[ids[1],htm@settings@columns$wellnum]
results$numImagesOK[i] <- length(idsOK)
results$numImages[i] <- length(ids)
results$numObjectsOK[i] <- numObjectsOK
results$objectsPerImage[i] <- numObjectsOK/length(idsOK)
# print(scorename)
# print(wellscore)
if( method == "mean_of_images" ) {
wellscore <- mean(htm@data[idsOK,measurement])
wellscoredeviation <- sd(htm@data[idsOK,measurement])
} else if (method == "median_of_images") {
wellscore <- median(htm@data[idsOK,measurement])
wellscoredeviation <- mad(htm@data[idsOK,measurement])
} else if (method== "weighted_mean_of_images") {
wellscore <- sum( htm@data[idsOK,measurement]*htm@data[idsOK,weighting] ) / sum(htm@data[idsOK,weighting])
wellscoredeviation <- NA
}
results[i,scorename] <- wellscore
results[i,scoredevname] <- wellscoredeviation
if( is.na(wellscore)) wellQC <- 0
results$wellQC[i] <- wellQC
} # well loop
measurement <- scorename
# put wellscores into HTM object
htm@wellSummary <- results
print(paste(" Wells Total:",length(results$wellQC)))
print(paste(" Wells OK:",sum(results$wellQC)))
print(paste(" Images Total:",sum(results$numImages)))
print(paste(" Images OK:",sum(results$numImagesOK)))
htmAddLog("Well Normalisation:")
htmAddLog("*******************")
experiments <- unique(htm@data[[htm@settings@columns$experiment]])
#negcontrols <- htm@settings@ctrlsNeg
negcontrols <- c(htmGetListSetting(htm,"statistics","negativeControl"))
#normmethod <- htmGetListSetting(htm,"statistics","normalisationMethod")
transformation <- htmGetListSetting(htm,"statistics","transformation")
# output
htmClearLog()
htmAddLog("");htmAddLog("Experiments:")
htmAddLog(experiments)
htmAddLog("");htmAddLog("Negative controls:")
htmAddLog(negcontrols)
#htmAddLog("");htmAddLog("Well normalisation method:")
#htmAddLog(normmethod)
htmAddLog("");htmAddLog("Measurement:")
htmAddLog(measurement);
htmAddLog("");
# check whether we know everything
if( is.null(experiments) ||
(negcontrols=="None selected") ||
#(normmethod=="None selected") ||
(measurement=="None selected")
)
{
print("")
print(" ERROR: cannot perform analysis due to lacking information (see above).")
gmessage("Error: see R console output.")
print("")
return(htm)
}
# todo:
# replace below print functions with showinfo, which could be turned off
# indicate the negative controls
#htm@wellSummary$negCtrl <- rep(control,nrow(htm@wellSummary))
htm@wellSummary$negCtrl <- rep(paste(negcontrols,collapse="--"),nrow(htm@wellSummary))
if(transformation == "log2") {
print("Computing log2 transformation")
# compute log transformation
logScoreName = paste("log2",measurement,sep="__")
htm@wellSummary[[logScoreName]] <- log2(htm@wellSummary[[measurement]])
# todo: this should be at a more prominent position
logScores = htm@wellSummary[[logScoreName]]
finiteLogScores = subset(logScores,is.finite(logScores))
minimum = min(finiteLogScores)
print(paste(" Replacing -Inf in log scores by ",minimum))
idsInf = which(is.infinite(logScores))
logScores[idsInf] <- minimum
htm@wellSummary[[logScoreName]] <- 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("")
#}
measurement = logScoreName
} # if log transformation
if(htmGetListSetting(htm,"statistics","gradientCorrection") == "medpolish") {
print("Apply medpolish")
medpolish_name = paste("medpolish",measurement,sep="__")
htm@wellSummary[[medpolish_name]] = rep(NA,nrow(htm@wellSummary))
for(experiment in experiments) {
indices_all <- which((htm@wellSummary$experiment == experiment))
# extract values
htm@wellSummary[indices_all, measurement]
xy = htm_convert_wellNum_to_xy(htm@wellSummary[indices_all, "wellNum"])
print(length(xy$x))
print(htm@wellSummary[indices_all, measurement])
mp = htmMedpolish(x=xy$x, y=xy$y, val=htm@wellSummary[indices_all, measurement])
print(mp$residuals)
print(indices_all)
htm@wellSummary[indices_all, medpolish_name] = mp$residuals
} # experiment loop
measurement = medpolish_name
} #medpolish
print("")
print("Computing Normalisations...")
zScoreName = paste("zScore",measurement,sep="__")
robust_z_score_name = paste("robust_z_score",measurement,sep="__")
minusMeanCtrlName = paste("minusMeanCtrl",measurement,sep="__")
htm@wellSummary[[zScoreName]] <- rep(NA,nrow(htm@wellSummary))
htm@wellSummary[[minusMeanCtrlName]] <- rep(NA,nrow(htm@wellSummary))
htm@wellSummary[[robust_z_score_name]] <- rep(NA,nrow(htm@wellSummary))
# init documentation of control values
if(transformation == "log2") {
ctrls_mean_name = "ctrls__log2__position_mean"
ctrls_median_name = "ctrls__log2__position_median"
ctrls_sd_name = "ctrls__log2__position_sd"
ctrls_mad_name = "ctrls__log2__position_mad"
} else {
ctrls_mean_name = "ctrls__position_mean"
ctrls_median_name = "ctrls__position_median"
ctrls_sd_name = "ctrls__position_sd"
ctrls_mad_name = "ctrls__position_mad"
}
htm@wellSummary[[ctrls_mean_name]] <- rep(NA,nrow(htm@wellSummary))
htm@wellSummary[[ctrls_median_name]] <- rep(NA,nrow(htm@wellSummary))
htm@wellSummary[[ctrls_sd_name]] <- rep(NA,nrow(htm@wellSummary))
htm@wellSummary[[ctrls_mad_name]] <- rep(NA,nrow(htm@wellSummary))
for(experiment in experiments) {
print("")
#print(paste(" Experiment:",experiment))
indices_all <- (htm@wellSummary$experiment == experiment)
indices_ok <- (htm@wellSummary$experiment == experiment) & (htm@wellSummary$wellQC)
if("all treatments" %in% negcontrols) {
indices_controls_ok <- indices_ok
} else {
#indices_controls_ok <- (htm@wellSummary$experiment == experiment) & (htm@wellSummary$treatment == control) & (htm@wellSummary$wellQC)
# combine different controls:
indices_controls_ok <- (htm@wellSummary$experiment == experiment) & (htm@wellSummary$treatment %in% negcontrols) & (htm@wellSummary$wellQC)
}
#print(paste(" Wells Total", sum(indices_all)))
#print(paste(" Wells Valid", sum(indices_ok)))
#print(paste(" Wells Valid Control", sum(indices_controls_ok)))
# here values are extracted
valuescontrol <- htm@wellSummary[indices_controls_ok, measurement]
print(measurement)
if(0) {
if("all treatments" %in% negcontrols) {
print("")
} else {
print(" Valid Control Wells:")
for (id in which(indices_controls_ok==T)) {
print(paste(" WellNum:",htm@wellSummary$wellNum[id]))
print(paste(" Treatment:",htm@wellSummary$treatment[id]))
print(paste(" Value:",htm@wellSummary[[measurement]][id]))
print(paste(" Objects_OK:",htm@wellSummary$numObjectsOK[id]))
print(paste(" Images_OK:",htm@wellSummary$numImagesOK[id]))
}
}
}
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 StdD:", sigmacontrol))
print(paste(" Control Median:", mediancontrol))
print(paste(" Control MAD:", madcontrol))
htm@wellSummary[indices_all, ctrls_mean_name] <- meancontrol
htm@wellSummary[indices_all, ctrls_sd_name] <- sigmacontrol
htm@wellSummary[indices_all, ctrls_median_name] <- mediancontrol
htm@wellSummary[indices_all, ctrls_mad_name] <- madcontrol
# computed scores on a well level
htm@wellSummary[indices_all, zScoreName] <- ( htm@wellSummary[indices_all, measurement] - meancontrol ) / ( sigmacontrol )
htm@wellSummary[indices_all, robust_z_score_name] <- ( htm@wellSummary[indices_all, measurement] - mediancontrol ) / ( madcontrol )
htm@wellSummary[indices_all, minusMeanCtrlName] <- ( htm@wellSummary[indices_all, measurement] - meancontrol )
} # experiment loop
# output
print("");print("Experiments:")
print(experiments)
print("");print("Negative controls:")
print(negcontrols)
#print("");print("Well normalisation method:")
#print(normmethod)
print("");print("Measurement:")
print(measurement)
return(htm@wellSummary)
}
#
guiHandler_AverageAndNormaliseMultipleFeatures <- function(h,...){
if(is.null(htm@settings@columns$treatment)) {
gmessage("You need to first specify the treatment column [Main..Configure..Assay columns]!")
return(NULL)
}
w <- gwindow("Statistical Analysis", visible=F)
# gui_ListSetting <- function(text, setting, key, choices, container) {
htm <- get("htm", envir = globalenv())
if( htmGetListSetting(htm,"statistics","compute_cell_based_stats_TF", gui=T) == T)
{
gui_AddRemoveVectorSetting(setting="statistics$ObjectFeatureSelection",
name=" Object features to be analyzed: ",
choices = colnames(htm@objectdata),
container = w, showSelected=F)
} else {
gui_AddRemoveVectorSetting(setting="statistics$ImageFeatureSelection",
name=" Image features to be analyzed: ",
choices = colnames(htm@data),
container = w, showSelected=F)
gui_ListSettingDropdown(text = " Method to average images within one position (well): ",
setting = "statistics",
key = "wellSummaryMethod",
choices = c("weighted_mean_of_images","mean_of_images","median_of_images"),
default = "weighted_mean_of_images",
container = w)
gui_ListSettingDropdown(text = " Number of objects per image: ",
setting = "statistics",
key = "objectCount",
choices = colnames(htm@data),
default = colnames(htm@data)[1],
container = w)
gui_ListSettingTextfield(text = " Well QC: Minimum number of valid objects: ",
setting = "statistics",
key = "WellQC_Minimum_Number_Objects",
type = "numeric",
default = 100,
container = w)
htmSetListSetting(htm, "statistics","treatmentWithinReplicateSummaryMethod","mean_of_wells", gui=T)
} # image/well based stats
gui_ListSettingDropdown(text = " Negative control ",
setting = "statistics",
key = "negativeControl",
choices = c("all treatments",sort(unique(htm@data[[htm@settings@columns$treatment]]))),
default = colnames(htm@data)[1],
container = w)
gui_ListSettingDropdown(text = " Data transformation ",
setting = "statistics",
key = "transformation",
choices = c("log2","none"),
default = "log2",
container = w)
obj <- glabel(" ", container = w)
gg <- ggroup(horizontal = TRUE, container=w, expand=T)
obj <- gbutton(" Analyze", container = gg, handler = function(h,...) {
if(htmGetListSetting(htm,"statistics","compute_cell_based_stats_TF", gui=T) == T) {
featureList = htmGetVectorSettings("statistics$ObjectFeatureSelection")
} else {
featureList = htmGetVectorSettings("statistics$ImageFeatureSelection")
}
# initialisation of the treatment stats
htm <- get("htm", envir = globalenv())
htm@other$treatmentSummaryList <- NULL; htm@other$treatmentSummaryList = list()
htm@other$treatmentSummaryMerge <- NULL; htm@other$treatmentSummaryMerge = data.frame()
assign("htm", htm, envir = globalenv())
for (feature in featureList) {
# image QC
htm <- get("htm", envir = globalenv())
htm <- htmApplyImageQCs(htm)
assign("htm", htm, envir = globalenv())
print(feature)
htmSetListSetting(htm,"statistics","measurement",feature,gui=T)
# well summary and normalisation (based on per_image values)
if(!(htmGetListSetting(htm,"statistics","compute_cell_based_stats_TF", gui=T) == T)) {
htm <- get("htm", envir = globalenv())
htm@wellSummary <- htmWellSummary(htm)
assign("htm", htm, envir = globalenv())
}
# image normalisation for image based statistics
if( htmGetListSetting(htm,"statistics","compute_image_based_stats_TF", gui=T) == T ) {
htm <- get("htm", envir = globalenv())
htm@data <- htmImageNormalization(htm)
assign("htm", htm, envir = globalenv())
}
# cell normalisation for cell based statistics
if(htmGetListSetting(htm,"statistics","compute_cell_based_stats_TF", gui=T) == T ) {
htm <- get("htm", envir = globalenv())
htm@objectdata <- htmObjectNormalization(htm)
assign("htm", htm, envir = globalenv())
}
# treatment statistics: well based, image based and cell based
htm <- get("htm", envir = globalenv())
htm@treatmentSummary <- htmTreatmentSummary(htm)
assign("htm", htm, envir = globalenv())
# save treatment summary
path = gfile("Save as...", type="save", initialfilename = paste0("TreatmentSummary--",htmGetListSetting(htm,"statistics","transformation",gui=T),"--",htmGetListSetting(htm,"statistics","measurement",gui=T),".csv"))
htmSaveDataTable(htm, "treatmentSummary", path)
# store all the treatment summaries in a list
if( htmGetListSetting(htm,"statistics","compute_cell_based_stats_TF", gui=T) == T ) {
readouts = c('t_test__objects__p_value','z_score__allBatches__per_object')
} else {
readouts = c('z_score__allBatches')
}
tablename = paste0("TreatmentSummary__",feature)
htm <- get("htm", envir = globalenv())
htm@other$treatmentSummaryList[[tablename]] <- data.frame(htm@treatmentSummary) # this syntax ensures that the data really is copied and not only a pointer to htm is stored in the list
for(readout in readouts) { # add featurename to columnname
colnames(htm@other$treatmentSummaryList[[tablename]])[which(names(htm@other$treatmentSummaryList[[tablename]] ) == readout)] <- paste(readout,feature,sep="__")
}
#print(readout)
#print(colnames(htm@other$treatmentSummaryList[[tablename]]))
assign("htm", htm, envir = globalenv())
}
#if(0) {
# l <- htmImageMultiFeatureAnalysis(htm, readout)
# htm@data <- l$images
# htm@other$treatFeat <- l$treatFeat
# htm@other$MDS <- htmMDStreatFeat(htm@other$treatFeat, negCtrl=htmGetListSetting(htm,"statistics","negativeControl"))
# assign("htm", htm, envir = globalenv())
# htmHeatmap_treatFeat(htm@other$treatFeat,-3,3)
#}
# compute summary table with all features
if(length(readouts)>1) {
print("")
print("More than one readout selected. Merging into one table...")
for (readout in readouts) {
mergeTableName = paste0(readout,"__merged")
# compute summary table with all features
print("Joining results...")
htm <- get("htm", envir = globalenv())
d <- join_all(htm@other$treatmentSummaryList,"treatment")
htm@other[[mergeTableName]] <- subset(d,select=c("treatment",colnames(d)[which(grepl(paste0("^",readout),colnames(d)))]))