-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.R
1882 lines (1744 loc) · 64 KB
/
app.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
## MSI Fragments Analysis V1 - 简易版,拥有基本功能,显示不同目标基因的bp范围
## Author: Wen Jiale
## MSI Fragments Analysis V2 - 2023/12/06
## 增加了panel选择和辅助判断,UI界面美化
## MSI Fragments Analysis V3 - 2023/1/09
## 增加了自动判别功能,增加了重比对功能
### Verbatim copy from seqinr package source 3.0-7
read.abif <- function(filename, max.bytes.in.file = file.info(filename)$size,
pied.de.pilote = 1.2, verbose = FALSE){
#
# Suppress warnings when reading strings with internal nul character:
#
RTC <- function(x, ...) suppressWarnings(rawToChar(x, ...))
#
# Define some shortcuts:
#
SInt32 <- function(f, ...) readBin(f, what = "integer", signed = TRUE, endian = "big", size = 4, ...)
SInt16 <- function(f, ...) readBin(f, what = "integer", signed = TRUE, endian = "big", size = 2, ...)
SInt8 <- function(f, ...) readBin(f, what = "integer", signed = TRUE, endian = "big", size = 1, ...)
UInt32 <- function(f, ...) readBin(f, what = "integer", signed = FALSE, endian = "big", size = 4, ...)
UInt16 <- function(f, ...) readBin(f, what = "integer", signed = FALSE, endian = "big", size = 2, ...)
UInt8 <- function(f, ...) readBin(f, what = "integer", signed = FALSE, endian = "big", size = 1, ...)
f32 <- function(f, ...) readBin(f, what = "numeric", size = 4, ...)
f64 <- function(f, ...) readBin(f, what = "numeric", size = 8, ...)
#
# Load raw data in memory:
#
fc <- file(filename, open = "rb")
rawdata <- readBin(fc, what = "raw", n = pied.de.pilote*max.bytes.in.file)
if(verbose) {
print(paste("number of bytes in file", filename, "is", length(rawdata)))
}
close(fc)
#
# Make a list to store results:
#
res <- list(Header = NULL, Directory = NA, Data = NA)
#
# Header section is 128 bytes long, located at a fixed position at the
# beginning of the file. We essentially need the number of item and dataoffset
#
res$Header$abif <- RTC(rawdata[1:4])
if(res$Header$abif != "ABIF") stop("file not in ABIF format")
if(verbose) print("OK: File is in ABIF format")
res$Header$version <- SInt16(rawdata[5:6])
if(verbose) print(paste("File in ABIF version", res$Header$version/100))
res$Header$DirEntry.name <- rawdata[7:10]
if(verbose) print(paste("DirEntry name: ", RTC(res$Header$DirEntry.name)))
res$Header$DirEntry.number <- SInt32(rawdata[11:14])
if(verbose) print(paste("DirEntry number: ", res$Header$DirEntry.number))
res$Header$DirEntry.elementtype <- SInt16(rawdata[15:16])
if(verbose) print(paste("DirEntry elementtype: ", res$Header$DirEntry.elementtype))
res$Header$DirEntry.elementsize <- SInt16(rawdata[17:18])
if(verbose) print(paste("DirEntry elementsize: ", res$Header$DirEntry.elementsize))
# This one is important:
res$Header$numelements <- SInt32(rawdata[19:22])
if(verbose) print(paste("DirEntry numelements: ", res$Header$numelements))
# This one is important too:
res$Header$dataoffset <- SInt32(rawdata[27:30])
if(verbose) print(paste("DirEntry dataoffset: ", res$Header$dataoffset))
dataoffset <- res$Header$dataoffset + 1 # start position is 1 in R vectors
res$Header$datahandle <- SInt32(rawdata[31:34])
if(verbose) print(paste("DirEntry datahandle: ", res$Header$datahandle))
res$Header$unused <- SInt16(rawdata[35:128], n = 47)
# Should be ingnored and set to zero
res$Header$unused[1:length(res$Header$unused)] <- 0
if(verbose) print(paste("DirEntry unused: ", length(res$Header$unused), "2-byte integers"))
#
# The directory is located at the offset specified in the header,
# and consist of an array of directory entries.
# We scan the directory to put values in a data.frame:
#
dirdf <- data.frame(list(name = character(0)))
dirdf$name <- as.character(dirdf$name) # force to characters
for(i in seq_len(res$Header$numelements)){
deb <- (i-1)*res$Header$DirEntry.elementsize + dataoffset
direntry <- rawdata[deb:(deb + res$Header$DirEntry.elementsize)]
dirdf[i, "name"] <- RTC(direntry[1:4])
dirdf[i, "tagnumber"] <- SInt32(direntry[5:8])
dirdf[i, "elementtype"] <- SInt16(direntry[9:10])
dirdf[i, "elementsize"] <- SInt16(direntry[11:12])
dirdf[i, "numelements"] <- SInt32(direntry[13:16])
dirdf[i, "datasize"] <- SInt32(direntry[17:20])
dirdf[i, "dataoffset"] <- SInt32(direntry[21:24])
}
if(verbose){
print("Element found:")
print(dirdf$name)
}
#
# Save Directory and make a list to store data:
#
res$Directory <- dirdf
res$Data <- vector("list", nrow(dirdf))
names(res$Data) <- paste(dirdf$name, dirdf$tagnumber, sep = ".")
#
# Data extraction:
#
for(i in seq_len(res$Header$numelements)){
deb <- (i-1)*res$Header$DirEntry.elementsize + dataoffset
# Short data are stored in dataoffset directly:
if(dirdf[i, "datasize"] > 4){
debinraw <- dirdf[i, "dataoffset"] + 1
} else {
debinraw <- deb + 20
}
elementtype <- dirdf[i, "elementtype"]
numelements <- dirdf[i, "numelements"]
elementsize <- dirdf[i, "elementsize"]
data <- rawdata[debinraw:(debinraw + numelements*elementsize)]
# unsigned 8 bits integer:
if(elementtype == 1) res$Data[[i]] <- UInt8(data, n = numelements)
# char or signed 8 bits integer
if(elementtype == 2){
res$Data[[i]] <- tryCatch(RTC(data),finally=paste(rawToChar(data,multiple=TRUE),collapse=""),error=function(er){cat(paste("an error was detected with the following message:",er," but this error was fixed\n",sep=" "))})
}
# unsigned 16 bits integer:
if(elementtype == 3) res$Data[[i]] <- UInt16(data, n = numelements)
# short:
if(elementtype == 4) res$Data[[i]] <- SInt16(data, n = numelements)
# long:
if(elementtype == 5) res$Data[[i]] <- SInt32(data, n = numelements)
# float:
if(elementtype == 7) res$Data[[i]] <- f32(data, n = numelements)
# double:
if(elementtype == 8) res$Data[[i]] <- f64(data, n = numelements)
# date:
if(elementtype == 10)
res$Data[[i]] <- list(year = SInt16(data, n = 1),
month = UInt8(data[-(1:2)], n = 1), day = UInt8(data[-(1:3)], n = 1))
# time:
if(elementtype == 11)
res$Data[[i]] <- list(hour = UInt8(data, n = 1),
minute = UInt8(data[-1], n = 1), second = UInt8(data[-(1:2)], n = 1),
hsecond = UInt8(data[-(1:3)], n = 1))
# bool:
if(elementtype == 13) res$Data[[i]] <- as.logical(UInt8(data))
# pString:
if(elementtype == 18){
n <- SInt8(rawdata[debinraw])
pString <- RTC(rawdata[(debinraw+1):(debinraw+n)])
res$Data[[i]] <- pString
}
# cString:
if(elementtype == 19) res$Data[[i]] <- RTC(data[1:(length(data) - 1) ])
# user:
if(elementtype >= 1024) res$Data[[i]] <- data
# legacy:
if(elementtype %in% c(12)) {
warning("unimplemented legacy type found in file")
}
if(elementtype %in% c(6, 9, 14, 15, 16, 17, 20, 128, 256, 384)) {
warning("unsupported legacy type found in file")
}
}
return(res)
}
# Imports a .fsa file from Applied Biosystems, using the provided converter
read.fsa <- function(
file,
lowess = TRUE,
lowess.top = 200,
processed = FALSE,
meta.extra = NULL,
quiet = FALSE,
...
) {
# Parse ABIF
fsa <- read.abif(file, ...)
# Scan dimensions
channelCount <- fsa$Data$`Dye#.1`
if("SCAN.1" %in% names(fsa$Data)) { scanCount <- fsa$Data$SCAN.1
} else { scanCount <- fsa$Data$Scan.1 ### Legacy
}
if(scanCount == 0) warning("Warning: No scan stored in this file\n")
if(channelCount == 0) warning("Warning: No channel stored in this file\n")
# Extract data
dyeNames <- character(0)
dyeWavelengths <- integer(0)
dyeColors <- character(0)
# DATA indexes
if(is.na(processed)) { processed <- any(sprintf("DATA.%i", c(9:12, 205:299)) %in% names(fsa$Data))
}
if(isTRUE(processed)) { dataTracks <- c(9:12, 205:299)
} else { dataTracks <- c(1:4, 105:199)
}
channelValues <- list()
for(i in 1:channelCount) {
# Get raw DATA
values <- fsa$Data[[ sprintf("DATA.%i", dataTracks[i]) ]]
# Apply lowess to reduce time bias
if(isTRUE(lowess) && scanCount > 0) {
x <- values
x[ as.integer(fsa$Data$OfSc.1) + 1L ] <- lowess.top
x[ x > lowess.top ] <- lowess.top
values <- values - lowess(x=1:length(values), y=x)$y
}
# Update value matrix
channelValues[[i]] <- values
# Get dye name
if(sprintf("DyeN.%i", i) %in% names(fsa$Data)) dyeNames[i] <- fsa$Data[[ sprintf("DyeN.%i", i) ]]
if(dyeNames[i] == "" && sprintf("DyeS.%i", i) %in% names(fsa$Data)) dyeNames[i] <- fsa$Data[[ sprintf("DyeS.%i", i) ]]
dyeNames[i] <- gsub(" ", "", dyeNames[i])
# Get dye wavelength
if(sprintf("DyeW.%i", i) %in% names(fsa$Data)) {
dyeWavelengths[i] <- fsa$Data[[ sprintf("DyeW.%i", i) ]]
dyeColors[i] <- wav2RGB(dyeWavelengths[i])
} else {
dyeWavelengths[i] <- NA
dyeColors[i] <- NA
}
}
# Channel size consistency
channelLengths <- sapply(channelValues, length)
if(isTRUE(processed)) scanCount <- channelLengths[1]
if(any(channelLengths != scanCount)) {
stop("Data length inconsistency: ", paste(channelLengths, collapse=", "))
}
# Store channels
x <- matrix(as.double(NA), ncol=channelCount, nrow=scanCount)
for(i in 1:channelCount) x[,i] <- channelValues[[i]]
# Automatic colors
if(all(is.na(dyeColors))) {
dyeColors <- rainbow(channelCount)
warning("No dye wavelength found, using arbitrary colors")
}
# Use dye names
names(dyeWavelengths) <- dyeNames
names(dyeColors) <- dyeNames
colnames(x) <- dyeNames
# Attributes
attr(x, "lowess") <- isTRUE(lowess)
attr(x, "wavelengths") <- dyeWavelengths
attr(x, "colors") <- dyeColors
# Metadata to collect
collect <- c(
sample = "SpNm",
well = "TUBE",
user = "User",
machine = "MCHN",
run.name = "RunN",
run.date = "RUND",
run.time = "RUNT",
runModule.name = "RMdN",
runModule.version = "RMdV",
runProtocole.name = "RPrN",
runProtocole.version = "RPrV",
meta.extra
)
# Start collection
meta <- list()
meta$file <- normalizePath(file)
for(metaName in names(collect)) {
values <- fsa$Data[ grep(sprintf("^%s\\.[0-9]+$", collect[ metaName ]), names(fsa$Data)) ]
if(length(values) > 0L) {
if(all(sapply(values, is.atomic))) {
meta[[ metaName ]] <- unlist(values)
if(length(values) == 1L) names(meta[[ metaName ]]) <- NULL
} else {
meta[[ metaName ]] <- as.matrix(as.data.frame(lapply(values, unlist)))
}
}
}
# Reshape dates
if("runDate" %in% names(meta) && "runTime" %in% names(meta)) {
dates <- sprintf("%04i-%02i-%02i %02i:%02i:%02i", meta$runDate["year",], meta$runDate["month",], meta$runDate["day",], meta$runTime["hour",], meta$runTime["minute",], meta$runTime["second",])
names(dates) <- c("runStart", "runStop", "collectionStart", "collectionStop")[ 1:length(dates) ]
meta$runDate <- NULL
meta$runTime <- NULL
meta <- c(meta, dates)
}
# Injection time (not portable)
regex <- "^.+<Token>DC_Injection_Time</Token><Value>(.+?)</Value>.+$"
if("RMdX.1" %in% names(fsa$Data) && grepl(regex, fsa$Data$RMdX.1)) meta$injectionTime <- sub(regex, "\\1", fsa$Data$RMdX.1)
# Store metadata
attr(x, "metaData") <- meta
# Off scale values (if any)
attr(x, "offScale") <- as.integer(fsa$Data$OfSc.1) + 1L
# S3 class
class(x) <- "fsa"
# Print meta data
if(!quiet) {
message("FSA metadata : ", paste(sprintf("%s=\"%s\"", names(meta), sapply(meta, "[", 1L)), collapse=", "))
}
return(x)
}
# Converts a light wavelength (in nm) into an RGB color namef
# Adapted from : RL <http://codingmess.blogspot.fr/2009/05/conversion-of-wavelength-in-nanometers.html>
wav2RGB <- function(wav) {
# Initialize
SSS <- R <- G <- B <- integer(length(wav))
# Color
zone <- wav >= 380 & wav < 440
R[zone] <- - (wav[zone] - 440) / (440 - 350)
B[zone] <- 1
zone <- wav >= 440 & wav < 490
G[zone] <- (wav[zone] - 440) / (490 - 440)
B[zone] <- 1
zone <- wav >= 490 & wav < 510
G[zone] <- 1
B[zone] <- - (wav[zone] - 510) / (510 - 490)
zone <- wav >= 510 & wav < 580
R[zone] <- (wav[zone] - 510) / (580 - 510)
G[zone] <- 1
zone <- wav >= 580 & wav < 645
R[zone] <- 1
G[zone] <- - (wav[zone] - 645) / (645 - 580)
zone <- wav >= 645 & wav <= 780
R[zone] <- 1
# Intensity correction
zone <- wav >= 380 & wav < 420
SSS[zone] <- 0.3 + 0.7*(wav[zone] - 350) / (420 - 350)
zone <- wav >= 420 & wav <= 700
SSS[zone] <- 1
zone <- wav > 700 & wav <= 780
SSS[zone] <- 0.3 + 0.7*(780 - wav[zone]) / (780 - 700)
# Color name
out <- rgb(SSS*R, SSS*G, SSS*B)
return(out)
}
try_align <- function(y, trim, allPeaks, fullLadder, useLadder, rMin) {
rSquared <- 0
numLadder <- length(useLadder)
################# 方法一: 从尾到头找
## 倒序
tryCatch({
if (rSquared < rMin) {
# diff_sequence <- c(20, 20, 20, 20, 6, 14, 20, 20, 20, 20, 6, 14, 20, 20, 20, 20, 6, 14, 20, 20, 10, 10, 20, 6, 14, 20, 20, 20, 20, 6, 14, 20, 20, 20, 20)
diff_sequence <- rev(diff(useLadder))
last_value <- tail(allPeaks, 1)
## 1bp <-> 1idx
tryPeaks <- allPeaks[y[allPeaks] >= 100]
### 防止有噪音和太低的情况
try1trs <- diff(tail(tryPeaks, 2))/20
try2trs <- diff(tail(allPeaks, 2))/20
trs <- max(try1trs, try2trs)
full_sequence <- numeric(length(diff_sequence) + 1)
candidate_values <- last_value
for (i in 1:length(full_sequence)) {
if (!is.null(last_value) && is.integer(last_value) && length(last_value) > 0) {
full_sequence[i] <- last_value
} else {
######## 空集时候直接跳过找下一项
diff_sequence[i] = diff_sequence[i] + diff_sequence[i-1]
last_value <- min(full_sequence[full_sequence > 0])
}
## 更新汇率
if (i > 1) {
trs <- sum(abs(diff(full_sequence))[abs(diff(full_sequence)) < 500])/sum(head(diff_sequence,i-1))
}
## 起始峰特殊情况
if (i < numLadder-1) {
last_value_range <- c(last_value - (diff_sequence[i] + diff_sequence[i+1] * 0.5) * trs, last_value - diff_sequence[i] * 0.5 * trs)
candidate_values <- allPeaks[allPeaks >= last_value_range[1] & allPeaks <= last_value_range[2]]
last_value <- candidate_values[which.max(y[candidate_values])]
} else {
last_value_range <- c(last_value - (1.5 *diff_sequence[i]) * trs, last_value - diff_sequence[i] * 0.5 * trs)
candidate_values <- allPeaks[allPeaks >= last_value_range[1] & allPeaks <= last_value_range[2]]
if(length(candidate_values) != 0) {
last_value <- max(candidate_values[y[candidate_values] > 100])
} else { last_value <- 0 }
}
}
truePeaks <- rev(full_sequence)
# Restrict modelization on interest zone
trueSizes <- fullLadder
usePeaks <- truePeaks[trueSizes %in% useLadder]
useSizes <- trueSizes[trueSizes %in% useLadder]
# Linear transformation of indexes in bp
model <- lm(useSizes ~ usePeaks)
# Check alignment
rSquared <- summary(model)$adj.r.squared
}
}, error = function(e) {
rSquared <- 0
})
################## 方法二:设上下阈值,从原点开始抛
### 用阈值选取true peaks
tryCatch({
if (rSquared < rMin) {
truePeaks <- allPeaks[y[allPeaks] <= 5000 & y[allPeaks] >= 100]
if (length(truePeaks) > length(fullLadder)) {
# Too many peaks retained (artefacts)
if (trim == "forward") {
trueSizes <- fullLadder
truePeaks <- head(truePeaks, length(fullLadder))
} else if (trim == "backward") {
trueSizes <- fullLadder
truePeaks <- tail(truePeaks, length(fullLadder))
} else {
stop("Detected more peaks than described in full size ladder", call. = FALSE)
}
} else if (length(truePeaks) < length(fullLadder)) {
# Not enough peaks retained (premature run ending)
if (trim == "forward") {
trueSizes <- head(fullLadder, length(truePeaks))
} else if (trim == "backward") {
trueSizes <- tail(fullLadder, length(truePeaks))
} else {
}
} else {
# Fine
trueSizes <- fullLadder
}
# Restrict modelization on interest zone
usePeaks <- truePeaks[trueSizes %in% useLadder]
useSizes <- trueSizes[trueSizes %in% useLadder]
# Linear transformation of indexes in bp
model <- lm(useSizes ~ usePeaks)
# Check alignment
rSquared <- summary(model)$adj.r.squared
}
}, error = function(e) {
rSquared <- 0
})
###################### 方法三:找到起始峰,对起始峰右边的进行从大到小排序
tryCatch({
if (rSquared < rMin) {
### 用确定起始峰选取true peaks
last_above_5000 <- max(which(y[allPeaks] > 5000))
if (is.na(last_above_5000)) {
cat("No values greater than 5000 found.")
} else {
right_of_last_above_5000 <- y[allPeaks][(last_above_5000 + 1):length(y[allPeaks])]
sorted_right_values <- sort(right_of_last_above_5000, decreasing = TRUE)
selected_values <- sorted_right_values[1:numLadder]
}
selected_indices <- which(y[allPeaks] %in% selected_values)
truePeaks <- sort(allPeaks[selected_indices])
trueSizes <- fullLadder
# Restrict modelization on interest zone
usePeaks <- truePeaks[trueSizes %in% useLadder]
useSizes <- trueSizes[trueSizes %in% useLadder]
# Linear transformation of indexes in bp
model <- lm(useSizes ~ usePeaks)
# Check alignment
rSquared <- summary(model)$adj.r.squared
if (is.na(rSquared)) {
stop("Unable to compute R-squared (not enough points for a linear model ?)", call. = FALSE)
}
}
}, error = function(e) {
rSquared <- 0
})
##################### 方法四: 找到起始峰,对起始峰右边去除距离相互最近的
tryCatch({
if (rSquared < rMin) {
### 用确定起始峰选取true peaks
last_above_5000 <- max(which(y[allPeaks] > 5000))
if (is.na(last_above_5000)) {
warning("No values greater than 5000 found.")
} else {
right_of_last_above_5000 <- y[allPeaks][(last_above_5000 + 1):length(y[allPeaks])]
selected_right_values <- right_of_last_above_5000[right_of_last_above_5000 > 100]
selected_values <- sort(selected_right_values, decreasing = TRUE)
selected_indices <- which(y[allPeaks] %in% selected_values)
truePeaks <- sort(allPeaks[selected_indices])
while (length(truePeaks) > length(useLadder)) {
differences <- abs(diff(truePeaks))
min_diff_index <- which.min(differences)
# 找到最小差值是由哪两个相邻的值相减而成的
element1 <- truePeaks[min_diff_index]
element2 <- truePeaks[min_diff_index + 1]
# 比较这两个对应值的y[peaks]
if (y[element1] > y[element2]) {
truePeaks <- truePeaks[-(min_diff_index + 1)]
} else {
truePeaks <- truePeaks[-min_diff_index]
}
}
# Restrict modelization on interest zone
usePeaks <- truePeaks[trueSizes %in% useLadder]
useSizes <- trueSizes[trueSizes %in% useLadder]
}
}
}, error = function(e) {
rSquared <- 0
})
return(list(usePeaks, useSizes))
}
# Size estimation based on few markers searched in predefined ranges
align.fsa <- function(
x,
channel = "LIZ",
fullLadder = c(20, 40, 60, 80, 100, 114, 120, 140, 160, 180, 200, 214, 220, 240, 250, 260, 280, 300, 314, 320, 340, 360, 380, 400, 414, 420, 440, 460, 480, 500, 514, 520, 540, 560, 580, 600),
useLadder = c(20, 40, 60, 80, 100, 114, 120, 140, 160, 180, 200, 214, 220, 240, 250, 260, 280, 300, 314, 320, 340, 360, 380, 400, 414, 420, 440, 460, 480, 500, 514, 520, 540, 560, 580, 600),
outThreshold = 0.15,
noiseLevel = 10,
surePeaks = 5,
leakingRatios = c(-1, 10),
trim = c("forward", "backward", "none"),
maskOffScale = FALSE,
rMin = 0.999,
rescue = FALSE,
ylim = NULL,
...
) {
# Args
trim <- match.arg(trim)
if (is.null(useLadder)) useLadder <- fullLadder
# Unrecoverable error
if (!channel %in% colnames(x)) {
warning("channel \"", channel, "\" not found (available: ", paste(colnames(x), collapse = ", "), ")")
return("stdNotFound")
}
# Postpone errors
rSquared <- 0
status <- try(silent = TRUE, expr = {
# Smoothed channel (offScale masked)
y <- x[, channel]
if (isTRUE(maskOffScale)) y[attr(x, "offScale")] <- NA
y <- ksmooth(x = 1:length(y), y = y, kernel = "normal", bandwidth = 5, n.points = length(y))$y
# Local maxima (above noise level)
allPeaks <- which(head(tail(y, -1), -1) >= tail(y, -2) & head(y, -2) < head(tail(y, -1), -1) & head(tail(y, -1), -1) > noiseLevel) + 1L
# Exclude outliers comparing intensity with sure peaks ('surePeaks' last ones)
surePeaks.i <- tail(allPeaks, surePeaks)
sureIntensity <- median(y[surePeaks.i])
if (outThreshold < 1) {
threshold <- outThreshold * sureIntensity
} else {
threshold <- outThreshold
}
outlierPeaks <- allPeaks[abs(y[allPeaks] - sureIntensity) >= threshold]
truePeaks <- allPeaks[abs(y[allPeaks] - sureIntensity) < threshold]
## 第一次尝试不清洗数据
tryCatch({
align_result <- try_align(y, trim, allPeaks, fullLadder, useLadder, rMin)
usePeaks <- align_result[[1]]
useSizes <- align_result[[2]]
# Linear transformation of indexes in bp
model <- lm(useSizes ~ usePeaks)
rSquared <- summary(model)$adj.r.squared
}, error = function(e) {
rSquared <- 0
})
## 第二次尝试清洗数据
tryCatch({
if (rSquared < rMin) {
# Exclude peaks with obvious leakage of one channel into others
leaking.comp <- apply(x[allPeaks, -grep(channel, colnames(x))] < leakingRatios[1] * x[allPeaks, channel], 1, any)
leaking.high <- apply(x[allPeaks, -grep(channel, colnames(x))] > leakingRatios[2] * x[allPeaks, channel], 1, any)
## 尝试清洗comb
tryPeaks <- allPeaks[!leaking.comp]
align_result <- try_align(y, trim, tryPeaks, fullLadder, useLadder, rMin)
usePeaks <- align_result[[1]]
useSizes <- align_result[[2]]
# Linear transformation of indexes in bp
model <- lm(useSizes ~ usePeaks)
rSquared <- summary(model)$adj.r.squared
}
}, error = function(e) {
rSquared <- 0
})
tryCatch({
if (rSquared < rMin) {
## 尝试清洗high
tryPeaks <- allPeaks[!leaking.high]
align_result <- try_align(y, trim, tryPeaks, fullLadder, useLadder, rMin)
usePeaks <- align_result[[1]]
useSizes <- align_result[[2]]
# Linear transformation of indexes in bp
model <- lm(useSizes ~ usePeaks)
rSquared <- summary(model)$adj.r.squared
}
}, error = function(e) {
rSquared <- 0
})
tryCatch({
if (rSquared < rMin) {
## 尝试清洗comb和high
tryPeaks <- allPeaks[!leaking.comp & !leaking.high]
align_result <- try_align(y, trim, tryPeaks, fullLadder, useLadder, rMin)
usePeaks <- align_result[[1]]
useSizes <- align_result[[2]]
# Linear transformation of indexes in bp
model <- lm(useSizes ~ usePeaks)
rSquared <- summary(model)$adj.r.squared
}
}, error = function(e) {
rSquared <- 0
})
# Store model
attr(x, "ladderModel") <- coefficients(model)
attr(x, "ladderExact") <- usePeaks
attr(x, "ladderR2") <- rSquared
names(attr(x, "ladderExact")) <- useSizes
})
# Alignment rescue data
if(isTRUE(rescue)) {
# Replace raw intensities with smoothed ones (for rescue plot only)
object <- x
object[,channel] <- y
# Plot profile
if(is.null(ylim)) ylim <- c(min(y, sureIntensity-threshold, na.rm=TRUE), max(y, sureIntensity+threshold, na.rm=TRUE))
plot(object, units=ifelse(is(status, "try-error"), "index", "bp"), ladder=!is(status, "try-error"), channels=channel, chanColors="#000000", ylim=ylim, nticks=10, all.bp=FALSE, ...)
# Highlight 'sure peaks'
if(is(status, "try-error")) { xcor <- surePeaks.i
} else { xcor <- attr(object, "ladderModel")[2] * surePeaks.i + attr(object, "ladderModel")[1]
}
points(x=xcor, y=y[surePeaks.i])
# All detected peaks and their status
if(is(status, "try-error")) { xcor <- allPeaks
} else { xcor <- attr(object, "ladderModel")[2] * allPeaks + attr(object, "ladderModel")[1]
}
col <- rep("#888888", length(allPeaks))
col[ allPeaks %in% outlierPeaks ] <- "#BB3333"
col[ allPeaks %in% leakingPeaks ] <- "#FFCC00"
col[ allPeaks %in% truePeaks ] <- "#33BB33"
if(length(xcor) > 0L) mtext(side=3, at=xcor, text="|", col=col)
# Intensity filter
xlim <- par()$usr[1:2]
segments(x0=xlim[1], x1=xlim[2], y0=sureIntensity, y1=sureIntensity, col="#33BB33")
rect(xleft=xlim[1], xright=xlim[2], ybottom=sureIntensity-threshold, ytop=sureIntensity+threshold, col="#33BB3333", border=NA)
rect(xleft=xlim[1], xright=xlim[2], ybottom=par("usr")[3], ytop=noiseLevel, col="#BB333333", border=NA)
# Legend
legend(x="topright", bg="#FFFFFF",
pch = c(1, NA, NA, NA, 124, 124, 124, 124, NA, NA, NA),
col = c("#000000", "#33BB33", NA, NA, "#BB3333", "#FFCC00", "#888888", "#33BB33", NA, "#000000", NA),
lty = c(NA, "solid", NA, NA, NA, NA, NA, NA, NA, "dotted", NA),
fill = c(NA, NA, "#33BB3333", "#BB333333", NA, NA, NA, NA, NA, NA, NA),
border = c(NA, NA, "#000000", "#000000", NA, NA, NA, NA, NA, NA, NA),
legend = c(
sprintf("'Sure' ladder peaks (%i last)", surePeaks),
"Ladder intensity (from 'sure' peaks)",
ifelse(
outThreshold < 1L,
sprintf("Tolerance (+/- %g%%)", signif(outThreshold*100L, 3)),
sprintf("Tolerance (+/- %g)", signif(outThreshold, 3))
),
sprintf("Noise (< %g)", signif(noiseLevel, 3)),
"Excluded : out of tolerance",
"Excluded : channel leakage",
"Excluded : trimmed",
"Retained",
sprintf("Matching to ladder sizes : %s", trim),
"Retained for alignment model",
sprintf("R-squared = %g (%s)", round(rSquared, 6), ifelse(rSquared > rMin, "OK", "MISALIGNED"))
)
)
}
# Call postponed errors
# if(is(status, "try-error")) {
# stop(conditionMessage(attr(status, "condition")), call.=FALSE)
# }
if (any(is.na(usePeaks))) {
mapping_info = c(attr(x, "metaData")$sample,0)
} else {
mapping_info = c(attr(x, "metaData")$sample,round(rSquared, 6))
}
return(list(x, mapping_info))
}
# Plot method for "fsa" S3 class
plot.fsa <- function(
x,
units = NA,
channels = NA,
chanColors = NA,
ladder = TRUE,
offScaleCol = "#FF0000",
offScalePch = "+",
offScaleCex = 0.4,
bg = "white",
fg = "black",
title = "",
title.adj = 0,
title.line = NA,
xlab = NA,
ylab = "Intensity",
xlim = NA,
ylim = NA,
xaxt = "s",
yaxt = "s",
bty = "o",
xaxp = NA,
nticks = 5L,
all.bp = TRUE,
peaks.alpha = 48L,
peaks.srt = 30,
peaks.adj = c(0, 0),
peaks.cex = 1.3,
peaks.font = 2,
legend.x = "topleft",
outfile = "channel_data.txt",
...
) {
# Defaults
if(identical(channels, NA)) channels <- colnames(x)
if(identical(chanColors, NA)) chanColors <- attr(x, "colors")
if(identical(units, NA)) {
if(is.null(attr(x, "ladderModel"))) { units <- "index"
} else { units <- "bp"
}
}
if(identical(xlab, NA)) xlab <- units
# Checks
if(length(channels) == 0) stop("No channel selected for plotting")
# 'channels' must be a character vector
if(is.numeric(channels)) channels <- colnames(x)[ channels ]
# Missing channel(s)
missing <- setdiff(channels, colnames(x))
if(length(missing) > 0) stop("channel(s) ", paste(missing, collapse=", "), " not found (available: ", paste(colnames(x), collapse=", "), ")")
# 'chanColors' must be a named character vector
if(is.null(names(chanColors))) {
# Unamed, supposed to be parallel with channels
if(length(channels) != length(chanColors)) stop("'chanColors' must be named, or have the same length as 'channels'")
names(chanColors) <- channels
} else {
# Already named, check if all are described
if(any(! channels %in% names(chanColors))) stop("Some 'channels' elements can't be found in 'chanColors' names")
}
# Empty plot
if(nrow(x) == 0 && (identical(xlim, NA) || identical(ylim, NA))) stop("Cannot plot an empty object without 'xlim' and 'ylim'")
# X scale
units <- match.arg(units, choices=c("index", "bp"))
if(units == "index") {
if(nrow(x) > 0) { xcor <- 1:nrow(x)
} else { xcor <- integer(0)
}
if(identical(xlim, NA)) xlim <- c(1, nrow(x))
if(identical(xaxp, NA)) xaxp <- NULL
} else if(units == "bp") {
if(is.null(attr(x, "ladderModel"))) stop("Can't plot an unaligned object in 'bp' units")
if(identical(xlim, NA)) xlim <- attr(x, "ladderModel")[2] * c(1, nrow(x)) + attr(x, "ladderModel")[1]
if(identical(xaxp, NA)) xaxp <- c((xlim[1] %/% nticks)*nticks, (xlim[2] %/% nticks)*nticks, diff(xlim %/% nticks))
if(nrow(x) > 0) { xcor <- attr(x, "ladderModel")[2] * 1:nrow(x) + attr(x, "ladderModel")[1]
} else { xcor <- integer(0)
}
}
# ylim
if(identical(ylim, NA)) {
# Values to consider
tmp <- as.vector(x[ xcor >= xlim[1] & xcor <= xlim[2] , channels ])
tmp <- tmp[ !is.na(tmp) ]
# Max in any
if(length(tmp) > 0) { ylim <- c(0, max(tmp))
} else { ylim <- c(-1, 1)
}
}
# Graphical parameters
savePar <- par(bg=bg, fg=fg, col=fg, col.axis=fg, col.lab=fg, col.main=fg, col.sub=fg)
on.exit(par(savePar))
# Mask off-scale values
offScaleValues <- x[ attr(x, "offScale") , , drop=FALSE ]
x[ attr(x, "offScale") ,] <- NA
# Background
plot(
x = NA, y = NA,
xlim = xlim, ylim = ylim,
xlab = xlab,
ylab = ylab,
xaxt = xaxt,
yaxt = yaxt,
bty = bty,
xaxp = xaxp,
...
)
# Peaks
peaks <- attr(x, "peaks")
# print(peaks)
if(!is.null(peaks)) {
# Ignore invisible peaks
peaks <- peaks[ !is.na(peaks$color) ,]
# Transparent version of peak colors
peaks$background <- sprintf(
"#%s",
apply(
rbind(
col2rgb(peaks$color),
peaks.alpha
),
2,
function(x) {
paste(sprintf("%02x", x), collapse="")
}
)
)
# Full height rectangles
rect(
xleft = peaks$size.min,
xright = peaks$size.max,
ybottom = -1e6,
ytop = 1e6,
col = peaks$background,
border = NA
)
if(all(c("N0", "N1", "N2") %in% colnames(peaks))) {
# Allele rectangles
rect(
xleft = peaks$size.min,
xright = peaks$size.max,
ybottom = c(peaks$N0, peaks$N0) * peaks$height / peaks$normalized,
ytop = c(peaks$N1, peaks$N2) * peaks$height / peaks$normalized,
col = peaks$background,
border = NA
)
}
# Names
text(
x = (peaks$size.min + peaks$size.max) / 2,
y = par("usr")[4] + diff(par("usr")[3:4]) / 50,
labels = rownames(peaks),
srt = peaks.srt,
adj = peaks.adj,
cex = peaks.cex,
font = peaks.font,
xpd = NA,
col = peaks$color
)
# Genotyping N1-based
if("present" %in% colnames(peaks)) {
text(
x = (peaks$size.min + peaks$size.max) / 2,
y = par("usr")[4],
adj = c(0.5, 1),
col = chanColors[ peaks$channel ],
labels = ifelse(peaks$present, "+", "-"),
font = 2
)
}
}
# Plot channels
for(h in channels) {
points(
x = xcor,
y = x[,h],
col = chanColors[h],
type = "l"
)
# 输出每个channel的bp坐标信息和y坐标轴
cat("Channel:", h, "\n")
cat("BP Coordinate\tY Coordinate\n")
for (i in 1:length(xcor)) {
if (!is.na(x[i, h]) && x[i, h] > 0 && xcor[i] > 0) {
cat(fsafile, "\t" ,h, "\t", xcor[i], "\t", x[i, h], "\n", file = outfile, append = TRUE)
}
}
}
scatter_plots <- list()
for (h in channels) {
scatter_plot <- plot_ly(
x = xcor,
y = x[, h],
type = "scatter",
mode = "lines",
line = list(color = chanColors[h]),
name = h
)
scatter_plots <- c(scatter_plots, list(scatter_plot))
}
# Create layout
layout <- list(
xaxis = list(range = input$x_range),
yaxis = list(range = input$y_range),
dragmode = "zoom",
title = title,
showlegend = TRUE
# Add other layout parameters as needed
)
# Combine scatter plots and layout into a plotly object
plotly_obj <- plot_ly(scatter_plots) %>% layout(layout)
# Print or save the plotly object as needed
print(plotly_obj)
# # Plot bp axis
# if(units == "bp" && isTRUE(all.bp)) axis(side=1, at=xlim[1]:xlim[2], labels=FALSE)
# Off scale points
if(length(attr(x, "offScale")) > 0) {
# Coordinates
xoff <- xcor[ attr(x, "offScale") ]
yoff <- offScaleValues
if(length(xoff) > 0) {
for(h in channels) {
# Color
if(is.na(offScaleCol)) { koff <- chanColors[h]
} else { koff <- offScaleCol
}
# Points
points(x=xoff, y=yoff[,h], col=koff, type="p", pch=offScalePch, cex=offScaleCex)
}
}
}
# Exact ladder
if(isTRUE(ladder)) {
if(!is.null(attr(x, "ladderExact"))) {
# Add ladder sizes
at <- switch(units,
"index" = attr(x, "ladderExact"),
"bp" = attr(x, "ladderModel")[2] * attr(x, "ladderExact") + attr(x, "ladderModel")[1]
)
segments(x0=at, y0=par("usr")[4], x1=at, y1=par("usr")[3]-diff(par("usr")[3:4])/8, lty="dotted", xpd=NA)
mtext(side=1, at=at, text=names(attr(x, "ladderExact")), line=2)
} else warning("Can't add ladder without alignment ('ladderExact' attribute)")
}
# Legend
inset <- c(par("din")[2]/1000, par("din")[1]/1000)
legend(legend.x, inset=inset, legend=colnames(x[, channels, drop=FALSE]), col=chanColors[channels], lty="solid", bg="#FFFFFF")