-
Notifications
You must be signed in to change notification settings - Fork 1
/
functions.R
1385 lines (1016 loc) · 42.7 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
#
# Select a subset of the data
#
# usage example:
# 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)
# notes:
# - this was implemented for Anna Steyer's CLEM project and is only available from
# the command line
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)
}
#
# Math functions
#
sem <- function(values) {
return (sd(values,na.rm=T)/sqrt(sum(!is.na(values))))
}
sem_above <- function(values) {
m = mean(values,na.rm=T)
a = which(values > m) # ignores NA
s = sqrt(sum((values[a]-m)^2)/length(a))
sem = s/sqrt(length(a))
return(sem)
}
sem_below <- function(values) {
m = mean(values,na.rm=T)
a = which(values < m) # ignores NA
s = sqrt(sum((values[a]-m)^2)/length(a))
sem = s/sqrt(length(a))
return(sem)
}
#
# Spatial position related
#
htm_convert_wellNum_posNum_to_xy <- function(wellID, posID) {
### GET INFO FROM HTM
plate.nrow = htm@settings@visualisation$number_positions_y
plate.ncol = htm@settings@visualisation$number_positions_x
plate.nwells = plate.nrow * plate.ncol
plate.nposrow = htm@settings@visualisation$number_subpositions_y
plate.nposcol = htm@settings@visualisation$number_subpositions_x
plate.npos = plate.nposrow * plate.nposcol
#### Prepare the LUTs
### 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;
}
}
### SUBPOSITIONS
plate.image.distance = 0.4/max(plate.nposcol,plate.nposrow);
#plate.image.size.cex <<- 2.5/plate.nposcol
plate.posNumToRow = vector(length=plate.npos);
plate.posNumToCol = vector(length=plate.npos);
ip = 1;
dd = plate.image.distance ;
dc = -(plate.nposcol-1)*dd/2;
for(ic in 1:plate.nposcol) {
dr = -(plate.nposrow-1)*dd/2;
for(ir in 1:plate.nposrow) {
plate.posNumToCol[ip] = dc;
plate.posNumToRow[ip] = dr;
ip = ip + 1;
dr = dr + dd;
}
dc = dc + dd;
}
### Deal with alphanumeric well IDs
if(any(grepl("(?i)[A-Z]",wellID))) {
wellNum = vector(length=length(wellID))
for(i in 1:length(wellID)) {
ir <- which(LETTERS == substr(wellID[i],1,1))
ic <- as.numeric(substr(wellID[i],2,1000000000))
wellNum[i] = (ir - 1) * plate.ncol + ic
#print(paste(wellID[i],wellNum[i]))
}
} else {
wellNum = wellID
}
## return
posNum = posID
list(y = plate.wellNumToRow[wellNum]+plate.posNumToRow[posNum],
x = plate.wellNumToCol[wellNum]+plate.posNumToCol[posNum])
}
htm_convert_wellNum_to_xy <- function(wellNum) {
### GET INFO FROM HTM
plate.nrow = htm@settings@visualisation$number_positions_y
plate.ncol = htm@settings@visualisation$number_positions_x
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])
}
convert_wellA01_to_wellNum <- function(wellA01, nc=12) {
## Example:
# convert_wellA01_to_wellNum(c("A01","B02","C02"), nc=12)
### GET INFO FROM HTM
#plate.nrow = htm@settings@visualisation$number_positions_y
#plate.ncol = htm@settings@visualisation$number_positions_x
n = length(wellA01)
### intialise
wellNum = vector(length=n)
###
for(i in 1:n) {
ir <- which(LETTERS == substr(wellA01[i],1,1))
ic <- as.numeric(substr(wellA01[i],2,1000000000))
wellNum[i] = (ir - 1) * nc + ic
print(paste(wellA01[i],wellNum[i]))
}
## return
return(wellNum)
# list(y = plate.wellNumToRow[wellNum],
# x = plate.wellNumToCol[wellNum])
}
#
# Data in- and out-put
#
htmLoadDataFromFile <- function(htm, tablename, path) {
print( paste("reading",path,"...") )
if(grepl("\t", readLines(path, n = 1))){
# File is tab-separated (there is at least 1 tab in the first line)
.table <- read.csv(path, sep = "\t", stringsAsFactors = FALSE)
} else{
# File is comma-separated
.table <- read.csv(path, stringsAsFactors = FALSE)
}
#.table = read.table(file=path, header=T, sep=",", stringsAsFactors=F, check.names=T)
if( is.null(htm) ) {
htm <- htmMake()
}
cmd <- paste("htm@",tablename," <- .table",sep="")
print(cmd)
eval(parse(text=cmd))
return(htm)
}
htmSaveDataTable <- function(htm, tablename, path) {
print(paste("writing",path,"..."))
.table = eval(parse(text=paste("htm@",tablename,sep="")))
write.csv(.table, file=path)
}
saveTable <- function(data) {
path = gfile("Save as...", type="save")
write.csv(data, file=path)
}
htmLoadSetttings <- function(htm, path) {
print(paste("loading",path))
load(path)
if(is.null(htm)) {
print("constructed new htm object with loaded settings")
htm <- htmMake()
htm@settings <- .settings
} else {
print("replacing settings in existing htm object.")
htm@settings <- .settings
}
print(.settings)
return(htm)
}
htmSaveSetttings <- function(htm, path) {
print(paste("saving",path))
.settings = htm@settings
save(.settings,file=path)
}
htmGetColumnNumber <- function(htm,colname) {
icol = which(colnames(htm@data)==colname)
if(length(icol)) {
return(icol)
} else {
return(0)
}
}
#
# QC
#
htmAddQC <- function(htm,.colname,.min,.max) {
qc = htm@settings@qc
if(qc[1,1]=="None selected") {
htm@settings@qc <- data.frame(colname=.colname, min=.min, max=.max)
} else {
htm@settings@qc <- rbind(htm@settings@qc,data.frame(colname=.colname, min=.min, max=.max))
}
#print(paste("added image QC: colname =",.colname,"; min =",.min,"; max =",.max))
return(htm)
}
htmGetQCs <- function(htm) {
nQCs = nrow(htm@settings@qc)
QCs = vector()
for(i in 1:nQCs) {
.colname = htm@settings@qc[i,1]
.min = htm@settings@qc[i,2]
.max = htm@settings@qc[i,3]
QCs[length(QCs)+1]=paste(.colname," min=",.min," max=",.max,sep="")
}
return(QCs)
}
htmRemoveQCs <- function(htm, indices) {
htm@settings@qc <- htm@settings@qc[-indices,]
if(nrow(htm@settings@qc)==0) {
htm@settings@qc <- data.frame(colname="None selected", min=NA, max=NA)
}
#print(htm@settings@qcImages)
return(htm)
}
htmApplyQCs <- function(htm) {
print("Performing QCs:")
# get QC dataframe from htm object
data = htm@data
qc = htm@settings@qc
if(qc[1,1]=="None selected") {
print(" No QCs selected. Setting all data to valid.")
htm@data$HTM_qc <- 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_qc <- passedQC # at this point something happens to the memory of htm...
}
print("")
print("Excluding experiments (settings QC of all rows to 0):")
experiments <- sort(unique(data[[htm@settings@columns$experiment]]))
experiments_to_exclude <- htmGetVectorSettings("statistics$experiments_to_exclude")
for(experiment in experiments) {
if(experiment %in% experiments_to_exclude) {
print(paste(experiment,"setting QC to failed"))
indices_all <- which((data[[htm@settings@columns$experiment]] == experiment))
htm@data$HTM_qc[indices_all] <- 0
}
}
print(" (The column HTM_qc has been updated or generated.)")
print("")
return(htm)
}
dataframeQC <- function(data=data.frame(),qc=data.frame()) {
passedallqc = rep(1, nrow(data) )
print(paste("QC:"))
for(i in 1:nrow(qc)) {
values = data[[as.character(qc$colname[i])]]
#passedthisqc = rep(NA, nrow(htm@data) )
passedthisqc <- ( (values >= qc$min[i]) & (values <= qc$max[i]) & !(is.na(values)))
passedallqc[ !passedthisqc ] <- 0
print(paste("Measurement:", qc$colname[i]))
print(paste(" Allowed range:", qc$min[i], "..",qc$max[i], "and not NA."))
print(paste(" Total:", length(passedthisqc)))
print(paste(" Failed:", sum(!passedthisqc)))
}
print(paste(" "))
print(paste("Summary of all QCs:"))
print(paste(" Total (all QCs):", length(passedallqc)))
print(paste(" Failed (all Qcs):", sum(!passedallqc)))
return(passedallqc)
}
#
# Get and set paramters
#
htmSetListSetting <- function(htm, setting, key, value, gui = F) {
if(gui==T) {
htm <- get("htm", envir = globalenv())
}
#print(setting)
#print(key)
#print(value)
#print(paste0("htmSetListSetting(htm" , ",'" , setting, "','" , key , "','" , value , "',gui=T)"))
.list = eval(parse(text=paste("htm@settings@",setting,sep="")))
.list[[key]]=value
eval(parse(text=paste("htm@settings@",setting," <- .list",sep="")))
if(gui==T) {
assign("htm", htm, envir = globalenv())
}
return(htm)
}
htmGetListSetting <- function(htm, .setting, .key, gui = F) {
if(gui==T) {
htm <- get("htm", envir = globalenv())
}
.list = eval(parse(text=paste("htm@settings@",.setting,sep="")))
if(is.null(.list[[.key]]) || is.na(.list[[.key]])) {
return("None selected")
} else {
return(.list[[.key]])
}
}
htmGetVectorSettings <- function(.setting) {
htm <- get("htm", envir = globalenv())
.out = eval(parse(text=paste("htm@settings@",.setting,sep="")))
if( is.null(eval(parse(text=paste("htm@settings@",.setting,sep="")))) ) {
.out = c("None selected")
}
return(.out)
}
htmAddVectorSetting <- function(.setting, .entry) {
htm <- get("htm", envir = globalenv())
if( is.null(eval(parse(text=paste("htm@settings@",.setting,sep="")))) ) {
.vector = c("None selected")
eval(parse(text=paste("htm@settings@",.setting,"<- .vector",sep="")))
}
.vector = eval(parse(text=paste("htm@settings@",.setting,sep="")))
if(.vector[1]=="None selected") {
.vector <- c(.entry)
} else if (.entry %in% .vector) {
print("This was already selected.")
.vector <- .vector
} else {
.vector <- c(.vector,.entry)
}
eval(parse(text=paste("htm@settings@",.setting,"<- .vector",sep="")))
print(paste("New setting of",.setting))
print(.vector)
assign("htm", htm, envir = globalenv())
}
htmRemoveVectorSetting <- function(.setting, .index) {
htm <- get("htm", envir = globalenv())
.vector = eval(parse(text=paste("htm@settings@",.setting,sep="")))
.vector <- .vector[-.index]
if(length(.vector)==0) {
.vector=c("None selected")
}
eval(parse(text=paste("htm@settings@",.setting,"<- .vector",sep="")))
print("New settings:")
print(.vector)
assign("htm", htm, envir = globalenv())
}
#
# Data normalisation
#
htmNormalization <- function(htm) {
print("*")
print("* Data normalization")
print("*" )
print("")
# add qc column if missing
if(is.null(htm@data$HTM_qc)){
print("No QC column found; setting all measurements to valid.")
htm@data$HTM_qc <- 1
}
# get data
data <- htm@data
# remove previously computed columns
drops = names(data)[which(grepl("HTM_norm", names(data)))]
data <- data[ ,!(names(data) %in% drops)]
# get all necessary information
measurements = htmGetVectorSettings("statistics$measurements")
experiments <- sort(unique(data[[htm@settings@columns$experiment]]))
transformation <- htmGetListSetting(htm,"statistics","transformation")
gradient_correction <- htmGetListSetting(htm,"statistics","gradient_correction")
normalisation <- htmGetListSetting(htm,"statistics","normalisation")
negcontrols <- c(htmGetListSetting(htm,"statistics","negativeControl"))
# compute
for (measurement in measurements) {
cat("\nMeasurement:\n")
print(measurement)
cat("\nNegative Control:\n")
print(negcontrols)
#
# Check
#
if( ! (measurement %in% names(data)) ) {
cat(names(data))
cat("\nError: selected measurement does exist in data columns!\n")
return(htm)
}
#
# Analyze
#
manipulation <- "__"
input <- measurement
# Log2
if(transformation == "log2") {
print("")
print("Log2:")
print(paste(" 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
print(paste(" Output:", output))
print(paste(" Number of data points:",length(data[[input]])))
print(paste(" 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") {
print(paste(" 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) {
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_qc) & !is.na(data[[input]]))
# extract values
xy = htm_convert_wellNum_to_xy(data[indices_all, htm@settings@columns$wellnum])
mp = htmMedpolish(x=xy$x, y=xy$y, val=data[indices_all, input])
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")) {
print(paste(" 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) {
print(paste(" Experiment:",experiment))
indices_all <- which( (data[[htm@settings@columns$experiment]] == experiment))
indices_ok <- which( (data[[htm@settings@columns$experiment]] == experiment) & (data$HTM_qc == 1) & !is.na(data[[input]]))
xy = htm_convert_wellNum_to_xy(data[indices_ok, htm@settings@columns$wellnum])
if(gradient_correction == "median_7x7") {
mp = htmLocalMedian(x=xy$x, y=xy$y, val=data[indices_ok, input], size=7)
}
if(gradient_correction == "median_5x5") {
mp = htmLocalMedian(x=xy$x, y=xy$y, val=data[indices_ok, input], size=5)
}
if(gradient_correction == "median_3x3") {
mp = htmLocalMedian(x=xy$x, y=xy$y, val=data[indices_ok, input], size=3)
}
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)
print(paste(" 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) {
print(paste(" Experiment:",experiment))
indices_all <- which((data[[htm@settings@columns$experiment]] == experiment))
xy = htm_convert_wellNum_to_xy(data[indices_all, htm@settings@columns$wellnum])
mp = htmLocalZScore(x=xy$x, y=xy$y, val=data[indices_all, input], size=5)
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") {
print("")
print("Per batch normalisation:")
print(paste(" Method:",normalisation))
print(paste(" Input:",input))
# init columns
manipulation <- paste0(manipulation,normalisation,"__")
output = paste0("HTM_norm",manipulation,measurement)
data[[output]] = NA
print(paste(" Output:",output))
# computation
#cat("\nComputing normalisations...\n")
for(experiment in experiments) {
#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_qc == 1) & !is.na(data[[input]]))
if("all treatments" %in% negcontrols) {
indices_controls_ok <- indices_ok
} else {
indices_controls_ok <- which((data[[htm@settings@columns$experiment]] == experiment)
& !is.na(data[[input]])
& (data$HTM_qc == 1)
& (data[[htm@settings@columns$treatment]] %in% negcontrols))
}
#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 == "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)
}
#
# Compute scalar product of each data point with the average effect of the whole treatment
#
htmComputeCombinedVector <- function(htm) {
print("*")
print("* Compute combined effect")
print("*" )
print("")
data <- htm@data
# 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"))
normalisation <- htmGetListSetting(htm,"statistics","normalisation")
cos_theta_exponent <- as.numeric(htmGetListSetting(htm,"statistics","cos_theta_exponent"))
treatments <- data[[htm@settings@columns$treatment]]
print("Performing quality cntrol:")
htm <- htmApplyQCs(htm)
print(paste("Total data points",length(data$HTM_qc)))
print(paste("Valid data points",sum(data$HTM_qc)))
#
# initialisation
#
length = paste("HTM",normalisation,"length",sep="__")
data <- data[ , !(names(data) %in% length) ]
cosine = paste("HTM",normalisation,"cosine",sep="__")
data <- data[ , !(names(data) %in% cosine) ]
projection = paste("HTM",normalisation,"projection",sep="__")
data <- data[ , !(names(data) %in% projection) ]
features = names(data)[which(grepl(normalisation,names(data)))]
cat("\nFeatures:")
print(features)
data[[length]] = NA
data[[cosine]] = NA
data[[projection]] = NA
# computation
cat("\nComputing combined effect\n")
for(experiment in experiments) {
if(experiment %in% experiments_to_exclude) next
print(paste(" Experiment:",experiment))
for (treatment in unique(treatments)) {
indices_ok <- which((data[[htm@settings@columns$experiment]] == experiment) & (data$HTM_qc == 1) & (data[[htm@settings@columns$treatment]] == treatment) )
indices_all <- which((data[[htm@settings@columns$experiment]] == experiment) & (data[[htm@settings@columns$treatment]] == treatment) )
# compute normalised direction
v_avg = vector()
for (feature in features) {
v_avg <- c(v_avg, mean(data[indices_ok, feature], na.rm=T))
}
print(treatment)
names(v_avg) <- features
print(v_avg)
# compute length
data[indices_all, length] = 0
for (feature in features) { # sum square
data[indices_all, length] = data[indices_all, length] + data[indices_all, feature]^2
}
data[indices_all, length] = sqrt(data[indices_all, length])
# compute cosine
data[indices_all, cosine] = 0
for (feature in features) { # scalar product
data[indices_all, cosine] = data[indices_all, cosine] + data[indices_all, feature] * v_avg[feature]
}
v_avg_norm <- sqrt(sum(v_avg*v_avg))
data[indices_all, cosine] = data[indices_all, cosine] / (data[indices_all, length] * v_avg_norm)
# compute projection
data[indices_all, projection] = data[indices_all, length] * sign(data[indices_all, cosine]) * abs(data[indices_all, cosine])^cos_theta_exponent
#data[indices_all, projection] = abs(data[indices_all, cosine])^cos_theta_exponent
}
} # experiment loop
return(data)
}
#
# Treatment Summary
#
htmTreatmentSummary_Data <- function(htm) {
print("")
print("Treatment Summary:")
print("******************")
print("")
# get all necessary information
data <- htm@data
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")
treatments <- sort(unique(data[[htm@settings@columns$treatment]]))
colObjectCount <- htmGetListSetting(htm,"statistics","objectCount")
#ctrls <- htm@settings@ctrlsNeg
negative_ctrl <- c(htmGetListSetting(htm,"statistics","negativeControl"))
positive_ctrl <- c(htmGetListSetting(htm,"statistics","positiveControl"))
# output
print("");print("Experiments:")
print(experiments)
print("");print(paste("Number of treatments:",length(treatments)))
print("");print(paste("Negative control:",negative_ctrl))
print("");print(paste("Positive control:",positive_ctrl))
print("");print(paste("Measurement:",measurement))
print(""); print("")
if(!(measurement %in% names(data))) {
print(paste("ERROR: measurement",measurement,"does not exist in data"))
return(0)
}
if(!(colObjectCount %in% names(data))) {
print(paste("ERROR: object count",colObjectCount,"does not exist in data"))
return(0)
}
numEntries = length(treatments)
results <- data.frame(measurement=rep(measurement,numEntries),
controls=rep(negative_ctrl,numEntries),
treatment=rep(NA,numEntries),
batches = rep(NA,numEntries),
means = rep(NA,numEntries),
median__means = rep(NA,numEntries),
#z_scores = rep(NA,numEntries),
#median__z_scores = rep(NA,numEntries),
t_test__estimate=rep(NA,numEntries),
t_test__p_value=rep(NA,numEntries),
t_test__p_value_adjusted=rep(NA,numEntries),
t_test__signCode=rep(NA,numEntries),
#z_score__allBatches=rep(NA,numEntries),
#robust_z_score__allBatches=rep(NA,numEntries),
mean_number_of_objects_per_image=rep(NA,numEntries),
numObjectsOK=rep(NA,numEntries),
numImagesOK=rep(NA,numEntries),
numReplicatesOK=rep(NA,numEntries),
#numPositionsOK=rep(NA,numEntries),
#numPositions=rep(NA,numEntries),
stringsAsFactors = FALSE
)
###################################
# Compute stats
###################################
print("Computing statistics...")
ids_treatments = split(1:nrow(data), data[[htm@settings@columns$treatment]])
i=0
for(ids in ids_treatments) {
# ********************************
# T-test
# ********************************