“位置感知”将序列与字母注释对齐

2024-10-06 11:23:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我们有2个DNA序列(字符串):

>1
ATGCAT
135198
>2
ATCAT

预期输出:首先,我们需要对齐这两个字符串,然后按索引获取相关注释:

ATGCAT
AT-CAT
13-198

第一部分可以使用生物串包完成:

library(Biostrings)

p <- DNAString("ATCAT")
s <- DNAString("ATGCAT")
s_annot <- "135198"

x <- pairwiseAlignment(pattern = p, subject = s)

aligned(x)
# A DNAStringSet instance of length 1
#     width seq
# [1]     6 AT-CAT
as.character(x)
# [1] "AT-CAT"
as.matrix(x)
#     [,1] [,2] [,3] [,4] [,5] [,6]
# [1,] "A"  "T"  "-"  "C"  "A"  "T" 

第二部分的当前解决方案:

annot <- unlist(strsplit(s_annot, ""))
annot[ which(c(as.matrix(x)) == "-") ] <- "-"
# [1] "1" "3" "-" "1" "9" "8"

工作正常,但我想知道是否有Biostrings方法(或任何其他软件包),可能是将注释保留在元数据槽中,然后在对齐后,我们在元数据中获得匹配基的匹配注释,如下所示:

getSlots("DNAString")
#      shared              offset              length     elementMetadata            metadata 
# "SharedRaw"           "integer"           "integer" "DataTable_OR_NULL"              "list" 

# just an idea, non-working code
s@metadata <- unlist(strsplit(s_annot , ""))
x <- pairwiseAlignment(pattern = p, subject = s)
metadata(x)
# [[1]]
# [1] "1" "3" "-" "1" "9" "8"

注意:

  • 在作者的许可下从BioStars偷来的
  • 作者想要biopython解决方案,所以如果可能的话,也可以添加标签postpython解决方案

Tags: 字符串as解决方案lengthatcatpatternsubject
2条回答

一种可能的解决办法:

dna_fun <- function(s, p, a) {
  s <- strsplit(s, "")[[1]]
  p <- strsplit(p, "")[[1]]
  a <- strsplit(a, "")[[1]]
  ls <- length(s)
  lp <- length(p)

  r <- lapply(c(1,seq(lp)), function(x) {
    v <- rep(1, 5)
    v[x] <- 2
    v
  })

  mat <- sapply(r, rep, x = p)
  tfm <- mat == matrix(rep(s, ls), ncol = ls)
  m <- which.max(colSums(tfm))

  p2 <- mat[, m]
  p2[!tfm[,m]] <- "-"

  a[!tfm[,m]] <- "-"

  p2 <- paste(p2, collapse = "")
  a <- paste(a, collapse = "")

  return(list(p2, a))
}

与:

dna_fun(s1, s2, annot)

你会得到:

[[1]]
[1] "AT-CAT"

[[2]]
[1] "13-198"

如果有相应的向量,可以将Mapdna_fun-函数一起使用:

s11 <- c("ATGCAT","ATCGAT")
s22 <- c("ATCAT","ATCAT")
annot2 <- c("135198","145892")

lm <- Map(dna_fun, s11, s22, annot2)

data.table::rbindlist(lm, idcol = "dna")

这使得:

      dna     V1     V2
1: ATGCAT AT-CAT 13-198
2: ATCGAT ATC-AT 145-92

数据:

s1 <- "ATGCAT"
s2 <- "ATCAT"
annot <- "135198"

根据要求,Biopython解决方案:

from Bio import Align

p = "ATCAT"
s = "ATGCAT"
s_annot = "135198"

aligner = Align.PairwiseAligner()
alignment = str(aligner.align(p, s)[0]).split()
middle = alignment.pop(1)
alignment.append("".join(c if m == "|" else m for c, m in zip(s_annot, middle)))

print("\n".join(alignment))

输出:

AT-CAT
ATGCAT
13-198

相关问题 更多 >