-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathHTvFunctions.R
2322 lines (1733 loc) · 74.3 KB
/
HTvFunctions.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
## %######################################################%##
# #
#### functions used by the ####
#### different scripts of the pipeline ####
# #
## %######################################################%##
# Many of the functions were not written specifically for the pipeline.
# We also use this script to check and install the required packages
packages <- c(
"parallel", "stringi", "data.table", "matrixStats",
"Biostrings", "ape", "igraph", "seqinr", "RColorBrewer"
)
missing <- setdiff(packages, rownames(installed.packages()))
# if the installation does not work, change the repository
# or install the packages in interactive mode
# The repository cannot be selected if this script is
# executed via Rscript
repository = "https://cran.us.r-project.org"
if(length(setdiff(missing,"Biostrings")) >0) {
install.packages(
pkgs = setdiff(missing,"Biostrings"),
repos = repository
)
}
# the Biostrings package is installed differently
if ("Biostrings" %in% missing) {
if (!requireNamespace("BiocManager", quietly = TRUE)) {
install.packages("BiocManager", repos = repository)
}
BiocManager::install("Biostrings")
}
stillMissing <- setdiff(packages, rownames(installed.packages()))
if(length(stillMissing) > 0) {
stop(paste(
"Package(s)",
paste(stillMissing),
"could not be installed. Consider installing it/them manually.")
)
}
# we load the packages we need for the functions below
l = lapply(setdiff(packages, c("igraph","seqinr","RColorBrewer")), require, character.only = TRUE)
options("stringsAsFactors" = F)
options("scipen" = 20)
# Some "general purpose" functions ---------------------------------------------------------
rescale <- function(x, range) {
# rescales a numeric vector so that its range (min and max)
# corresponds to the range argument (a 2-number vector)
ampl <- max(range) - min(range)
amplx <- max(x, na.rm = T) - min(x, na.rm = T)
xb <- x * ampl / amplx
xb - min(xb, na.rm = T) + min(range)
}
mids <- function(v) {
# returns the midpoints between any two successive elements of v (a numeric vector)
i <- 2:length(v)
(v[i - 1L] + v[i]) / 2L
}
lastChars <- function(string, n) {
# convenience function to extract the last n characters of words
stri_sub(string, nchar(string) - n + 1L, length = n)
}
Split <- function(x, f, drop = FALSE, sep = ".", recursive = F,...) {
# splits a vector/table recursively by each factor of "f" if f is a list
# and if "recursive" is TRUE
ls <- split(x, f, drop = drop, sep = sep, ...)
if(recursive & is.list(f)) {
for(i in 2:length(f)) {
fields = splitToColumns(names(ls), sep)
names(ls) <- fields[,ncol(fields)]
ls = split(
x = ls,
f= data.frame(fields[,1:(ncol(fields)-1L)]),
drop = drop,
sep = sep,
...)
}
}
ls
}
reList <- function(list, len = NA) {
# rearranges a list whose names are integers so that the names of
# elements of the list are placed at equivalent indices of a new list.
# this can be used to optimise the speed of access to the list elements
indices <- as.integer(names(list))
if (any(is.na(indices))) {
return(list)
stop("some names are not convertible to integers")
}
m <- max(indices)
if (!is.na(len) & len >= m) {
m <- as.integer(len)
}
temp <- vector(mode = "list", m)
temp[indices] <- list
temp
}
toInteger <- function(string,
sorted = F,
unique = T) {
# turns a string vector into integers
if (is.numeric(string)) {
return(string)
} else {
if (unique) {
u <- unique(string)
} else {
u <- string
}
if (sorted) {
u <- sort(u)
}
return(chmatch(string, u))
}
}
splitEqual <- function(x, n, ...) {
# splits an object (x, a vector or a table) into n classes of equal sizes, returns a list
l <- length(x)
if (is.data.frame(x)) {
l <- nrow(x)
}
if (n == 1L) {
f <- rep(1L, l)
} else {
f <- cut(1:l, n)
}
split(x, f, ...)
}
occurrences <- function(table) {
# returns the occurence of each element of a vector or table (e.g. 1 if it's
# the first time it appears, 2 if the 2nd time, etc). If vect is a table,
# returns the occurence of each row
dt <- data.table(table)
dt[, pos_ := 1:.N]
counts <- dt[, .(occ = 1:.N, pos_), by = setdiff(colnames(dt), "pos_")]
res <- integer(nrow(dt))
res[counts$pos_] <- counts$occ
res
}
writeT <- function(data, path, ...) {
# convenience function to write a data.table to disk with commonly used settings
fwrite(
data,
path,
quote = F,
row.names = F,
na = "NA",
sep = "\t",
...
)
}
splitToColumns <- function(vect,
split,
columns,
empty = "",
mode = "character") {
# split a character vector and returns a matrix. Characters are split upon each
# occurence of the split argument (a character of length one). empty defines
# what the empty cell should be, and mode is the mode of the returned matrix.
# This basically does what stri_split_fixed() does, but may sometime be more
# convenient or faster
vect <- as.character(vect)
nc <- stri_length(split)
out <- NULL
if (!missing(columns)) {
cols <- as.integer(columns)
cols <- cols[cols >= 1]
out <- matrix(empty, length(vect), length(cols))
} else {
cols <- 1:1000
}
col <- 1
repeat {
temp <- vect
pos <- as.vector(regexpr(split, vect, fixed = T)) - 1
f <- pos >= 0
temp[f] <- stri_sub(vect[f], 0, pos[f])
if (!missing(columns)) {
if (col %in% cols) {
out[, match(col, cols)] <- temp
}
} else {
out <- cbind(out, temp)
}
col <- col + 1
if (col > max(cols) | !any(f)) {
break
}
vect[f] <- stri_sub(vect[f], pos[f] + nc + 1, stri_length(vect[f]))
vect[!f] <- empty
}
if (ncol(out) == 1) {
out <- as.vector(out)
}
storage.mode(out) <- mode
out
}
clusterize <- function(vect, limit, group = "n") {
# takes a numeric vector and assigns elements to groups based
# on the maximum distance between them. Returns the groups as integers
dt <- data.table(g = group, v = vect)
dt$n <- 1:nrow(dt)
dt <- dt[order(g, v), ]
vect <- dt$v
group <- dt$g
pos <- 2:length(vect)
w <- c(
1,
which(vect[pos] - vect[pos - 1] > limit |
group[pos] != group[pos - 1]) + 1,
length(vect) + 1
)
pos <- 2:length(w)
groupSize <- w[pos] - w[pos - 1]
group <- rep(1:length(groupSize), groupSize)
group[order(dt$n)]
}
intersection <- function(start,
end,
start2,
end2,
range = F,
negative = T,
olv = 1L) {
# returns the length (or range, if range is TRUE) of intersections for pairs of
# ranges defined by their start and end coordinates (numeric vectors, typically
# integers). "negative" allows for negative intersection lengths (when ranges
# do no intersect). If FALSE, intersection lengths cannot be < 0. If the end of
# a range is the same of the start of the other range, the overlap is considered
# to be olv (a number)
minEnd <- pmin(pmax(start, end), pmax(start2, end2))
maxStart <- pmax(pmin(start, end), pmin(start2, end2))
if (range) {
r <- cbind(maxStart, minEnd)
# when ranges do not intersect, the range of the intersection is NA
r[maxStart > minEnd, ] <- NA
return(r)
}
inter <- minEnd - maxStart + olv
if (!negative) {
inter[inter < 0] <- 0L
}
inter
}
# Functions related to genetic/genomic ranges (sequence_id, start, end) or positions ---------------------------------------------------
regionSets <- function(regions) {
# gives a number ("set" identifier) to all regions that are included in the
# same genomic region. "regions" is a 3-column data frame with sequence id,
# start and end positions, ordered by sequence name, start coordinate, and -end
pb <- txtProgressBar(
char = "*",
width = 100,
style = 3
)
nrows <- nrow(regions)
rows <- 2:nrows
newSeq <- c(FALSE, regions[rows, 1] != regions[rows - 1, 1], T)
ends <- c(regions[, 3], 0)
set <- rep(NA, nrows)
end <- ends[1]
n <- 1
for (i in 2:(nrows + 1)) {
if (ends[i] > end | newSeq[i]) {
set[n:(i - 1)] <- n
n <- i
end <- ends[i]
setTxtProgressBar(pb, i / nrows)
}
}
set
}
assignToRegion <- function(bed, pos, olv = T) {
# assigns positions (like SNPs) to genome regions defined in a data frame in
# bed-style format (sequenceID, start, end) and pos is a data frame specifying
# sequenceID and position. If a position is in the area of overlap between 2
# regions, it will be assigned to the second one
bed <- as.data.table(bed)
pos <- as.data.table(pos)
setnames(bed, 1:3, c("sequenceID", "start", "end"))
setnames(pos, 1:2, c("sequenceID", "pos"))
# we will identify regions by their rows in the original bed
bed[, id := 1:.N]
bed <- bed[sequenceID %in% pos$sequenceID, ]
# we convert coordinates into global coordinates to call .bincode once
# This requires estimating the length of sequences, which is the max coordinate per sequenceID
seqLengths <- rbind(bed[, .(sequenceID, pos = end)], pos)[, max(pos) + 1L,
by =
sequenceID
]
# we conver the coordinates for the bed and pos tables combined.
starts <- globalCoords(
bed$sequenceID,
bed$start,
seqLengths$V1,
seqLengths$sequenceID
)
pos <- globalCoords(
pos$sequenceID,
pos$pos,
seqLengths$V1,
seqLengths$sequenceID
)
# creates a data table with start and ends in the same "boundary" column.
# "+1" gives a bit or headroom (probably not needed).
# These will be the intervals for binning. We use "id" to keep track of
# the rows (regions id) of the original bed
dt <- data.table(
boundary = c(starts, starts + bed[, end - start + 1L]),
id=rep(bed$id,2)
)
setorder(dt, boundary)
# "region" will be the region (id) covering an interval (only for the start of this interval).
dt[, c("row", "region") := .(1:.N, as.integer(NA))]
# The idea is that when a region ends, the interval should get the region that main contain the one that ended or be NA (if between 2 regions)
rows <- dt$row[-1]
# first rows regions that do not overlap with others (whose ids appear successively in the table)
short <- dt[, which(id[rows - 1L] == id[rows])]
# all the rows of these regions (first and last)
shorts <- c(short, short + 1L)
if (length(shorts) < nrow(dt)) {
# if there are overlapping regions
# for each of these overlapping regions, we create a vector that represent all the rows of dt that are covered by that region
if (length(shorts) == 0) {
rows <- dt[, .(row = row[1L]:(row[.N] - 1L), size = row[.N] - row[1L]), by = id]
} else {
rows <- dt[-shorts, .(row = row[1L]:(row[.N] - 1L), size = row[.N] - row[1L]), by = id]
}
# puts the longest regions on top
setorder(rows, -size)
# so we can add a region id for each row in dt.
dt[rows$row, region := rows$id]
# If there are duplicates in rows$row, ids of shorter regions will overwrite longer ones. This takes advantage from the fact that r operates in vector order
}
# we now copy the ids for short regions.
dt[short, region := id]
dt[.bincode(pos, boundary, F, T), region]
}
globalCoords <- function(sequences, pos, seqLengths, seqNames) {
# converts sequence/contig positions into unique genome positions assuming
# contiguous sequences whose lengths and name are provided in order
names(seqLengths) <- NULL
seqStart <- cumsum(as.numeric(c(1, seqLengths[-length(seqLengths)])))
if (!is.numeric(seqNames)) {
return(pos + seqStart[chmatch(sequences, seqNames)] - 1L)
} else {
return(pos + seqStart[match(sequences, seqNames)] - 1L)
}
}
genomeCov <- function(bed,
minCov = 1L,
seqLength = NULL,
seqNames = NULL,
combine = F,
successive = T) {
# computes sequencing depth of a genome by aligned reads, given alignment
# starts and ends of reads in a data table in bed-like format. Outputs
# successive interval for a given depth. Ignores intervals covered by less than
# minCov reads. seqLength specify the sequence length in case one wants
# to record intervals with 0 depth (required for last intervals of contigs that
# may have 0 detph). "combine" combines successive intervals covered by at
# least 1 read (i.e. regions that were sequenced)
# remembers column names of the bed
nams <- names(bed)[1:3]
setnames(bed, 1:3, c("sequenceID", "start", "end"))
if (minCov == 0L &
!is.null(seqLength) &
!is.null(seqNames)) {
# if one wants to record intervals with zero depth, we apply a trick where we add one artificial
# read totally covering each contig. This adds 1X coverage to all positions, but afterwards we substract this.
bed <- rbind(bed, data.table(
sequenceID = seqNames,
start = 1L,
end = seqLength
))
}
# "melts" the bed to obtain 2 rows per read: alignment start and alignment end + an index (n) of 1 for starts and -1 for ends.
#We also converts sequenceID names to integers to save memory. We then add 1 to end positions, as this will facilitate merging intervals
dt <- bed[, data.table(
seqID = rep(toInteger(sequenceID, unique = F), 2),
pos = c(start, end + 1L),
n = rep(c(1L, -1L), each = .N)
)]
# orders the table by sequenceID and position (regardless of start and end)
setorder(dt, seqID, pos)
# this is the workhorse function to compute coverage at each position since reads starts add 1 to the coverage and ends remove 1
dt[, cov := cumsum(n)]
# reads starting or ending at the same position creates duplicate positions.
# We only retain the last row among each set of duplicates as this is the one with accurate depth
dt <- dt[!duplicated(data.table(seqID, pos), fromLast = T)]
# to combine regions with at least 1X depth, we convert all depth > 1 into 1
if (combine) {
dt[cov > 1L, cov := 1L]
}
# we combine successive rows in the same sequenceID ifthey have identical depth
# (may happen if a read ends just before another read starts).
# This effectively combines region with ≥ 1X if combine == T
if (successive) {
dt <- dt[c(T, diff(seqID) != 0L | diff(cov) != 0L)]
}
# we convert the table back to interval format
nr <- 2:nrow(dt) - 1L
res <- dt[, data.table(
seqID = seqID[nr],
start = pos[nr],
end = pos[nr + 1L] - 1L,
cov = cov[nr]
)]
if (minCov == 0L) {
# if we want intervals with 0 depth
if (!is.null(seqLength) &
!is.null(seqNames)) {
res[, cov := cov - 1L]
} else {
nr <- 2:nrow(res)
res <- res[c(seqID[nr - 1L] == seqID[nr] | cov[nr] == 0L, T)]
}
}
res <- res[cov >= minCov]
res[, seqID := bed[seqID, sequenceID]]
setnames(res, 1:3, nams)
setnames(bed, 1:3, nams)
res
}
combineRegions <- function(bed, distance = 0L) {
# combines regions (a 3-column data table with sequence name, start and end
# position) that are distant by a certain 'distance'. By default it will
# aggregate contiguous or overlapping regions, but distance could be > 0
# (regions separated by distance pb or less) or negative (requires a certain
# amount of overlap)
bed <- as.data.table(bed)
setnames(bed, c("sequenceID", "start", "end"))
bed[end < start, c("start", "end") := .(end, start)]
bed[, end := end + distance]
res <- genomeCov(bed, combine = T)
res[, end := end - distance]
res[, -4, with = F]
}
# Functions related to DNA sequences and alignments -------------------------------------------
compl <- function(bases) {
# complements DNA/RNA bases in a character string
chartr(
"acgtmrwsykvhdbACGTMRWSYKVHDB",
"tgcakywsrmbdhvTGCAKYWSRMBDHV",
bases
)
}
revCom <- function(seqs) {
# reverse complements DNA sequences. Ambiguities are not treated
com <- compl(seqs)
seqs[] <- stri_reverse(com)
seqs
}
patternLeadingGap <- function(x) {
# determines the length of pattern leading gaps of pairwise alignments generated by biostrings
stopifnot(is(x, "PairwiseAlignments"), type(x) == "global")
start(subject(x)) - 1L
}
subjectLeadingGap <- function(x) {
# determines the length of subject leading gaps of pairwise alignments generated by biostrings
stopifnot(is(x, "PairwiseAlignments"), type(x) == "global")
start(pattern(x)) - 1L
}
alignWithEndGaps <- function(seq1, seq2, ...) {
# pairwise aligns sequences (DNAStringSets) with Biostring while preserving the
# end gaps, adding "-" when necessary (Biostrings does not preserve end gaps by
# default). Returns a data.table with two columns (character vectors) : aligned
# pattern and aligned subject
aln <- pairwiseAlignment(seq1, seq2, ...)
aln <- data.table(
pattern = as.character(pattern(aln)),
subject = as.character(subject(aln)),
pgap = patternLeadingGap(aln),
sgap = subjectLeadingGap(aln)
)
f <- aln$sgap > 0
missing <- stri_sub(seq1[f], 1, aln$sgap[f])
aln[f, subject := stri_join(gsub("[A-Z,a-z]", "-", missing), subject)]
aln[f, pattern := stri_join(missing, pattern)]
f <- aln$pgap > 0
missing <- stri_sub(seq2[f], 1, aln$pgap[f])
aln[f, pattern := stri_join(gsub("[A-Z,a-z]", "-", missing), pattern)]
aln[f, subject := stri_join(missing, subject)]
subjectTrailingGap <- nchar(seq1) - nchar(gsub("-", "", aln$pattern))
patternTrailingGap <- nchar(seq2) - nchar(gsub("-", "", aln$subject))
f <- subjectTrailingGap > 0
missing <- stri_sub(seq1[f], nchar(seq1[f]) - subjectTrailingGap[f] +
1, nchar(seq1[f]))
aln[f, subject := stri_join(subject, gsub("[A-Z,a-z]", "-", missing))]
aln[f, pattern := stri_join(pattern, missing)]
f <- patternTrailingGap > 0
missing <- stri_sub(seq2[f], nchar(seq2[f]) - patternTrailingGap[f] +
1, nchar(seq2[f]))
aln[f, pattern := stri_join(pattern, gsub("[A-Z,a-z]", "-", missing))]
aln[f, subject := stri_join(subject, missing)]
return(aln[, .(pattern, subject)])
}
splitAlignment <- function(aln, coords, fillGaps = F) {
# splits a pairwise sequence alignment data table returned by
# alignWithEndGaps() into nucleotides, and generates coordinates of each
# nucleotide according to "coords", which is a data.table with sequence names,
# starts and ends of aligned regions for each sequence. deleted nucleotides are
# not given coordinates, except if fillGaps is TRUE
setnames(coords, c("seq1", "seq2", "start", "end", "start2", "end2"))
nc <- nchar(aln$pattern)
nuc <- data.table(
base1 = unlist(strsplit(stri_flatten(aln$pattern), "")),
base2 = unlist(strsplit(stri_flatten(aln$subject), "")),
seq1 = rep(coords$seq1, nc),
seq2 = rep(coords$seq2, nc)
)
nuc$pos1 <- 0L
nuc$pos2 <- 0L
nuc[base1 != "-", pos1 := unlist(Map(":", coords$start, coords$end))]
nuc[base2 != "-", pos2 := unlist(Map(":", coords$start2, coords$end2))]
nuc$aln <- rep(1:nrow(coords), nc)
if (fillGaps) {
n <- 2:nrow(nuc)
newAln <- nuc[, c(T, aln[n] != aln[n - 1L], T)]
fillG <- function(pos) {
inGap <- pos == 0L
startGap <- which(inGap[n] & (!inGap[n - 1L] | newAln[n])) + 1L
endGap <- which(inGap[n - 1L] & (!inGap[n] | newAln[n]))
if (tail(inGap, 1)) {
endGap <- c(endGap, max(n))
}
previousPos <- pos[startGap - 1L]
if (startGap[1] == 1L) {
previouPos <- c(0L, previousPos)
}
nextPos <- pos[endGap + 1L]
if (is.na(tail(nextPos, 1))) {
nextPos[length(nextPos)] <- 0L
}
toTake <- ifelse((previousPos < nextPos &
!newAln[startGap]) | newAln[endGap + 1L],
previousPos,
nextPos
)
pos[inGap] <- rep(toTake, endGap - startGap + 1L)
pos
}
nuc[, c("pos1", "pos2") := .(fillG(pos1), fillG(pos2))]
}
nuc
}
splitStringInParts <- function(string, size) {
# splits a character string into a character vector
# whose word length is defined by "size" (an integer)
pat <- paste0(".{1,", size, "}")
res <- stri_extract_all_regex(string, pat)
names(res) <- names(string)
res
}
aaToCDS <- function(aas, cds, collapse = T) {
# generates a codon alignment based on a protein alignment and the
# corresponding cds, both being character vectors. Returns a character vector
# is collapse is TRUE. If collapse is FALSE, keeps codon separate and returns
# a list of vector of codons. This function does NOT check whether the proteins
# actually correspond to the cds according to a genetic code
if (any(stri_length(gsub("-", "", aas, fixed = T)) != stri_length(cds) /
3)) {
stop("CDS length must be exactly 3 times protein length")
}
codons <- splitStringInParts(cds, 3)
aas <- strsplit(aas, "", fixed = T)
fillCodons <- function(aas, codons) {
res <- character(length(aas))
deleted <- aas == "-"
res[!deleted] <- codons
res[deleted] <- "---"
res
}
res <- Map(fillCodons, aas, codons)
if (collapse) {
res <- sapply(res, stri_flatten)
}
res
}
subSeq <- function(string, start, end, reverse = T) {
# builds upon Biostrings' subseq() to automatically reverse complement the
# sequences (by default) if end coordinates are lower than starts. string is an
# XStringSet, and start and end are integer vectors. Works like substring()
f <- start > end
temp <- end
end[f] <- start[f]
start[f] <- temp[f]
subs <- subseq(string, start, end)
if (reverse & any(f)) {
subs[f] <- reverseComplement(subs[f])
}
subs
}
seqinrAlignment <- function(seqs, names = NULL) {
# generates a seqinr alignment object from a character vector
if (is.null(names)) {
if (!is.null(names(seqs))) {
names <- names(seqs)
} else {
names <- paste(rep("seq", length(seqs)), 1:length(seqs), sep = "_")
}
}
if (var(nchar(seqs)) > 0) {
stop("sequence lengths differ")
}
aln <- list(
nb = length(seqs),
nam = names,
seq = as.character(seqs),
com = NA
)
class(aln) <- "alignment"
aln
}
# Functions related to pairs of elements -------------------------------------------------
clusterFromPairs <- function(V1,
V2,
reciprocal = F,
int = F) {
# assigns elements to clusters via single-linkage clustering, based on pairs
# (e.g., query - subject). Pairs are elements of V1 and V2 (vectors of equal
# length) at the same position If an element is found in several pairs (and
# clusters, iteratively), the elements of these pairs (or clusters) will be
# assigned to the same cluster
if (length(V1) != length(V2)) {
stop("provide vectors of equal length")
}
m <- 0
if (!int) {
# we assign unique cluster ids (integers) to elements (faster than union())
uniq <- unique(c(V1, V2))
if (is.character(V1)) {
V1 <- chmatch(V1, uniq)
} else {
V1 <- match(V1, uniq)
}
if (is.character(V2)) {
V2 <- chmatch(V2, uniq)
} else {
V2 <- match(V2, uniq)
}
# will give the correspondance between current cluster ids (the indices of m) and new
# clusters ids (values of m), for replacement. Initially, they are the same
m <- 1:length(uniq)
} else {
m <- 1:max(V1, V2)
}
if (!reciprocal) {
# if there is no reciprocity in pairs
# we now have reciprocal pairs of clusters
pairs <- data.table(q = c(V1, V2), s = c(V2, V1))
} else {
pairs <- data.table(q = V1, s = V2)
}
f <- pairs[, q > s]
while (any(f)) {
# clustering proceeds until the 2 elements of every pair are assigned to the same cluster
# for a given query cluster we need lowest cluster id in all pairs where it is found, including itself.
# So there's no need to use rows for which the cluster is lower than the query
mins <- pairs[f, min(s), by = q]
# and we replace each cluster id by this lowest id in both query and subject clusters
# (these 2 lines are much faster than a match())
m[mins$q] <- mins$V1
pairs[, c("q", "s") := .(m[q], m[s])]
f <- pairs[, q > s]
cat("*")
}
# we get cluster ids corresponding to V1 elements since they are the same for V2
res <- pairs$q[1:length(V1)]
# this removes possible gaps in cluster numbering
match(res, unique(res))
}
pastePair <- function(string1, string2, sep = "_") {
# paste elements of string1 and string2 together (character vectors) so that
# the lower of the two (in alphabetical order) is at the left of the pasted
# result
f <- string1 < string2
if (!is.character(string1)) {
string1 <- as.character(string1)
string2 <- as.character(string2)
}
ifelse(f,
stri_join(string1, string2, sep = sep),
stri_join(string2, string1, sep = sep)
)
}
allPairs <- function(v,
sort = T,
noDups = T,
reciprocal = F,
same = F,
v2 = NA) {
# returns all possible pairs for elements of a vector, or two vectors (2dn
# vector specified in v2). Much faster than combn(v, 2). reciprocal = T means
# reciprocal pairs are returned. sort = T means pairs are sorted alphabetically
# or numerically. same tells if pairs comprising the same element twice should
# be returned (only valid if v2 = NA)
if (noDups) {
v <- unique(v)
}
v2 <- unique(v2)
if (sort) {
v <- sort(v)
}
v2 <- sort(v2)
if (all(is.na(v2)) & !reciprocal) {
i <- 0L
if (!same) {
i <- 1L
}
lv <- length(v)
V2 <- unlist(lapply((i + 1):lv, function(x) {
v[x:lv]
}))
return(data.table(V1 = rep(v, lv:1 - i), V2))
}
else {
self <- F
if (all(is.na(v2))) {
v2 <- v
}
self <- T
cb <- data.table(
V1 = rep(v, each = length(v2)),
V2 = rep(v2, length(v))
)
if (!self & reciprocal) {
cb <- rbind(cb, cb[, 2:1])
}
cb
}
}
data.tableFromCommunities <- function(comm) {
# creates a data table from communities generated by iGraph
cNumbers <- unlist(Map(rep, 1:length(comm), sapply(comm[1:length(comm)], length)))
members <- unlist(comm[1:length(comm)])
data.table(member = as.integer(members), community = cNumbers)
}
combineHits <- function(blast,
maxDist = 50,
maxOverlap = 30,
maxDiff = 50,
blastX = F) {
# combines nearby HSPs in a bast tabular output, if these HSPs involve the same
# query and subject. Do not combine HSPs that are distant by more than maxDist
# and overlap by more than maxOverlap. bastX should be TRUE if hits are
# obtained by blastx
blast <- blast[, 1:12, with = F]
setnames(
blast,
c(
"query", "subject", "identity", "length", "mismatches",